1//===- MIPS.cpp -----------------------------------------------------------===//
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 "InputFiles.h"
10#include "OutputSections.h"
11#include "Symbols.h"
12#include "SyntheticSections.h"
13#include "Target.h"
14#include "Thunks.h"
15#include "lld/Common/ErrorHandler.h"
16#include "llvm/Object/ELF.h"
17
18using namespace llvm;
19using namespace llvm::object;
20using namespace llvm::ELF;
21
22namespace lld {
23namespace elf {
24namespace {
25template <class ELFT> class MIPS final : public TargetInfo {
26public:
27  MIPS();
28  uint32_t calcEFlags() const override;
29  RelExpr getRelExpr(RelType type, const Symbol &s,
30                     const uint8_t *loc) const override;
31  int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
32  RelType getDynRel(RelType type) const override;
33  void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
34  void writePltHeader(uint8_t *buf) const override;
35  void writePlt(uint8_t *buf, const Symbol &sym,
36                uint64_t pltEntryAddr) const override;
37  bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
38                  uint64_t branchAddr, const Symbol &s,
39                  int64_t a) const override;
40  void relocateOne(uint8_t *loc, RelType type, uint64_t val) const override;
41  bool usesOnlyLowPageBits(RelType type) const override;
42};
43} // namespace
44
45template <class ELFT> MIPS<ELFT>::MIPS() {
46  gotPltHeaderEntriesNum = 2;
47  defaultMaxPageSize = 65536;
48  gotBaseSymInGotPlt = false;
49  pltEntrySize = 16;
50  pltHeaderSize = 32;
51  copyRel = R_MIPS_COPY;
52  noneRel = R_MIPS_NONE;
53  pltRel = R_MIPS_JUMP_SLOT;
54  needsThunks = true;
55
56  // Set `sigrie 1` as a trap instruction.
57  write32(trapInstr.data(), 0x04170001);
58
59  if (ELFT::Is64Bits) {
60    relativeRel = (R_MIPS_64 << 8) | R_MIPS_REL32;
61    symbolicRel = R_MIPS_64;
62    tlsGotRel = R_MIPS_TLS_TPREL64;
63    tlsModuleIndexRel = R_MIPS_TLS_DTPMOD64;
64    tlsOffsetRel = R_MIPS_TLS_DTPREL64;
65  } else {
66    relativeRel = R_MIPS_REL32;
67    symbolicRel = R_MIPS_32;
68    tlsGotRel = R_MIPS_TLS_TPREL32;
69    tlsModuleIndexRel = R_MIPS_TLS_DTPMOD32;
70    tlsOffsetRel = R_MIPS_TLS_DTPREL32;
71  }
72}
73
74template <class ELFT> uint32_t MIPS<ELFT>::calcEFlags() const {
75  return calcMipsEFlags<ELFT>();
76}
77
78template <class ELFT>
79RelExpr MIPS<ELFT>::getRelExpr(RelType type, const Symbol &s,
80                               const uint8_t *loc) const {
81  // See comment in the calculateMipsRelChain.
82  if (ELFT::Is64Bits || config->mipsN32Abi)
83    type &= 0xff;
84
85  switch (type) {
86  case R_MIPS_JALR:
87    // Older versions of clang would erroneously emit this relocation not only
88    // against functions (loaded from the GOT) but also against data symbols
89    // (e.g. a table of function pointers). When we encounter this, ignore the
90    // relocation and emit a warning instead.
91    if (!s.isFunc() && s.type != STT_NOTYPE) {
92      warn(getErrorLocation(loc) +
93           "found R_MIPS_JALR relocation against non-function symbol " +
94           toString(s) + ". This is invalid and most likely a compiler bug.");
95      return R_NONE;
96    }
97
98    // If the target symbol is not preemptible and is not microMIPS,
99    // it might be possible to replace jalr/jr instruction by bal/b.
100    // It depends on the target symbol's offset.
101    if (!s.isPreemptible && !(s.getVA() & 0x1))
102      return R_PC;
103    return R_NONE;
104  case R_MICROMIPS_JALR:
105    return R_NONE;
106  case R_MIPS_GPREL16:
107  case R_MIPS_GPREL32:
108  case R_MICROMIPS_GPREL16:
109  case R_MICROMIPS_GPREL7_S2:
110    return R_MIPS_GOTREL;
111  case R_MIPS_26:
112  case R_MICROMIPS_26_S1:
113    return R_PLT;
114  case R_MICROMIPS_PC26_S1:
115    return R_PLT_PC;
116  case R_MIPS_HI16:
117  case R_MIPS_LO16:
118  case R_MIPS_HIGHER:
119  case R_MIPS_HIGHEST:
120  case R_MICROMIPS_HI16:
121  case R_MICROMIPS_LO16:
122    // R_MIPS_HI16/R_MIPS_LO16 relocations against _gp_disp calculate
123    // offset between start of function and 'gp' value which by default
124    // equal to the start of .got section. In that case we consider these
125    // relocations as relative.
126    if (&s == ElfSym::mipsGpDisp)
127      return R_MIPS_GOT_GP_PC;
128    if (&s == ElfSym::mipsLocalGp)
129      return R_MIPS_GOT_GP;
130    LLVM_FALLTHROUGH;
131  case R_MIPS_32:
132  case R_MIPS_64:
133  case R_MIPS_GOT_OFST:
134  case R_MIPS_SUB:
135  case R_MIPS_TLS_DTPREL_HI16:
136  case R_MIPS_TLS_DTPREL_LO16:
137  case R_MIPS_TLS_DTPREL32:
138  case R_MIPS_TLS_DTPREL64:
139  case R_MICROMIPS_TLS_DTPREL_HI16:
140  case R_MICROMIPS_TLS_DTPREL_LO16:
141    return R_ABS;
142  case R_MIPS_TLS_TPREL_HI16:
143  case R_MIPS_TLS_TPREL_LO16:
144  case R_MIPS_TLS_TPREL32:
145  case R_MIPS_TLS_TPREL64:
146  case R_MICROMIPS_TLS_TPREL_HI16:
147  case R_MICROMIPS_TLS_TPREL_LO16:
148    return R_TLS;
149  case R_MIPS_PC32:
150  case R_MIPS_PC16:
151  case R_MIPS_PC19_S2:
152  case R_MIPS_PC21_S2:
153  case R_MIPS_PC26_S2:
154  case R_MIPS_PCHI16:
155  case R_MIPS_PCLO16:
156  case R_MICROMIPS_PC7_S1:
157  case R_MICROMIPS_PC10_S1:
158  case R_MICROMIPS_PC16_S1:
159  case R_MICROMIPS_PC18_S3:
160  case R_MICROMIPS_PC19_S2:
161  case R_MICROMIPS_PC23_S2:
162  case R_MICROMIPS_PC21_S1:
163    return R_PC;
164  case R_MIPS_GOT16:
165  case R_MICROMIPS_GOT16:
166    if (s.isLocal())
167      return R_MIPS_GOT_LOCAL_PAGE;
168    LLVM_FALLTHROUGH;
169  case R_MIPS_CALL16:
170  case R_MIPS_GOT_DISP:
171  case R_MIPS_TLS_GOTTPREL:
172  case R_MICROMIPS_CALL16:
173  case R_MICROMIPS_TLS_GOTTPREL:
174    return R_MIPS_GOT_OFF;
175  case R_MIPS_CALL_HI16:
176  case R_MIPS_CALL_LO16:
177  case R_MIPS_GOT_HI16:
178  case R_MIPS_GOT_LO16:
179  case R_MICROMIPS_CALL_HI16:
180  case R_MICROMIPS_CALL_LO16:
181  case R_MICROMIPS_GOT_HI16:
182  case R_MICROMIPS_GOT_LO16:
183    return R_MIPS_GOT_OFF32;
184  case R_MIPS_GOT_PAGE:
185    return R_MIPS_GOT_LOCAL_PAGE;
186  case R_MIPS_TLS_GD:
187  case R_MICROMIPS_TLS_GD:
188    return R_MIPS_TLSGD;
189  case R_MIPS_TLS_LDM:
190  case R_MICROMIPS_TLS_LDM:
191    return R_MIPS_TLSLD;
192  case R_MIPS_NONE:
193    return R_NONE;
194  default:
195    error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
196          ") against symbol " + toString(s));
197    return R_NONE;
198  }
199}
200
201template <class ELFT> RelType MIPS<ELFT>::getDynRel(RelType type) const {
202  if (type == symbolicRel)
203    return type;
204  return R_MIPS_NONE;
205}
206
207template <class ELFT>
208void MIPS<ELFT>::writeGotPlt(uint8_t *buf, const Symbol &) const {
209  uint64_t va = in.plt->getVA();
210  if (isMicroMips())
211    va |= 1;
212  write32(buf, va);
213}
214
215template <endianness E> static uint32_t readShuffle(const uint8_t *loc) {
216  // The major opcode of a microMIPS instruction needs to appear
217  // in the first 16-bit word (lowest address) for efficient hardware
218  // decode so that it knows if the instruction is 16-bit or 32-bit
219  // as early as possible. To do so, little-endian binaries keep 16-bit
220  // words in a big-endian order. That is why we have to swap these
221  // words to get a correct value.
222  uint32_t v = read32(loc);
223  if (E == support::little)
224    return (v << 16) | (v >> 16);
225  return v;
226}
227
228static void writeValue(uint8_t *loc, uint64_t v, uint8_t bitsSize,
229                       uint8_t shift) {
230  uint32_t instr = read32(loc);
231  uint32_t mask = 0xffffffff >> (32 - bitsSize);
232  uint32_t data = (instr & ~mask) | ((v >> shift) & mask);
233  write32(loc, data);
234}
235
236template <endianness E>
237static void writeShuffleValue(uint8_t *loc, uint64_t v, uint8_t bitsSize,
238                              uint8_t shift) {
239  // See comments in readShuffle for purpose of this code.
240  uint16_t *words = (uint16_t *)loc;
241  if (E == support::little)
242    std::swap(words[0], words[1]);
243
244  writeValue(loc, v, bitsSize, shift);
245
246  if (E == support::little)
247    std::swap(words[0], words[1]);
248}
249
250template <endianness E>
251static void writeMicroRelocation16(uint8_t *loc, uint64_t v, uint8_t bitsSize,
252                                   uint8_t shift) {
253  uint16_t instr = read16(loc);
254  uint16_t mask = 0xffff >> (16 - bitsSize);
255  uint16_t data = (instr & ~mask) | ((v >> shift) & mask);
256  write16(loc, data);
257}
258
259template <class ELFT> void MIPS<ELFT>::writePltHeader(uint8_t *buf) const {
260  if (isMicroMips()) {
261    uint64_t gotPlt = in.gotPlt->getVA();
262    uint64_t plt = in.plt->getVA();
263    // Overwrite trap instructions written by Writer::writeTrapInstr.
264    memset(buf, 0, pltHeaderSize);
265
266    write16(buf, isMipsR6() ? 0x7860 : 0x7980);  // addiupc v1, (GOTPLT) - .
267    write16(buf + 4, 0xff23);    // lw      $25, 0($3)
268    write16(buf + 8, 0x0535);    // subu16  $2,  $2, $3
269    write16(buf + 10, 0x2525);   // srl16   $2,  $2, 2
270    write16(buf + 12, 0x3302);   // addiu   $24, $2, -2
271    write16(buf + 14, 0xfffe);
272    write16(buf + 16, 0x0dff);   // move    $15, $31
273    if (isMipsR6()) {
274      write16(buf + 18, 0x0f83); // move    $28, $3
275      write16(buf + 20, 0x472b); // jalrc   $25
276      write16(buf + 22, 0x0c00); // nop
277      relocateOne(buf, R_MICROMIPS_PC19_S2, gotPlt - plt);
278    } else {
279      write16(buf + 18, 0x45f9); // jalrc   $25
280      write16(buf + 20, 0x0f83); // move    $28, $3
281      write16(buf + 22, 0x0c00); // nop
282      relocateOne(buf, R_MICROMIPS_PC23_S2, gotPlt - plt);
283    }
284    return;
285  }
286
287  if (config->mipsN32Abi) {
288    write32(buf, 0x3c0e0000);      // lui   $14, %hi(&GOTPLT[0])
289    write32(buf + 4, 0x8dd90000);  // lw    $25, %lo(&GOTPLT[0])($14)
290    write32(buf + 8, 0x25ce0000);  // addiu $14, $14, %lo(&GOTPLT[0])
291    write32(buf + 12, 0x030ec023); // subu  $24, $24, $14
292    write32(buf + 16, 0x03e07825); // move  $15, $31
293    write32(buf + 20, 0x0018c082); // srl   $24, $24, 2
294  } else if (ELFT::Is64Bits) {
295    write32(buf, 0x3c0e0000);      // lui   $14, %hi(&GOTPLT[0])
296    write32(buf + 4, 0xddd90000);  // ld    $25, %lo(&GOTPLT[0])($14)
297    write32(buf + 8, 0x25ce0000);  // addiu $14, $14, %lo(&GOTPLT[0])
298    write32(buf + 12, 0x030ec023); // subu  $24, $24, $14
299    write32(buf + 16, 0x03e07825); // move  $15, $31
300    write32(buf + 20, 0x0018c0c2); // srl   $24, $24, 3
301  } else {
302    write32(buf, 0x3c1c0000);      // lui   $28, %hi(&GOTPLT[0])
303    write32(buf + 4, 0x8f990000);  // lw    $25, %lo(&GOTPLT[0])($28)
304    write32(buf + 8, 0x279c0000);  // addiu $28, $28, %lo(&GOTPLT[0])
305    write32(buf + 12, 0x031cc023); // subu  $24, $24, $28
306    write32(buf + 16, 0x03e07825); // move  $15, $31
307    write32(buf + 20, 0x0018c082); // srl   $24, $24, 2
308  }
309
310  uint32_t jalrInst = config->zHazardplt ? 0x0320fc09 : 0x0320f809;
311  write32(buf + 24, jalrInst); // jalr.hb $25 or jalr $25
312  write32(buf + 28, 0x2718fffe); // subu  $24, $24, 2
313
314  uint64_t gotPlt = in.gotPlt->getVA();
315  writeValue(buf, gotPlt + 0x8000, 16, 16);
316  writeValue(buf + 4, gotPlt, 16, 0);
317  writeValue(buf + 8, gotPlt, 16, 0);
318}
319
320template <class ELFT>
321void MIPS<ELFT>::writePlt(uint8_t *buf, const Symbol &sym,
322                          uint64_t pltEntryAddr) const {
323  uint64_t gotPltEntryAddr = sym.getGotPltVA();
324  if (isMicroMips()) {
325    // Overwrite trap instructions written by Writer::writeTrapInstr.
326    memset(buf, 0, pltEntrySize);
327
328    if (isMipsR6()) {
329      write16(buf, 0x7840);      // addiupc $2, (GOTPLT) - .
330      write16(buf + 4, 0xff22);  // lw $25, 0($2)
331      write16(buf + 8, 0x0f02);  // move $24, $2
332      write16(buf + 10, 0x4723); // jrc $25 / jr16 $25
333      relocateOne(buf, R_MICROMIPS_PC19_S2, gotPltEntryAddr - pltEntryAddr);
334    } else {
335      write16(buf, 0x7900);      // addiupc $2, (GOTPLT) - .
336      write16(buf + 4, 0xff22);  // lw $25, 0($2)
337      write16(buf + 8, 0x4599);  // jrc $25 / jr16 $25
338      write16(buf + 10, 0x0f02); // move $24, $2
339      relocateOne(buf, R_MICROMIPS_PC23_S2, gotPltEntryAddr - pltEntryAddr);
340    }
341    return;
342  }
343
344  uint32_t loadInst = ELFT::Is64Bits ? 0xddf90000 : 0x8df90000;
345  uint32_t jrInst = isMipsR6() ? (config->zHazardplt ? 0x03200409 : 0x03200009)
346                               : (config->zHazardplt ? 0x03200408 : 0x03200008);
347  uint32_t addInst = ELFT::Is64Bits ? 0x65f80000 : 0x25f80000;
348
349  write32(buf, 0x3c0f0000);     // lui   $15, %hi(.got.plt entry)
350  write32(buf + 4, loadInst);   // l[wd] $25, %lo(.got.plt entry)($15)
351  write32(buf + 8, jrInst);     // jr  $25 / jr.hb $25
352  write32(buf + 12, addInst);   // [d]addiu $24, $15, %lo(.got.plt entry)
353  writeValue(buf, gotPltEntryAddr + 0x8000, 16, 16);
354  writeValue(buf + 4, gotPltEntryAddr, 16, 0);
355  writeValue(buf + 12, gotPltEntryAddr, 16, 0);
356}
357
358template <class ELFT>
359bool MIPS<ELFT>::needsThunk(RelExpr expr, RelType type, const InputFile *file,
360                            uint64_t branchAddr, const Symbol &s,
361                            int64_t /*a*/) const {
362  // Any MIPS PIC code function is invoked with its address in register $t9.
363  // So if we have a branch instruction from non-PIC code to the PIC one
364  // we cannot make the jump directly and need to create a small stubs
365  // to save the target function address.
366  // See page 3-38 ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
367  if (type != R_MIPS_26 && type != R_MIPS_PC26_S2 &&
368      type != R_MICROMIPS_26_S1 && type != R_MICROMIPS_PC26_S1)
369    return false;
370  auto *f = dyn_cast_or_null<ObjFile<ELFT>>(file);
371  if (!f)
372    return false;
373  // If current file has PIC code, LA25 stub is not required.
374  if (f->getObj().getHeader()->e_flags & EF_MIPS_PIC)
375    return false;
376  auto *d = dyn_cast<Defined>(&s);
377  // LA25 is required if target file has PIC code
378  // or target symbol is a PIC symbol.
379  return d && isMipsPIC<ELFT>(d);
380}
381
382template <class ELFT>
383int64_t MIPS<ELFT>::getImplicitAddend(const uint8_t *buf, RelType type) const {
384  const endianness e = ELFT::TargetEndianness;
385  switch (type) {
386  case R_MIPS_32:
387  case R_MIPS_GPREL32:
388  case R_MIPS_TLS_DTPREL32:
389  case R_MIPS_TLS_TPREL32:
390    return SignExtend64<32>(read32(buf));
391  case R_MIPS_26:
392    // FIXME (simon): If the relocation target symbol is not a PLT entry
393    // we should use another expression for calculation:
394    // ((A << 2) | (P & 0xf0000000)) >> 2
395    return SignExtend64<28>(read32(buf) << 2);
396  case R_MIPS_GOT16:
397  case R_MIPS_HI16:
398  case R_MIPS_PCHI16:
399    return SignExtend64<16>(read32(buf)) << 16;
400  case R_MIPS_GPREL16:
401  case R_MIPS_LO16:
402  case R_MIPS_PCLO16:
403  case R_MIPS_TLS_DTPREL_HI16:
404  case R_MIPS_TLS_DTPREL_LO16:
405  case R_MIPS_TLS_TPREL_HI16:
406  case R_MIPS_TLS_TPREL_LO16:
407    return SignExtend64<16>(read32(buf));
408  case R_MICROMIPS_GOT16:
409  case R_MICROMIPS_HI16:
410    return SignExtend64<16>(readShuffle<e>(buf)) << 16;
411  case R_MICROMIPS_GPREL16:
412  case R_MICROMIPS_LO16:
413  case R_MICROMIPS_TLS_DTPREL_HI16:
414  case R_MICROMIPS_TLS_DTPREL_LO16:
415  case R_MICROMIPS_TLS_TPREL_HI16:
416  case R_MICROMIPS_TLS_TPREL_LO16:
417    return SignExtend64<16>(readShuffle<e>(buf));
418  case R_MICROMIPS_GPREL7_S2:
419    return SignExtend64<9>(readShuffle<e>(buf) << 2);
420  case R_MIPS_PC16:
421    return SignExtend64<18>(read32(buf) << 2);
422  case R_MIPS_PC19_S2:
423    return SignExtend64<21>(read32(buf) << 2);
424  case R_MIPS_PC21_S2:
425    return SignExtend64<23>(read32(buf) << 2);
426  case R_MIPS_PC26_S2:
427    return SignExtend64<28>(read32(buf) << 2);
428  case R_MIPS_PC32:
429    return SignExtend64<32>(read32(buf));
430  case R_MICROMIPS_26_S1:
431    return SignExtend64<27>(readShuffle<e>(buf) << 1);
432  case R_MICROMIPS_PC7_S1:
433    return SignExtend64<8>(read16(buf) << 1);
434  case R_MICROMIPS_PC10_S1:
435    return SignExtend64<11>(read16(buf) << 1);
436  case R_MICROMIPS_PC16_S1:
437    return SignExtend64<17>(readShuffle<e>(buf) << 1);
438  case R_MICROMIPS_PC18_S3:
439    return SignExtend64<21>(readShuffle<e>(buf) << 3);
440  case R_MICROMIPS_PC19_S2:
441    return SignExtend64<21>(readShuffle<e>(buf) << 2);
442  case R_MICROMIPS_PC21_S1:
443    return SignExtend64<22>(readShuffle<e>(buf) << 1);
444  case R_MICROMIPS_PC23_S2:
445    return SignExtend64<25>(readShuffle<e>(buf) << 2);
446  case R_MICROMIPS_PC26_S1:
447    return SignExtend64<27>(readShuffle<e>(buf) << 1);
448  default:
449    return 0;
450  }
451}
452
453static std::pair<uint32_t, uint64_t>
454calculateMipsRelChain(uint8_t *loc, RelType type, uint64_t val) {
455  // MIPS N64 ABI packs multiple relocations into the single relocation
456  // record. In general, all up to three relocations can have arbitrary
457  // types. In fact, Clang and GCC uses only a few combinations. For now,
458  // we support two of them. That is allow to pass at least all LLVM
459  // test suite cases.
460  // <any relocation> / R_MIPS_SUB / R_MIPS_HI16 | R_MIPS_LO16
461  // <any relocation> / R_MIPS_64 / R_MIPS_NONE
462  // The first relocation is a 'real' relocation which is calculated
463  // using the corresponding symbol's value. The second and the third
464  // relocations used to modify result of the first one: extend it to
465  // 64-bit, extract high or low part etc. For details, see part 2.9 Relocation
466  // at the https://dmz-portal.mips.com/mw/images/8/82/007-4658-001.pdf
467  RelType type2 = (type >> 8) & 0xff;
468  RelType type3 = (type >> 16) & 0xff;
469  if (type2 == R_MIPS_NONE && type3 == R_MIPS_NONE)
470    return std::make_pair(type, val);
471  if (type2 == R_MIPS_64 && type3 == R_MIPS_NONE)
472    return std::make_pair(type2, val);
473  if (type2 == R_MIPS_SUB && (type3 == R_MIPS_HI16 || type3 == R_MIPS_LO16))
474    return std::make_pair(type3, -val);
475  error(getErrorLocation(loc) + "unsupported relocations combination " +
476        Twine(type));
477  return std::make_pair(type & 0xff, val);
478}
479
480static bool isBranchReloc(RelType type) {
481  return type == R_MIPS_26 || type == R_MIPS_PC26_S2 ||
482         type == R_MIPS_PC21_S2 || type == R_MIPS_PC16;
483}
484
485static bool isMicroBranchReloc(RelType type) {
486  return type == R_MICROMIPS_26_S1 || type == R_MICROMIPS_PC16_S1 ||
487         type == R_MICROMIPS_PC10_S1 || type == R_MICROMIPS_PC7_S1;
488}
489
490template <class ELFT>
491static uint64_t fixupCrossModeJump(uint8_t *loc, RelType type, uint64_t val) {
492  // Here we need to detect jump/branch from regular MIPS code
493  // to a microMIPS target and vice versa. In that cases jump
494  // instructions need to be replaced by their "cross-mode"
495  // equivalents.
496  const endianness e = ELFT::TargetEndianness;
497  bool isMicroTgt = val & 0x1;
498  bool isCrossJump = (isMicroTgt && isBranchReloc(type)) ||
499                     (!isMicroTgt && isMicroBranchReloc(type));
500  if (!isCrossJump)
501    return val;
502
503  switch (type) {
504  case R_MIPS_26: {
505    uint32_t inst = read32(loc) >> 26;
506    if (inst == 0x3 || inst == 0x1d) { // JAL or JALX
507      writeValue(loc, 0x1d << 26, 32, 0);
508      return val;
509    }
510    break;
511  }
512  case R_MICROMIPS_26_S1: {
513    uint32_t inst = readShuffle<e>(loc) >> 26;
514    if (inst == 0x3d || inst == 0x3c) { // JAL32 or JALX32
515      val >>= 1;
516      writeShuffleValue<e>(loc, 0x3c << 26, 32, 0);
517      return val;
518    }
519    break;
520  }
521  case R_MIPS_PC26_S2:
522  case R_MIPS_PC21_S2:
523  case R_MIPS_PC16:
524  case R_MICROMIPS_PC16_S1:
525  case R_MICROMIPS_PC10_S1:
526  case R_MICROMIPS_PC7_S1:
527    // FIXME (simon): Support valid branch relocations.
528    break;
529  default:
530    llvm_unreachable("unexpected jump/branch relocation");
531  }
532
533  error(getErrorLocation(loc) +
534        "unsupported jump/branch instruction between ISA modes referenced by " +
535        toString(type) + " relocation");
536  return val;
537}
538
539template <class ELFT>
540void MIPS<ELFT>::relocateOne(uint8_t *loc, RelType type, uint64_t val) const {
541  const endianness e = ELFT::TargetEndianness;
542
543  if (ELFT::Is64Bits || config->mipsN32Abi)
544    std::tie(type, val) = calculateMipsRelChain(loc, type, val);
545
546  // Detect cross-mode jump/branch and fix instruction.
547  val = fixupCrossModeJump<ELFT>(loc, type, val);
548
549  // Thread pointer and DRP offsets from the start of TLS data area.
550  // https://www.linux-mips.org/wiki/NPTL
551  if (type == R_MIPS_TLS_DTPREL_HI16 || type == R_MIPS_TLS_DTPREL_LO16 ||
552      type == R_MIPS_TLS_DTPREL32 || type == R_MIPS_TLS_DTPREL64 ||
553      type == R_MICROMIPS_TLS_DTPREL_HI16 ||
554      type == R_MICROMIPS_TLS_DTPREL_LO16) {
555    val -= 0x8000;
556  }
557
558  switch (type) {
559  case R_MIPS_32:
560  case R_MIPS_GPREL32:
561  case R_MIPS_TLS_DTPREL32:
562  case R_MIPS_TLS_TPREL32:
563    write32(loc, val);
564    break;
565  case R_MIPS_64:
566  case R_MIPS_TLS_DTPREL64:
567  case R_MIPS_TLS_TPREL64:
568    write64(loc, val);
569    break;
570  case R_MIPS_26:
571    writeValue(loc, val, 26, 2);
572    break;
573  case R_MIPS_GOT16:
574    // The R_MIPS_GOT16 relocation's value in "relocatable" linking mode
575    // is updated addend (not a GOT index). In that case write high 16 bits
576    // to store a correct addend value.
577    if (config->relocatable) {
578      writeValue(loc, val + 0x8000, 16, 16);
579    } else {
580      checkInt(loc, val, 16, type);
581      writeValue(loc, val, 16, 0);
582    }
583    break;
584  case R_MICROMIPS_GOT16:
585    if (config->relocatable) {
586      writeShuffleValue<e>(loc, val + 0x8000, 16, 16);
587    } else {
588      checkInt(loc, val, 16, type);
589      writeShuffleValue<e>(loc, val, 16, 0);
590    }
591    break;
592  case R_MIPS_CALL16:
593  case R_MIPS_GOT_DISP:
594  case R_MIPS_GOT_PAGE:
595  case R_MIPS_GPREL16:
596  case R_MIPS_TLS_GD:
597  case R_MIPS_TLS_GOTTPREL:
598  case R_MIPS_TLS_LDM:
599    checkInt(loc, val, 16, type);
600    LLVM_FALLTHROUGH;
601  case R_MIPS_CALL_LO16:
602  case R_MIPS_GOT_LO16:
603  case R_MIPS_GOT_OFST:
604  case R_MIPS_LO16:
605  case R_MIPS_PCLO16:
606  case R_MIPS_TLS_DTPREL_LO16:
607  case R_MIPS_TLS_TPREL_LO16:
608    writeValue(loc, val, 16, 0);
609    break;
610  case R_MICROMIPS_GPREL16:
611  case R_MICROMIPS_TLS_GD:
612  case R_MICROMIPS_TLS_LDM:
613    checkInt(loc, val, 16, type);
614    writeShuffleValue<e>(loc, val, 16, 0);
615    break;
616  case R_MICROMIPS_CALL16:
617  case R_MICROMIPS_CALL_LO16:
618  case R_MICROMIPS_LO16:
619  case R_MICROMIPS_TLS_DTPREL_LO16:
620  case R_MICROMIPS_TLS_GOTTPREL:
621  case R_MICROMIPS_TLS_TPREL_LO16:
622    writeShuffleValue<e>(loc, val, 16, 0);
623    break;
624  case R_MICROMIPS_GPREL7_S2:
625    checkInt(loc, val, 7, type);
626    writeShuffleValue<e>(loc, val, 7, 2);
627    break;
628  case R_MIPS_CALL_HI16:
629  case R_MIPS_GOT_HI16:
630  case R_MIPS_HI16:
631  case R_MIPS_PCHI16:
632  case R_MIPS_TLS_DTPREL_HI16:
633  case R_MIPS_TLS_TPREL_HI16:
634    writeValue(loc, val + 0x8000, 16, 16);
635    break;
636  case R_MICROMIPS_CALL_HI16:
637  case R_MICROMIPS_GOT_HI16:
638  case R_MICROMIPS_HI16:
639  case R_MICROMIPS_TLS_DTPREL_HI16:
640  case R_MICROMIPS_TLS_TPREL_HI16:
641    writeShuffleValue<e>(loc, val + 0x8000, 16, 16);
642    break;
643  case R_MIPS_HIGHER:
644    writeValue(loc, val + 0x80008000, 16, 32);
645    break;
646  case R_MIPS_HIGHEST:
647    writeValue(loc, val + 0x800080008000, 16, 48);
648    break;
649  case R_MIPS_JALR:
650    val -= 4;
651    // Replace jalr/jr instructions by bal/b if the target
652    // offset fits into the 18-bit range.
653    if (isInt<18>(val)) {
654      switch (read32(loc)) {
655      case 0x0320f809:  // jalr $25 => bal sym
656        write32(loc, 0x04110000 | ((val >> 2) & 0xffff));
657        break;
658      case 0x03200008:  // jr $25 => b sym
659        write32(loc, 0x10000000 | ((val >> 2) & 0xffff));
660        break;
661      }
662    }
663    break;
664  case R_MICROMIPS_JALR:
665    // Ignore this optimization relocation for now
666    break;
667  case R_MIPS_PC16:
668    checkAlignment(loc, val, 4, type);
669    checkInt(loc, val, 18, type);
670    writeValue(loc, val, 16, 2);
671    break;
672  case R_MIPS_PC19_S2:
673    checkAlignment(loc, val, 4, type);
674    checkInt(loc, val, 21, type);
675    writeValue(loc, val, 19, 2);
676    break;
677  case R_MIPS_PC21_S2:
678    checkAlignment(loc, val, 4, type);
679    checkInt(loc, val, 23, type);
680    writeValue(loc, val, 21, 2);
681    break;
682  case R_MIPS_PC26_S2:
683    checkAlignment(loc, val, 4, type);
684    checkInt(loc, val, 28, type);
685    writeValue(loc, val, 26, 2);
686    break;
687  case R_MIPS_PC32:
688    writeValue(loc, val, 32, 0);
689    break;
690  case R_MICROMIPS_26_S1:
691  case R_MICROMIPS_PC26_S1:
692    checkInt(loc, val, 27, type);
693    writeShuffleValue<e>(loc, val, 26, 1);
694    break;
695  case R_MICROMIPS_PC7_S1:
696    checkInt(loc, val, 8, type);
697    writeMicroRelocation16<e>(loc, val, 7, 1);
698    break;
699  case R_MICROMIPS_PC10_S1:
700    checkInt(loc, val, 11, type);
701    writeMicroRelocation16<e>(loc, val, 10, 1);
702    break;
703  case R_MICROMIPS_PC16_S1:
704    checkInt(loc, val, 17, type);
705    writeShuffleValue<e>(loc, val, 16, 1);
706    break;
707  case R_MICROMIPS_PC18_S3:
708    checkInt(loc, val, 21, type);
709    writeShuffleValue<e>(loc, val, 18, 3);
710    break;
711  case R_MICROMIPS_PC19_S2:
712    checkInt(loc, val, 21, type);
713    writeShuffleValue<e>(loc, val, 19, 2);
714    break;
715  case R_MICROMIPS_PC21_S1:
716    checkInt(loc, val, 22, type);
717    writeShuffleValue<e>(loc, val, 21, 1);
718    break;
719  case R_MICROMIPS_PC23_S2:
720    checkInt(loc, val, 25, type);
721    writeShuffleValue<e>(loc, val, 23, 2);
722    break;
723  default:
724    llvm_unreachable("unknown relocation");
725  }
726}
727
728template <class ELFT> bool MIPS<ELFT>::usesOnlyLowPageBits(RelType type) const {
729  return type == R_MIPS_LO16 || type == R_MIPS_GOT_OFST ||
730         type == R_MICROMIPS_LO16;
731}
732
733// Return true if the symbol is a PIC function.
734template <class ELFT> bool isMipsPIC(const Defined *sym) {
735  if (!sym->isFunc())
736    return false;
737
738  if (sym->stOther & STO_MIPS_PIC)
739    return true;
740
741  if (!sym->section)
742    return false;
743
744  ObjFile<ELFT> *file =
745      cast<InputSectionBase>(sym->section)->template getFile<ELFT>();
746  if (!file)
747    return false;
748
749  return file->getObj().getHeader()->e_flags & EF_MIPS_PIC;
750}
751
752template <class ELFT> TargetInfo *getMipsTargetInfo() {
753  static MIPS<ELFT> target;
754  return &target;
755}
756
757template TargetInfo *getMipsTargetInfo<ELF32LE>();
758template TargetInfo *getMipsTargetInfo<ELF32BE>();
759template TargetInfo *getMipsTargetInfo<ELF64LE>();
760template TargetInfo *getMipsTargetInfo<ELF64BE>();
761
762template bool isMipsPIC<ELF32LE>(const Defined *);
763template bool isMipsPIC<ELF32BE>(const Defined *);
764template bool isMipsPIC<ELF64LE>(const Defined *);
765template bool isMipsPIC<ELF64BE>(const Defined *);
766
767} // namespace elf
768} // namespace lld
769