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