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