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