1 //===-- PPCMCTargetDesc.cpp - PowerPC Target Descriptions -----------------===//
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 // This file provides PowerPC specific target descriptions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MCTargetDesc/PPCMCTargetDesc.h"
14 #include "MCTargetDesc/PPCInstPrinter.h"
15 #include "MCTargetDesc/PPCMCAsmInfo.h"
16 #include "PPCELFStreamer.h"
17 #include "PPCTargetStreamer.h"
18 #include "TargetInfo/PowerPCTargetInfo.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/MC/MCAssembler.h"
24 #include "llvm/MC/MCAsmBackend.h"
25 #include "llvm/MC/MCCodeEmitter.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDwarf.h"
28 #include "llvm/MC/MCELFStreamer.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCObjectWriter.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCSymbolELF.h"
37 #include "llvm/MC/MCSymbolXCOFF.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CodeGen.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/raw_ostream.h"
44 
45 using namespace llvm;
46 
47 #define GET_INSTRINFO_MC_DESC
48 #include "PPCGenInstrInfo.inc"
49 
50 #define GET_SUBTARGETINFO_MC_DESC
51 #include "PPCGenSubtargetInfo.inc"
52 
53 #define GET_REGINFO_MC_DESC
54 #include "PPCGenRegisterInfo.inc"
55 
56 PPCTargetStreamer::PPCTargetStreamer(MCStreamer &S) : MCTargetStreamer(S) {}
57 
58 // Pin the vtable to this file.
59 PPCTargetStreamer::~PPCTargetStreamer() = default;
60 
61 static MCInstrInfo *createPPCMCInstrInfo() {
62   MCInstrInfo *X = new MCInstrInfo();
63   InitPPCMCInstrInfo(X);
64   return X;
65 }
66 
67 static MCRegisterInfo *createPPCMCRegisterInfo(const Triple &TT) {
68   bool isPPC64 =
69       (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le);
70   unsigned Flavour = isPPC64 ? 0 : 1;
71   unsigned RA = isPPC64 ? PPC::LR8 : PPC::LR;
72 
73   MCRegisterInfo *X = new MCRegisterInfo();
74   InitPPCMCRegisterInfo(X, RA, Flavour, Flavour);
75   return X;
76 }
77 
78 static MCSubtargetInfo *createPPCMCSubtargetInfo(const Triple &TT,
79                                                  StringRef CPU, StringRef FS) {
80   return createPPCMCSubtargetInfoImpl(TT, CPU, FS);
81 }
82 
83 static MCAsmInfo *createPPCMCAsmInfo(const MCRegisterInfo &MRI,
84                                      const Triple &TheTriple,
85                                      const MCTargetOptions &Options) {
86   bool isPPC64 = (TheTriple.getArch() == Triple::ppc64 ||
87                   TheTriple.getArch() == Triple::ppc64le);
88 
89   MCAsmInfo *MAI;
90   if (TheTriple.isOSBinFormatXCOFF())
91     MAI = new PPCXCOFFMCAsmInfo(isPPC64, TheTriple);
92   else
93     MAI = new PPCELFMCAsmInfo(isPPC64, TheTriple);
94 
95   // Initial state of the frame pointer is R1.
96   unsigned Reg = isPPC64 ? PPC::X1 : PPC::R1;
97   MCCFIInstruction Inst =
98       MCCFIInstruction::cfiDefCfa(nullptr, MRI.getDwarfRegNum(Reg, true), 0);
99   MAI->addInitialFrameState(Inst);
100 
101   return MAI;
102 }
103 
104 static MCStreamer *createPPCMCStreamer(const Triple &T, MCContext &Context,
105                                        std::unique_ptr<MCAsmBackend> &&MAB,
106                                        std::unique_ptr<MCObjectWriter> &&OW,
107                                        std::unique_ptr<MCCodeEmitter> &&Emitter,
108                                        bool RelaxAll) {
109   return createPPCELFStreamer(Context, std::move(MAB), std::move(OW),
110                               std::move(Emitter));
111 }
112 
113 namespace {
114 
115 class PPCTargetAsmStreamer : public PPCTargetStreamer {
116   formatted_raw_ostream &OS;
117 
118 public:
119   PPCTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS)
120       : PPCTargetStreamer(S), OS(OS) {}
121 
122   void emitTCEntry(const MCSymbol &S) override {
123     if (const MCSymbolXCOFF *XSym = dyn_cast<MCSymbolXCOFF>(&S)) {
124       MCSymbolXCOFF *TCSym =
125           cast<MCSymbolXCOFF>(Streamer.getContext().getOrCreateSymbol(
126               XSym->getSymbolTableName() + "[TC]"));
127       OS << "\t.tc " << TCSym->getName() << "," << XSym->getName() << '\n';
128 
129       if (TCSym->hasRename())
130         Streamer.emitXCOFFRenameDirective(TCSym, TCSym->getSymbolTableName());
131       return;
132     }
133 
134     OS << "\t.tc " << S.getName() << "[TC]," << S.getName() << '\n';
135   }
136 
137   void emitMachine(StringRef CPU) override {
138     OS << "\t.machine " << CPU << '\n';
139   }
140 
141   void emitAbiVersion(int AbiVersion) override {
142     OS << "\t.abiversion " << AbiVersion << '\n';
143   }
144 
145   void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override {
146     const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
147 
148     OS << "\t.localentry\t";
149     S->print(OS, MAI);
150     OS << ", ";
151     LocalOffset->print(OS, MAI);
152     OS << '\n';
153   }
154 };
155 
156 class PPCTargetELFStreamer : public PPCTargetStreamer {
157 public:
158   PPCTargetELFStreamer(MCStreamer &S) : PPCTargetStreamer(S) {}
159 
160   MCELFStreamer &getStreamer() {
161     return static_cast<MCELFStreamer &>(Streamer);
162   }
163 
164   void emitTCEntry(const MCSymbol &S) override {
165     // Creates a R_PPC64_TOC relocation
166     Streamer.emitValueToAlignment(8);
167     Streamer.emitSymbolValue(&S, 8);
168   }
169 
170   void emitMachine(StringRef CPU) override {
171     // FIXME: Is there anything to do in here or does this directive only
172     // limit the parser?
173   }
174 
175   void emitAbiVersion(int AbiVersion) override {
176     MCAssembler &MCA = getStreamer().getAssembler();
177     unsigned Flags = MCA.getELFHeaderEFlags();
178     Flags &= ~ELF::EF_PPC64_ABI;
179     Flags |= (AbiVersion & ELF::EF_PPC64_ABI);
180     MCA.setELFHeaderEFlags(Flags);
181   }
182 
183   void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override {
184     MCAssembler &MCA = getStreamer().getAssembler();
185 
186     // encodePPC64LocalEntryOffset will report an error if it cannot
187     // encode LocalOffset.
188     unsigned Encoded = encodePPC64LocalEntryOffset(LocalOffset);
189 
190     unsigned Other = S->getOther();
191     Other &= ~ELF::STO_PPC64_LOCAL_MASK;
192     Other |= Encoded;
193     S->setOther(Other);
194 
195     // For GAS compatibility, unless we already saw a .abiversion directive,
196     // set e_flags to indicate ELFv2 ABI.
197     unsigned Flags = MCA.getELFHeaderEFlags();
198     if ((Flags & ELF::EF_PPC64_ABI) == 0)
199       MCA.setELFHeaderEFlags(Flags | 2);
200   }
201 
202   void emitAssignment(MCSymbol *S, const MCExpr *Value) override {
203     auto *Symbol = cast<MCSymbolELF>(S);
204 
205     // When encoding an assignment to set symbol A to symbol B, also copy
206     // the st_other bits encoding the local entry point offset.
207     if (copyLocalEntry(Symbol, Value))
208       UpdateOther.insert(Symbol);
209     else
210       UpdateOther.erase(Symbol);
211   }
212 
213   void finish() override {
214     for (auto *Sym : UpdateOther)
215       if (Sym->isVariable())
216         copyLocalEntry(Sym, Sym->getVariableValue());
217 
218     // Clear the set of symbols that needs to be updated so the streamer can
219     // be reused without issues.
220     UpdateOther.clear();
221   }
222 
223 private:
224   SmallPtrSet<MCSymbolELF *, 32> UpdateOther;
225 
226   bool copyLocalEntry(MCSymbolELF *D, const MCExpr *S) {
227     auto *Ref = dyn_cast<const MCSymbolRefExpr>(S);
228     if (!Ref)
229       return false;
230     const auto &RhsSym = cast<MCSymbolELF>(Ref->getSymbol());
231     unsigned Other = D->getOther();
232     Other &= ~ELF::STO_PPC64_LOCAL_MASK;
233     Other |= RhsSym.getOther() & ELF::STO_PPC64_LOCAL_MASK;
234     D->setOther(Other);
235     return true;
236   }
237 
238   unsigned encodePPC64LocalEntryOffset(const MCExpr *LocalOffset) {
239     MCAssembler &MCA = getStreamer().getAssembler();
240     int64_t Offset;
241     if (!LocalOffset->evaluateAsAbsolute(Offset, MCA))
242       MCA.getContext().reportFatalError(
243           LocalOffset->getLoc(), ".localentry expression must be absolute.");
244 
245     switch (Offset) {
246     default:
247       MCA.getContext().reportFatalError(
248           LocalOffset->getLoc(),
249           ".localentry expression is not a valid power of 2.");
250     case 0:
251       return 0;
252     case 1:
253       return 1 << ELF::STO_PPC64_LOCAL_BIT;
254     case 4:
255     case 8:
256     case 16:
257     case 32:
258     case 64:
259       return (int)Log2(Offset) << (int)ELF::STO_PPC64_LOCAL_BIT;
260     }
261   }
262 };
263 
264 class PPCTargetMachOStreamer : public PPCTargetStreamer {
265 public:
266   PPCTargetMachOStreamer(MCStreamer &S) : PPCTargetStreamer(S) {}
267 
268   void emitTCEntry(const MCSymbol &S) override {
269     llvm_unreachable("Unknown pseudo-op: .tc");
270   }
271 
272   void emitMachine(StringRef CPU) override {
273     // FIXME: We should update the CPUType, CPUSubType in the Object file if
274     // the new values are different from the defaults.
275   }
276 
277   void emitAbiVersion(int AbiVersion) override {
278     llvm_unreachable("Unknown pseudo-op: .abiversion");
279   }
280 
281   void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override {
282     llvm_unreachable("Unknown pseudo-op: .localentry");
283   }
284 };
285 
286 class PPCTargetXCOFFStreamer : public PPCTargetStreamer {
287 public:
288   PPCTargetXCOFFStreamer(MCStreamer &S) : PPCTargetStreamer(S) {}
289 
290   void emitTCEntry(const MCSymbol &S) override {
291     const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
292     const unsigned PointerSize = MAI->getCodePointerSize();
293     Streamer.emitValueToAlignment(PointerSize);
294     Streamer.emitSymbolValue(&S, PointerSize);
295   }
296 
297   void emitMachine(StringRef CPU) override {
298     llvm_unreachable("Machine pseudo-ops are invalid for XCOFF.");
299   }
300 
301   void emitAbiVersion(int AbiVersion) override {
302     llvm_unreachable("ABI-version pseudo-ops are invalid for XCOFF.");
303   }
304 
305   void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset) override {
306     llvm_unreachable("Local-entry pseudo-ops are invalid for XCOFF.");
307   }
308 };
309 
310 } // end anonymous namespace
311 
312 static MCTargetStreamer *createAsmTargetStreamer(MCStreamer &S,
313                                                  formatted_raw_ostream &OS,
314                                                  MCInstPrinter *InstPrint,
315                                                  bool isVerboseAsm) {
316   return new PPCTargetAsmStreamer(S, OS);
317 }
318 
319 static MCTargetStreamer *
320 createObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo &STI) {
321   const Triple &TT = STI.getTargetTriple();
322   if (TT.isOSBinFormatELF())
323     return new PPCTargetELFStreamer(S);
324   if (TT.isOSBinFormatXCOFF())
325     return new PPCTargetXCOFFStreamer(S);
326   return new PPCTargetMachOStreamer(S);
327 }
328 
329 static MCInstPrinter *createPPCMCInstPrinter(const Triple &T,
330                                              unsigned SyntaxVariant,
331                                              const MCAsmInfo &MAI,
332                                              const MCInstrInfo &MII,
333                                              const MCRegisterInfo &MRI) {
334   return new PPCInstPrinter(MAI, MII, MRI, T);
335 }
336 
337 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCTargetMC() {
338   for (Target *T :
339        {&getThePPC32Target(), &getThePPC64Target(), &getThePPC64LETarget()}) {
340     // Register the MC asm info.
341     RegisterMCAsmInfoFn C(*T, createPPCMCAsmInfo);
342 
343     // Register the MC instruction info.
344     TargetRegistry::RegisterMCInstrInfo(*T, createPPCMCInstrInfo);
345 
346     // Register the MC register info.
347     TargetRegistry::RegisterMCRegInfo(*T, createPPCMCRegisterInfo);
348 
349     // Register the MC subtarget info.
350     TargetRegistry::RegisterMCSubtargetInfo(*T, createPPCMCSubtargetInfo);
351 
352     // Register the MC Code Emitter
353     TargetRegistry::RegisterMCCodeEmitter(*T, createPPCMCCodeEmitter);
354 
355     // Register the asm backend.
356     TargetRegistry::RegisterMCAsmBackend(*T, createPPCAsmBackend);
357 
358     // Register the elf streamer.
359     TargetRegistry::RegisterELFStreamer(*T, createPPCMCStreamer);
360 
361     // Register the object target streamer.
362     TargetRegistry::RegisterObjectTargetStreamer(*T,
363                                                  createObjectTargetStreamer);
364 
365     // Register the asm target streamer.
366     TargetRegistry::RegisterAsmTargetStreamer(*T, createAsmTargetStreamer);
367 
368     // Register the MCInstPrinter.
369     TargetRegistry::RegisterMCInstPrinter(*T, createPPCMCInstPrinter);
370   }
371 }
372