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