1 //===-- AArch64AsmBackend.cpp - AArch64 Assembler Backend -----------------===//
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 "MCTargetDesc/AArch64FixupKinds.h"
10 #include "MCTargetDesc/AArch64MCExpr.h"
11 #include "MCTargetDesc/AArch64MCTargetDesc.h"
12 #include "Utils/AArch64BaseInfo.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/BinaryFormat/MachO.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCDirectives.h"
19 #include "llvm/MC/MCELFObjectWriter.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCObjectWriter.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionELF.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCTargetOptions.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/EndianStream.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/TargetRegistry.h"
30 using namespace llvm;
31
32 namespace {
33
34 class AArch64AsmBackend : public MCAsmBackend {
35 static const unsigned PCRelFlagVal =
36 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits | MCFixupKindInfo::FKF_IsPCRel;
37 protected:
38 Triple TheTriple;
39
40 public:
AArch64AsmBackend(const Target & T,const Triple & TT,bool IsLittleEndian)41 AArch64AsmBackend(const Target &T, const Triple &TT, bool IsLittleEndian)
42 : MCAsmBackend(IsLittleEndian ? support::little : support::big),
43 TheTriple(TT) {}
44
getNumFixupKinds() const45 unsigned getNumFixupKinds() const override {
46 return AArch64::NumTargetFixupKinds;
47 }
48
49 Optional<MCFixupKind> getFixupKind(StringRef Name) const override;
50
getFixupKindInfo(MCFixupKind Kind) const51 const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
52 const static MCFixupKindInfo Infos[AArch64::NumTargetFixupKinds] = {
53 // This table *must* be in the order that the fixup_* kinds are defined
54 // in AArch64FixupKinds.h.
55 //
56 // Name Offset (bits) Size (bits) Flags
57 {"fixup_aarch64_pcrel_adr_imm21", 0, 32, PCRelFlagVal},
58 {"fixup_aarch64_pcrel_adrp_imm21", 0, 32, PCRelFlagVal},
59 {"fixup_aarch64_add_imm12", 10, 12, 0},
60 {"fixup_aarch64_ldst_imm12_scale1", 10, 12, 0},
61 {"fixup_aarch64_ldst_imm12_scale2", 10, 12, 0},
62 {"fixup_aarch64_ldst_imm12_scale4", 10, 12, 0},
63 {"fixup_aarch64_ldst_imm12_scale8", 10, 12, 0},
64 {"fixup_aarch64_ldst_imm12_scale16", 10, 12, 0},
65 {"fixup_aarch64_ldr_pcrel_imm19", 5, 19, PCRelFlagVal},
66 {"fixup_aarch64_movw", 5, 16, 0},
67 {"fixup_aarch64_pcrel_branch14", 5, 14, PCRelFlagVal},
68 {"fixup_aarch64_pcrel_branch19", 5, 19, PCRelFlagVal},
69 {"fixup_aarch64_pcrel_branch26", 0, 26, PCRelFlagVal},
70 {"fixup_aarch64_pcrel_call26", 0, 26, PCRelFlagVal},
71 {"fixup_aarch64_tlsdesc_call", 0, 0, 0}};
72
73 // Fixup kinds from .reloc directive are like R_AARCH64_NONE. They do not
74 // require any extra processing.
75 if (Kind >= FirstLiteralRelocationKind)
76 return MCAsmBackend::getFixupKindInfo(FK_NONE);
77
78 if (Kind < FirstTargetFixupKind)
79 return MCAsmBackend::getFixupKindInfo(Kind);
80
81 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
82 "Invalid kind!");
83 return Infos[Kind - FirstTargetFixupKind];
84 }
85
86 void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
87 const MCValue &Target, MutableArrayRef<char> Data,
88 uint64_t Value, bool IsResolved,
89 const MCSubtargetInfo *STI) const override;
90
91 bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
92 const MCRelaxableFragment *DF,
93 const MCAsmLayout &Layout) const override;
94 void relaxInstruction(MCInst &Inst,
95 const MCSubtargetInfo &STI) const override;
96 bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
97
HandleAssemblerFlag(MCAssemblerFlag Flag)98 void HandleAssemblerFlag(MCAssemblerFlag Flag) {}
99
getPointerSize() const100 unsigned getPointerSize() const { return 8; }
101
102 unsigned getFixupKindContainereSizeInBytes(unsigned Kind) const;
103
104 bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
105 const MCValue &Target) override;
106 };
107
108 } // end anonymous namespace
109
110 /// The number of bytes the fixup may change.
getFixupKindNumBytes(unsigned Kind)111 static unsigned getFixupKindNumBytes(unsigned Kind) {
112 switch (Kind) {
113 default:
114 llvm_unreachable("Unknown fixup kind!");
115
116 case AArch64::fixup_aarch64_tlsdesc_call:
117 return 0;
118
119 case FK_Data_1:
120 return 1;
121
122 case FK_Data_2:
123 case FK_SecRel_2:
124 return 2;
125
126 case AArch64::fixup_aarch64_movw:
127 case AArch64::fixup_aarch64_pcrel_branch14:
128 case AArch64::fixup_aarch64_add_imm12:
129 case AArch64::fixup_aarch64_ldst_imm12_scale1:
130 case AArch64::fixup_aarch64_ldst_imm12_scale2:
131 case AArch64::fixup_aarch64_ldst_imm12_scale4:
132 case AArch64::fixup_aarch64_ldst_imm12_scale8:
133 case AArch64::fixup_aarch64_ldst_imm12_scale16:
134 case AArch64::fixup_aarch64_ldr_pcrel_imm19:
135 case AArch64::fixup_aarch64_pcrel_branch19:
136 return 3;
137
138 case AArch64::fixup_aarch64_pcrel_adr_imm21:
139 case AArch64::fixup_aarch64_pcrel_adrp_imm21:
140 case AArch64::fixup_aarch64_pcrel_branch26:
141 case AArch64::fixup_aarch64_pcrel_call26:
142 case FK_Data_4:
143 case FK_SecRel_4:
144 return 4;
145
146 case FK_Data_8:
147 return 8;
148 }
149 }
150
AdrImmBits(unsigned Value)151 static unsigned AdrImmBits(unsigned Value) {
152 unsigned lo2 = Value & 0x3;
153 unsigned hi19 = (Value & 0x1ffffc) >> 2;
154 return (hi19 << 5) | (lo2 << 29);
155 }
156
adjustFixupValue(const MCFixup & Fixup,const MCValue & Target,uint64_t Value,MCContext & Ctx,const Triple & TheTriple,bool IsResolved)157 static uint64_t adjustFixupValue(const MCFixup &Fixup, const MCValue &Target,
158 uint64_t Value, MCContext &Ctx,
159 const Triple &TheTriple, bool IsResolved) {
160 int64_t SignedValue = static_cast<int64_t>(Value);
161 switch (Fixup.getTargetKind()) {
162 default:
163 llvm_unreachable("Unknown fixup kind!");
164 case AArch64::fixup_aarch64_pcrel_adr_imm21:
165 if (SignedValue > 2097151 || SignedValue < -2097152)
166 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
167 return AdrImmBits(Value & 0x1fffffULL);
168 case AArch64::fixup_aarch64_pcrel_adrp_imm21:
169 assert(!IsResolved);
170 if (TheTriple.isOSBinFormatCOFF())
171 return AdrImmBits(Value & 0x1fffffULL);
172 return AdrImmBits((Value & 0x1fffff000ULL) >> 12);
173 case AArch64::fixup_aarch64_ldr_pcrel_imm19:
174 case AArch64::fixup_aarch64_pcrel_branch19:
175 // Signed 21-bit immediate
176 if (SignedValue > 2097151 || SignedValue < -2097152)
177 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
178 if (Value & 0x3)
179 Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
180 // Low two bits are not encoded.
181 return (Value >> 2) & 0x7ffff;
182 case AArch64::fixup_aarch64_add_imm12:
183 case AArch64::fixup_aarch64_ldst_imm12_scale1:
184 if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
185 Value &= 0xfff;
186 // Unsigned 12-bit immediate
187 if (Value >= 0x1000)
188 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
189 return Value;
190 case AArch64::fixup_aarch64_ldst_imm12_scale2:
191 if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
192 Value &= 0xfff;
193 // Unsigned 12-bit immediate which gets multiplied by 2
194 if (Value >= 0x2000)
195 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
196 if (Value & 0x1)
197 Ctx.reportError(Fixup.getLoc(), "fixup must be 2-byte aligned");
198 return Value >> 1;
199 case AArch64::fixup_aarch64_ldst_imm12_scale4:
200 if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
201 Value &= 0xfff;
202 // Unsigned 12-bit immediate which gets multiplied by 4
203 if (Value >= 0x4000)
204 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
205 if (Value & 0x3)
206 Ctx.reportError(Fixup.getLoc(), "fixup must be 4-byte aligned");
207 return Value >> 2;
208 case AArch64::fixup_aarch64_ldst_imm12_scale8:
209 if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
210 Value &= 0xfff;
211 // Unsigned 12-bit immediate which gets multiplied by 8
212 if (Value >= 0x8000)
213 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
214 if (Value & 0x7)
215 Ctx.reportError(Fixup.getLoc(), "fixup must be 8-byte aligned");
216 return Value >> 3;
217 case AArch64::fixup_aarch64_ldst_imm12_scale16:
218 if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
219 Value &= 0xfff;
220 // Unsigned 12-bit immediate which gets multiplied by 16
221 if (Value >= 0x10000)
222 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
223 if (Value & 0xf)
224 Ctx.reportError(Fixup.getLoc(), "fixup must be 16-byte aligned");
225 return Value >> 4;
226 case AArch64::fixup_aarch64_movw: {
227 AArch64MCExpr::VariantKind RefKind =
228 static_cast<AArch64MCExpr::VariantKind>(Target.getRefKind());
229 if (AArch64MCExpr::getSymbolLoc(RefKind) != AArch64MCExpr::VK_ABS &&
230 AArch64MCExpr::getSymbolLoc(RefKind) != AArch64MCExpr::VK_SABS) {
231 if (!RefKind) {
232 // The fixup is an expression
233 if (SignedValue > 0xFFFF || SignedValue < -0xFFFF)
234 Ctx.reportError(Fixup.getLoc(),
235 "fixup value out of range [-0xFFFF, 0xFFFF]");
236
237 // Invert the negative immediate because it will feed into a MOVN.
238 if (SignedValue < 0)
239 SignedValue = ~SignedValue;
240 Value = static_cast<uint64_t>(SignedValue);
241 } else
242 // VK_GOTTPREL, VK_TPREL, VK_DTPREL are movw fixups, but they can't
243 // ever be resolved in the assembler.
244 Ctx.reportError(Fixup.getLoc(),
245 "relocation for a thread-local variable points to an "
246 "absolute symbol");
247 return Value;
248 }
249
250 if (!IsResolved) {
251 // FIXME: Figure out when this can actually happen, and verify our
252 // behavior.
253 Ctx.reportError(Fixup.getLoc(), "unresolved movw fixup not yet "
254 "implemented");
255 return Value;
256 }
257
258 if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS) {
259 switch (AArch64MCExpr::getAddressFrag(RefKind)) {
260 case AArch64MCExpr::VK_G0:
261 break;
262 case AArch64MCExpr::VK_G1:
263 SignedValue = SignedValue >> 16;
264 break;
265 case AArch64MCExpr::VK_G2:
266 SignedValue = SignedValue >> 32;
267 break;
268 case AArch64MCExpr::VK_G3:
269 SignedValue = SignedValue >> 48;
270 break;
271 default:
272 llvm_unreachable("Variant kind doesn't correspond to fixup");
273 }
274
275 } else {
276 switch (AArch64MCExpr::getAddressFrag(RefKind)) {
277 case AArch64MCExpr::VK_G0:
278 break;
279 case AArch64MCExpr::VK_G1:
280 Value = Value >> 16;
281 break;
282 case AArch64MCExpr::VK_G2:
283 Value = Value >> 32;
284 break;
285 case AArch64MCExpr::VK_G3:
286 Value = Value >> 48;
287 break;
288 default:
289 llvm_unreachable("Variant kind doesn't correspond to fixup");
290 }
291 }
292
293 if (RefKind & AArch64MCExpr::VK_NC) {
294 Value &= 0xFFFF;
295 }
296 else if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS) {
297 if (SignedValue > 0xFFFF || SignedValue < -0xFFFF)
298 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
299
300 // Invert the negative immediate because it will feed into a MOVN.
301 if (SignedValue < 0)
302 SignedValue = ~SignedValue;
303 Value = static_cast<uint64_t>(SignedValue);
304 }
305 else if (Value > 0xFFFF) {
306 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
307 }
308 return Value;
309 }
310 case AArch64::fixup_aarch64_pcrel_branch14:
311 // Signed 16-bit immediate
312 if (SignedValue > 32767 || SignedValue < -32768)
313 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
314 // Low two bits are not encoded (4-byte alignment assumed).
315 if (Value & 0x3)
316 Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
317 return (Value >> 2) & 0x3fff;
318 case AArch64::fixup_aarch64_pcrel_branch26:
319 case AArch64::fixup_aarch64_pcrel_call26:
320 // Signed 28-bit immediate
321 if (SignedValue > 134217727 || SignedValue < -134217728)
322 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
323 // Low two bits are not encoded (4-byte alignment assumed).
324 if (Value & 0x3)
325 Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
326 return (Value >> 2) & 0x3ffffff;
327 case FK_Data_1:
328 case FK_Data_2:
329 case FK_Data_4:
330 case FK_Data_8:
331 case FK_SecRel_2:
332 case FK_SecRel_4:
333 return Value;
334 }
335 }
336
getFixupKind(StringRef Name) const337 Optional<MCFixupKind> AArch64AsmBackend::getFixupKind(StringRef Name) const {
338 if (!TheTriple.isOSBinFormatELF())
339 return None;
340
341 unsigned Type = llvm::StringSwitch<unsigned>(Name)
342 #define ELF_RELOC(X, Y) .Case(#X, Y)
343 #include "llvm/BinaryFormat/ELFRelocs/AArch64.def"
344 #undef ELF_RELOC
345 .Default(-1u);
346 if (Type == -1u)
347 return None;
348 return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
349 }
350
351 /// getFixupKindContainereSizeInBytes - The number of bytes of the
352 /// container involved in big endian or 0 if the item is little endian
getFixupKindContainereSizeInBytes(unsigned Kind) const353 unsigned AArch64AsmBackend::getFixupKindContainereSizeInBytes(unsigned Kind) const {
354 if (Endian == support::little)
355 return 0;
356
357 switch (Kind) {
358 default:
359 llvm_unreachable("Unknown fixup kind!");
360
361 case FK_Data_1:
362 return 1;
363 case FK_Data_2:
364 return 2;
365 case FK_Data_4:
366 return 4;
367 case FK_Data_8:
368 return 8;
369
370 case AArch64::fixup_aarch64_tlsdesc_call:
371 case AArch64::fixup_aarch64_movw:
372 case AArch64::fixup_aarch64_pcrel_branch14:
373 case AArch64::fixup_aarch64_add_imm12:
374 case AArch64::fixup_aarch64_ldst_imm12_scale1:
375 case AArch64::fixup_aarch64_ldst_imm12_scale2:
376 case AArch64::fixup_aarch64_ldst_imm12_scale4:
377 case AArch64::fixup_aarch64_ldst_imm12_scale8:
378 case AArch64::fixup_aarch64_ldst_imm12_scale16:
379 case AArch64::fixup_aarch64_ldr_pcrel_imm19:
380 case AArch64::fixup_aarch64_pcrel_branch19:
381 case AArch64::fixup_aarch64_pcrel_adr_imm21:
382 case AArch64::fixup_aarch64_pcrel_adrp_imm21:
383 case AArch64::fixup_aarch64_pcrel_branch26:
384 case AArch64::fixup_aarch64_pcrel_call26:
385 // Instructions are always little endian
386 return 0;
387 }
388 }
389
applyFixup(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target,MutableArrayRef<char> Data,uint64_t Value,bool IsResolved,const MCSubtargetInfo * STI) const390 void AArch64AsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
391 const MCValue &Target,
392 MutableArrayRef<char> Data, uint64_t Value,
393 bool IsResolved,
394 const MCSubtargetInfo *STI) const {
395 if (!Value)
396 return; // Doesn't change encoding.
397 unsigned Kind = Fixup.getKind();
398 if (Kind >= FirstLiteralRelocationKind)
399 return;
400 unsigned NumBytes = getFixupKindNumBytes(Kind);
401 MCFixupKindInfo Info = getFixupKindInfo(Fixup.getKind());
402 MCContext &Ctx = Asm.getContext();
403 int64_t SignedValue = static_cast<int64_t>(Value);
404 // Apply any target-specific value adjustments.
405 Value = adjustFixupValue(Fixup, Target, Value, Ctx, TheTriple, IsResolved);
406
407 // Shift the value into position.
408 Value <<= Info.TargetOffset;
409
410 unsigned Offset = Fixup.getOffset();
411 assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
412
413 // Used to point to big endian bytes.
414 unsigned FulleSizeInBytes = getFixupKindContainereSizeInBytes(Fixup.getKind());
415
416 // For each byte of the fragment that the fixup touches, mask in the
417 // bits from the fixup value.
418 if (FulleSizeInBytes == 0) {
419 // Handle as little-endian
420 for (unsigned i = 0; i != NumBytes; ++i) {
421 Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
422 }
423 } else {
424 // Handle as big-endian
425 assert((Offset + FulleSizeInBytes) <= Data.size() && "Invalid fixup size!");
426 assert(NumBytes <= FulleSizeInBytes && "Invalid fixup size!");
427 for (unsigned i = 0; i != NumBytes; ++i) {
428 unsigned Idx = FulleSizeInBytes - 1 - i;
429 Data[Offset + Idx] |= uint8_t((Value >> (i * 8)) & 0xff);
430 }
431 }
432
433 // FIXME: getFixupKindInfo() and getFixupKindNumBytes() could be fixed to
434 // handle this more cleanly. This may affect the output of -show-mc-encoding.
435 AArch64MCExpr::VariantKind RefKind =
436 static_cast<AArch64MCExpr::VariantKind>(Target.getRefKind());
437 if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS ||
438 (!RefKind && Fixup.getTargetKind() == AArch64::fixup_aarch64_movw)) {
439 // If the immediate is negative, generate MOVN else MOVZ.
440 // (Bit 30 = 0) ==> MOVN, (Bit 30 = 1) ==> MOVZ.
441 if (SignedValue < 0)
442 Data[Offset + 3] &= ~(1 << 6);
443 else
444 Data[Offset + 3] |= (1 << 6);
445 }
446 }
447
fixupNeedsRelaxation(const MCFixup & Fixup,uint64_t Value,const MCRelaxableFragment * DF,const MCAsmLayout & Layout) const448 bool AArch64AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
449 uint64_t Value,
450 const MCRelaxableFragment *DF,
451 const MCAsmLayout &Layout) const {
452 // FIXME: This isn't correct for AArch64. Just moving the "generic" logic
453 // into the targets for now.
454 //
455 // Relax if the value is too big for a (signed) i8.
456 return int64_t(Value) != int64_t(int8_t(Value));
457 }
458
relaxInstruction(MCInst & Inst,const MCSubtargetInfo & STI) const459 void AArch64AsmBackend::relaxInstruction(MCInst &Inst,
460 const MCSubtargetInfo &STI) const {
461 llvm_unreachable("AArch64AsmBackend::relaxInstruction() unimplemented");
462 }
463
writeNopData(raw_ostream & OS,uint64_t Count) const464 bool AArch64AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
465 // If the count is not 4-byte aligned, we must be writing data into the text
466 // section (otherwise we have unaligned instructions, and thus have far
467 // bigger problems), so just write zeros instead.
468 OS.write_zeros(Count % 4);
469
470 // We are properly aligned, so write NOPs as requested.
471 Count /= 4;
472 for (uint64_t i = 0; i != Count; ++i)
473 support::endian::write<uint32_t>(OS, 0xd503201f, Endian);
474 return true;
475 }
476
shouldForceRelocation(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target)477 bool AArch64AsmBackend::shouldForceRelocation(const MCAssembler &Asm,
478 const MCFixup &Fixup,
479 const MCValue &Target) {
480 unsigned Kind = Fixup.getKind();
481 if (Kind >= FirstLiteralRelocationKind)
482 return true;
483
484 // The ADRP instruction adds some multiple of 0x1000 to the current PC &
485 // ~0xfff. This means that the required offset to reach a symbol can vary by
486 // up to one step depending on where the ADRP is in memory. For example:
487 //
488 // ADRP x0, there
489 // there:
490 //
491 // If the ADRP occurs at address 0xffc then "there" will be at 0x1000 and
492 // we'll need that as an offset. At any other address "there" will be in the
493 // same page as the ADRP and the instruction should encode 0x0. Assuming the
494 // section isn't 0x1000-aligned, we therefore need to delegate this decision
495 // to the linker -- a relocation!
496 if (Kind == AArch64::fixup_aarch64_pcrel_adrp_imm21)
497 return true;
498
499 AArch64MCExpr::VariantKind RefKind =
500 static_cast<AArch64MCExpr::VariantKind>(Target.getRefKind());
501 AArch64MCExpr::VariantKind SymLoc = AArch64MCExpr::getSymbolLoc(RefKind);
502 // LDR GOT relocations need a relocation
503 if (Kind == AArch64::fixup_aarch64_ldr_pcrel_imm19 &&
504 SymLoc == AArch64MCExpr::VK_GOT)
505 return true;
506 return false;
507 }
508
509 namespace {
510
511 namespace CU {
512
513 /// Compact unwind encoding values.
514 enum CompactUnwindEncodings {
515 /// A "frameless" leaf function, where no non-volatile registers are
516 /// saved. The return remains in LR throughout the function.
517 UNWIND_ARM64_MODE_FRAMELESS = 0x02000000,
518
519 /// No compact unwind encoding available. Instead the low 23-bits of
520 /// the compact unwind encoding is the offset of the DWARF FDE in the
521 /// __eh_frame section. This mode is never used in object files. It is only
522 /// generated by the linker in final linked images, which have only DWARF info
523 /// for a function.
524 UNWIND_ARM64_MODE_DWARF = 0x03000000,
525
526 /// This is a standard arm64 prologue where FP/LR are immediately
527 /// pushed on the stack, then SP is copied to FP. If there are any
528 /// non-volatile register saved, they are copied into the stack fame in pairs
529 /// in a contiguous ranger right below the saved FP/LR pair. Any subset of the
530 /// five X pairs and four D pairs can be saved, but the memory layout must be
531 /// in register number order.
532 UNWIND_ARM64_MODE_FRAME = 0x04000000,
533
534 /// Frame register pair encodings.
535 UNWIND_ARM64_FRAME_X19_X20_PAIR = 0x00000001,
536 UNWIND_ARM64_FRAME_X21_X22_PAIR = 0x00000002,
537 UNWIND_ARM64_FRAME_X23_X24_PAIR = 0x00000004,
538 UNWIND_ARM64_FRAME_X25_X26_PAIR = 0x00000008,
539 UNWIND_ARM64_FRAME_X27_X28_PAIR = 0x00000010,
540 UNWIND_ARM64_FRAME_D8_D9_PAIR = 0x00000100,
541 UNWIND_ARM64_FRAME_D10_D11_PAIR = 0x00000200,
542 UNWIND_ARM64_FRAME_D12_D13_PAIR = 0x00000400,
543 UNWIND_ARM64_FRAME_D14_D15_PAIR = 0x00000800
544 };
545
546 } // end CU namespace
547
548 // FIXME: This should be in a separate file.
549 class DarwinAArch64AsmBackend : public AArch64AsmBackend {
550 const MCRegisterInfo &MRI;
551
552 /// Encode compact unwind stack adjustment for frameless functions.
553 /// See UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK in compact_unwind_encoding.h.
554 /// The stack size always needs to be 16 byte aligned.
encodeStackAdjustment(uint32_t StackSize) const555 uint32_t encodeStackAdjustment(uint32_t StackSize) const {
556 return (StackSize / 16) << 12;
557 }
558
559 public:
DarwinAArch64AsmBackend(const Target & T,const Triple & TT,const MCRegisterInfo & MRI)560 DarwinAArch64AsmBackend(const Target &T, const Triple &TT,
561 const MCRegisterInfo &MRI)
562 : AArch64AsmBackend(T, TT, /*IsLittleEndian*/ true), MRI(MRI) {}
563
564 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const565 createObjectTargetWriter() const override {
566 uint32_t CPUType = cantFail(MachO::getCPUType(TheTriple));
567 uint32_t CPUSubType = cantFail(MachO::getCPUSubType(TheTriple));
568 return createAArch64MachObjectWriter(CPUType, CPUSubType,
569 TheTriple.isArch32Bit());
570 }
571
572 /// Generate the compact unwind encoding from the CFI directives.
generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction> Instrs) const573 uint32_t generateCompactUnwindEncoding(
574 ArrayRef<MCCFIInstruction> Instrs) const override {
575 if (Instrs.empty())
576 return CU::UNWIND_ARM64_MODE_FRAMELESS;
577
578 bool HasFP = false;
579 unsigned StackSize = 0;
580
581 uint32_t CompactUnwindEncoding = 0;
582 for (size_t i = 0, e = Instrs.size(); i != e; ++i) {
583 const MCCFIInstruction &Inst = Instrs[i];
584
585 switch (Inst.getOperation()) {
586 default:
587 // Cannot handle this directive: bail out.
588 return CU::UNWIND_ARM64_MODE_DWARF;
589 case MCCFIInstruction::OpDefCfa: {
590 // Defines a frame pointer.
591 unsigned XReg =
592 getXRegFromWReg(*MRI.getLLVMRegNum(Inst.getRegister(), true));
593
594 // Other CFA registers than FP are not supported by compact unwind.
595 // Fallback on DWARF.
596 // FIXME: When opt-remarks are supported in MC, add a remark to notify
597 // the user.
598 if (XReg != AArch64::FP)
599 return CU::UNWIND_ARM64_MODE_DWARF;
600
601 assert(XReg == AArch64::FP && "Invalid frame pointer!");
602 assert(i + 2 < e && "Insufficient CFI instructions to define a frame!");
603
604 const MCCFIInstruction &LRPush = Instrs[++i];
605 assert(LRPush.getOperation() == MCCFIInstruction::OpOffset &&
606 "Link register not pushed!");
607 const MCCFIInstruction &FPPush = Instrs[++i];
608 assert(FPPush.getOperation() == MCCFIInstruction::OpOffset &&
609 "Frame pointer not pushed!");
610
611 unsigned LRReg = *MRI.getLLVMRegNum(LRPush.getRegister(), true);
612 unsigned FPReg = *MRI.getLLVMRegNum(FPPush.getRegister(), true);
613
614 LRReg = getXRegFromWReg(LRReg);
615 FPReg = getXRegFromWReg(FPReg);
616
617 assert(LRReg == AArch64::LR && FPReg == AArch64::FP &&
618 "Pushing invalid registers for frame!");
619
620 // Indicate that the function has a frame.
621 CompactUnwindEncoding |= CU::UNWIND_ARM64_MODE_FRAME;
622 HasFP = true;
623 break;
624 }
625 case MCCFIInstruction::OpDefCfaOffset: {
626 assert(StackSize == 0 && "We already have the CFA offset!");
627 StackSize = std::abs(Inst.getOffset());
628 break;
629 }
630 case MCCFIInstruction::OpOffset: {
631 // Registers are saved in pairs. We expect there to be two consecutive
632 // `.cfi_offset' instructions with the appropriate registers specified.
633 unsigned Reg1 = *MRI.getLLVMRegNum(Inst.getRegister(), true);
634 if (i + 1 == e)
635 return CU::UNWIND_ARM64_MODE_DWARF;
636
637 const MCCFIInstruction &Inst2 = Instrs[++i];
638 if (Inst2.getOperation() != MCCFIInstruction::OpOffset)
639 return CU::UNWIND_ARM64_MODE_DWARF;
640 unsigned Reg2 = *MRI.getLLVMRegNum(Inst2.getRegister(), true);
641
642 // N.B. The encodings must be in register number order, and the X
643 // registers before the D registers.
644
645 // X19/X20 pair = 0x00000001,
646 // X21/X22 pair = 0x00000002,
647 // X23/X24 pair = 0x00000004,
648 // X25/X26 pair = 0x00000008,
649 // X27/X28 pair = 0x00000010
650 Reg1 = getXRegFromWReg(Reg1);
651 Reg2 = getXRegFromWReg(Reg2);
652
653 if (Reg1 == AArch64::X19 && Reg2 == AArch64::X20 &&
654 (CompactUnwindEncoding & 0xF1E) == 0)
655 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X19_X20_PAIR;
656 else if (Reg1 == AArch64::X21 && Reg2 == AArch64::X22 &&
657 (CompactUnwindEncoding & 0xF1C) == 0)
658 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X21_X22_PAIR;
659 else if (Reg1 == AArch64::X23 && Reg2 == AArch64::X24 &&
660 (CompactUnwindEncoding & 0xF18) == 0)
661 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X23_X24_PAIR;
662 else if (Reg1 == AArch64::X25 && Reg2 == AArch64::X26 &&
663 (CompactUnwindEncoding & 0xF10) == 0)
664 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X25_X26_PAIR;
665 else if (Reg1 == AArch64::X27 && Reg2 == AArch64::X28 &&
666 (CompactUnwindEncoding & 0xF00) == 0)
667 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X27_X28_PAIR;
668 else {
669 Reg1 = getDRegFromBReg(Reg1);
670 Reg2 = getDRegFromBReg(Reg2);
671
672 // D8/D9 pair = 0x00000100,
673 // D10/D11 pair = 0x00000200,
674 // D12/D13 pair = 0x00000400,
675 // D14/D15 pair = 0x00000800
676 if (Reg1 == AArch64::D8 && Reg2 == AArch64::D9 &&
677 (CompactUnwindEncoding & 0xE00) == 0)
678 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D8_D9_PAIR;
679 else if (Reg1 == AArch64::D10 && Reg2 == AArch64::D11 &&
680 (CompactUnwindEncoding & 0xC00) == 0)
681 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D10_D11_PAIR;
682 else if (Reg1 == AArch64::D12 && Reg2 == AArch64::D13 &&
683 (CompactUnwindEncoding & 0x800) == 0)
684 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D12_D13_PAIR;
685 else if (Reg1 == AArch64::D14 && Reg2 == AArch64::D15)
686 CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D14_D15_PAIR;
687 else
688 // A pair was pushed which we cannot handle.
689 return CU::UNWIND_ARM64_MODE_DWARF;
690 }
691
692 break;
693 }
694 }
695 }
696
697 if (!HasFP) {
698 // With compact unwind info we can only represent stack adjustments of up
699 // to 65520 bytes.
700 if (StackSize > 65520)
701 return CU::UNWIND_ARM64_MODE_DWARF;
702
703 CompactUnwindEncoding |= CU::UNWIND_ARM64_MODE_FRAMELESS;
704 CompactUnwindEncoding |= encodeStackAdjustment(StackSize);
705 }
706
707 return CompactUnwindEncoding;
708 }
709 };
710
711 } // end anonymous namespace
712
713 namespace {
714
715 class ELFAArch64AsmBackend : public AArch64AsmBackend {
716 public:
717 uint8_t OSABI;
718 bool IsILP32;
719
ELFAArch64AsmBackend(const Target & T,const Triple & TT,uint8_t OSABI,bool IsLittleEndian,bool IsILP32)720 ELFAArch64AsmBackend(const Target &T, const Triple &TT, uint8_t OSABI,
721 bool IsLittleEndian, bool IsILP32)
722 : AArch64AsmBackend(T, TT, IsLittleEndian), OSABI(OSABI),
723 IsILP32(IsILP32) {}
724
725 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const726 createObjectTargetWriter() const override {
727 return createAArch64ELFObjectWriter(OSABI, IsILP32);
728 }
729 };
730
731 }
732
733 namespace {
734 class COFFAArch64AsmBackend : public AArch64AsmBackend {
735 public:
COFFAArch64AsmBackend(const Target & T,const Triple & TheTriple)736 COFFAArch64AsmBackend(const Target &T, const Triple &TheTriple)
737 : AArch64AsmBackend(T, TheTriple, /*IsLittleEndian*/ true) {}
738
739 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const740 createObjectTargetWriter() const override {
741 return createAArch64WinCOFFObjectWriter();
742 }
743 };
744 }
745
createAArch64leAsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options)746 MCAsmBackend *llvm::createAArch64leAsmBackend(const Target &T,
747 const MCSubtargetInfo &STI,
748 const MCRegisterInfo &MRI,
749 const MCTargetOptions &Options) {
750 const Triple &TheTriple = STI.getTargetTriple();
751 if (TheTriple.isOSBinFormatMachO()) {
752 return new DarwinAArch64AsmBackend(T, TheTriple, MRI);
753 }
754
755 if (TheTriple.isOSBinFormatCOFF())
756 return new COFFAArch64AsmBackend(T, TheTriple);
757
758 assert(TheTriple.isOSBinFormatELF() && "Invalid target");
759
760 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
761 bool IsILP32 = Options.getABIName() == "ilp32";
762 return new ELFAArch64AsmBackend(T, TheTriple, OSABI, /*IsLittleEndian=*/true,
763 IsILP32);
764 }
765
createAArch64beAsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options)766 MCAsmBackend *llvm::createAArch64beAsmBackend(const Target &T,
767 const MCSubtargetInfo &STI,
768 const MCRegisterInfo &MRI,
769 const MCTargetOptions &Options) {
770 const Triple &TheTriple = STI.getTargetTriple();
771 assert(TheTriple.isOSBinFormatELF() &&
772 "Big endian is only supported for ELF targets!");
773 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
774 bool IsILP32 = Options.getABIName() == "ilp32";
775 return new ELFAArch64AsmBackend(T, TheTriple, OSABI, /*IsLittleEndian=*/false,
776 IsILP32);
777 }
778