RuntimeDyldMachOAArch64.h: Fix a warning. [-Wunused-variable]
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / Targets / RuntimeDyldMachOAArch64.h
1 //===-- RuntimeDyldMachOAArch64.h -- MachO/AArch64 specific code. -*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_RUNTIMEDYLDMACHOAARCH64_H
11 #define LLVM_RUNTIMEDYLDMACHOAARCH64_H
12
13 #include "../RuntimeDyldMachO.h"
14
15 #define DEBUG_TYPE "dyld"
16
17 namespace llvm {
18
19 class RuntimeDyldMachOAArch64
20     : public RuntimeDyldMachOCRTPBase<RuntimeDyldMachOAArch64> {
21 public:
22   RuntimeDyldMachOAArch64(RTDyldMemoryManager *MM)
23       : RuntimeDyldMachOCRTPBase(MM) {}
24
25   unsigned getMaxStubSize() override { return 8; }
26
27   unsigned getStubAlignment() override { return 8; }
28
29   /// Extract the addend encoded in the instruction / memory location.
30   int64_t decodeAddend(uint8_t *LocalAddress, unsigned NumBytes,
31                        uint32_t RelType) const {
32     int64_t Addend = 0;
33     // Verify that the relocation has the correct size and alignment.
34     switch (RelType) {
35     default:
36       llvm_unreachable("Unsupported relocation type!");
37     case MachO::ARM64_RELOC_UNSIGNED:
38       assert((NumBytes >= 4 && NumBytes <= 8) && "Invalid relocation size.");
39       break;
40     case MachO::ARM64_RELOC_BRANCH26:
41     case MachO::ARM64_RELOC_PAGE21:
42     case MachO::ARM64_RELOC_PAGEOFF12:
43     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
44     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
45       assert(NumBytes == 4 && "Invalid relocation size.");
46       assert((((uintptr_t)LocalAddress & 0x3) == 0) &&
47              "Instruction address is not aligned to 4 bytes.");
48       break;
49     }
50
51     switch (RelType) {
52     default:
53       llvm_unreachable("Unsupported relocation type!");
54     case MachO::ARM64_RELOC_UNSIGNED:
55       // This could be an unaligned memory location - use memcpy.
56       memcpy(&Addend, LocalAddress, NumBytes);
57       break;
58     case MachO::ARM64_RELOC_BRANCH26: {
59       // Verify that the relocation points to the expected branch instruction.
60       uint32_t *p = (uint32_t *)LocalAddress;
61       assert((*p & 0xFC000000) == 0x14000000 && "Expected branch instruction.");
62
63       // Get the 26 bit addend encoded in the branch instruction and sign-extend
64       // to 64 bit. The lower 2 bits are always zeros and are therefore implicit
65       // (<< 2).
66       Addend = (*p & 0x03FFFFFF) << 2;
67       Addend = SignExtend64(Addend, 28);
68       break;
69     }
70     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
71     case MachO::ARM64_RELOC_PAGE21: {
72       // Verify that the relocation points to the expected adrp instruction.
73       uint32_t *p = (uint32_t *)LocalAddress;
74       assert((*p & 0x9F000000) == 0x90000000 && "Expected adrp instruction.");
75
76       // Get the 21 bit addend encoded in the adrp instruction and sign-extend
77       // to 64 bit. The lower 12 bits (4096 byte page) are always zeros and are
78       // therefore implicit (<< 12).
79       Addend = ((*p & 0x60000000) >> 29) | ((*p & 0x01FFFFE0) >> 3) << 12;
80       Addend = SignExtend64(Addend, 33);
81       break;
82     }
83     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: {
84       // Verify that the relocation points to one of the expected load / store
85       // instructions.
86       uint32_t *p = (uint32_t *)LocalAddress;
87       (void)p;
88       assert((*p & 0x3B000000) == 0x39000000 &&
89              "Only expected load / store instructions.");
90     } // fall-through
91     case MachO::ARM64_RELOC_PAGEOFF12: {
92       // Verify that the relocation points to one of the expected load / store
93       // or add / sub instructions.
94       uint32_t *p = (uint32_t *)LocalAddress;
95       assert((((*p & 0x3B000000) == 0x39000000) ||
96               ((*p & 0x11C00000) == 0x11000000)   ) &&
97              "Expected load / store  or add/sub instruction.");
98
99       // Get the 12 bit addend encoded in the instruction.
100       Addend = (*p & 0x003FFC00) >> 10;
101
102       // Check which instruction we are decoding to obtain the implicit shift
103       // factor of the instruction.
104       int ImplicitShift = 0;
105       if ((*p & 0x3B000000) == 0x39000000) { // << load / store
106         // For load / store instructions the size is encoded in bits 31:30.
107         ImplicitShift = ((*p >> 30) & 0x3);
108         if (ImplicitShift == 0) {
109           // Check if this a vector op to get the correct shift value.
110           if ((*p & 0x04800000) == 0x04800000)
111             ImplicitShift = 4;
112         }
113       }
114       // Compensate for implicit shift.
115       Addend <<= ImplicitShift;
116       break;
117     }
118     }
119     return Addend;
120   }
121
122   /// Extract the addend encoded in the instruction.
123   void encodeAddend(uint8_t *LocalAddress, uint32_t RelType,
124                     int64_t Addend) const {
125     // Verify that the relocation has the correct alignment.
126     switch (RelType) {
127     default:
128       llvm_unreachable("Unsupported relocation type!");
129     case MachO::ARM64_RELOC_UNSIGNED:
130       llvm_unreachable("Invalid relocation type for instruction.");
131     case MachO::ARM64_RELOC_BRANCH26:
132     case MachO::ARM64_RELOC_PAGE21:
133     case MachO::ARM64_RELOC_PAGEOFF12:
134     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
135     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
136       assert((((uintptr_t)LocalAddress & 0x3) == 0) &&
137              "Instruction address is not aligned to 4 bytes.");
138       break;
139     }
140
141     switch (RelType) {
142     default:
143       llvm_unreachable("Unsupported relocation type!");
144     case MachO::ARM64_RELOC_BRANCH26: {
145       // Verify that the relocation points to the expected branch instruction.
146       uint32_t *p = (uint32_t *)LocalAddress;
147       assert((*p & 0xFC000000) == 0x14000000 && "Expected branch instruction.");
148
149       // Verify addend value.
150       assert((Addend & 0x3) == 0 && "Branch target is not aligned");
151       assert(isInt<28>(Addend) && "Branch target is out of range.");
152
153       // Encode the addend as 26 bit immediate in the branch instruction.
154       *p = (*p & 0xFC000000) | ((uint32_t)(Addend >> 2) & 0x03FFFFFF);
155       break;
156     }
157     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
158     case MachO::ARM64_RELOC_PAGE21: {
159       // Verify that the relocation points to the expected adrp instruction.
160       uint32_t *p = (uint32_t *)LocalAddress;
161       assert((*p & 0x9F000000) == 0x90000000 && "Expected adrp instruction.");
162
163       // Check that the addend fits into 21 bits (+ 12 lower bits).
164       assert((Addend & 0xFFF) == 0 && "ADRP target is not page aligned.");
165       assert(isInt<33>(Addend) && "Invalid page reloc value.");
166
167       // Encode the addend into the instruction.
168       uint32_t ImmLoValue = (uint32_t)(Addend << 17) & 0x60000000;
169       uint32_t ImmHiValue = (uint32_t)(Addend >> 9) & 0x00FFFFE0;
170       *p = (*p & 0x9F00001F) | ImmHiValue | ImmLoValue;
171       break;
172     }
173     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: {
174       // Verify that the relocation points to one of the expected load / store
175       // instructions.
176       uint32_t *p = (uint32_t *)LocalAddress;
177       assert((*p & 0x3B000000) == 0x39000000 &&
178              "Only expected load / store instructions.");
179       (void)p;
180     } // fall-through
181     case MachO::ARM64_RELOC_PAGEOFF12: {
182       // Verify that the relocation points to one of the expected load / store
183       // or add / sub instructions.
184       uint32_t *p = (uint32_t *)LocalAddress;
185       assert((((*p & 0x3B000000) == 0x39000000) ||
186               ((*p & 0x11C00000) == 0x11000000)   ) &&
187              "Expected load / store  or add/sub instruction.");
188
189       // Check which instruction we are decoding to obtain the implicit shift
190       // factor of the instruction and verify alignment.
191       int ImplicitShift = 0;
192       if ((*p & 0x3B000000) == 0x39000000) { // << load / store
193         // For load / store instructions the size is encoded in bits 31:30.
194         ImplicitShift = ((*p >> 30) & 0x3);
195         switch (ImplicitShift) {
196         case 0:
197           // Check if this a vector op to get the correct shift value.
198           if ((*p & 0x04800000) == 0x04800000) {
199             ImplicitShift = 4;
200             assert(((Addend & 0xF) == 0) &&
201                    "128-bit LDR/STR not 16-byte aligned.");
202           }
203           break;
204         case 1:
205           assert(((Addend & 0x1) == 0) && "16-bit LDR/STR not 2-byte aligned.");
206           break;
207         case 2:
208           assert(((Addend & 0x3) == 0) && "32-bit LDR/STR not 4-byte aligned.");
209           break;
210         case 3:
211           assert(((Addend & 0x7) == 0) && "64-bit LDR/STR not 8-byte aligned.");
212           break;
213         }
214       }
215       // Compensate for implicit shift.
216       Addend >>= ImplicitShift;
217       assert(isUInt<12>(Addend) && "Addend cannot be encoded.");
218
219       // Encode the addend into the instruction.
220       *p = (*p & 0xFFC003FF) | ((uint32_t)(Addend << 10) & 0x003FFC00);
221       break;
222     }
223     }
224   }
225
226   relocation_iterator
227   processRelocationRef(unsigned SectionID, relocation_iterator RelI,
228                        ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
229                        const SymbolTableMap &Symbols, StubMap &Stubs) override {
230     const MachOObjectFile &Obj =
231         static_cast<const MachOObjectFile &>(*ObjImg.getObjectFile());
232     MachO::any_relocation_info RelInfo =
233         Obj.getRelocation(RelI->getRawDataRefImpl());
234
235     assert(!Obj.isRelocationScattered(RelInfo) && "");
236
237     // ARM64 has an ARM64_RELOC_ADDEND relocation type that carries an explicit
238     // addend for the following relocation. If found: (1) store the associated
239     // addend, (2) consume the next relocation, and (3) use the stored addend to
240     // override the addend.
241     int64_t ExplicitAddend = 0;
242     if (Obj.getAnyRelocationType(RelInfo) == MachO::ARM64_RELOC_ADDEND) {
243       assert(!Obj.getPlainRelocationExternal(RelInfo));
244       assert(!Obj.getAnyRelocationPCRel(RelInfo));
245       assert(Obj.getAnyRelocationLength(RelInfo) == 2);
246       int64_t RawAddend = Obj.getPlainRelocationSymbolNum(RelInfo);
247       // Sign-extend the 24-bit to 64-bit.
248       ExplicitAddend = SignExtend64(RawAddend, 24);
249       ++RelI;
250       RelInfo = Obj.getRelocation(RelI->getRawDataRefImpl());
251     }
252
253     RelocationEntry RE(getBasicRelocationEntry(SectionID, ObjImg, RelI));
254     RelocationValueRef Value(
255         getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
256
257     assert((ExplicitAddend == 0 || RE.Addend == 0) && "Relocation has "\
258       "ARM64_RELOC_ADDEND and embedded addend in the instruction.");
259     if (ExplicitAddend) {
260       RE.Addend = ExplicitAddend;
261       Value.Addend = ExplicitAddend;
262     }
263
264     bool IsExtern = Obj.getPlainRelocationExternal(RelInfo);
265     if (!IsExtern && RE.IsPCRel)
266       makeValueAddendPCRel(Value, ObjImg, RelI);
267
268     RE.Addend = Value.Addend;
269
270     if (RE.RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGE21 ||
271         RE.RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12)
272       processGOTRelocation(RE, Value, Stubs);
273     else {
274       if (Value.SymbolName)
275         addRelocationForSymbol(RE, Value.SymbolName);
276       else
277         addRelocationForSection(RE, Value.SectionID);
278     }
279
280     return ++RelI;
281   }
282
283   void resolveRelocation(const RelocationEntry &RE, uint64_t Value) {
284     DEBUG(dumpRelocationToResolve(RE, Value));
285
286     const SectionEntry &Section = Sections[RE.SectionID];
287     uint8_t *LocalAddress = Section.Address + RE.Offset;
288
289     switch (RE.RelType) {
290     default:
291       llvm_unreachable("Invalid relocation type!");
292     case MachO::ARM64_RELOC_UNSIGNED: {
293       assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_UNSIGNED not supported");
294       // Mask in the target value a byte at a time (we don't have an alignment
295       // guarantee for the target address, so this is safest).
296       if (RE.Size < 2)
297         llvm_unreachable("Invalid size for ARM64_RELOC_UNSIGNED");
298
299       writeBytesUnaligned(LocalAddress, Value + RE.Addend, 1 << RE.Size);
300       break;
301     }
302     case MachO::ARM64_RELOC_BRANCH26: {
303       assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_BRANCH26 not supported");
304       // Check if branch is in range.
305       uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
306       int64_t PCRelVal = Value - FinalAddress + RE.Addend;
307       encodeAddend(LocalAddress, RE.RelType, PCRelVal);
308       break;
309     }
310     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
311     case MachO::ARM64_RELOC_PAGE21: {
312       assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_PAGE21 not supported");
313       // Adjust for PC-relative relocation and offset.
314       uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
315       int64_t PCRelVal =
316         ((Value + RE.Addend) & (-4096)) - (FinalAddress & (-4096));
317       encodeAddend(LocalAddress, RE.RelType, PCRelVal);
318       break;
319     }
320     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
321     case MachO::ARM64_RELOC_PAGEOFF12: {
322       assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_PAGEOFF21 not supported");
323       // Add the offset from the symbol.
324       Value += RE.Addend;
325       // Mask out the page address and only use the lower 12 bits.
326       Value &= 0xFFF;
327       encodeAddend(LocalAddress, RE.RelType, Value);
328       break;
329     }
330     case MachO::ARM64_RELOC_SUBTRACTOR:
331     case MachO::ARM64_RELOC_POINTER_TO_GOT:
332     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
333     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
334       llvm_unreachable("Relocation type not yet implemented!");
335     case MachO::ARM64_RELOC_ADDEND:
336       llvm_unreachable("ARM64_RELOC_ADDEND should have been handeled by "
337                        "processRelocationRef!");
338     }
339   }
340
341   void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
342                        const SectionRef &Section) {}
343
344 private:
345   void processGOTRelocation(const RelocationEntry &RE,
346                             RelocationValueRef &Value, StubMap &Stubs) {
347     assert(RE.Size == 2);
348     SectionEntry &Section = Sections[RE.SectionID];
349     StubMap::const_iterator i = Stubs.find(Value);
350     uint8_t *Addr;
351     if (i != Stubs.end())
352       Addr = Section.Address + i->second;
353     else {
354       // FIXME: There must be a better way to do this then to check and fix the
355       // alignment every time!!!
356       uintptr_t BaseAddress = uintptr_t(Section.Address);
357       uintptr_t StubAlignment = getStubAlignment();
358       uintptr_t StubAddress =
359           (BaseAddress + Section.StubOffset + StubAlignment - 1) &
360           -StubAlignment;
361       unsigned StubOffset = StubAddress - BaseAddress;
362       Stubs[Value] = StubOffset;
363       assert(((StubAddress % getStubAlignment()) == 0) &&
364              "GOT entry not aligned");
365       RelocationEntry GOTRE(RE.SectionID, StubOffset,
366                             MachO::ARM64_RELOC_UNSIGNED, Value.Addend,
367                             /*IsPCRel=*/false, /*Size=*/3);
368       if (Value.SymbolName)
369         addRelocationForSymbol(GOTRE, Value.SymbolName);
370       else
371         addRelocationForSection(GOTRE, Value.SectionID);
372       Section.StubOffset = StubOffset + getMaxStubSize();
373       Addr = (uint8_t *)StubAddress;
374     }
375     RelocationEntry TargetRE(RE.SectionID, RE.Offset, RE.RelType, /*Addend=*/0,
376                              RE.IsPCRel, RE.Size);
377     resolveRelocation(TargetRE, (uint64_t)Addr);
378   }
379 };
380 }
381
382 #undef DEBUG_TYPE
383
384 #endif // LLVM_RUNTIMEDYLDMACHOAARCH64_H