1 //===-- PPCAsmBackend.cpp - PPC 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/PPCFixupKinds.h"
10 #include "MCTargetDesc/PPCMCTargetDesc.h"
11 #include "llvm/BinaryFormat/ELF.h"
12 #include "llvm/BinaryFormat/MachO.h"
13 #include "llvm/MC/MCAsmBackend.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCELFObjectWriter.h"
16 #include "llvm/MC/MCFixupKindInfo.h"
17 #include "llvm/MC/MCMachObjectWriter.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/MCSymbolELF.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/TargetRegistry.h"
25 using namespace llvm;
26 
27 static uint64_t adjustFixupValue(unsigned Kind, uint64_t Value) {
28   switch (Kind) {
29   default:
30     llvm_unreachable("Unknown fixup kind!");
31   case FK_Data_1:
32   case FK_Data_2:
33   case FK_Data_4:
34   case FK_Data_8:
35   case PPC::fixup_ppc_nofixup:
36     return Value;
37   case PPC::fixup_ppc_brcond14:
38   case PPC::fixup_ppc_brcond14abs:
39     return Value & 0xfffc;
40   case PPC::fixup_ppc_br24:
41   case PPC::fixup_ppc_br24abs:
42     return Value & 0x3fffffc;
43   case PPC::fixup_ppc_half16:
44     return Value & 0xffff;
45   case PPC::fixup_ppc_half16ds:
46     return Value & 0xfffc;
47   }
48 }
49 
50 static unsigned getFixupKindNumBytes(unsigned Kind) {
51   switch (Kind) {
52   default:
53     llvm_unreachable("Unknown fixup kind!");
54   case FK_Data_1:
55     return 1;
56   case FK_Data_2:
57   case PPC::fixup_ppc_half16:
58   case PPC::fixup_ppc_half16ds:
59     return 2;
60   case FK_Data_4:
61   case PPC::fixup_ppc_brcond14:
62   case PPC::fixup_ppc_brcond14abs:
63   case PPC::fixup_ppc_br24:
64   case PPC::fixup_ppc_br24abs:
65     return 4;
66   case FK_Data_8:
67     return 8;
68   case PPC::fixup_ppc_nofixup:
69     return 0;
70   }
71 }
72 
73 namespace {
74 
75 class PPCAsmBackend : public MCAsmBackend {
76 protected:
77   Triple TT;
78 public:
79   PPCAsmBackend(const Target &T, const Triple &TT)
80       : MCAsmBackend(TT.isLittleEndian() ? support::little : support::big),
81         TT(TT) {}
82 
83   unsigned getNumFixupKinds() const override {
84     return PPC::NumTargetFixupKinds;
85   }
86 
87   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
88     const static MCFixupKindInfo InfosBE[PPC::NumTargetFixupKinds] = {
89       // name                    offset  bits  flags
90       { "fixup_ppc_br24",        6,      24,   MCFixupKindInfo::FKF_IsPCRel },
91       { "fixup_ppc_brcond14",    16,     14,   MCFixupKindInfo::FKF_IsPCRel },
92       { "fixup_ppc_br24abs",     6,      24,   0 },
93       { "fixup_ppc_brcond14abs", 16,     14,   0 },
94       { "fixup_ppc_half16",       0,     16,   0 },
95       { "fixup_ppc_half16ds",     0,     14,   0 },
96       { "fixup_ppc_nofixup",      0,      0,   0 }
97     };
98     const static MCFixupKindInfo InfosLE[PPC::NumTargetFixupKinds] = {
99       // name                    offset  bits  flags
100       { "fixup_ppc_br24",        2,      24,   MCFixupKindInfo::FKF_IsPCRel },
101       { "fixup_ppc_brcond14",    2,      14,   MCFixupKindInfo::FKF_IsPCRel },
102       { "fixup_ppc_br24abs",     2,      24,   0 },
103       { "fixup_ppc_brcond14abs", 2,      14,   0 },
104       { "fixup_ppc_half16",      0,      16,   0 },
105       { "fixup_ppc_half16ds",    2,      14,   0 },
106       { "fixup_ppc_nofixup",     0,       0,   0 }
107     };
108 
109     // Fixup kinds from .reloc directive are like R_PPC_NONE/R_PPC64_NONE. They
110     // do not require any extra processing.
111     if (Kind >= FirstLiteralRelocationKind)
112       return MCAsmBackend::getFixupKindInfo(FK_NONE);
113 
114     if (Kind < FirstTargetFixupKind)
115       return MCAsmBackend::getFixupKindInfo(Kind);
116 
117     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
118            "Invalid kind!");
119     return (Endian == support::little
120                 ? InfosLE
121                 : InfosBE)[Kind - FirstTargetFixupKind];
122   }
123 
124   void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
125                   const MCValue &Target, MutableArrayRef<char> Data,
126                   uint64_t Value, bool IsResolved,
127                   const MCSubtargetInfo *STI) const override {
128     MCFixupKind Kind = Fixup.getKind();
129     if (Kind >= FirstLiteralRelocationKind)
130       return;
131     Value = adjustFixupValue(Kind, Value);
132     if (!Value) return;           // Doesn't change encoding.
133 
134     unsigned Offset = Fixup.getOffset();
135     unsigned NumBytes = getFixupKindNumBytes(Kind);
136 
137     // For each byte of the fragment that the fixup touches, mask in the bits
138     // from the fixup value. The Value has been "split up" into the appropriate
139     // bitfields above.
140     for (unsigned i = 0; i != NumBytes; ++i) {
141       unsigned Idx = Endian == support::little ? i : (NumBytes - 1 - i);
142       Data[Offset + i] |= uint8_t((Value >> (Idx * 8)) & 0xff);
143     }
144   }
145 
146   bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
147                              const MCValue &Target) override {
148     MCFixupKind Kind = Fixup.getKind();
149     switch ((unsigned)Kind) {
150     default:
151       return Kind >= FirstLiteralRelocationKind;
152     case PPC::fixup_ppc_br24:
153     case PPC::fixup_ppc_br24abs:
154       // If the target symbol has a local entry point we must not attempt
155       // to resolve the fixup directly.  Emit a relocation and leave
156       // resolution of the final target address to the linker.
157       if (const MCSymbolRefExpr *A = Target.getSymA()) {
158         if (const auto *S = dyn_cast<MCSymbolELF>(&A->getSymbol())) {
159           // The "other" values are stored in the last 6 bits of the second
160           // byte. The traditional defines for STO values assume the full byte
161           // and thus the shift to pack it.
162           unsigned Other = S->getOther() << 2;
163           if ((Other & ELF::STO_PPC64_LOCAL_MASK) != 0)
164             return true;
165         }
166       }
167       return false;
168     }
169   }
170 
171   bool mayNeedRelaxation(const MCInst &Inst,
172                          const MCSubtargetInfo &STI) const override {
173     // FIXME.
174     return false;
175   }
176 
177   bool fixupNeedsRelaxation(const MCFixup &Fixup,
178                             uint64_t Value,
179                             const MCRelaxableFragment *DF,
180                             const MCAsmLayout &Layout) const override {
181     // FIXME.
182     llvm_unreachable("relaxInstruction() unimplemented");
183   }
184 
185   void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
186                         MCInst &Res) const override {
187     // FIXME.
188     llvm_unreachable("relaxInstruction() unimplemented");
189   }
190 
191   bool writeNopData(raw_ostream &OS, uint64_t Count) const override {
192     uint64_t NumNops = Count / 4;
193     for (uint64_t i = 0; i != NumNops; ++i)
194       support::endian::write<uint32_t>(OS, 0x60000000, Endian);
195 
196     OS.write_zeros(Count % 4);
197 
198     return true;
199   }
200 };
201 } // end anonymous namespace
202 
203 
204 // FIXME: This should be in a separate file.
205 namespace {
206 
207 class ELFPPCAsmBackend : public PPCAsmBackend {
208 public:
209   ELFPPCAsmBackend(const Target &T, const Triple &TT) : PPCAsmBackend(T, TT) {}
210 
211   std::unique_ptr<MCObjectTargetWriter>
212   createObjectTargetWriter() const override {
213     uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
214     bool Is64 = TT.isPPC64();
215     return createPPCELFObjectWriter(Is64, OSABI);
216   }
217 
218   Optional<MCFixupKind> getFixupKind(StringRef Name) const override;
219 };
220 
221 class XCOFFPPCAsmBackend : public PPCAsmBackend {
222 public:
223   XCOFFPPCAsmBackend(const Target &T, const Triple &TT)
224       : PPCAsmBackend(T, TT) {}
225 
226   std::unique_ptr<MCObjectTargetWriter>
227   createObjectTargetWriter() const override {
228     return createPPCXCOFFObjectWriter(TT.isArch64Bit());
229   }
230 };
231 
232 } // end anonymous namespace
233 
234 Optional<MCFixupKind> ELFPPCAsmBackend::getFixupKind(StringRef Name) const {
235   if (TT.isOSBinFormatELF()) {
236     unsigned Type;
237     if (TT.isPPC64()) {
238       Type = llvm::StringSwitch<unsigned>(Name)
239 #define ELF_RELOC(X, Y) .Case(#X, Y)
240 #include "llvm/BinaryFormat/ELFRelocs/PowerPC64.def"
241 #undef ELF_RELOC
242                  .Default(-1u);
243     } else {
244       Type = llvm::StringSwitch<unsigned>(Name)
245 #define ELF_RELOC(X, Y) .Case(#X, Y)
246 #include "llvm/BinaryFormat/ELFRelocs/PowerPC.def"
247 #undef ELF_RELOC
248                  .Default(-1u);
249     }
250     if (Type != -1u)
251       return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
252   }
253   return None;
254 }
255 
256 MCAsmBackend *llvm::createPPCAsmBackend(const Target &T,
257                                         const MCSubtargetInfo &STI,
258                                         const MCRegisterInfo &MRI,
259                                         const MCTargetOptions &Options) {
260   const Triple &TT = STI.getTargetTriple();
261   if (TT.isOSBinFormatXCOFF())
262     return new XCOFFPPCAsmBackend(T, TT);
263 
264   return new ELFPPCAsmBackend(T, TT);
265 }
266