xref: /openbsd-src/gnu/llvm/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp (revision a96b36398fcfb4953e8190127da8bf074c7552f1)
1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
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 contains a printer that converts from our internal representation
10 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
11 // the output mechanism used by `llc'.
12 //
13 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
14 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "MCTargetDesc/PPCInstPrinter.h"
19 #include "MCTargetDesc/PPCMCExpr.h"
20 #include "MCTargetDesc/PPCMCTargetDesc.h"
21 #include "MCTargetDesc/PPCPredicates.h"
22 #include "PPC.h"
23 #include "PPCInstrInfo.h"
24 #include "PPCMachineFunctionInfo.h"
25 #include "PPCSubtarget.h"
26 #include "PPCTargetMachine.h"
27 #include "PPCTargetStreamer.h"
28 #include "TargetInfo/PowerPCTargetInfo.h"
29 #include "llvm/ADT/MapVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Triple.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/BinaryFormat/ELF.h"
35 #include "llvm/CodeGen/AsmPrinter.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/StackMaps.h"
44 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/MC/MCAsmInfo.h"
50 #include "llvm/MC/MCContext.h"
51 #include "llvm/MC/MCDirectives.h"
52 #include "llvm/MC/MCExpr.h"
53 #include "llvm/MC/MCInst.h"
54 #include "llvm/MC/MCInstBuilder.h"
55 #include "llvm/MC/MCSectionELF.h"
56 #include "llvm/MC/MCSectionXCOFF.h"
57 #include "llvm/MC/MCStreamer.h"
58 #include "llvm/MC/MCSymbol.h"
59 #include "llvm/MC/MCSymbolELF.h"
60 #include "llvm/MC/MCSymbolXCOFF.h"
61 #include "llvm/MC/SectionKind.h"
62 #include "llvm/MC/TargetRegistry.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CodeGen.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/Error.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/Process.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Transforms/Utils/ModuleUtils.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <memory>
76 #include <new>
77 
78 using namespace llvm;
79 using namespace llvm::XCOFF;
80 
81 #define DEBUG_TYPE "asmprinter"
82 
83 static cl::opt<bool> EnableSSPCanaryBitInTB(
84     "aix-ssp-tb-bit", cl::init(false),
85     cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden);
86 
87 // Specialize DenseMapInfo to allow
88 // std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind> in DenseMap.
89 // This specialization is needed here because that type is used as keys in the
90 // map representing TOC entries.
91 namespace llvm {
92 template <>
93 struct DenseMapInfo<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>> {
94   using TOCKey = std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>;
95 
getEmptyKeyllvm::DenseMapInfo96   static inline TOCKey getEmptyKey() {
97     return {nullptr, MCSymbolRefExpr::VariantKind::VK_None};
98   }
getTombstoneKeyllvm::DenseMapInfo99   static inline TOCKey getTombstoneKey() {
100     return {nullptr, MCSymbolRefExpr::VariantKind::VK_Invalid};
101   }
getHashValuellvm::DenseMapInfo102   static unsigned getHashValue(const TOCKey &PairVal) {
103     return detail::combineHashValue(
104         DenseMapInfo<const MCSymbol *>::getHashValue(PairVal.first),
105         DenseMapInfo<int>::getHashValue(PairVal.second));
106   }
isEqualllvm::DenseMapInfo107   static bool isEqual(const TOCKey &A, const TOCKey &B) { return A == B; }
108 };
109 } // end namespace llvm
110 
111 namespace {
112 
113 enum {
114   // GNU attribute tags for PowerPC ABI
115   Tag_GNU_Power_ABI_FP = 4,
116   Tag_GNU_Power_ABI_Vector = 8,
117   Tag_GNU_Power_ABI_Struct_Return = 12,
118 
119   // GNU attribute values for PowerPC float ABI, as combination of two parts
120   Val_GNU_Power_ABI_NoFloat = 0b00,
121   Val_GNU_Power_ABI_HardFloat_DP = 0b01,
122   Val_GNU_Power_ABI_SoftFloat_DP = 0b10,
123   Val_GNU_Power_ABI_HardFloat_SP = 0b11,
124 
125   Val_GNU_Power_ABI_LDBL_IBM128 = 0b0100,
126   Val_GNU_Power_ABI_LDBL_64 = 0b1000,
127   Val_GNU_Power_ABI_LDBL_IEEE128 = 0b1100,
128 };
129 
130 class PPCAsmPrinter : public AsmPrinter {
131 protected:
132   // For TLS on AIX, we need to be able to identify TOC entries of specific
133   // VariantKind so we can add the right relocations when we generate the
134   // entries. So each entry is represented by a pair of MCSymbol and
135   // VariantKind. For example, we need to be able to identify the following
136   // entry as a TLSGD entry so we can add the @m relocation:
137   //   .tc .i[TC],i[TL]@m
138   // By default, VK_None is used for the VariantKind.
139   MapVector<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>,
140             MCSymbol *>
141       TOC;
142   const PPCSubtarget *Subtarget = nullptr;
143 
144 public:
PPCAsmPrinter(TargetMachine & TM,std::unique_ptr<MCStreamer> Streamer)145   explicit PPCAsmPrinter(TargetMachine &TM,
146                          std::unique_ptr<MCStreamer> Streamer)
147       : AsmPrinter(TM, std::move(Streamer)) {}
148 
getPassName() const149   StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
150 
151   MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym,
152                                    MCSymbolRefExpr::VariantKind Kind =
153                                        MCSymbolRefExpr::VariantKind::VK_None);
154 
doInitialization(Module & M)155   bool doInitialization(Module &M) override {
156     if (!TOC.empty())
157       TOC.clear();
158     return AsmPrinter::doInitialization(M);
159   }
160 
161   void emitInstruction(const MachineInstr *MI) override;
162 
163   /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
164   /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
165   /// The \p MI would be INLINEASM ONLY.
166   void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
167 
168   void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
169   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
170                        const char *ExtraCode, raw_ostream &O) override;
171   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
172                              const char *ExtraCode, raw_ostream &O) override;
173 
174   void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
175   void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
176   void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
runOnMachineFunction(MachineFunction & MF)177   bool runOnMachineFunction(MachineFunction &MF) override {
178     Subtarget = &MF.getSubtarget<PPCSubtarget>();
179     bool Changed = AsmPrinter::runOnMachineFunction(MF);
180     emitXRayTable();
181     return Changed;
182   }
183 };
184 
185 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
186 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
187 public:
PPCLinuxAsmPrinter(TargetMachine & TM,std::unique_ptr<MCStreamer> Streamer)188   explicit PPCLinuxAsmPrinter(TargetMachine &TM,
189                               std::unique_ptr<MCStreamer> Streamer)
190       : PPCAsmPrinter(TM, std::move(Streamer)) {}
191 
getPassName() const192   StringRef getPassName() const override {
193     return "Linux PPC Assembly Printer";
194   }
195 
196   void emitGNUAttributes(Module &M);
197 
198   void emitStartOfAsmFile(Module &M) override;
199   void emitEndOfAsmFile(Module &) override;
200 
201   void emitFunctionEntryLabel() override;
202 
203   void emitFunctionBodyStart() override;
204   void emitFunctionBodyEnd() override;
205   void emitInstruction(const MachineInstr *MI) override;
206 };
207 
208 class PPCAIXAsmPrinter : public PPCAsmPrinter {
209 private:
210   /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern
211   /// linkage for them in AIX.
212   SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols;
213 
214   /// A format indicator and unique trailing identifier to form part of the
215   /// sinit/sterm function names.
216   std::string FormatIndicatorAndUniqueModId;
217 
218   // Record a list of GlobalAlias associated with a GlobalObject.
219   // This is used for AIX's extra-label-at-definition aliasing strategy.
220   DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>>
221       GOAliasMap;
222 
223   uint16_t getNumberOfVRSaved();
224   void emitTracebackTable();
225 
226   SmallVector<const GlobalVariable *, 8> TOCDataGlobalVars;
227 
228   void emitGlobalVariableHelper(const GlobalVariable *);
229 
230   // Get the offset of an alias based on its AliaseeObject.
231   uint64_t getAliasOffset(const Constant *C);
232 
233 public:
PPCAIXAsmPrinter(TargetMachine & TM,std::unique_ptr<MCStreamer> Streamer)234   PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
235       : PPCAsmPrinter(TM, std::move(Streamer)) {
236     if (MAI->isLittleEndian())
237       report_fatal_error(
238           "cannot create AIX PPC Assembly Printer for a little-endian target");
239   }
240 
getPassName() const241   StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
242 
243   bool doInitialization(Module &M) override;
244 
245   void emitXXStructorList(const DataLayout &DL, const Constant *List,
246                           bool IsCtor) override;
247 
248   void SetupMachineFunction(MachineFunction &MF) override;
249 
250   void emitGlobalVariable(const GlobalVariable *GV) override;
251 
252   void emitFunctionDescriptor() override;
253 
254   void emitFunctionEntryLabel() override;
255 
256   void emitFunctionBodyEnd() override;
257 
258   void emitPGORefs();
259 
260   void emitEndOfAsmFile(Module &) override;
261 
262   void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
263 
264   void emitInstruction(const MachineInstr *MI) override;
265 
266   bool doFinalization(Module &M) override;
267 
268   void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
269 };
270 
271 } // end anonymous namespace
272 
PrintSymbolOperand(const MachineOperand & MO,raw_ostream & O)273 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
274                                        raw_ostream &O) {
275   // Computing the address of a global symbol, not calling it.
276   const GlobalValue *GV = MO.getGlobal();
277   getSymbol(GV)->print(O, MAI);
278   printOffset(MO.getOffset(), O);
279 }
280 
printOperand(const MachineInstr * MI,unsigned OpNo,raw_ostream & O)281 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
282                                  raw_ostream &O) {
283   const DataLayout &DL = getDataLayout();
284   const MachineOperand &MO = MI->getOperand(OpNo);
285 
286   switch (MO.getType()) {
287   case MachineOperand::MO_Register: {
288     // The MI is INLINEASM ONLY and UseVSXReg is always false.
289     const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
290 
291     // Linux assembler (Others?) does not take register mnemonics.
292     // FIXME - What about special registers used in mfspr/mtspr?
293     O << PPCRegisterInfo::stripRegisterPrefix(RegName);
294     return;
295   }
296   case MachineOperand::MO_Immediate:
297     O << MO.getImm();
298     return;
299 
300   case MachineOperand::MO_MachineBasicBlock:
301     MO.getMBB()->getSymbol()->print(O, MAI);
302     return;
303   case MachineOperand::MO_ConstantPoolIndex:
304     O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
305       << MO.getIndex();
306     return;
307   case MachineOperand::MO_BlockAddress:
308     GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
309     return;
310   case MachineOperand::MO_GlobalAddress: {
311     PrintSymbolOperand(MO, O);
312     return;
313   }
314 
315   default:
316     O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
317     return;
318   }
319 }
320 
321 /// PrintAsmOperand - Print out an operand for an inline asm expression.
322 ///
PrintAsmOperand(const MachineInstr * MI,unsigned OpNo,const char * ExtraCode,raw_ostream & O)323 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
324                                     const char *ExtraCode, raw_ostream &O) {
325   // Does this asm operand have a single letter operand modifier?
326   if (ExtraCode && ExtraCode[0]) {
327     if (ExtraCode[1] != 0) return true; // Unknown modifier.
328 
329     switch (ExtraCode[0]) {
330     default:
331       // See if this is a generic print operand
332       return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
333     case 'L': // Write second word of DImode reference.
334       // Verify that this operand has two consecutive registers.
335       if (!MI->getOperand(OpNo).isReg() ||
336           OpNo+1 == MI->getNumOperands() ||
337           !MI->getOperand(OpNo+1).isReg())
338         return true;
339       ++OpNo;   // Return the high-part.
340       break;
341     case 'I':
342       // Write 'i' if an integer constant, otherwise nothing.  Used to print
343       // addi vs add, etc.
344       if (MI->getOperand(OpNo).isImm())
345         O << "i";
346       return false;
347     case 'x':
348       if(!MI->getOperand(OpNo).isReg())
349         return true;
350       // This operand uses VSX numbering.
351       // If the operand is a VMX register, convert it to a VSX register.
352       Register Reg = MI->getOperand(OpNo).getReg();
353       if (PPCInstrInfo::isVRRegister(Reg))
354         Reg = PPC::VSX32 + (Reg - PPC::V0);
355       else if (PPCInstrInfo::isVFRegister(Reg))
356         Reg = PPC::VSX32 + (Reg - PPC::VF0);
357       const char *RegName;
358       RegName = PPCInstPrinter::getRegisterName(Reg);
359       RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
360       O << RegName;
361       return false;
362     }
363   }
364 
365   printOperand(MI, OpNo, O);
366   return false;
367 }
368 
369 // At the moment, all inline asm memory operands are a single register.
370 // In any case, the output of this routine should always be just one
371 // assembler operand.
PrintAsmMemoryOperand(const MachineInstr * MI,unsigned OpNo,const char * ExtraCode,raw_ostream & O)372 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
373                                           const char *ExtraCode,
374                                           raw_ostream &O) {
375   if (ExtraCode && ExtraCode[0]) {
376     if (ExtraCode[1] != 0) return true; // Unknown modifier.
377 
378     switch (ExtraCode[0]) {
379     default: return true;  // Unknown modifier.
380     case 'L': // A memory reference to the upper word of a double word op.
381       O << getDataLayout().getPointerSize() << "(";
382       printOperand(MI, OpNo, O);
383       O << ")";
384       return false;
385     case 'y': // A memory reference for an X-form instruction
386       O << "0, ";
387       printOperand(MI, OpNo, O);
388       return false;
389     case 'I':
390       // Write 'i' if an integer constant, otherwise nothing.  Used to print
391       // addi vs add, etc.
392       if (MI->getOperand(OpNo).isImm())
393         O << "i";
394       return false;
395     case 'U': // Print 'u' for update form.
396     case 'X': // Print 'x' for indexed form.
397       // FIXME: Currently for PowerPC memory operands are always loaded
398       // into a register, so we never get an update or indexed form.
399       // This is bad even for offset forms, since even if we know we
400       // have a value in -16(r1), we will generate a load into r<n>
401       // and then load from 0(r<n>).  Until that issue is fixed,
402       // tolerate 'U' and 'X' but don't output anything.
403       assert(MI->getOperand(OpNo).isReg());
404       return false;
405     }
406   }
407 
408   assert(MI->getOperand(OpNo).isReg());
409   O << "0(";
410   printOperand(MI, OpNo, O);
411   O << ")";
412   return false;
413 }
414 
415 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
416 /// exists for it.  If not, create one.  Then return a symbol that references
417 /// the TOC entry.
418 MCSymbol *
lookUpOrCreateTOCEntry(const MCSymbol * Sym,MCSymbolRefExpr::VariantKind Kind)419 PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym,
420                                       MCSymbolRefExpr::VariantKind Kind) {
421   MCSymbol *&TOCEntry = TOC[{Sym, Kind}];
422   if (!TOCEntry)
423     TOCEntry = createTempSymbol("C");
424   return TOCEntry;
425 }
426 
LowerSTACKMAP(StackMaps & SM,const MachineInstr & MI)427 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
428   unsigned NumNOPBytes = MI.getOperand(1).getImm();
429 
430   auto &Ctx = OutStreamer->getContext();
431   MCSymbol *MILabel = Ctx.createTempSymbol();
432   OutStreamer->emitLabel(MILabel);
433 
434   SM.recordStackMap(*MILabel, MI);
435   assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
436 
437   // Scan ahead to trim the shadow.
438   const MachineBasicBlock &MBB = *MI.getParent();
439   MachineBasicBlock::const_iterator MII(MI);
440   ++MII;
441   while (NumNOPBytes > 0) {
442     if (MII == MBB.end() || MII->isCall() ||
443         MII->getOpcode() == PPC::DBG_VALUE ||
444         MII->getOpcode() == TargetOpcode::PATCHPOINT ||
445         MII->getOpcode() == TargetOpcode::STACKMAP)
446       break;
447     ++MII;
448     NumNOPBytes -= 4;
449   }
450 
451   // Emit nops.
452   for (unsigned i = 0; i < NumNOPBytes; i += 4)
453     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
454 }
455 
456 // Lower a patchpoint of the form:
457 // [<def>], <id>, <numBytes>, <target>, <numArgs>
LowerPATCHPOINT(StackMaps & SM,const MachineInstr & MI)458 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
459   auto &Ctx = OutStreamer->getContext();
460   MCSymbol *MILabel = Ctx.createTempSymbol();
461   OutStreamer->emitLabel(MILabel);
462 
463   SM.recordPatchPoint(*MILabel, MI);
464   PatchPointOpers Opers(&MI);
465 
466   unsigned EncodedBytes = 0;
467   const MachineOperand &CalleeMO = Opers.getCallTarget();
468 
469   if (CalleeMO.isImm()) {
470     int64_t CallTarget = CalleeMO.getImm();
471     if (CallTarget) {
472       assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
473              "High 16 bits of call target should be zero.");
474       Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
475       EncodedBytes = 0;
476       // Materialize the jump address:
477       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
478                                       .addReg(ScratchReg)
479                                       .addImm((CallTarget >> 32) & 0xFFFF));
480       ++EncodedBytes;
481       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
482                                       .addReg(ScratchReg)
483                                       .addReg(ScratchReg)
484                                       .addImm(32).addImm(16));
485       ++EncodedBytes;
486       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
487                                       .addReg(ScratchReg)
488                                       .addReg(ScratchReg)
489                                       .addImm((CallTarget >> 16) & 0xFFFF));
490       ++EncodedBytes;
491       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
492                                       .addReg(ScratchReg)
493                                       .addReg(ScratchReg)
494                                       .addImm(CallTarget & 0xFFFF));
495 
496       // Save the current TOC pointer before the remote call.
497       int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
498       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
499                                       .addReg(PPC::X2)
500                                       .addImm(TOCSaveOffset)
501                                       .addReg(PPC::X1));
502       ++EncodedBytes;
503 
504       // If we're on ELFv1, then we need to load the actual function pointer
505       // from the function descriptor.
506       if (!Subtarget->isELFv2ABI()) {
507         // Load the new TOC pointer and the function address, but not r11
508         // (needing this is rare, and loading it here would prevent passing it
509         // via a 'nest' parameter.
510         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
511                                         .addReg(PPC::X2)
512                                         .addImm(8)
513                                         .addReg(ScratchReg));
514         ++EncodedBytes;
515         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
516                                         .addReg(ScratchReg)
517                                         .addImm(0)
518                                         .addReg(ScratchReg));
519         ++EncodedBytes;
520       }
521 
522       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
523                                       .addReg(ScratchReg));
524       ++EncodedBytes;
525       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
526       ++EncodedBytes;
527 
528       // Restore the TOC pointer after the call.
529       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
530                                       .addReg(PPC::X2)
531                                       .addImm(TOCSaveOffset)
532                                       .addReg(PPC::X1));
533       ++EncodedBytes;
534     }
535   } else if (CalleeMO.isGlobal()) {
536     const GlobalValue *GValue = CalleeMO.getGlobal();
537     MCSymbol *MOSymbol = getSymbol(GValue);
538     const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
539 
540     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
541                                     .addExpr(SymVar));
542     EncodedBytes += 2;
543   }
544 
545   // Each instruction is 4 bytes.
546   EncodedBytes *= 4;
547 
548   // Emit padding.
549   unsigned NumBytes = Opers.getNumPatchBytes();
550   assert(NumBytes >= EncodedBytes &&
551          "Patchpoint can't request size less than the length of a call.");
552   assert((NumBytes - EncodedBytes) % 4 == 0 &&
553          "Invalid number of NOP bytes requested!");
554   for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
555     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
556 }
557 
558 /// This helper function creates the TlsGetAddr MCSymbol for AIX. We will
559 /// create the csect and use the qual-name symbol instead of creating just the
560 /// external symbol.
createMCSymbolForTlsGetAddr(MCContext & Ctx)561 static MCSymbol *createMCSymbolForTlsGetAddr(MCContext &Ctx) {
562   return Ctx
563       .getXCOFFSection(".__tls_get_addr", SectionKind::getText(),
564                        XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER))
565       ->getQualNameSymbol();
566 }
567 
568 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
569 /// call to __tls_get_addr to the current output stream.
EmitTlsCall(const MachineInstr * MI,MCSymbolRefExpr::VariantKind VK)570 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
571                                 MCSymbolRefExpr::VariantKind VK) {
572   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
573   unsigned Opcode = PPC::BL8_NOP_TLS;
574 
575   assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI");
576   if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG ||
577       MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) {
578     Kind = MCSymbolRefExpr::VK_PPC_NOTOC;
579     Opcode = PPC::BL8_NOTOC_TLS;
580   }
581   const Module *M = MF->getFunction().getParent();
582 
583   assert(MI->getOperand(0).isReg() &&
584          ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
585           (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
586          "GETtls[ld]ADDR[32] must define GPR3");
587   assert(MI->getOperand(1).isReg() &&
588          ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
589           (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
590          "GETtls[ld]ADDR[32] must read GPR3");
591 
592   if (Subtarget->isAIXABI()) {
593     // On AIX, the variable offset should already be in R4 and the region handle
594     // should already be in R3.
595     // For TLSGD, which currently is the only supported access model, we only
596     // need to generate an absolute branch to .__tls_get_addr.
597     Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4;
598     (void)VarOffsetReg;
599     assert(MI->getOperand(2).isReg() &&
600            MI->getOperand(2).getReg() == VarOffsetReg &&
601            "GETtls[ld]ADDR[32] must read GPR4");
602     MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext);
603     const MCExpr *TlsRef = MCSymbolRefExpr::create(
604         TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
605     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BLA).addExpr(TlsRef));
606     return;
607   }
608 
609   MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol("__tls_get_addr");
610 
611   if (Subtarget->is32BitELFABI() && isPositionIndependent())
612     Kind = MCSymbolRefExpr::VK_PLT;
613 
614   const MCExpr *TlsRef =
615     MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
616 
617   // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
618   if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
619       M->getPICLevel() == PICLevel::BigPIC)
620     TlsRef = MCBinaryExpr::createAdd(
621         TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
622   const MachineOperand &MO = MI->getOperand(2);
623   const GlobalValue *GValue = MO.getGlobal();
624   MCSymbol *MOSymbol = getSymbol(GValue);
625   const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
626   EmitToStreamer(*OutStreamer,
627                  MCInstBuilder(Subtarget->isPPC64() ? Opcode
628                                                     : (unsigned)PPC::BL_TLS)
629                      .addExpr(TlsRef)
630                      .addExpr(SymVar));
631 }
632 
633 /// Map a machine operand for a TOC pseudo-machine instruction to its
634 /// corresponding MCSymbol.
getMCSymbolForTOCPseudoMO(const MachineOperand & MO,AsmPrinter & AP)635 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO,
636                                            AsmPrinter &AP) {
637   switch (MO.getType()) {
638   case MachineOperand::MO_GlobalAddress:
639     return AP.getSymbol(MO.getGlobal());
640   case MachineOperand::MO_ConstantPoolIndex:
641     return AP.GetCPISymbol(MO.getIndex());
642   case MachineOperand::MO_JumpTableIndex:
643     return AP.GetJTISymbol(MO.getIndex());
644   case MachineOperand::MO_BlockAddress:
645     return AP.GetBlockAddressSymbol(MO.getBlockAddress());
646   default:
647     llvm_unreachable("Unexpected operand type to get symbol.");
648   }
649 }
650 
651 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
652 /// the current output stream.
653 ///
emitInstruction(const MachineInstr * MI)654 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
655   PPC_MC::verifyInstructionPredicates(MI->getOpcode(),
656                                       getSubtargetInfo().getFeatureBits());
657 
658   MCInst TmpInst;
659   const bool IsPPC64 = Subtarget->isPPC64();
660   const bool IsAIX = Subtarget->isAIXABI();
661   const Module *M = MF->getFunction().getParent();
662   PICLevel::Level PL = M->getPICLevel();
663 
664 #ifndef NDEBUG
665   // Validate that SPE and FPU are mutually exclusive in codegen
666   if (!MI->isInlineAsm()) {
667     for (const MachineOperand &MO: MI->operands()) {
668       if (MO.isReg()) {
669         Register Reg = MO.getReg();
670         if (Subtarget->hasSPE()) {
671           if (PPC::F4RCRegClass.contains(Reg) ||
672               PPC::F8RCRegClass.contains(Reg) ||
673               PPC::VFRCRegClass.contains(Reg) ||
674               PPC::VRRCRegClass.contains(Reg) ||
675               PPC::VSFRCRegClass.contains(Reg) ||
676               PPC::VSSRCRegClass.contains(Reg)
677               )
678             llvm_unreachable("SPE targets cannot have FPRegs!");
679         } else {
680           if (PPC::SPERCRegClass.contains(Reg))
681             llvm_unreachable("SPE register found in FPU-targeted code!");
682         }
683       }
684     }
685   }
686 #endif
687 
688   auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
689                                                 ptrdiff_t OriginalOffset) {
690     // Apply an offset to the TOC-based expression such that the adjusted
691     // notional offset from the TOC base (to be encoded into the instruction's D
692     // or DS field) is the signed 16-bit truncation of the original notional
693     // offset from the TOC base.
694     // This is consistent with the treatment used both by XL C/C++ and
695     // by AIX ld -r.
696     ptrdiff_t Adjustment =
697         OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
698     return MCBinaryExpr::createAdd(
699         Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
700   };
701 
702   auto getTOCEntryLoadingExprForXCOFF =
703       [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
704        this](const MCSymbol *MOSymbol, const MCExpr *Expr,
705              MCSymbolRefExpr::VariantKind VK =
706                  MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * {
707     const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
708     const auto TOCEntryIter = TOC.find({MOSymbol, VK});
709     assert(TOCEntryIter != TOC.end() &&
710            "Could not find the TOC entry for this symbol.");
711     const ptrdiff_t EntryDistanceFromTOCBase =
712         (TOCEntryIter - TOC.begin()) * EntryByteSize;
713     constexpr int16_t PositiveTOCRange = INT16_MAX;
714 
715     if (EntryDistanceFromTOCBase > PositiveTOCRange)
716       return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
717 
718     return Expr;
719   };
720   auto GetVKForMO = [&](const MachineOperand &MO) {
721     // For GD TLS access on AIX, we have two TOC entries for the symbol (one for
722     // the variable offset and the other for the region handle). They are
723     // differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG.
724     if (MO.getTargetFlags() & PPCII::MO_TLSGDM_FLAG)
725       return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM;
726     if (MO.getTargetFlags() & PPCII::MO_TLSGD_FLAG)
727       return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD;
728     return MCSymbolRefExpr::VariantKind::VK_None;
729   };
730 
731   // Lower multi-instruction pseudo operations.
732   switch (MI->getOpcode()) {
733   default: break;
734   case TargetOpcode::DBG_VALUE:
735     llvm_unreachable("Should be handled target independently");
736   case TargetOpcode::STACKMAP:
737     return LowerSTACKMAP(SM, *MI);
738   case TargetOpcode::PATCHPOINT:
739     return LowerPATCHPOINT(SM, *MI);
740 
741   case PPC::MoveGOTtoLR: {
742     // Transform %lr = MoveGOTtoLR
743     // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
744     // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
745     // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
746     //      blrl
747     // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
748     MCSymbol *GOTSymbol =
749       OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
750     const MCExpr *OffsExpr =
751       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
752                                                       MCSymbolRefExpr::VK_PPC_LOCAL,
753                                                       OutContext),
754                               MCConstantExpr::create(4, OutContext),
755                               OutContext);
756 
757     // Emit the 'bl'.
758     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
759     return;
760   }
761   case PPC::MovePCtoLR:
762   case PPC::MovePCtoLR8: {
763     // Transform %lr = MovePCtoLR
764     // Into this, where the label is the PIC base:
765     //     bl L1$pb
766     // L1$pb:
767     MCSymbol *PICBase = MF->getPICBaseSymbol();
768 
769     // Emit the 'bl'.
770     EmitToStreamer(*OutStreamer,
771                    MCInstBuilder(PPC::BL)
772                        // FIXME: We would like an efficient form for this, so we
773                        // don't have to do a lot of extra uniquing.
774                        .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
775 
776     // Emit the label.
777     OutStreamer->emitLabel(PICBase);
778     return;
779   }
780   case PPC::UpdateGBR: {
781     // Transform %rd = UpdateGBR(%rt, %ri)
782     // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
783     //       add %rd, %rt, %ri
784     // or into (if secure plt mode is on):
785     //       addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
786     //       addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
787     // Get the offset from the GOT Base Register to the GOT
788     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
789     if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
790       unsigned PICR = TmpInst.getOperand(0).getReg();
791       MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
792           M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
793                                                  : ".LTOC");
794       const MCExpr *PB =
795           MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
796 
797       const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
798           MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
799 
800       const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
801       EmitToStreamer(
802           *OutStreamer,
803           MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
804 
805       const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
806       EmitToStreamer(
807           *OutStreamer,
808           MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
809       return;
810     } else {
811       MCSymbol *PICOffset =
812         MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
813       TmpInst.setOpcode(PPC::LWZ);
814       const MCExpr *Exp =
815         MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
816       const MCExpr *PB =
817         MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
818                                 MCSymbolRefExpr::VK_None,
819                                 OutContext);
820       const MCOperand TR = TmpInst.getOperand(1);
821       const MCOperand PICR = TmpInst.getOperand(0);
822 
823       // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
824       TmpInst.getOperand(1) =
825           MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
826       TmpInst.getOperand(0) = TR;
827       TmpInst.getOperand(2) = PICR;
828       EmitToStreamer(*OutStreamer, TmpInst);
829 
830       TmpInst.setOpcode(PPC::ADD4);
831       TmpInst.getOperand(0) = PICR;
832       TmpInst.getOperand(1) = TR;
833       TmpInst.getOperand(2) = PICR;
834       EmitToStreamer(*OutStreamer, TmpInst);
835       return;
836     }
837   }
838   case PPC::RETGUARD_LOAD_PC: {
839     unsigned DEST = MI->getOperand(0).getReg();
840     unsigned LR  = MI->getOperand(1).getReg();
841     MCSymbol *HereSym = MI->getOperand(2).getMCSymbol();
842 
843     unsigned MTLR = PPC::MTLR;
844     unsigned MFLR = PPC::MFLR;
845     unsigned BL   = PPC::BL;
846     if (Subtarget->isPPC64()) {
847       MTLR = PPC::MTLR8;
848       MFLR = PPC::MFLR8;
849       BL   = PPC::BL8;
850     }
851 
852     // Cache the current LR
853     EmitToStreamer(*OutStreamer, MCInstBuilder(MFLR)
854                                  .addReg(LR));
855 
856     // Create the BL forward
857     const MCExpr *HereExpr = MCSymbolRefExpr::create(HereSym, OutContext);
858     EmitToStreamer(*OutStreamer, MCInstBuilder(BL)
859                                  .addExpr(HereExpr));
860     OutStreamer->emitLabel(HereSym);
861 
862     // Grab the result
863     EmitToStreamer(*OutStreamer, MCInstBuilder(MFLR)
864                                  .addReg(DEST));
865     // Restore LR
866     EmitToStreamer(*OutStreamer, MCInstBuilder(MTLR)
867                                  .addReg(LR));
868     return;
869   }
870   case PPC::RETGUARD_LOAD_GOT: {
871     if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
872       StringRef GOTName = (PL == PICLevel::SmallPIC ?
873                                  "_GLOBAL_OFFSET_TABLE_" : ".LTOC");
874       unsigned DEST     = MI->getOperand(0).getReg();
875       unsigned HERE     = MI->getOperand(1).getReg();
876       MCSymbol *HereSym = MI->getOperand(2).getMCSymbol();
877       MCSymbol *GOTSym  = OutContext.getOrCreateSymbol(GOTName);
878       const MCExpr *HereExpr = MCSymbolRefExpr::create(HereSym, OutContext);
879       const MCExpr *GOTExpr  = MCSymbolRefExpr::create(GOTSym, OutContext);
880 
881       // Get offset from Here to GOT
882       const MCExpr *GOTDeltaExpr =
883         MCBinaryExpr::createSub(GOTExpr, HereExpr, OutContext);
884       const MCExpr *GOTDeltaHi =
885         PPCMCExpr::createHa(GOTDeltaExpr, OutContext);
886       const MCExpr *GOTDeltaLo =
887         PPCMCExpr::createLo(GOTDeltaExpr, OutContext);
888 
889       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
890                                    .addReg(DEST)
891                                    .addReg(HERE)
892                                    .addExpr(GOTDeltaHi));
893       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
894                                    .addReg(DEST)
895                                    .addReg(DEST)
896                                    .addExpr(GOTDeltaLo));
897     }
898     return;
899   }
900   case PPC::RETGUARD_LOAD_COOKIE: {
901     unsigned DEST       = MI->getOperand(0).getReg();
902     MCSymbol *CookieSym = getSymbol(MI->getOperand(1).getGlobal());
903     const MCExpr *CookieExprHa = MCSymbolRefExpr::create(
904         CookieSym, MCSymbolRefExpr::VK_PPC_HA, OutContext);
905     const MCExpr *CookieExprLo = MCSymbolRefExpr::create(
906         CookieSym, MCSymbolRefExpr::VK_PPC_LO, OutContext);
907 
908     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LIS)
909                                  .addReg(DEST)
910                                  .addExpr(CookieExprHa));
911     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
912                                  .addReg(DEST)
913                                  .addExpr(CookieExprLo)
914                                  .addReg(DEST));
915     return;
916   }
917   case PPC::LWZtoc: {
918     // Transform %rN = LWZtoc @op1, %r2
919     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
920 
921     // Change the opcode to LWZ.
922     TmpInst.setOpcode(PPC::LWZ);
923 
924     const MachineOperand &MO = MI->getOperand(1);
925     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
926            "Invalid operand for LWZtoc.");
927 
928     // Map the operand to its corresponding MCSymbol.
929     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
930 
931     // Create a reference to the GOT entry for the symbol. The GOT entry will be
932     // synthesized later.
933     if (PL == PICLevel::SmallPIC && !IsAIX) {
934       const MCExpr *Exp =
935         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
936                                 OutContext);
937       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
938       EmitToStreamer(*OutStreamer, TmpInst);
939       return;
940     }
941 
942     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
943 
944     // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
945     // storage allocated in the TOC which contains the address of
946     // 'MOSymbol'. Said TOC entry will be synthesized later.
947     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
948     const MCExpr *Exp =
949         MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
950 
951     // AIX uses the label directly as the lwz displacement operand for
952     // references into the toc section. The displacement value will be generated
953     // relative to the toc-base.
954     if (IsAIX) {
955       assert(
956           TM.getCodeModel() == CodeModel::Small &&
957           "This pseudo should only be selected for 32-bit small code model.");
958       Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK);
959       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
960 
961       // Print MO for better readability
962       if (isVerbose())
963         OutStreamer->getCommentOS() << MO << '\n';
964       EmitToStreamer(*OutStreamer, TmpInst);
965       return;
966     }
967 
968     // Create an explicit subtract expression between the local symbol and
969     // '.LTOC' to manifest the toc-relative offset.
970     const MCExpr *PB = MCSymbolRefExpr::create(
971         OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
972     Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
973     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
974     EmitToStreamer(*OutStreamer, TmpInst);
975     return;
976   }
977   case PPC::ADDItoc:
978   case PPC::ADDItoc8: {
979     assert(IsAIX && TM.getCodeModel() == CodeModel::Small &&
980            "PseudoOp only valid for small code model AIX");
981 
982     // Transform %rN = ADDItoc/8 @op1, %r2.
983     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
984 
985     // Change the opcode to load address.
986     TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8));
987 
988     const MachineOperand &MO = MI->getOperand(1);
989     assert(MO.isGlobal() && "Invalid operand for ADDItoc[8].");
990 
991     // Map the operand to its corresponding MCSymbol.
992     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
993 
994     const MCExpr *Exp =
995         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_None, OutContext);
996 
997     TmpInst.getOperand(1) = TmpInst.getOperand(2);
998     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
999     EmitToStreamer(*OutStreamer, TmpInst);
1000     return;
1001   }
1002   case PPC::LDtocJTI:
1003   case PPC::LDtocCPT:
1004   case PPC::LDtocBA:
1005   case PPC::LDtoc: {
1006     // Transform %x3 = LDtoc @min1, %x2
1007     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1008 
1009     // Change the opcode to LD.
1010     TmpInst.setOpcode(PPC::LD);
1011 
1012     const MachineOperand &MO = MI->getOperand(1);
1013     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1014            "Invalid operand!");
1015 
1016     // Map the operand to its corresponding MCSymbol.
1017     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1018 
1019     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1020 
1021     // Map the machine operand to its corresponding MCSymbol, then map the
1022     // global address operand to be a reference to the TOC entry we will
1023     // synthesize later.
1024     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
1025 
1026     MCSymbolRefExpr::VariantKind VKExpr =
1027         IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
1028     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext);
1029     TmpInst.getOperand(1) = MCOperand::createExpr(
1030         IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp);
1031 
1032     // Print MO for better readability
1033     if (isVerbose() && IsAIX)
1034       OutStreamer->getCommentOS() << MO << '\n';
1035     EmitToStreamer(*OutStreamer, TmpInst);
1036     return;
1037   }
1038   case PPC::ADDIStocHA: {
1039     assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
1040            "This pseudo should only be selected for 32-bit large code model on"
1041            " AIX.");
1042 
1043     // Transform %rd = ADDIStocHA %rA, @sym(%r2)
1044     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1045 
1046     // Change the opcode to ADDIS.
1047     TmpInst.setOpcode(PPC::ADDIS);
1048 
1049     const MachineOperand &MO = MI->getOperand(2);
1050     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1051            "Invalid operand for ADDIStocHA.");
1052 
1053     // Map the machine operand to its corresponding MCSymbol.
1054     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1055 
1056     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1057 
1058     // Always use TOC on AIX. Map the global address operand to be a reference
1059     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
1060     // reference the storage allocated in the TOC which contains the address of
1061     // 'MOSymbol'.
1062     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
1063     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
1064                                                 MCSymbolRefExpr::VK_PPC_U,
1065                                                 OutContext);
1066     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1067     EmitToStreamer(*OutStreamer, TmpInst);
1068     return;
1069   }
1070   case PPC::LWZtocL: {
1071     assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
1072            "This pseudo should only be selected for 32-bit large code model on"
1073            " AIX.");
1074 
1075     // Transform %rd = LWZtocL @sym, %rs.
1076     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1077 
1078     // Change the opcode to lwz.
1079     TmpInst.setOpcode(PPC::LWZ);
1080 
1081     const MachineOperand &MO = MI->getOperand(1);
1082     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1083            "Invalid operand for LWZtocL.");
1084 
1085     // Map the machine operand to its corresponding MCSymbol.
1086     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1087 
1088     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1089 
1090     // Always use TOC on AIX. Map the global address operand to be a reference
1091     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
1092     // reference the storage allocated in the TOC which contains the address of
1093     // 'MOSymbol'.
1094     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
1095     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
1096                                                 MCSymbolRefExpr::VK_PPC_L,
1097                                                 OutContext);
1098     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1099     EmitToStreamer(*OutStreamer, TmpInst);
1100     return;
1101   }
1102   case PPC::ADDIStocHA8: {
1103     // Transform %xd = ADDIStocHA8 %x2, @sym
1104     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1105 
1106     // Change the opcode to ADDIS8. If the global address is the address of
1107     // an external symbol, is a jump table address, is a block address, or is a
1108     // constant pool index with large code model enabled, then generate a TOC
1109     // entry and reference that. Otherwise, reference the symbol directly.
1110     TmpInst.setOpcode(PPC::ADDIS8);
1111 
1112     const MachineOperand &MO = MI->getOperand(2);
1113     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1114            "Invalid operand for ADDIStocHA8!");
1115 
1116     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1117 
1118     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1119 
1120     const bool GlobalToc =
1121         MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
1122     if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
1123         (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
1124       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK);
1125 
1126     VK = IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA;
1127 
1128     const MCExpr *Exp =
1129         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1130 
1131     if (!MO.isJTI() && MO.getOffset())
1132       Exp = MCBinaryExpr::createAdd(Exp,
1133                                     MCConstantExpr::create(MO.getOffset(),
1134                                                            OutContext),
1135                                     OutContext);
1136 
1137     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1138     EmitToStreamer(*OutStreamer, TmpInst);
1139     return;
1140   }
1141   case PPC::LDtocL: {
1142     // Transform %xd = LDtocL @sym, %xs
1143     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1144 
1145     // Change the opcode to LD. If the global address is the address of
1146     // an external symbol, is a jump table address, is a block address, or is
1147     // a constant pool index with large code model enabled, then generate a
1148     // TOC entry and reference that. Otherwise, reference the symbol directly.
1149     TmpInst.setOpcode(PPC::LD);
1150 
1151     const MachineOperand &MO = MI->getOperand(1);
1152     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
1153             MO.isBlockAddress()) &&
1154            "Invalid operand for LDtocL!");
1155 
1156     LLVM_DEBUG(assert(
1157         (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1158         "LDtocL used on symbol that could be accessed directly is "
1159         "invalid. Must match ADDIStocHA8."));
1160 
1161     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1162 
1163     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1164 
1165     if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
1166       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK);
1167 
1168     VK = IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO;
1169     const MCExpr *Exp =
1170         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1171     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1172     EmitToStreamer(*OutStreamer, TmpInst);
1173     return;
1174   }
1175   case PPC::ADDItocL: {
1176     // Transform %xd = ADDItocL %xs, @sym
1177     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1178 
1179     // Change the opcode to ADDI8. If the global address is external, then
1180     // generate a TOC entry and reference that. Otherwise, reference the
1181     // symbol directly.
1182     TmpInst.setOpcode(PPC::ADDI8);
1183 
1184     const MachineOperand &MO = MI->getOperand(2);
1185     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
1186 
1187     LLVM_DEBUG(assert(
1188         !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1189         "Interposable definitions must use indirect access."));
1190 
1191     const MCExpr *Exp =
1192         MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this),
1193                                 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
1194     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1195     EmitToStreamer(*OutStreamer, TmpInst);
1196     return;
1197   }
1198   case PPC::ADDISgotTprelHA: {
1199     // Transform: %xd = ADDISgotTprelHA %x2, @sym
1200     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1201     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1202     const MachineOperand &MO = MI->getOperand(2);
1203     const GlobalValue *GValue = MO.getGlobal();
1204     MCSymbol *MOSymbol = getSymbol(GValue);
1205     const MCExpr *SymGotTprel =
1206         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
1207                                 OutContext);
1208     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1209                                  .addReg(MI->getOperand(0).getReg())
1210                                  .addReg(MI->getOperand(1).getReg())
1211                                  .addExpr(SymGotTprel));
1212     return;
1213   }
1214   case PPC::LDgotTprelL:
1215   case PPC::LDgotTprelL32: {
1216     // Transform %xd = LDgotTprelL @sym, %xs
1217     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1218 
1219     // Change the opcode to LD.
1220     TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
1221     const MachineOperand &MO = MI->getOperand(1);
1222     const GlobalValue *GValue = MO.getGlobal();
1223     MCSymbol *MOSymbol = getSymbol(GValue);
1224     const MCExpr *Exp = MCSymbolRefExpr::create(
1225         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
1226                           : MCSymbolRefExpr::VK_PPC_GOT_TPREL,
1227         OutContext);
1228     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1229     EmitToStreamer(*OutStreamer, TmpInst);
1230     return;
1231   }
1232 
1233   case PPC::PPC32PICGOT: {
1234     MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1235     MCSymbol *GOTRef = OutContext.createTempSymbol();
1236     MCSymbol *NextInstr = OutContext.createTempSymbol();
1237 
1238     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
1239       // FIXME: We would like an efficient form for this, so we don't have to do
1240       // a lot of extra uniquing.
1241       .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
1242     const MCExpr *OffsExpr =
1243       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
1244                                 MCSymbolRefExpr::create(GOTRef, OutContext),
1245         OutContext);
1246     OutStreamer->emitLabel(GOTRef);
1247     OutStreamer->emitValue(OffsExpr, 4);
1248     OutStreamer->emitLabel(NextInstr);
1249     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
1250                                  .addReg(MI->getOperand(0).getReg()));
1251     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
1252                                  .addReg(MI->getOperand(1).getReg())
1253                                  .addImm(0)
1254                                  .addReg(MI->getOperand(0).getReg()));
1255     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
1256                                  .addReg(MI->getOperand(0).getReg())
1257                                  .addReg(MI->getOperand(1).getReg())
1258                                  .addReg(MI->getOperand(0).getReg()));
1259     return;
1260   }
1261   case PPC::PPC32GOT: {
1262     MCSymbol *GOTSymbol =
1263         OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1264     const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1265         GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1266     const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1267         GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1268     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1269                                  .addReg(MI->getOperand(0).getReg())
1270                                  .addExpr(SymGotTlsL));
1271     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1272                                  .addReg(MI->getOperand(0).getReg())
1273                                  .addReg(MI->getOperand(0).getReg())
1274                                  .addExpr(SymGotTlsHA));
1275     return;
1276   }
1277   case PPC::ADDIStlsgdHA: {
1278     // Transform: %xd = ADDIStlsgdHA %x2, @sym
1279     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1280     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1281     const MachineOperand &MO = MI->getOperand(2);
1282     const GlobalValue *GValue = MO.getGlobal();
1283     MCSymbol *MOSymbol = getSymbol(GValue);
1284     const MCExpr *SymGotTlsGD =
1285       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
1286                               OutContext);
1287     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1288                                  .addReg(MI->getOperand(0).getReg())
1289                                  .addReg(MI->getOperand(1).getReg())
1290                                  .addExpr(SymGotTlsGD));
1291     return;
1292   }
1293   case PPC::ADDItlsgdL:
1294     // Transform: %xd = ADDItlsgdL %xs, @sym
1295     // Into:      %xd = ADDI8 %xs, sym@got@tlsgd@l
1296   case PPC::ADDItlsgdL32: {
1297     // Transform: %rd = ADDItlsgdL32 %rs, @sym
1298     // Into:      %rd = ADDI %rs, sym@got@tlsgd
1299     const MachineOperand &MO = MI->getOperand(2);
1300     const GlobalValue *GValue = MO.getGlobal();
1301     MCSymbol *MOSymbol = getSymbol(GValue);
1302     const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1303         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1304                           : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
1305         OutContext);
1306     EmitToStreamer(*OutStreamer,
1307                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1308                    .addReg(MI->getOperand(0).getReg())
1309                    .addReg(MI->getOperand(1).getReg())
1310                    .addExpr(SymGotTlsGD));
1311     return;
1312   }
1313   case PPC::GETtlsADDR:
1314     // Transform: %x3 = GETtlsADDR %x3, @sym
1315     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1316   case PPC::GETtlsADDRPCREL:
1317   case PPC::GETtlsADDR32AIX:
1318   case PPC::GETtlsADDR64AIX:
1319     // Transform: %r3 = GETtlsADDRNNAIX %r3, %r4 (for NN == 32/64).
1320     // Into: BLA .__tls_get_addr()
1321     // Unlike on Linux, there is no symbol or relocation needed for this call.
1322   case PPC::GETtlsADDR32: {
1323     // Transform: %r3 = GETtlsADDR32 %r3, @sym
1324     // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1325     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1326     return;
1327   }
1328   case PPC::ADDIStlsldHA: {
1329     // Transform: %xd = ADDIStlsldHA %x2, @sym
1330     // Into:      %xd = ADDIS8 %x2, sym@got@tlsld@ha
1331     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1332     const MachineOperand &MO = MI->getOperand(2);
1333     const GlobalValue *GValue = MO.getGlobal();
1334     MCSymbol *MOSymbol = getSymbol(GValue);
1335     const MCExpr *SymGotTlsLD =
1336       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
1337                               OutContext);
1338     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1339                                  .addReg(MI->getOperand(0).getReg())
1340                                  .addReg(MI->getOperand(1).getReg())
1341                                  .addExpr(SymGotTlsLD));
1342     return;
1343   }
1344   case PPC::ADDItlsldL:
1345     // Transform: %xd = ADDItlsldL %xs, @sym
1346     // Into:      %xd = ADDI8 %xs, sym@got@tlsld@l
1347   case PPC::ADDItlsldL32: {
1348     // Transform: %rd = ADDItlsldL32 %rs, @sym
1349     // Into:      %rd = ADDI %rs, sym@got@tlsld
1350     const MachineOperand &MO = MI->getOperand(2);
1351     const GlobalValue *GValue = MO.getGlobal();
1352     MCSymbol *MOSymbol = getSymbol(GValue);
1353     const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1354         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1355                           : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
1356         OutContext);
1357     EmitToStreamer(*OutStreamer,
1358                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1359                        .addReg(MI->getOperand(0).getReg())
1360                        .addReg(MI->getOperand(1).getReg())
1361                        .addExpr(SymGotTlsLD));
1362     return;
1363   }
1364   case PPC::GETtlsldADDR:
1365     // Transform: %x3 = GETtlsldADDR %x3, @sym
1366     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1367   case PPC::GETtlsldADDRPCREL:
1368   case PPC::GETtlsldADDR32: {
1369     // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1370     // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1371     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1372     return;
1373   }
1374   case PPC::ADDISdtprelHA:
1375     // Transform: %xd = ADDISdtprelHA %xs, @sym
1376     // Into:      %xd = ADDIS8 %xs, sym@dtprel@ha
1377   case PPC::ADDISdtprelHA32: {
1378     // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1379     // Into:      %rd = ADDIS %rs, sym@dtprel@ha
1380     const MachineOperand &MO = MI->getOperand(2);
1381     const GlobalValue *GValue = MO.getGlobal();
1382     MCSymbol *MOSymbol = getSymbol(GValue);
1383     const MCExpr *SymDtprel =
1384       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
1385                               OutContext);
1386     EmitToStreamer(
1387         *OutStreamer,
1388         MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1389             .addReg(MI->getOperand(0).getReg())
1390             .addReg(MI->getOperand(1).getReg())
1391             .addExpr(SymDtprel));
1392     return;
1393   }
1394   case PPC::PADDIdtprel: {
1395     // Transform: %rd = PADDIdtprel %rs, @sym
1396     // Into:      %rd = PADDI8 %rs, sym@dtprel
1397     const MachineOperand &MO = MI->getOperand(2);
1398     const GlobalValue *GValue = MO.getGlobal();
1399     MCSymbol *MOSymbol = getSymbol(GValue);
1400     const MCExpr *SymDtprel = MCSymbolRefExpr::create(
1401         MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext);
1402     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8)
1403                                      .addReg(MI->getOperand(0).getReg())
1404                                      .addReg(MI->getOperand(1).getReg())
1405                                      .addExpr(SymDtprel));
1406     return;
1407   }
1408 
1409   case PPC::ADDIdtprelL:
1410     // Transform: %xd = ADDIdtprelL %xs, @sym
1411     // Into:      %xd = ADDI8 %xs, sym@dtprel@l
1412   case PPC::ADDIdtprelL32: {
1413     // Transform: %rd = ADDIdtprelL32 %rs, @sym
1414     // Into:      %rd = ADDI %rs, sym@dtprel@l
1415     const MachineOperand &MO = MI->getOperand(2);
1416     const GlobalValue *GValue = MO.getGlobal();
1417     MCSymbol *MOSymbol = getSymbol(GValue);
1418     const MCExpr *SymDtprel =
1419       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
1420                               OutContext);
1421     EmitToStreamer(*OutStreamer,
1422                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1423                        .addReg(MI->getOperand(0).getReg())
1424                        .addReg(MI->getOperand(1).getReg())
1425                        .addExpr(SymDtprel));
1426     return;
1427   }
1428   case PPC::MFOCRF:
1429   case PPC::MFOCRF8:
1430     if (!Subtarget->hasMFOCRF()) {
1431       // Transform: %r3 = MFOCRF %cr7
1432       // Into:      %r3 = MFCR   ;; cr7
1433       unsigned NewOpcode =
1434         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1435       OutStreamer->AddComment(PPCInstPrinter::
1436                               getRegisterName(MI->getOperand(1).getReg()));
1437       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1438                                   .addReg(MI->getOperand(0).getReg()));
1439       return;
1440     }
1441     break;
1442   case PPC::MTOCRF:
1443   case PPC::MTOCRF8:
1444     if (!Subtarget->hasMFOCRF()) {
1445       // Transform: %cr7 = MTOCRF %r3
1446       // Into:      MTCRF mask, %r3 ;; cr7
1447       unsigned NewOpcode =
1448         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1449       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1450                               ->getEncodingValue(MI->getOperand(0).getReg());
1451       OutStreamer->AddComment(PPCInstPrinter::
1452                               getRegisterName(MI->getOperand(0).getReg()));
1453       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1454                                      .addImm(Mask)
1455                                      .addReg(MI->getOperand(1).getReg()));
1456       return;
1457     }
1458     break;
1459   case PPC::LD:
1460   case PPC::STD:
1461   case PPC::LWA_32:
1462   case PPC::LWA: {
1463     // Verify alignment is legal, so we don't create relocations
1464     // that can't be supported.
1465     unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1466     const MachineOperand &MO = MI->getOperand(OpNum);
1467     if (MO.isGlobal()) {
1468       const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
1469       if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1470         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1471     }
1472     // Now process the instruction normally.
1473     break;
1474   }
1475   case PPC::PseudoEIEIO: {
1476     EmitToStreamer(
1477         *OutStreamer,
1478         MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1479     EmitToStreamer(
1480         *OutStreamer,
1481         MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1482     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::EnforceIEIO));
1483     return;
1484   }
1485   }
1486 
1487   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1488   EmitToStreamer(*OutStreamer, TmpInst);
1489 }
1490 
emitGNUAttributes(Module & M)1491 void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) {
1492   // Emit float ABI into GNU attribute
1493   Metadata *MD = M.getModuleFlag("float-abi");
1494   MDString *FloatABI = dyn_cast_or_null<MDString>(MD);
1495   if (!FloatABI)
1496     return;
1497   StringRef flt = FloatABI->getString();
1498   // TODO: Support emitting soft-fp and hard double/single attributes.
1499   if (flt == "doubledouble")
1500     OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1501                                   Val_GNU_Power_ABI_HardFloat_DP |
1502                                       Val_GNU_Power_ABI_LDBL_IBM128);
1503   else if (flt == "ieeequad")
1504     OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1505                                   Val_GNU_Power_ABI_HardFloat_DP |
1506                                       Val_GNU_Power_ABI_LDBL_IEEE128);
1507   else if (flt == "ieeedouble")
1508     OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1509                                   Val_GNU_Power_ABI_HardFloat_DP |
1510                                       Val_GNU_Power_ABI_LDBL_64);
1511 }
1512 
emitInstruction(const MachineInstr * MI)1513 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1514   if (!Subtarget->isPPC64())
1515     return PPCAsmPrinter::emitInstruction(MI);
1516 
1517   switch (MI->getOpcode()) {
1518   default:
1519     return PPCAsmPrinter::emitInstruction(MI);
1520   case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1521     // .begin:
1522     //   b .end # lis 0, FuncId[16..32]
1523     //   nop    # li  0, FuncId[0..15]
1524     //   std 0, -8(1)
1525     //   mflr 0
1526     //   bl __xray_FunctionEntry
1527     //   mtlr 0
1528     // .end:
1529     //
1530     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1531     // of instructions change.
1532     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1533     MCSymbol *EndOfSled = OutContext.createTempSymbol();
1534     OutStreamer->emitLabel(BeginOfSled);
1535     EmitToStreamer(*OutStreamer,
1536                    MCInstBuilder(PPC::B).addExpr(
1537                        MCSymbolRefExpr::create(EndOfSled, OutContext)));
1538     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1539     EmitToStreamer(
1540         *OutStreamer,
1541         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1542     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1543     EmitToStreamer(*OutStreamer,
1544                    MCInstBuilder(PPC::BL8_NOP)
1545                        .addExpr(MCSymbolRefExpr::create(
1546                            OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1547                            OutContext)));
1548     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1549     OutStreamer->emitLabel(EndOfSled);
1550     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1551     break;
1552   }
1553   case TargetOpcode::PATCHABLE_RET: {
1554     unsigned RetOpcode = MI->getOperand(0).getImm();
1555     MCInst RetInst;
1556     RetInst.setOpcode(RetOpcode);
1557     for (const auto &MO : llvm::drop_begin(MI->operands())) {
1558       MCOperand MCOp;
1559       if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1560         RetInst.addOperand(MCOp);
1561     }
1562 
1563     bool IsConditional;
1564     if (RetOpcode == PPC::BCCLR) {
1565       IsConditional = true;
1566     } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1567                RetOpcode == PPC::TCRETURNai8) {
1568       break;
1569     } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1570       IsConditional = false;
1571     } else {
1572       EmitToStreamer(*OutStreamer, RetInst);
1573       break;
1574     }
1575 
1576     MCSymbol *FallthroughLabel;
1577     if (IsConditional) {
1578       // Before:
1579       //   bgtlr cr0
1580       //
1581       // After:
1582       //   ble cr0, .end
1583       // .p2align 3
1584       // .begin:
1585       //   blr    # lis 0, FuncId[16..32]
1586       //   nop    # li  0, FuncId[0..15]
1587       //   std 0, -8(1)
1588       //   mflr 0
1589       //   bl __xray_FunctionExit
1590       //   mtlr 0
1591       //   blr
1592       // .end:
1593       //
1594       // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1595       // of instructions change.
1596       FallthroughLabel = OutContext.createTempSymbol();
1597       EmitToStreamer(
1598           *OutStreamer,
1599           MCInstBuilder(PPC::BCC)
1600               .addImm(PPC::InvertPredicate(
1601                   static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1602               .addReg(MI->getOperand(2).getReg())
1603               .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1604       RetInst = MCInst();
1605       RetInst.setOpcode(PPC::BLR8);
1606     }
1607     // .p2align 3
1608     // .begin:
1609     //   b(lr)? # lis 0, FuncId[16..32]
1610     //   nop    # li  0, FuncId[0..15]
1611     //   std 0, -8(1)
1612     //   mflr 0
1613     //   bl __xray_FunctionExit
1614     //   mtlr 0
1615     //   b(lr)?
1616     //
1617     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1618     // of instructions change.
1619     OutStreamer->emitCodeAlignment(Align(8), &getSubtargetInfo());
1620     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1621     OutStreamer->emitLabel(BeginOfSled);
1622     EmitToStreamer(*OutStreamer, RetInst);
1623     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1624     EmitToStreamer(
1625         *OutStreamer,
1626         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1627     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1628     EmitToStreamer(*OutStreamer,
1629                    MCInstBuilder(PPC::BL8_NOP)
1630                        .addExpr(MCSymbolRefExpr::create(
1631                            OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1632                            OutContext)));
1633     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1634     EmitToStreamer(*OutStreamer, RetInst);
1635     if (IsConditional)
1636       OutStreamer->emitLabel(FallthroughLabel);
1637     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1638     break;
1639   }
1640   case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1641     llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1642   case TargetOpcode::PATCHABLE_TAIL_CALL:
1643     // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1644     // normal function exit from a tail exit.
1645     llvm_unreachable("Tail call is handled in the normal case. See comments "
1646                      "around this assert.");
1647   }
1648 }
1649 
emitStartOfAsmFile(Module & M)1650 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1651   if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1652     PPCTargetStreamer *TS =
1653       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1654     TS->emitAbiVersion(2);
1655   }
1656 
1657   if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1658       !isPositionIndependent())
1659     return AsmPrinter::emitStartOfAsmFile(M);
1660 
1661   if (M.getPICLevel() == PICLevel::SmallPIC)
1662     return AsmPrinter::emitStartOfAsmFile(M);
1663 
1664   OutStreamer->switchSection(OutContext.getELFSection(
1665       ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1666 
1667   MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1668   MCSymbol *CurrentPos = OutContext.createTempSymbol();
1669 
1670   OutStreamer->emitLabel(CurrentPos);
1671 
1672   // The GOT pointer points to the middle of the GOT, in order to reference the
1673   // entire 64kB range.  0x8000 is the midpoint.
1674   const MCExpr *tocExpr =
1675     MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1676                             MCConstantExpr::create(0x8000, OutContext),
1677                             OutContext);
1678 
1679   OutStreamer->emitAssignment(TOCSym, tocExpr);
1680 
1681   OutStreamer->switchSection(getObjFileLowering().getTextSection());
1682 }
1683 
emitFunctionEntryLabel()1684 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1685   // linux/ppc32 - Normal entry label.
1686   if (!Subtarget->isPPC64() &&
1687       (!isPositionIndependent() ||
1688        MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1689     return AsmPrinter::emitFunctionEntryLabel();
1690 
1691   if (!Subtarget->isPPC64()) {
1692     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1693     if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1694       MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1695       MCSymbol *PICBase = MF->getPICBaseSymbol();
1696       OutStreamer->emitLabel(RelocSymbol);
1697 
1698       const MCExpr *OffsExpr =
1699         MCBinaryExpr::createSub(
1700           MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1701                                                                OutContext),
1702                                   MCSymbolRefExpr::create(PICBase, OutContext),
1703           OutContext);
1704       OutStreamer->emitValue(OffsExpr, 4);
1705       OutStreamer->emitLabel(CurrentFnSym);
1706       return;
1707     } else
1708       return AsmPrinter::emitFunctionEntryLabel();
1709   }
1710 
1711   // ELFv2 ABI - Normal entry label.
1712   if (Subtarget->isELFv2ABI()) {
1713     // In the Large code model, we allow arbitrary displacements between
1714     // the text section and its associated TOC section.  We place the
1715     // full 8-byte offset to the TOC in memory immediately preceding
1716     // the function global entry point.
1717     if (TM.getCodeModel() == CodeModel::Large
1718         && !MF->getRegInfo().use_empty(PPC::X2)) {
1719       const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1720 
1721       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1722       MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1723       const MCExpr *TOCDeltaExpr =
1724         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1725                                 MCSymbolRefExpr::create(GlobalEPSymbol,
1726                                                         OutContext),
1727                                 OutContext);
1728 
1729       OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1730       OutStreamer->emitValue(TOCDeltaExpr, 8);
1731     }
1732     return AsmPrinter::emitFunctionEntryLabel();
1733   }
1734 
1735   // Emit an official procedure descriptor.
1736   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1737   MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1738       ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1739   OutStreamer->switchSection(Section);
1740   OutStreamer->emitLabel(CurrentFnSym);
1741   OutStreamer->emitValueToAlignment(Align(8));
1742   MCSymbol *Symbol1 = CurrentFnSymForSize;
1743   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1744   // entry point.
1745   OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1746                          8 /*size*/);
1747   MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1748   // Generates a R_PPC64_TOC relocation for TOC base insertion.
1749   OutStreamer->emitValue(
1750     MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1751     8/*size*/);
1752   // Emit a null environment pointer.
1753   OutStreamer->emitIntValue(0, 8 /* size */);
1754   OutStreamer->switchSection(Current.first, Current.second);
1755 }
1756 
emitEndOfAsmFile(Module & M)1757 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
1758   const DataLayout &DL = getDataLayout();
1759 
1760   bool isPPC64 = DL.getPointerSizeInBits() == 64;
1761 
1762   PPCTargetStreamer *TS =
1763       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1764 
1765   emitGNUAttributes(M);
1766 
1767   if (!TOC.empty()) {
1768     const char *Name = isPPC64 ? ".toc" : ".got2";
1769     MCSectionELF *Section = OutContext.getELFSection(
1770         Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1771     OutStreamer->switchSection(Section);
1772     if (!isPPC64)
1773       OutStreamer->emitValueToAlignment(Align(4));
1774 
1775     for (const auto &TOCMapPair : TOC) {
1776       const MCSymbol *const TOCEntryTarget = TOCMapPair.first.first;
1777       MCSymbol *const TOCEntryLabel = TOCMapPair.second;
1778 
1779       OutStreamer->emitLabel(TOCEntryLabel);
1780       if (isPPC64)
1781         TS->emitTCEntry(*TOCEntryTarget, TOCMapPair.first.second);
1782       else
1783         OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
1784     }
1785   }
1786 
1787   PPCAsmPrinter::emitEndOfAsmFile(M);
1788 }
1789 
1790 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
emitFunctionBodyStart()1791 void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
1792   // In the ELFv2 ABI, in functions that use the TOC register, we need to
1793   // provide two entry points.  The ABI guarantees that when calling the
1794   // local entry point, r2 is set up by the caller to contain the TOC base
1795   // for this function, and when calling the global entry point, r12 is set
1796   // up by the caller to hold the address of the global entry point.  We
1797   // thus emit a prefix sequence along the following lines:
1798   //
1799   // func:
1800   // .Lfunc_gepNN:
1801   //         # global entry point
1802   //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1803   //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1804   // .Lfunc_lepNN:
1805   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1806   //         # local entry point, followed by function body
1807   //
1808   // For the Large code model, we create
1809   //
1810   // .Lfunc_tocNN:
1811   //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1812   // func:
1813   // .Lfunc_gepNN:
1814   //         # global entry point
1815   //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1816   //         add   r2,r2,r12
1817   // .Lfunc_lepNN:
1818   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1819   //         # local entry point, followed by function body
1820   //
1821   // This ensures we have r2 set up correctly while executing the function
1822   // body, no matter which entry point is called.
1823   const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1824   const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
1825                           !MF->getRegInfo().use_empty(PPC::R2);
1826   const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
1827                                 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
1828   const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
1829                                    Subtarget->isELFv2ABI() && UsesX2OrR2;
1830 
1831   // Only do all that if the function uses R2 as the TOC pointer
1832   // in the first place. We don't need the global entry point if the
1833   // function uses R2 as an allocatable register.
1834   if (NonPCrelGEPRequired || PCrelGEPRequired) {
1835     // Note: The logic here must be synchronized with the code in the
1836     // branch-selection pass which sets the offset of the first block in the
1837     // function. This matters because it affects the alignment.
1838     MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
1839     OutStreamer->emitLabel(GlobalEntryLabel);
1840     const MCSymbolRefExpr *GlobalEntryLabelExp =
1841       MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1842 
1843     if (TM.getCodeModel() != CodeModel::Large) {
1844       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1845       const MCExpr *TOCDeltaExpr =
1846         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1847                                 GlobalEntryLabelExp, OutContext);
1848 
1849       const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
1850       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1851                                    .addReg(PPC::X2)
1852                                    .addReg(PPC::X12)
1853                                    .addExpr(TOCDeltaHi));
1854 
1855       const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
1856       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1857                                    .addReg(PPC::X2)
1858                                    .addReg(PPC::X2)
1859                                    .addExpr(TOCDeltaLo));
1860     } else {
1861       MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
1862       const MCExpr *TOCOffsetDeltaExpr =
1863         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1864                                 GlobalEntryLabelExp, OutContext);
1865 
1866       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1867                                    .addReg(PPC::X2)
1868                                    .addExpr(TOCOffsetDeltaExpr)
1869                                    .addReg(PPC::X12));
1870       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1871                                    .addReg(PPC::X2)
1872                                    .addReg(PPC::X2)
1873                                    .addReg(PPC::X12));
1874     }
1875 
1876     MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
1877     OutStreamer->emitLabel(LocalEntryLabel);
1878     const MCSymbolRefExpr *LocalEntryLabelExp =
1879        MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1880     const MCExpr *LocalOffsetExp =
1881       MCBinaryExpr::createSub(LocalEntryLabelExp,
1882                               GlobalEntryLabelExp, OutContext);
1883 
1884     PPCTargetStreamer *TS =
1885       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1886     TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1887   } else if (Subtarget->isUsingPCRelativeCalls()) {
1888     // When generating the entry point for a function we have a few scenarios
1889     // based on whether or not that function uses R2 and whether or not that
1890     // function makes calls (or is a leaf function).
1891     // 1) A leaf function that does not use R2 (or treats it as callee-saved
1892     //    and preserves it). In this case st_other=0 and both
1893     //    the local and global entry points for the function are the same.
1894     //    No special entry point code is required.
1895     // 2) A function uses the TOC pointer R2. This function may or may not have
1896     //    calls. In this case st_other=[2,6] and the global and local entry
1897     //    points are different. Code to correctly setup the TOC pointer in R2
1898     //    is put between the global and local entry points. This case is
1899     //    covered by the if statatement above.
1900     // 3) A function does not use the TOC pointer R2 but does have calls.
1901     //    In this case st_other=1 since we do not know whether or not any
1902     //    of the callees clobber R2. This case is dealt with in this else if
1903     //    block. Tail calls are considered calls and the st_other should also
1904     //    be set to 1 in that case as well.
1905     // 4) The function does not use the TOC pointer but R2 is used inside
1906     //    the function. In this case st_other=1 once again.
1907     // 5) This function uses inline asm. We mark R2 as reserved if the function
1908     //    has inline asm as we have to assume that it may be used.
1909     if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
1910         MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
1911       PPCTargetStreamer *TS =
1912           static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1913       TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
1914                          MCConstantExpr::create(1, OutContext));
1915     }
1916   }
1917 }
1918 
1919 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1920 /// directive.
1921 ///
emitFunctionBodyEnd()1922 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
1923   // Only the 64-bit target requires a traceback table.  For now,
1924   // we only emit the word of zeroes that GDB requires to find
1925   // the end of the function, and zeroes for the eight-byte
1926   // mandatory fields.
1927   // FIXME: We should fill in the eight-byte mandatory fields as described in
1928   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1929   // currently make use of these fields).
1930   if (Subtarget->isPPC64()) {
1931     OutStreamer->emitIntValue(0, 4/*size*/);
1932     OutStreamer->emitIntValue(0, 8/*size*/);
1933   }
1934 }
1935 
emitLinkage(const GlobalValue * GV,MCSymbol * GVSym) const1936 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
1937                                    MCSymbol *GVSym) const {
1938 
1939   assert(MAI->hasVisibilityOnlyWithLinkage() &&
1940          "AIX's linkage directives take a visibility setting.");
1941 
1942   MCSymbolAttr LinkageAttr = MCSA_Invalid;
1943   switch (GV->getLinkage()) {
1944   case GlobalValue::ExternalLinkage:
1945     LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
1946     break;
1947   case GlobalValue::LinkOnceAnyLinkage:
1948   case GlobalValue::LinkOnceODRLinkage:
1949   case GlobalValue::WeakAnyLinkage:
1950   case GlobalValue::WeakODRLinkage:
1951   case GlobalValue::ExternalWeakLinkage:
1952     LinkageAttr = MCSA_Weak;
1953     break;
1954   case GlobalValue::AvailableExternallyLinkage:
1955     LinkageAttr = MCSA_Extern;
1956     break;
1957   case GlobalValue::PrivateLinkage:
1958     return;
1959   case GlobalValue::InternalLinkage:
1960     assert(GV->getVisibility() == GlobalValue::DefaultVisibility &&
1961            "InternalLinkage should not have other visibility setting.");
1962     LinkageAttr = MCSA_LGlobal;
1963     break;
1964   case GlobalValue::AppendingLinkage:
1965     llvm_unreachable("Should never emit this");
1966   case GlobalValue::CommonLinkage:
1967     llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
1968   }
1969 
1970   assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
1971 
1972   MCSymbolAttr VisibilityAttr = MCSA_Invalid;
1973   if (!TM.getIgnoreXCOFFVisibility()) {
1974     if (GV->hasDLLExportStorageClass() && !GV->hasDefaultVisibility())
1975       report_fatal_error(
1976           "Cannot not be both dllexport and non-default visibility");
1977     switch (GV->getVisibility()) {
1978 
1979     // TODO: "internal" Visibility needs to go here.
1980     case GlobalValue::DefaultVisibility:
1981       if (GV->hasDLLExportStorageClass())
1982         VisibilityAttr = MAI->getExportedVisibilityAttr();
1983       break;
1984     case GlobalValue::HiddenVisibility:
1985       VisibilityAttr = MAI->getHiddenVisibilityAttr();
1986       break;
1987     case GlobalValue::ProtectedVisibility:
1988       VisibilityAttr = MAI->getProtectedVisibilityAttr();
1989       break;
1990     }
1991   }
1992 
1993   OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
1994                                                     VisibilityAttr);
1995 }
1996 
SetupMachineFunction(MachineFunction & MF)1997 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1998   // Setup CurrentFnDescSym and its containing csect.
1999   MCSectionXCOFF *FnDescSec =
2000       cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
2001           &MF.getFunction(), TM));
2002   FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
2003 
2004   CurrentFnDescSym = FnDescSec->getQualNameSymbol();
2005 
2006   return AsmPrinter::SetupMachineFunction(MF);
2007 }
2008 
getNumberOfVRSaved()2009 uint16_t PPCAIXAsmPrinter::getNumberOfVRSaved() {
2010   // Calculate the number of VRs be saved.
2011   // Vector registers 20 through 31 are marked as reserved and cannot be used
2012   // in the default ABI.
2013   const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
2014   if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
2015       TM.getAIXExtendedAltivecABI()) {
2016     const MachineRegisterInfo &MRI = MF->getRegInfo();
2017     for (unsigned Reg = PPC::V20; Reg <= PPC::V31; ++Reg)
2018       if (MRI.isPhysRegModified(Reg))
2019         // Number of VRs saved.
2020         return PPC::V31 - Reg + 1;
2021   }
2022   return 0;
2023 }
2024 
emitFunctionBodyEnd()2025 void PPCAIXAsmPrinter::emitFunctionBodyEnd() {
2026 
2027   if (!TM.getXCOFFTracebackTable())
2028     return;
2029 
2030   emitTracebackTable();
2031 
2032   // If ShouldEmitEHBlock returns true, then the eh info table
2033   // will be emitted via `AIXException::endFunction`. Otherwise, we
2034   // need to emit a dumy eh info table when VRs are saved. We could not
2035   // consolidate these two places into one because there is no easy way
2036   // to access register information in `AIXException` class.
2037   if (!TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) &&
2038       (getNumberOfVRSaved() > 0)) {
2039     // Emit dummy EH Info Table.
2040     OutStreamer->switchSection(getObjFileLowering().getCompactUnwindSection());
2041     MCSymbol *EHInfoLabel =
2042         TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF);
2043     OutStreamer->emitLabel(EHInfoLabel);
2044 
2045     // Version number.
2046     OutStreamer->emitInt32(0);
2047 
2048     const DataLayout &DL = MMI->getModule()->getDataLayout();
2049     const unsigned PointerSize = DL.getPointerSize();
2050     // Add necessary paddings in 64 bit mode.
2051     OutStreamer->emitValueToAlignment(Align(PointerSize));
2052 
2053     OutStreamer->emitIntValue(0, PointerSize);
2054     OutStreamer->emitIntValue(0, PointerSize);
2055     OutStreamer->switchSection(MF->getSection());
2056   }
2057 }
2058 
emitTracebackTable()2059 void PPCAIXAsmPrinter::emitTracebackTable() {
2060 
2061   // Create a symbol for the end of function.
2062   MCSymbol *FuncEnd = createTempSymbol(MF->getName());
2063   OutStreamer->emitLabel(FuncEnd);
2064 
2065   OutStreamer->AddComment("Traceback table begin");
2066   // Begin with a fullword of zero.
2067   OutStreamer->emitIntValueInHexWithPadding(0, 4 /*size*/);
2068 
2069   SmallString<128> CommentString;
2070   raw_svector_ostream CommentOS(CommentString);
2071 
2072   auto EmitComment = [&]() {
2073     OutStreamer->AddComment(CommentOS.str());
2074     CommentString.clear();
2075   };
2076 
2077   auto EmitCommentAndValue = [&](uint64_t Value, int Size) {
2078     EmitComment();
2079     OutStreamer->emitIntValueInHexWithPadding(Value, Size);
2080   };
2081 
2082   unsigned int Version = 0;
2083   CommentOS << "Version = " << Version;
2084   EmitCommentAndValue(Version, 1);
2085 
2086   // There is a lack of information in the IR to assist with determining the
2087   // source language. AIX exception handling mechanism would only search for
2088   // personality routine and LSDA area when such language supports exception
2089   // handling. So to be conservatively correct and allow runtime to do its job,
2090   // we need to set it to C++ for now.
2091   TracebackTable::LanguageID LanguageIdentifier =
2092       TracebackTable::CPlusPlus; // C++
2093 
2094   CommentOS << "Language = "
2095             << getNameForTracebackTableLanguageId(LanguageIdentifier);
2096   EmitCommentAndValue(LanguageIdentifier, 1);
2097 
2098   //  This is only populated for the third and fourth bytes.
2099   uint32_t FirstHalfOfMandatoryField = 0;
2100 
2101   // Emit the 3rd byte of the mandatory field.
2102 
2103   // We always set traceback offset bit to true.
2104   FirstHalfOfMandatoryField |= TracebackTable::HasTraceBackTableOffsetMask;
2105 
2106   const PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
2107   const MachineRegisterInfo &MRI = MF->getRegInfo();
2108 
2109   // Check the function uses floating-point processor instructions or not
2110   for (unsigned Reg = PPC::F0; Reg <= PPC::F31; ++Reg) {
2111     if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2112       FirstHalfOfMandatoryField |= TracebackTable::IsFloatingPointPresentMask;
2113       break;
2114     }
2115   }
2116 
2117 #define GENBOOLCOMMENT(Prefix, V, Field)                                       \
2118   CommentOS << (Prefix) << ((V) & (TracebackTable::Field##Mask) ? "+" : "-")   \
2119             << #Field
2120 
2121 #define GENVALUECOMMENT(PrefixAndName, V, Field)                               \
2122   CommentOS << (PrefixAndName) << " = "                                        \
2123             << static_cast<unsigned>(((V) & (TracebackTable::Field##Mask)) >>  \
2124                                      (TracebackTable::Field##Shift))
2125 
2126   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsGlobaLinkage);
2127   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsOutOfLineEpilogOrPrologue);
2128   EmitComment();
2129 
2130   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasTraceBackTableOffset);
2131   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsInternalProcedure);
2132   EmitComment();
2133 
2134   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasControlledStorage);
2135   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsTOCless);
2136   EmitComment();
2137 
2138   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsFloatingPointPresent);
2139   EmitComment();
2140   GENBOOLCOMMENT("", FirstHalfOfMandatoryField,
2141                  IsFloatingPointOperationLogOrAbortEnabled);
2142   EmitComment();
2143 
2144   OutStreamer->emitIntValueInHexWithPadding(
2145       (FirstHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2146 
2147   // Set the 4th byte of the mandatory field.
2148   FirstHalfOfMandatoryField |= TracebackTable::IsFunctionNamePresentMask;
2149 
2150   const PPCRegisterInfo *RegInfo =
2151       static_cast<const PPCRegisterInfo *>(Subtarget->getRegisterInfo());
2152   Register FrameReg = RegInfo->getFrameRegister(*MF);
2153   if (FrameReg == (Subtarget->isPPC64() ? PPC::X31 : PPC::R31))
2154     FirstHalfOfMandatoryField |= TracebackTable::IsAllocaUsedMask;
2155 
2156   const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
2157   if (!MustSaveCRs.empty())
2158     FirstHalfOfMandatoryField |= TracebackTable::IsCRSavedMask;
2159 
2160   if (FI->mustSaveLR())
2161     FirstHalfOfMandatoryField |= TracebackTable::IsLRSavedMask;
2162 
2163   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsInterruptHandler);
2164   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsFunctionNamePresent);
2165   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsAllocaUsed);
2166   EmitComment();
2167   GENVALUECOMMENT("OnConditionDirective", FirstHalfOfMandatoryField,
2168                   OnConditionDirective);
2169   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsCRSaved);
2170   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsLRSaved);
2171   EmitComment();
2172   OutStreamer->emitIntValueInHexWithPadding((FirstHalfOfMandatoryField & 0xff),
2173                                             1);
2174 
2175   // Set the 5th byte of mandatory field.
2176   uint32_t SecondHalfOfMandatoryField = 0;
2177 
2178   // Always store back chain.
2179   SecondHalfOfMandatoryField |= TracebackTable::IsBackChainStoredMask;
2180 
2181   uint32_t FPRSaved = 0;
2182   for (unsigned Reg = PPC::F14; Reg <= PPC::F31; ++Reg) {
2183     if (MRI.isPhysRegModified(Reg)) {
2184       FPRSaved = PPC::F31 - Reg + 1;
2185       break;
2186     }
2187   }
2188   SecondHalfOfMandatoryField |= (FPRSaved << TracebackTable::FPRSavedShift) &
2189                                 TracebackTable::FPRSavedMask;
2190   GENBOOLCOMMENT("", SecondHalfOfMandatoryField, IsBackChainStored);
2191   GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, IsFixup);
2192   GENVALUECOMMENT(", NumOfFPRsSaved", SecondHalfOfMandatoryField, FPRSaved);
2193   EmitComment();
2194   OutStreamer->emitIntValueInHexWithPadding(
2195       (SecondHalfOfMandatoryField & 0xff000000) >> 24, 1);
2196 
2197   // Set the 6th byte of mandatory field.
2198 
2199   // Check whether has Vector Instruction,We only treat instructions uses vector
2200   // register as vector instructions.
2201   bool HasVectorInst = false;
2202   for (unsigned Reg = PPC::V0; Reg <= PPC::V31; ++Reg)
2203     if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2204       // Has VMX instruction.
2205       HasVectorInst = true;
2206       break;
2207     }
2208 
2209   if (FI->hasVectorParms() || HasVectorInst)
2210     SecondHalfOfMandatoryField |= TracebackTable::HasVectorInfoMask;
2211 
2212   uint16_t NumOfVRSaved = getNumberOfVRSaved();
2213   bool ShouldEmitEHBlock =
2214       TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) || NumOfVRSaved > 0;
2215 
2216   if (ShouldEmitEHBlock)
2217     SecondHalfOfMandatoryField |= TracebackTable::HasExtensionTableMask;
2218 
2219   uint32_t GPRSaved = 0;
2220 
2221   // X13 is reserved under 64-bit environment.
2222   unsigned GPRBegin = Subtarget->isPPC64() ? PPC::X14 : PPC::R13;
2223   unsigned GPREnd = Subtarget->isPPC64() ? PPC::X31 : PPC::R31;
2224 
2225   for (unsigned Reg = GPRBegin; Reg <= GPREnd; ++Reg) {
2226     if (MRI.isPhysRegModified(Reg)) {
2227       GPRSaved = GPREnd - Reg + 1;
2228       break;
2229     }
2230   }
2231 
2232   SecondHalfOfMandatoryField |= (GPRSaved << TracebackTable::GPRSavedShift) &
2233                                 TracebackTable::GPRSavedMask;
2234 
2235   GENBOOLCOMMENT("", SecondHalfOfMandatoryField, HasExtensionTable);
2236   GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasVectorInfo);
2237   GENVALUECOMMENT(", NumOfGPRsSaved", SecondHalfOfMandatoryField, GPRSaved);
2238   EmitComment();
2239   OutStreamer->emitIntValueInHexWithPadding(
2240       (SecondHalfOfMandatoryField & 0x00ff0000) >> 16, 1);
2241 
2242   // Set the 7th byte of mandatory field.
2243   uint32_t NumberOfFixedParms = FI->getFixedParmsNum();
2244   SecondHalfOfMandatoryField |=
2245       (NumberOfFixedParms << TracebackTable::NumberOfFixedParmsShift) &
2246       TracebackTable::NumberOfFixedParmsMask;
2247   GENVALUECOMMENT("NumberOfFixedParms", SecondHalfOfMandatoryField,
2248                   NumberOfFixedParms);
2249   EmitComment();
2250   OutStreamer->emitIntValueInHexWithPadding(
2251       (SecondHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2252 
2253   // Set the 8th byte of mandatory field.
2254 
2255   // Always set parameter on stack.
2256   SecondHalfOfMandatoryField |= TracebackTable::HasParmsOnStackMask;
2257 
2258   uint32_t NumberOfFPParms = FI->getFloatingPointParmsNum();
2259   SecondHalfOfMandatoryField |=
2260       (NumberOfFPParms << TracebackTable::NumberOfFloatingPointParmsShift) &
2261       TracebackTable::NumberOfFloatingPointParmsMask;
2262 
2263   GENVALUECOMMENT("NumberOfFPParms", SecondHalfOfMandatoryField,
2264                   NumberOfFloatingPointParms);
2265   GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasParmsOnStack);
2266   EmitComment();
2267   OutStreamer->emitIntValueInHexWithPadding(SecondHalfOfMandatoryField & 0xff,
2268                                             1);
2269 
2270   // Generate the optional fields of traceback table.
2271 
2272   // Parameter type.
2273   if (NumberOfFixedParms || NumberOfFPParms) {
2274     uint32_t ParmsTypeValue = FI->getParmsType();
2275 
2276     Expected<SmallString<32>> ParmsType =
2277         FI->hasVectorParms()
2278             ? XCOFF::parseParmsTypeWithVecInfo(
2279                   ParmsTypeValue, NumberOfFixedParms, NumberOfFPParms,
2280                   FI->getVectorParmsNum())
2281             : XCOFF::parseParmsType(ParmsTypeValue, NumberOfFixedParms,
2282                                     NumberOfFPParms);
2283 
2284     assert(ParmsType && toString(ParmsType.takeError()).c_str());
2285     if (ParmsType) {
2286       CommentOS << "Parameter type = " << ParmsType.get();
2287       EmitComment();
2288     }
2289     OutStreamer->emitIntValueInHexWithPadding(ParmsTypeValue,
2290                                               sizeof(ParmsTypeValue));
2291   }
2292   // Traceback table offset.
2293   OutStreamer->AddComment("Function size");
2294   if (FirstHalfOfMandatoryField & TracebackTable::HasTraceBackTableOffsetMask) {
2295     MCSymbol *FuncSectSym = getObjFileLowering().getFunctionEntryPointSymbol(
2296         &(MF->getFunction()), TM);
2297     OutStreamer->emitAbsoluteSymbolDiff(FuncEnd, FuncSectSym, 4);
2298   }
2299 
2300   // Since we unset the Int_Handler.
2301   if (FirstHalfOfMandatoryField & TracebackTable::IsInterruptHandlerMask)
2302     report_fatal_error("Hand_Mask not implement yet");
2303 
2304   if (FirstHalfOfMandatoryField & TracebackTable::HasControlledStorageMask)
2305     report_fatal_error("Ctl_Info not implement yet");
2306 
2307   if (FirstHalfOfMandatoryField & TracebackTable::IsFunctionNamePresentMask) {
2308     StringRef Name = MF->getName().substr(0, INT16_MAX);
2309     int16_t NameLength = Name.size();
2310     CommentOS << "Function name len = "
2311               << static_cast<unsigned int>(NameLength);
2312     EmitCommentAndValue(NameLength, 2);
2313     OutStreamer->AddComment("Function Name");
2314     OutStreamer->emitBytes(Name);
2315   }
2316 
2317   if (FirstHalfOfMandatoryField & TracebackTable::IsAllocaUsedMask) {
2318     uint8_t AllocReg = XCOFF::AllocRegNo;
2319     OutStreamer->AddComment("AllocaUsed");
2320     OutStreamer->emitIntValueInHex(AllocReg, sizeof(AllocReg));
2321   }
2322 
2323   if (SecondHalfOfMandatoryField & TracebackTable::HasVectorInfoMask) {
2324     uint16_t VRData = 0;
2325     if (NumOfVRSaved) {
2326       // Number of VRs saved.
2327       VRData |= (NumOfVRSaved << TracebackTable::NumberOfVRSavedShift) &
2328                 TracebackTable::NumberOfVRSavedMask;
2329       // This bit is supposed to set only when the special register
2330       // VRSAVE is saved on stack.
2331       // However, IBM XL compiler sets the bit when any vector registers
2332       // are saved on the stack. We will follow XL's behavior on AIX
2333       // so that we don't get surprise behavior change for C code.
2334       VRData |= TracebackTable::IsVRSavedOnStackMask;
2335     }
2336 
2337     // Set has_varargs.
2338     if (FI->getVarArgsFrameIndex())
2339       VRData |= TracebackTable::HasVarArgsMask;
2340 
2341     // Vector parameters number.
2342     unsigned VectorParmsNum = FI->getVectorParmsNum();
2343     VRData |= (VectorParmsNum << TracebackTable::NumberOfVectorParmsShift) &
2344               TracebackTable::NumberOfVectorParmsMask;
2345 
2346     if (HasVectorInst)
2347       VRData |= TracebackTable::HasVMXInstructionMask;
2348 
2349     GENVALUECOMMENT("NumOfVRsSaved", VRData, NumberOfVRSaved);
2350     GENBOOLCOMMENT(", ", VRData, IsVRSavedOnStack);
2351     GENBOOLCOMMENT(", ", VRData, HasVarArgs);
2352     EmitComment();
2353     OutStreamer->emitIntValueInHexWithPadding((VRData & 0xff00) >> 8, 1);
2354 
2355     GENVALUECOMMENT("NumOfVectorParams", VRData, NumberOfVectorParms);
2356     GENBOOLCOMMENT(", ", VRData, HasVMXInstruction);
2357     EmitComment();
2358     OutStreamer->emitIntValueInHexWithPadding(VRData & 0x00ff, 1);
2359 
2360     uint32_t VecParmTypeValue = FI->getVecExtParmsType();
2361 
2362     Expected<SmallString<32>> VecParmsType =
2363         XCOFF::parseVectorParmsType(VecParmTypeValue, VectorParmsNum);
2364     assert(VecParmsType && toString(VecParmsType.takeError()).c_str());
2365     if (VecParmsType) {
2366       CommentOS << "Vector Parameter type = " << VecParmsType.get();
2367       EmitComment();
2368     }
2369     OutStreamer->emitIntValueInHexWithPadding(VecParmTypeValue,
2370                                               sizeof(VecParmTypeValue));
2371     // Padding 2 bytes.
2372     CommentOS << "Padding";
2373     EmitCommentAndValue(0, 2);
2374   }
2375 
2376   uint8_t ExtensionTableFlag = 0;
2377   if (SecondHalfOfMandatoryField & TracebackTable::HasExtensionTableMask) {
2378     if (ShouldEmitEHBlock)
2379       ExtensionTableFlag |= ExtendedTBTableFlag::TB_EH_INFO;
2380     if (EnableSSPCanaryBitInTB &&
2381         TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(MF))
2382       ExtensionTableFlag |= ExtendedTBTableFlag::TB_SSP_CANARY;
2383 
2384     CommentOS << "ExtensionTableFlag = "
2385               << getExtendedTBTableFlagString(ExtensionTableFlag);
2386     EmitCommentAndValue(ExtensionTableFlag, sizeof(ExtensionTableFlag));
2387   }
2388 
2389   if (ExtensionTableFlag & ExtendedTBTableFlag::TB_EH_INFO) {
2390     auto &Ctx = OutStreamer->getContext();
2391     MCSymbol *EHInfoSym =
2392         TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF);
2393     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(EHInfoSym);
2394     const MCSymbol *TOCBaseSym =
2395         cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2396             ->getQualNameSymbol();
2397     const MCExpr *Exp =
2398         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx),
2399                                 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
2400 
2401     const DataLayout &DL = getDataLayout();
2402     OutStreamer->emitValueToAlignment(Align(4));
2403     OutStreamer->AddComment("EHInfo Table");
2404     OutStreamer->emitValue(Exp, DL.getPointerSize());
2405   }
2406 #undef GENBOOLCOMMENT
2407 #undef GENVALUECOMMENT
2408 }
2409 
isSpecialLLVMGlobalArrayToSkip(const GlobalVariable * GV)2410 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) {
2411   return GV->hasAppendingLinkage() &&
2412          StringSwitch<bool>(GV->getName())
2413              // TODO: Linker could still eliminate the GV if we just skip
2414              // handling llvm.used array. Skipping them for now until we or the
2415              // AIX OS team come up with a good solution.
2416              .Case("llvm.used", true)
2417              // It's correct to just skip llvm.compiler.used array here.
2418              .Case("llvm.compiler.used", true)
2419              .Default(false);
2420 }
2421 
isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable * GV)2422 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) {
2423   return StringSwitch<bool>(GV->getName())
2424       .Cases("llvm.global_ctors", "llvm.global_dtors", true)
2425       .Default(false);
2426 }
2427 
getAliasOffset(const Constant * C)2428 uint64_t PPCAIXAsmPrinter::getAliasOffset(const Constant *C) {
2429   if (auto *GA = dyn_cast<GlobalAlias>(C))
2430     return getAliasOffset(GA->getAliasee());
2431   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2432     const MCExpr *LowC = lowerConstant(CE);
2433     const MCBinaryExpr *CBE = dyn_cast<MCBinaryExpr>(LowC);
2434     if (!CBE)
2435       return 0;
2436     if (CBE->getOpcode() != MCBinaryExpr::Add)
2437       report_fatal_error("Only adding an offset is supported now.");
2438     auto *RHS = dyn_cast<MCConstantExpr>(CBE->getRHS());
2439     if (!RHS)
2440       report_fatal_error("Unable to get the offset of alias.");
2441     return RHS->getValue();
2442   }
2443   return 0;
2444 }
2445 
emitGlobalVariable(const GlobalVariable * GV)2446 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
2447   // Special LLVM global arrays have been handled at the initialization.
2448   if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV))
2449     return;
2450 
2451   // If the Global Variable has the toc-data attribute, it needs to be emitted
2452   // when we emit the .toc section.
2453   if (GV->hasAttribute("toc-data")) {
2454     TOCDataGlobalVars.push_back(GV);
2455     return;
2456   }
2457 
2458   emitGlobalVariableHelper(GV);
2459 }
2460 
emitGlobalVariableHelper(const GlobalVariable * GV)2461 void PPCAIXAsmPrinter::emitGlobalVariableHelper(const GlobalVariable *GV) {
2462   assert(!GV->getName().startswith("llvm.") &&
2463          "Unhandled intrinsic global variable.");
2464 
2465   if (GV->hasComdat())
2466     report_fatal_error("COMDAT not yet supported by AIX.");
2467 
2468   MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
2469 
2470   if (GV->isDeclarationForLinker()) {
2471     emitLinkage(GV, GVSym);
2472     return;
2473   }
2474 
2475   SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
2476   if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly() &&
2477       !GVKind.isThreadLocal()) // Checks for both ThreadData and ThreadBSS.
2478     report_fatal_error("Encountered a global variable kind that is "
2479                        "not supported yet.");
2480 
2481   // Print GV in verbose mode
2482   if (isVerbose()) {
2483     if (GV->hasInitializer()) {
2484       GV->printAsOperand(OutStreamer->getCommentOS(),
2485                          /*PrintType=*/false, GV->getParent());
2486       OutStreamer->getCommentOS() << '\n';
2487     }
2488   }
2489 
2490   MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
2491       getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
2492 
2493   // Switch to the containing csect.
2494   OutStreamer->switchSection(Csect);
2495 
2496   const DataLayout &DL = GV->getParent()->getDataLayout();
2497 
2498   // Handle common and zero-initialized local symbols.
2499   if (GV->hasCommonLinkage() || GVKind.isBSSLocal() ||
2500       GVKind.isThreadBSSLocal()) {
2501     Align Alignment = GV->getAlign().value_or(DL.getPreferredAlign(GV));
2502     uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
2503     GVSym->setStorageClass(
2504         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV));
2505 
2506     if (GVKind.isBSSLocal() || GVKind.isThreadBSSLocal())
2507       OutStreamer->emitXCOFFLocalCommonSymbol(
2508           OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
2509           GVSym, Alignment);
2510     else
2511       OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
2512     return;
2513   }
2514 
2515   MCSymbol *EmittedInitSym = GVSym;
2516 
2517   // Emit linkage for the global variable and its aliases.
2518   emitLinkage(GV, EmittedInitSym);
2519   for (const GlobalAlias *GA : GOAliasMap[GV])
2520     emitLinkage(GA, getSymbol(GA));
2521 
2522   emitAlignment(getGVAlignment(GV, DL), GV);
2523 
2524   // When -fdata-sections is enabled, every GlobalVariable will
2525   // be put into its own csect; therefore, label is not necessary here.
2526   if (!TM.getDataSections() || GV->hasSection())
2527     OutStreamer->emitLabel(EmittedInitSym);
2528 
2529   // No alias to emit.
2530   if (!GOAliasMap[GV].size()) {
2531     emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
2532     return;
2533   }
2534 
2535   // Aliases with the same offset should be aligned. Record the list of aliases
2536   // associated with the offset.
2537   AliasMapTy AliasList;
2538   for (const GlobalAlias *GA : GOAliasMap[GV])
2539     AliasList[getAliasOffset(GA->getAliasee())].push_back(GA);
2540 
2541   // Emit alias label and element value for global variable.
2542   emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer(),
2543                      &AliasList);
2544 }
2545 
emitFunctionDescriptor()2546 void PPCAIXAsmPrinter::emitFunctionDescriptor() {
2547   const DataLayout &DL = getDataLayout();
2548   const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
2549 
2550   MCSectionSubPair Current = OutStreamer->getCurrentSection();
2551   // Emit function descriptor.
2552   OutStreamer->switchSection(
2553       cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
2554 
2555   // Emit aliasing label for function descriptor csect.
2556   for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
2557     OutStreamer->emitLabel(getSymbol(Alias));
2558 
2559   // Emit function entry point address.
2560   OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
2561                          PointerSize);
2562   // Emit TOC base address.
2563   const MCSymbol *TOCBaseSym =
2564       cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2565           ->getQualNameSymbol();
2566   OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
2567                          PointerSize);
2568   // Emit a null environment pointer.
2569   OutStreamer->emitIntValue(0, PointerSize);
2570 
2571   OutStreamer->switchSection(Current.first, Current.second);
2572 }
2573 
emitFunctionEntryLabel()2574 void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
2575   // It's not necessary to emit the label when we have individual
2576   // function in its own csect.
2577   if (!TM.getFunctionSections())
2578     PPCAsmPrinter::emitFunctionEntryLabel();
2579 
2580   // Emit aliasing label for function entry point label.
2581   for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
2582     OutStreamer->emitLabel(
2583         getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
2584 }
2585 
emitPGORefs()2586 void PPCAIXAsmPrinter::emitPGORefs() {
2587   if (OutContext.hasXCOFFSection(
2588           "__llvm_prf_cnts",
2589           XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) {
2590     MCSection *CntsSection = OutContext.getXCOFFSection(
2591         "__llvm_prf_cnts", SectionKind::getData(),
2592         XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD),
2593         /*MultiSymbolsAllowed*/ true);
2594 
2595     OutStreamer->switchSection(CntsSection);
2596     if (OutContext.hasXCOFFSection(
2597             "__llvm_prf_data",
2598             XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD)))
2599       OutStreamer->emitXCOFFRefDirective("__llvm_prf_data[RW]");
2600     if (OutContext.hasXCOFFSection(
2601             "__llvm_prf_names",
2602             XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD)))
2603       OutStreamer->emitXCOFFRefDirective("__llvm_prf_names[RO]");
2604     if (OutContext.hasXCOFFSection(
2605             "__llvm_prf_vnds",
2606             XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD)))
2607       OutStreamer->emitXCOFFRefDirective("__llvm_prf_vnds[RW]");
2608   }
2609 }
2610 
emitEndOfAsmFile(Module & M)2611 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
2612   // If there are no functions and there are no toc-data definitions in this
2613   // module, we will never need to reference the TOC base.
2614   if (M.empty() && TOCDataGlobalVars.empty())
2615     return;
2616 
2617   emitPGORefs();
2618 
2619   // Switch to section to emit TOC base.
2620   OutStreamer->switchSection(getObjFileLowering().getTOCBaseSection());
2621 
2622   PPCTargetStreamer *TS =
2623       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2624 
2625   for (auto &I : TOC) {
2626     MCSectionXCOFF *TCEntry;
2627     // Setup the csect for the current TC entry. If the variant kind is
2628     // VK_PPC_AIX_TLSGDM the entry represents the region handle, we create a
2629     // new symbol to prefix the name with a dot.
2630     if (I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM) {
2631       SmallString<128> Name;
2632       StringRef Prefix = ".";
2633       Name += Prefix;
2634       Name += cast<MCSymbolXCOFF>(I.first.first)->getSymbolTableName();
2635       MCSymbol *S = OutContext.getOrCreateSymbol(Name);
2636       TCEntry = cast<MCSectionXCOFF>(
2637           getObjFileLowering().getSectionForTOCEntry(S, TM));
2638     } else {
2639       TCEntry = cast<MCSectionXCOFF>(
2640           getObjFileLowering().getSectionForTOCEntry(I.first.first, TM));
2641     }
2642     OutStreamer->switchSection(TCEntry);
2643 
2644     OutStreamer->emitLabel(I.second);
2645     TS->emitTCEntry(*I.first.first, I.first.second);
2646   }
2647 
2648   for (const auto *GV : TOCDataGlobalVars)
2649     emitGlobalVariableHelper(GV);
2650 }
2651 
doInitialization(Module & M)2652 bool PPCAIXAsmPrinter::doInitialization(Module &M) {
2653   const bool Result = PPCAsmPrinter::doInitialization(M);
2654 
2655   auto setCsectAlignment = [this](const GlobalObject *GO) {
2656     // Declarations have 0 alignment which is set by default.
2657     if (GO->isDeclarationForLinker())
2658       return;
2659 
2660     SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
2661     MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
2662         getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
2663 
2664     Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
2665     Csect->ensureMinAlignment(GOAlign);
2666   };
2667 
2668   // We need to know, up front, the alignment of csects for the assembly path,
2669   // because once a .csect directive gets emitted, we could not change the
2670   // alignment value on it.
2671   for (const auto &G : M.globals()) {
2672     if (isSpecialLLVMGlobalArrayToSkip(&G))
2673       continue;
2674 
2675     if (isSpecialLLVMGlobalArrayForStaticInit(&G)) {
2676       // Generate a format indicator and a unique module id to be a part of
2677       // the sinit and sterm function names.
2678       if (FormatIndicatorAndUniqueModId.empty()) {
2679         std::string UniqueModuleId = getUniqueModuleId(&M);
2680         if (UniqueModuleId != "")
2681           // TODO: Use source file full path to generate the unique module id
2682           // and add a format indicator as a part of function name in case we
2683           // will support more than one format.
2684           FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
2685         else
2686           // Use the Pid and current time as the unique module id when we cannot
2687           // generate one based on a module's strong external symbols.
2688           // FIXME: Adjust the comment accordingly after we use source file full
2689           // path instead.
2690           FormatIndicatorAndUniqueModId =
2691               "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) +
2692               "_" + llvm::itostr(time(nullptr));
2693       }
2694 
2695       emitSpecialLLVMGlobal(&G);
2696       continue;
2697     }
2698 
2699     setCsectAlignment(&G);
2700   }
2701 
2702   for (const auto &F : M)
2703     setCsectAlignment(&F);
2704 
2705   // Construct an aliasing list for each GlobalObject.
2706   for (const auto &Alias : M.aliases()) {
2707     const GlobalObject *Base = Alias.getAliaseeObject();
2708     if (!Base)
2709       report_fatal_error(
2710           "alias without a base object is not yet supported on AIX");
2711     GOAliasMap[Base].push_back(&Alias);
2712   }
2713 
2714   return Result;
2715 }
2716 
emitInstruction(const MachineInstr * MI)2717 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
2718   switch (MI->getOpcode()) {
2719   default:
2720     break;
2721   case PPC::TW:
2722   case PPC::TWI:
2723   case PPC::TD:
2724   case PPC::TDI: {
2725     if (MI->getNumOperands() < 5)
2726       break;
2727     const MachineOperand &LangMO = MI->getOperand(3);
2728     const MachineOperand &ReasonMO = MI->getOperand(4);
2729     if (!LangMO.isImm() || !ReasonMO.isImm())
2730       break;
2731     MCSymbol *TempSym = OutContext.createNamedTempSymbol();
2732     OutStreamer->emitLabel(TempSym);
2733     OutStreamer->emitXCOFFExceptDirective(CurrentFnSym, TempSym,
2734                  LangMO.getImm(), ReasonMO.getImm(),
2735                  Subtarget->isPPC64() ? MI->getMF()->getInstructionCount() * 8 :
2736                  MI->getMF()->getInstructionCount() * 4,
2737 		 MMI->hasDebugInfo());
2738     break;
2739   }
2740   case PPC::GETtlsADDR64AIX:
2741   case PPC::GETtlsADDR32AIX: {
2742     // The reference to .__tls_get_addr is unknown to the assembler
2743     // so we need to emit an external symbol reference.
2744     MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext);
2745     ExtSymSDNodeSymbols.insert(TlsGetAddr);
2746     break;
2747   }
2748   case PPC::BL8:
2749   case PPC::BL:
2750   case PPC::BL8_NOP:
2751   case PPC::BL_NOP: {
2752     const MachineOperand &MO = MI->getOperand(0);
2753     if (MO.isSymbol()) {
2754       MCSymbolXCOFF *S =
2755           cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
2756       ExtSymSDNodeSymbols.insert(S);
2757     }
2758   } break;
2759   case PPC::BL_TLS:
2760   case PPC::BL8_TLS:
2761   case PPC::BL8_TLS_:
2762   case PPC::BL8_NOP_TLS:
2763     report_fatal_error("TLS call not yet implemented");
2764   case PPC::TAILB:
2765   case PPC::TAILB8:
2766   case PPC::TAILBA:
2767   case PPC::TAILBA8:
2768   case PPC::TAILBCTR:
2769   case PPC::TAILBCTR8:
2770     if (MI->getOperand(0).isSymbol())
2771       report_fatal_error("Tail call for extern symbol not yet supported.");
2772     break;
2773   case PPC::DST:
2774   case PPC::DST64:
2775   case PPC::DSTT:
2776   case PPC::DSTT64:
2777   case PPC::DSTST:
2778   case PPC::DSTST64:
2779   case PPC::DSTSTT:
2780   case PPC::DSTSTT64:
2781     EmitToStreamer(
2782         *OutStreamer,
2783         MCInstBuilder(PPC::ORI).addReg(PPC::R0).addReg(PPC::R0).addImm(0));
2784     return;
2785   }
2786   return PPCAsmPrinter::emitInstruction(MI);
2787 }
2788 
doFinalization(Module & M)2789 bool PPCAIXAsmPrinter::doFinalization(Module &M) {
2790   // Do streamer related finalization for DWARF.
2791   if (!MAI->usesDwarfFileAndLocDirectives() && MMI->hasDebugInfo())
2792     OutStreamer->doFinalizationAtSectionEnd(
2793         OutStreamer->getContext().getObjectFileInfo()->getTextSection());
2794 
2795   for (MCSymbol *Sym : ExtSymSDNodeSymbols)
2796     OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
2797   return PPCAsmPrinter::doFinalization(M);
2798 }
2799 
mapToSinitPriority(int P)2800 static unsigned mapToSinitPriority(int P) {
2801   if (P < 0 || P > 65535)
2802     report_fatal_error("invalid init priority");
2803 
2804   if (P <= 20)
2805     return P;
2806 
2807   if (P < 81)
2808     return 20 + (P - 20) * 16;
2809 
2810   if (P <= 1124)
2811     return 1004 + (P - 81);
2812 
2813   if (P < 64512)
2814     return 2047 + (P - 1124) * 33878;
2815 
2816   return 2147482625u + (P - 64512);
2817 }
2818 
convertToSinitPriority(int Priority)2819 static std::string convertToSinitPriority(int Priority) {
2820   // This helper function converts clang init priority to values used in sinit
2821   // and sterm functions.
2822   //
2823   // The conversion strategies are:
2824   // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm
2825   // reserved priority range [0, 1023] by
2826   // - directly mapping the first 21 and the last 20 elements of the ranges
2827   // - linear interpolating the intermediate values with a step size of 16.
2828   //
2829   // We map the non reserved clang/gnu priority range of [101, 65535] into the
2830   // sinit/sterm priority range [1024, 2147483648] by:
2831   // - directly mapping the first and the last 1024 elements of the ranges
2832   // - linear interpolating the intermediate values with a step size of 33878.
2833   unsigned int P = mapToSinitPriority(Priority);
2834 
2835   std::string PrioritySuffix;
2836   llvm::raw_string_ostream os(PrioritySuffix);
2837   os << llvm::format_hex_no_prefix(P, 8);
2838   os.flush();
2839   return PrioritySuffix;
2840 }
2841 
emitXXStructorList(const DataLayout & DL,const Constant * List,bool IsCtor)2842 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
2843                                           const Constant *List, bool IsCtor) {
2844   SmallVector<Structor, 8> Structors;
2845   preprocessXXStructorList(DL, List, Structors);
2846   if (Structors.empty())
2847     return;
2848 
2849   unsigned Index = 0;
2850   for (Structor &S : Structors) {
2851     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func))
2852       S.Func = CE->getOperand(0);
2853 
2854     llvm::GlobalAlias::create(
2855         GlobalValue::ExternalLinkage,
2856         (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
2857             llvm::Twine(convertToSinitPriority(S.Priority)) +
2858             llvm::Twine("_", FormatIndicatorAndUniqueModId) +
2859             llvm::Twine("_", llvm::utostr(Index++)),
2860         cast<Function>(S.Func));
2861   }
2862 }
2863 
emitTTypeReference(const GlobalValue * GV,unsigned Encoding)2864 void PPCAIXAsmPrinter::emitTTypeReference(const GlobalValue *GV,
2865                                           unsigned Encoding) {
2866   if (GV) {
2867     MCSymbol *TypeInfoSym = TM.getSymbol(GV);
2868     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(TypeInfoSym);
2869     const MCSymbol *TOCBaseSym =
2870         cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2871             ->getQualNameSymbol();
2872     auto &Ctx = OutStreamer->getContext();
2873     const MCExpr *Exp =
2874         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx),
2875                                 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
2876     OutStreamer->emitValue(Exp, GetSizeOfEncodedValue(Encoding));
2877   } else
2878     OutStreamer->emitIntValue(0, GetSizeOfEncodedValue(Encoding));
2879 }
2880 
2881 // Return a pass that prints the PPC assembly code for a MachineFunction to the
2882 // given output stream.
2883 static AsmPrinter *
createPPCAsmPrinterPass(TargetMachine & tm,std::unique_ptr<MCStreamer> && Streamer)2884 createPPCAsmPrinterPass(TargetMachine &tm,
2885                         std::unique_ptr<MCStreamer> &&Streamer) {
2886   if (tm.getTargetTriple().isOSAIX())
2887     return new PPCAIXAsmPrinter(tm, std::move(Streamer));
2888 
2889   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
2890 }
2891 
2892 // Force static initialization.
LLVMInitializePowerPCAsmPrinter()2893 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
2894   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
2895                                      createPPCAsmPrinterPass);
2896   TargetRegistry::RegisterAsmPrinter(getThePPC32LETarget(),
2897                                      createPPCAsmPrinterPass);
2898   TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
2899                                      createPPCAsmPrinterPass);
2900   TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
2901                                      createPPCAsmPrinterPass);
2902 }
2903