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/MachineFunction.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
40 #include "llvm/CodeGen/MachineOperand.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/StackMaps.h"
43 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/GlobalValue.h"
46 #include "llvm/IR/GlobalVariable.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/MC/MCAsmInfo.h"
49 #include "llvm/MC/MCContext.h"
50 #include "llvm/MC/MCDirectives.h"
51 #include "llvm/MC/MCExpr.h"
52 #include "llvm/MC/MCInst.h"
53 #include "llvm/MC/MCInstBuilder.h"
54 #include "llvm/MC/MCSectionELF.h"
55 #include "llvm/MC/MCSectionXCOFF.h"
56 #include "llvm/MC/MCStreamer.h"
57 #include "llvm/MC/MCSymbol.h"
58 #include "llvm/MC/MCSymbolELF.h"
59 #include "llvm/MC/MCSymbolXCOFF.h"
60 #include "llvm/MC/SectionKind.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CodeGen.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/Process.h"
66 #include "llvm/Support/TargetRegistry.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include "llvm/Target/TargetMachine.h"
69 #include "llvm/Transforms/Utils/ModuleUtils.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <memory>
74 #include <new>
75 
76 using namespace llvm;
77 
78 #define DEBUG_TYPE "asmprinter"
79 
80 namespace {
81 
82 class PPCAsmPrinter : public AsmPrinter {
83 protected:
84   MapVector<const MCSymbol *, MCSymbol *> TOC;
85   const PPCSubtarget *Subtarget = nullptr;
86   StackMaps SM;
87 
88 public:
89   explicit PPCAsmPrinter(TargetMachine &TM,
90                          std::unique_ptr<MCStreamer> Streamer)
91       : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
92 
93   StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
94 
95   MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym);
96 
97   bool doInitialization(Module &M) override {
98     if (!TOC.empty())
99       TOC.clear();
100     return AsmPrinter::doInitialization(M);
101   }
102 
103   void emitInstruction(const MachineInstr *MI) override;
104 
105   /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
106   /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
107   /// The \p MI would be INLINEASM ONLY.
108   void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
109 
110   void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
111   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
112                        const char *ExtraCode, raw_ostream &O) override;
113   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
114                              const char *ExtraCode, raw_ostream &O) override;
115 
116   void emitEndOfAsmFile(Module &M) override;
117 
118   void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
119   void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
120   void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
121   bool runOnMachineFunction(MachineFunction &MF) override {
122     Subtarget = &MF.getSubtarget<PPCSubtarget>();
123     bool Changed = AsmPrinter::runOnMachineFunction(MF);
124     emitXRayTable();
125     return Changed;
126   }
127 };
128 
129 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
130 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
131 public:
132   explicit PPCLinuxAsmPrinter(TargetMachine &TM,
133                               std::unique_ptr<MCStreamer> Streamer)
134       : PPCAsmPrinter(TM, std::move(Streamer)) {}
135 
136   StringRef getPassName() const override {
137     return "Linux PPC Assembly Printer";
138   }
139 
140   void emitStartOfAsmFile(Module &M) override;
141   void emitEndOfAsmFile(Module &) override;
142 
143   void emitFunctionEntryLabel() override;
144 
145   void emitFunctionBodyStart() override;
146   void emitFunctionBodyEnd() override;
147   void emitInstruction(const MachineInstr *MI) override;
148 };
149 
150 class PPCAIXAsmPrinter : public PPCAsmPrinter {
151 private:
152   /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern
153   /// linkage for them in AIX.
154   SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols;
155 
156   /// A format indicator and unique trailing identifier to form part of the
157   /// sinit/sterm function names.
158   std::string FormatIndicatorAndUniqueModId;
159 
160   static void ValidateGV(const GlobalVariable *GV);
161   // Record a list of GlobalAlias associated with a GlobalObject.
162   // This is used for AIX's extra-label-at-definition aliasing strategy.
163   DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>>
164       GOAliasMap;
165 
166 public:
167   PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
168       : PPCAsmPrinter(TM, std::move(Streamer)) {
169     if (MAI->isLittleEndian())
170       report_fatal_error(
171           "cannot create AIX PPC Assembly Printer for a little-endian target");
172   }
173 
174   StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
175 
176   bool doInitialization(Module &M) override;
177 
178   void emitXXStructorList(const DataLayout &DL, const Constant *List,
179                           bool IsCtor) override;
180 
181   void SetupMachineFunction(MachineFunction &MF) override;
182 
183   void emitGlobalVariable(const GlobalVariable *GV) override;
184 
185   void emitFunctionDescriptor() override;
186 
187   void emitFunctionEntryLabel() override;
188 
189   void emitEndOfAsmFile(Module &) override;
190 
191   void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
192 
193   void emitInstruction(const MachineInstr *MI) override;
194 
195   bool doFinalization(Module &M) override;
196 };
197 
198 } // end anonymous namespace
199 
200 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
201                                        raw_ostream &O) {
202   // Computing the address of a global symbol, not calling it.
203   const GlobalValue *GV = MO.getGlobal();
204   getSymbol(GV)->print(O, MAI);
205   printOffset(MO.getOffset(), O);
206 }
207 
208 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
209                                  raw_ostream &O) {
210   const DataLayout &DL = getDataLayout();
211   const MachineOperand &MO = MI->getOperand(OpNo);
212 
213   switch (MO.getType()) {
214   case MachineOperand::MO_Register: {
215     // The MI is INLINEASM ONLY and UseVSXReg is always false.
216     const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
217 
218     // Linux assembler (Others?) does not take register mnemonics.
219     // FIXME - What about special registers used in mfspr/mtspr?
220     O << PPCRegisterInfo::stripRegisterPrefix(RegName);
221     return;
222   }
223   case MachineOperand::MO_Immediate:
224     O << MO.getImm();
225     return;
226 
227   case MachineOperand::MO_MachineBasicBlock:
228     MO.getMBB()->getSymbol()->print(O, MAI);
229     return;
230   case MachineOperand::MO_ConstantPoolIndex:
231     O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
232       << MO.getIndex();
233     return;
234   case MachineOperand::MO_BlockAddress:
235     GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
236     return;
237   case MachineOperand::MO_GlobalAddress: {
238     PrintSymbolOperand(MO, O);
239     return;
240   }
241 
242   default:
243     O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
244     return;
245   }
246 }
247 
248 /// PrintAsmOperand - Print out an operand for an inline asm expression.
249 ///
250 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
251                                     const char *ExtraCode, raw_ostream &O) {
252   // Does this asm operand have a single letter operand modifier?
253   if (ExtraCode && ExtraCode[0]) {
254     if (ExtraCode[1] != 0) return true; // Unknown modifier.
255 
256     switch (ExtraCode[0]) {
257     default:
258       // See if this is a generic print operand
259       return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
260     case 'L': // Write second word of DImode reference.
261       // Verify that this operand has two consecutive registers.
262       if (!MI->getOperand(OpNo).isReg() ||
263           OpNo+1 == MI->getNumOperands() ||
264           !MI->getOperand(OpNo+1).isReg())
265         return true;
266       ++OpNo;   // Return the high-part.
267       break;
268     case 'I':
269       // Write 'i' if an integer constant, otherwise nothing.  Used to print
270       // addi vs add, etc.
271       if (MI->getOperand(OpNo).isImm())
272         O << "i";
273       return false;
274     case 'x':
275       if(!MI->getOperand(OpNo).isReg())
276         return true;
277       // This operand uses VSX numbering.
278       // If the operand is a VMX register, convert it to a VSX register.
279       Register Reg = MI->getOperand(OpNo).getReg();
280       if (PPCInstrInfo::isVRRegister(Reg))
281         Reg = PPC::VSX32 + (Reg - PPC::V0);
282       else if (PPCInstrInfo::isVFRegister(Reg))
283         Reg = PPC::VSX32 + (Reg - PPC::VF0);
284       const char *RegName;
285       RegName = PPCInstPrinter::getRegisterName(Reg);
286       RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
287       O << RegName;
288       return false;
289     }
290   }
291 
292   printOperand(MI, OpNo, O);
293   return false;
294 }
295 
296 // At the moment, all inline asm memory operands are a single register.
297 // In any case, the output of this routine should always be just one
298 // assembler operand.
299 
300 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
301                                           const char *ExtraCode,
302                                           raw_ostream &O) {
303   if (ExtraCode && ExtraCode[0]) {
304     if (ExtraCode[1] != 0) return true; // Unknown modifier.
305 
306     switch (ExtraCode[0]) {
307     default: return true;  // Unknown modifier.
308     case 'L': // A memory reference to the upper word of a double word op.
309       O << getDataLayout().getPointerSize() << "(";
310       printOperand(MI, OpNo, O);
311       O << ")";
312       return false;
313     case 'y': // A memory reference for an X-form instruction
314       O << "0, ";
315       printOperand(MI, OpNo, O);
316       return false;
317     case 'U': // Print 'u' for update form.
318     case 'X': // Print 'x' for indexed form.
319       // FIXME: Currently for PowerPC memory operands are always loaded
320       // into a register, so we never get an update or indexed form.
321       // This is bad even for offset forms, since even if we know we
322       // have a value in -16(r1), we will generate a load into r<n>
323       // and then load from 0(r<n>).  Until that issue is fixed,
324       // tolerate 'U' and 'X' but don't output anything.
325       assert(MI->getOperand(OpNo).isReg());
326       return false;
327     }
328   }
329 
330   assert(MI->getOperand(OpNo).isReg());
331   O << "0(";
332   printOperand(MI, OpNo, O);
333   O << ")";
334   return false;
335 }
336 
337 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
338 /// exists for it.  If not, create one.  Then return a symbol that references
339 /// the TOC entry.
340 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym) {
341   MCSymbol *&TOCEntry = TOC[Sym];
342   if (!TOCEntry)
343     TOCEntry = createTempSymbol("C");
344   return TOCEntry;
345 }
346 
347 void PPCAsmPrinter::emitEndOfAsmFile(Module &M) {
348   emitStackMaps(SM);
349 }
350 
351 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
352   unsigned NumNOPBytes = MI.getOperand(1).getImm();
353 
354   auto &Ctx = OutStreamer->getContext();
355   MCSymbol *MILabel = Ctx.createTempSymbol();
356   OutStreamer->emitLabel(MILabel);
357 
358   SM.recordStackMap(*MILabel, MI);
359   assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
360 
361   // Scan ahead to trim the shadow.
362   const MachineBasicBlock &MBB = *MI.getParent();
363   MachineBasicBlock::const_iterator MII(MI);
364   ++MII;
365   while (NumNOPBytes > 0) {
366     if (MII == MBB.end() || MII->isCall() ||
367         MII->getOpcode() == PPC::DBG_VALUE ||
368         MII->getOpcode() == TargetOpcode::PATCHPOINT ||
369         MII->getOpcode() == TargetOpcode::STACKMAP)
370       break;
371     ++MII;
372     NumNOPBytes -= 4;
373   }
374 
375   // Emit nops.
376   for (unsigned i = 0; i < NumNOPBytes; i += 4)
377     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
378 }
379 
380 // Lower a patchpoint of the form:
381 // [<def>], <id>, <numBytes>, <target>, <numArgs>
382 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
383   auto &Ctx = OutStreamer->getContext();
384   MCSymbol *MILabel = Ctx.createTempSymbol();
385   OutStreamer->emitLabel(MILabel);
386 
387   SM.recordPatchPoint(*MILabel, MI);
388   PatchPointOpers Opers(&MI);
389 
390   unsigned EncodedBytes = 0;
391   const MachineOperand &CalleeMO = Opers.getCallTarget();
392 
393   if (CalleeMO.isImm()) {
394     int64_t CallTarget = CalleeMO.getImm();
395     if (CallTarget) {
396       assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
397              "High 16 bits of call target should be zero.");
398       Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
399       EncodedBytes = 0;
400       // Materialize the jump address:
401       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
402                                       .addReg(ScratchReg)
403                                       .addImm((CallTarget >> 32) & 0xFFFF));
404       ++EncodedBytes;
405       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
406                                       .addReg(ScratchReg)
407                                       .addReg(ScratchReg)
408                                       .addImm(32).addImm(16));
409       ++EncodedBytes;
410       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
411                                       .addReg(ScratchReg)
412                                       .addReg(ScratchReg)
413                                       .addImm((CallTarget >> 16) & 0xFFFF));
414       ++EncodedBytes;
415       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
416                                       .addReg(ScratchReg)
417                                       .addReg(ScratchReg)
418                                       .addImm(CallTarget & 0xFFFF));
419 
420       // Save the current TOC pointer before the remote call.
421       int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
422       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
423                                       .addReg(PPC::X2)
424                                       .addImm(TOCSaveOffset)
425                                       .addReg(PPC::X1));
426       ++EncodedBytes;
427 
428       // If we're on ELFv1, then we need to load the actual function pointer
429       // from the function descriptor.
430       if (!Subtarget->isELFv2ABI()) {
431         // Load the new TOC pointer and the function address, but not r11
432         // (needing this is rare, and loading it here would prevent passing it
433         // via a 'nest' parameter.
434         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
435                                         .addReg(PPC::X2)
436                                         .addImm(8)
437                                         .addReg(ScratchReg));
438         ++EncodedBytes;
439         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
440                                         .addReg(ScratchReg)
441                                         .addImm(0)
442                                         .addReg(ScratchReg));
443         ++EncodedBytes;
444       }
445 
446       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
447                                       .addReg(ScratchReg));
448       ++EncodedBytes;
449       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
450       ++EncodedBytes;
451 
452       // Restore the TOC pointer after the call.
453       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
454                                       .addReg(PPC::X2)
455                                       .addImm(TOCSaveOffset)
456                                       .addReg(PPC::X1));
457       ++EncodedBytes;
458     }
459   } else if (CalleeMO.isGlobal()) {
460     const GlobalValue *GValue = CalleeMO.getGlobal();
461     MCSymbol *MOSymbol = getSymbol(GValue);
462     const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
463 
464     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
465                                     .addExpr(SymVar));
466     EncodedBytes += 2;
467   }
468 
469   // Each instruction is 4 bytes.
470   EncodedBytes *= 4;
471 
472   // Emit padding.
473   unsigned NumBytes = Opers.getNumPatchBytes();
474   assert(NumBytes >= EncodedBytes &&
475          "Patchpoint can't request size less than the length of a call.");
476   assert((NumBytes - EncodedBytes) % 4 == 0 &&
477          "Invalid number of NOP bytes requested!");
478   for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
479     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
480 }
481 
482 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
483 /// call to __tls_get_addr to the current output stream.
484 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
485                                 MCSymbolRefExpr::VariantKind VK) {
486   StringRef Name = "__tls_get_addr";
487   MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name);
488   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
489   unsigned Opcode = PPC::BL8_NOP_TLS;
490 
491   assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI");
492   if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG ||
493       MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) {
494     Kind = MCSymbolRefExpr::VK_PPC_NOTOC;
495     Opcode = PPC::BL8_NOTOC_TLS;
496   }
497   const Module *M = MF->getFunction().getParent();
498 
499   assert(MI->getOperand(0).isReg() &&
500          ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
501           (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
502          "GETtls[ld]ADDR[32] must define GPR3");
503   assert(MI->getOperand(1).isReg() &&
504          ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
505           (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
506          "GETtls[ld]ADDR[32] must read GPR3");
507 
508   if (Subtarget->is32BitELFABI() && isPositionIndependent())
509     Kind = MCSymbolRefExpr::VK_PLT;
510 
511   const MCExpr *TlsRef =
512     MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
513 
514   // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
515   if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
516       M->getPICLevel() == PICLevel::BigPIC)
517     TlsRef = MCBinaryExpr::createAdd(
518         TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
519   const MachineOperand &MO = MI->getOperand(2);
520   const GlobalValue *GValue = MO.getGlobal();
521   MCSymbol *MOSymbol = getSymbol(GValue);
522   const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
523   EmitToStreamer(*OutStreamer,
524                  MCInstBuilder(Subtarget->isPPC64() ? Opcode
525                                                     : (unsigned)PPC::BL_TLS)
526                      .addExpr(TlsRef)
527                      .addExpr(SymVar));
528 }
529 
530 /// Map a machine operand for a TOC pseudo-machine instruction to its
531 /// corresponding MCSymbol.
532 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO,
533                                            AsmPrinter &AP) {
534   switch (MO.getType()) {
535   case MachineOperand::MO_GlobalAddress:
536     return AP.getSymbol(MO.getGlobal());
537   case MachineOperand::MO_ConstantPoolIndex:
538     return AP.GetCPISymbol(MO.getIndex());
539   case MachineOperand::MO_JumpTableIndex:
540     return AP.GetJTISymbol(MO.getIndex());
541   case MachineOperand::MO_BlockAddress:
542     return AP.GetBlockAddressSymbol(MO.getBlockAddress());
543   default:
544     llvm_unreachable("Unexpected operand type to get symbol.");
545   }
546 }
547 
548 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
549 /// the current output stream.
550 ///
551 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
552   MCInst TmpInst;
553   const bool IsPPC64 = Subtarget->isPPC64();
554   const bool IsAIX = Subtarget->isAIXABI();
555   const Module *M = MF->getFunction().getParent();
556   PICLevel::Level PL = M->getPICLevel();
557 
558 #ifndef NDEBUG
559   // Validate that SPE and FPU are mutually exclusive in codegen
560   if (!MI->isInlineAsm()) {
561     for (const MachineOperand &MO: MI->operands()) {
562       if (MO.isReg()) {
563         Register Reg = MO.getReg();
564         if (Subtarget->hasSPE()) {
565           if (PPC::F4RCRegClass.contains(Reg) ||
566               PPC::F8RCRegClass.contains(Reg) ||
567               PPC::VFRCRegClass.contains(Reg) ||
568               PPC::VRRCRegClass.contains(Reg) ||
569               PPC::VSFRCRegClass.contains(Reg) ||
570               PPC::VSSRCRegClass.contains(Reg)
571               )
572             llvm_unreachable("SPE targets cannot have FPRegs!");
573         } else {
574           if (PPC::SPERCRegClass.contains(Reg))
575             llvm_unreachable("SPE register found in FPU-targeted code!");
576         }
577       }
578     }
579   }
580 #endif
581 
582   auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
583                                                 ptrdiff_t OriginalOffset) {
584     // Apply an offset to the TOC-based expression such that the adjusted
585     // notional offset from the TOC base (to be encoded into the instruction's D
586     // or DS field) is the signed 16-bit truncation of the original notional
587     // offset from the TOC base.
588     // This is consistent with the treatment used both by XL C/C++ and
589     // by AIX ld -r.
590     ptrdiff_t Adjustment =
591         OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
592     return MCBinaryExpr::createAdd(
593         Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
594   };
595 
596   auto getTOCEntryLoadingExprForXCOFF =
597       [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
598        this](const MCSymbol *MOSymbol, const MCExpr *Expr) -> const MCExpr * {
599     const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
600     const auto TOCEntryIter = TOC.find(MOSymbol);
601     assert(TOCEntryIter != TOC.end() &&
602            "Could not find the TOC entry for this symbol.");
603     const ptrdiff_t EntryDistanceFromTOCBase =
604         (TOCEntryIter - TOC.begin()) * EntryByteSize;
605     constexpr int16_t PositiveTOCRange = INT16_MAX;
606 
607     if (EntryDistanceFromTOCBase > PositiveTOCRange)
608       return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
609 
610     return Expr;
611   };
612 
613   // Lower multi-instruction pseudo operations.
614   switch (MI->getOpcode()) {
615   default: break;
616   case TargetOpcode::DBG_VALUE:
617     llvm_unreachable("Should be handled target independently");
618   case TargetOpcode::STACKMAP:
619     return LowerSTACKMAP(SM, *MI);
620   case TargetOpcode::PATCHPOINT:
621     return LowerPATCHPOINT(SM, *MI);
622 
623   case PPC::MoveGOTtoLR: {
624     // Transform %lr = MoveGOTtoLR
625     // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
626     // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
627     // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
628     //      blrl
629     // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
630     MCSymbol *GOTSymbol =
631       OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
632     const MCExpr *OffsExpr =
633       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
634                                                       MCSymbolRefExpr::VK_PPC_LOCAL,
635                                                       OutContext),
636                               MCConstantExpr::create(4, OutContext),
637                               OutContext);
638 
639     // Emit the 'bl'.
640     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
641     return;
642   }
643   case PPC::MovePCtoLR:
644   case PPC::MovePCtoLR8: {
645     // Transform %lr = MovePCtoLR
646     // Into this, where the label is the PIC base:
647     //     bl L1$pb
648     // L1$pb:
649     MCSymbol *PICBase = MF->getPICBaseSymbol();
650 
651     // Emit the 'bl'.
652     EmitToStreamer(*OutStreamer,
653                    MCInstBuilder(PPC::BL)
654                        // FIXME: We would like an efficient form for this, so we
655                        // don't have to do a lot of extra uniquing.
656                        .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
657 
658     // Emit the label.
659     OutStreamer->emitLabel(PICBase);
660     return;
661   }
662   case PPC::UpdateGBR: {
663     // Transform %rd = UpdateGBR(%rt, %ri)
664     // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
665     //       add %rd, %rt, %ri
666     // or into (if secure plt mode is on):
667     //       addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
668     //       addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
669     // Get the offset from the GOT Base Register to the GOT
670     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
671     if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
672       unsigned PICR = TmpInst.getOperand(0).getReg();
673       MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
674           M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
675                                                  : ".LTOC");
676       const MCExpr *PB =
677           MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
678 
679       const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
680           MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
681 
682       const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
683       EmitToStreamer(
684           *OutStreamer,
685           MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
686 
687       const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
688       EmitToStreamer(
689           *OutStreamer,
690           MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
691       return;
692     } else {
693       MCSymbol *PICOffset =
694         MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
695       TmpInst.setOpcode(PPC::LWZ);
696       const MCExpr *Exp =
697         MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
698       const MCExpr *PB =
699         MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
700                                 MCSymbolRefExpr::VK_None,
701                                 OutContext);
702       const MCOperand TR = TmpInst.getOperand(1);
703       const MCOperand PICR = TmpInst.getOperand(0);
704 
705       // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
706       TmpInst.getOperand(1) =
707           MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
708       TmpInst.getOperand(0) = TR;
709       TmpInst.getOperand(2) = PICR;
710       EmitToStreamer(*OutStreamer, TmpInst);
711 
712       TmpInst.setOpcode(PPC::ADD4);
713       TmpInst.getOperand(0) = PICR;
714       TmpInst.getOperand(1) = TR;
715       TmpInst.getOperand(2) = PICR;
716       EmitToStreamer(*OutStreamer, TmpInst);
717       return;
718     }
719   }
720   case PPC::LWZtoc: {
721     // Transform %rN = LWZtoc @op1, %r2
722     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
723 
724     // Change the opcode to LWZ.
725     TmpInst.setOpcode(PPC::LWZ);
726 
727     const MachineOperand &MO = MI->getOperand(1);
728     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
729            "Invalid operand for LWZtoc.");
730 
731     // Map the operand to its corresponding MCSymbol.
732     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
733 
734     // Create a reference to the GOT entry for the symbol. The GOT entry will be
735     // synthesized later.
736     if (PL == PICLevel::SmallPIC && !IsAIX) {
737       const MCExpr *Exp =
738         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
739                                 OutContext);
740       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
741       EmitToStreamer(*OutStreamer, TmpInst);
742       return;
743     }
744 
745     // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
746     // storage allocated in the TOC which contains the address of
747     // 'MOSymbol'. Said TOC entry will be synthesized later.
748     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
749     const MCExpr *Exp =
750         MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
751 
752     // AIX uses the label directly as the lwz displacement operand for
753     // references into the toc section. The displacement value will be generated
754     // relative to the toc-base.
755     if (IsAIX) {
756       assert(
757           TM.getCodeModel() == CodeModel::Small &&
758           "This pseudo should only be selected for 32-bit small code model.");
759       Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp);
760       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
761       EmitToStreamer(*OutStreamer, TmpInst);
762       return;
763     }
764 
765     // Create an explicit subtract expression between the local symbol and
766     // '.LTOC' to manifest the toc-relative offset.
767     const MCExpr *PB = MCSymbolRefExpr::create(
768         OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
769     Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
770     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
771     EmitToStreamer(*OutStreamer, TmpInst);
772     return;
773   }
774   case PPC::LDtocJTI:
775   case PPC::LDtocCPT:
776   case PPC::LDtocBA:
777   case PPC::LDtoc: {
778     // Transform %x3 = LDtoc @min1, %x2
779     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
780 
781     // Change the opcode to LD.
782     TmpInst.setOpcode(PPC::LD);
783 
784     const MachineOperand &MO = MI->getOperand(1);
785     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
786            "Invalid operand!");
787 
788     // Map the operand to its corresponding MCSymbol.
789     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
790 
791     // Map the machine operand to its corresponding MCSymbol, then map the
792     // global address operand to be a reference to the TOC entry we will
793     // synthesize later.
794     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
795 
796     const MCSymbolRefExpr::VariantKind VK =
797         IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
798     const MCExpr *Exp =
799         MCSymbolRefExpr::create(TOCEntry, VK, OutContext);
800     TmpInst.getOperand(1) = MCOperand::createExpr(
801         IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp) : Exp);
802     EmitToStreamer(*OutStreamer, TmpInst);
803     return;
804   }
805   case PPC::ADDIStocHA: {
806     assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
807            "This pseudo should only be selected for 32-bit large code model on"
808            " AIX.");
809 
810     // Transform %rd = ADDIStocHA %rA, @sym(%r2)
811     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
812 
813     // Change the opcode to ADDIS.
814     TmpInst.setOpcode(PPC::ADDIS);
815 
816     const MachineOperand &MO = MI->getOperand(2);
817     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
818            "Invalid operand for ADDIStocHA.");
819 
820     // Map the machine operand to its corresponding MCSymbol.
821     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
822 
823     // Always use TOC on AIX. Map the global address operand to be a reference
824     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
825     // reference the storage allocated in the TOC which contains the address of
826     // 'MOSymbol'.
827     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
828     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
829                                                 MCSymbolRefExpr::VK_PPC_U,
830                                                 OutContext);
831     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
832     EmitToStreamer(*OutStreamer, TmpInst);
833     return;
834   }
835   case PPC::LWZtocL: {
836     assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
837            "This pseudo should only be selected for 32-bit large code model on"
838            " AIX.");
839 
840     // Transform %rd = LWZtocL @sym, %rs.
841     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
842 
843     // Change the opcode to lwz.
844     TmpInst.setOpcode(PPC::LWZ);
845 
846     const MachineOperand &MO = MI->getOperand(1);
847     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
848            "Invalid operand for LWZtocL.");
849 
850     // Map the machine operand to its corresponding MCSymbol.
851     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
852 
853     // Always use TOC on AIX. Map the global address operand to be a reference
854     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
855     // reference the storage allocated in the TOC which contains the address of
856     // 'MOSymbol'.
857     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
858     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
859                                                 MCSymbolRefExpr::VK_PPC_L,
860                                                 OutContext);
861     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
862     EmitToStreamer(*OutStreamer, TmpInst);
863     return;
864   }
865   case PPC::ADDIStocHA8: {
866     // Transform %xd = ADDIStocHA8 %x2, @sym
867     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
868 
869     // Change the opcode to ADDIS8. If the global address is the address of
870     // an external symbol, is a jump table address, is a block address, or is a
871     // constant pool index with large code model enabled, then generate a TOC
872     // entry and reference that. Otherwise, reference the symbol directly.
873     TmpInst.setOpcode(PPC::ADDIS8);
874 
875     const MachineOperand &MO = MI->getOperand(2);
876     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
877            "Invalid operand for ADDIStocHA8!");
878 
879     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
880 
881     const bool GlobalToc =
882         MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
883     if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
884         (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
885       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
886 
887     const MCSymbolRefExpr::VariantKind VK =
888         IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA;
889 
890     const MCExpr *Exp =
891         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
892 
893     if (!MO.isJTI() && MO.getOffset())
894       Exp = MCBinaryExpr::createAdd(Exp,
895                                     MCConstantExpr::create(MO.getOffset(),
896                                                            OutContext),
897                                     OutContext);
898 
899     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
900     EmitToStreamer(*OutStreamer, TmpInst);
901     return;
902   }
903   case PPC::LDtocL: {
904     // Transform %xd = LDtocL @sym, %xs
905     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
906 
907     // Change the opcode to LD. If the global address is the address of
908     // an external symbol, is a jump table address, is a block address, or is
909     // a constant pool index with large code model enabled, then generate a
910     // TOC entry and reference that. Otherwise, reference the symbol directly.
911     TmpInst.setOpcode(PPC::LD);
912 
913     const MachineOperand &MO = MI->getOperand(1);
914     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
915             MO.isBlockAddress()) &&
916            "Invalid operand for LDtocL!");
917 
918     LLVM_DEBUG(assert(
919         (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
920         "LDtocL used on symbol that could be accessed directly is "
921         "invalid. Must match ADDIStocHA8."));
922 
923     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
924 
925     if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
926       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
927 
928     const MCSymbolRefExpr::VariantKind VK =
929         IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO;
930     const MCExpr *Exp =
931         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
932     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
933     EmitToStreamer(*OutStreamer, TmpInst);
934     return;
935   }
936   case PPC::ADDItocL: {
937     // Transform %xd = ADDItocL %xs, @sym
938     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
939 
940     // Change the opcode to ADDI8. If the global address is external, then
941     // generate a TOC entry and reference that. Otherwise, reference the
942     // symbol directly.
943     TmpInst.setOpcode(PPC::ADDI8);
944 
945     const MachineOperand &MO = MI->getOperand(2);
946     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
947 
948     LLVM_DEBUG(assert(
949         !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
950         "Interposable definitions must use indirect access."));
951 
952     const MCExpr *Exp =
953         MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this),
954                                 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
955     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
956     EmitToStreamer(*OutStreamer, TmpInst);
957     return;
958   }
959   case PPC::ADDISgotTprelHA: {
960     // Transform: %xd = ADDISgotTprelHA %x2, @sym
961     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
962     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
963     const MachineOperand &MO = MI->getOperand(2);
964     const GlobalValue *GValue = MO.getGlobal();
965     MCSymbol *MOSymbol = getSymbol(GValue);
966     const MCExpr *SymGotTprel =
967         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
968                                 OutContext);
969     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
970                                  .addReg(MI->getOperand(0).getReg())
971                                  .addReg(MI->getOperand(1).getReg())
972                                  .addExpr(SymGotTprel));
973     return;
974   }
975   case PPC::LDgotTprelL:
976   case PPC::LDgotTprelL32: {
977     // Transform %xd = LDgotTprelL @sym, %xs
978     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
979 
980     // Change the opcode to LD.
981     TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
982     const MachineOperand &MO = MI->getOperand(1);
983     const GlobalValue *GValue = MO.getGlobal();
984     MCSymbol *MOSymbol = getSymbol(GValue);
985     const MCExpr *Exp = MCSymbolRefExpr::create(
986         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
987                           : MCSymbolRefExpr::VK_PPC_GOT_TPREL,
988         OutContext);
989     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
990     EmitToStreamer(*OutStreamer, TmpInst);
991     return;
992   }
993 
994   case PPC::PPC32PICGOT: {
995     MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
996     MCSymbol *GOTRef = OutContext.createTempSymbol();
997     MCSymbol *NextInstr = OutContext.createTempSymbol();
998 
999     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
1000       // FIXME: We would like an efficient form for this, so we don't have to do
1001       // a lot of extra uniquing.
1002       .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
1003     const MCExpr *OffsExpr =
1004       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
1005                                 MCSymbolRefExpr::create(GOTRef, OutContext),
1006         OutContext);
1007     OutStreamer->emitLabel(GOTRef);
1008     OutStreamer->emitValue(OffsExpr, 4);
1009     OutStreamer->emitLabel(NextInstr);
1010     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
1011                                  .addReg(MI->getOperand(0).getReg()));
1012     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
1013                                  .addReg(MI->getOperand(1).getReg())
1014                                  .addImm(0)
1015                                  .addReg(MI->getOperand(0).getReg()));
1016     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
1017                                  .addReg(MI->getOperand(0).getReg())
1018                                  .addReg(MI->getOperand(1).getReg())
1019                                  .addReg(MI->getOperand(0).getReg()));
1020     return;
1021   }
1022   case PPC::PPC32GOT: {
1023     MCSymbol *GOTSymbol =
1024         OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1025     const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1026         GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1027     const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1028         GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1029     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1030                                  .addReg(MI->getOperand(0).getReg())
1031                                  .addExpr(SymGotTlsL));
1032     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1033                                  .addReg(MI->getOperand(0).getReg())
1034                                  .addReg(MI->getOperand(0).getReg())
1035                                  .addExpr(SymGotTlsHA));
1036     return;
1037   }
1038   case PPC::ADDIStlsgdHA: {
1039     // Transform: %xd = ADDIStlsgdHA %x2, @sym
1040     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1041     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1042     const MachineOperand &MO = MI->getOperand(2);
1043     const GlobalValue *GValue = MO.getGlobal();
1044     MCSymbol *MOSymbol = getSymbol(GValue);
1045     const MCExpr *SymGotTlsGD =
1046       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
1047                               OutContext);
1048     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1049                                  .addReg(MI->getOperand(0).getReg())
1050                                  .addReg(MI->getOperand(1).getReg())
1051                                  .addExpr(SymGotTlsGD));
1052     return;
1053   }
1054   case PPC::ADDItlsgdL:
1055     // Transform: %xd = ADDItlsgdL %xs, @sym
1056     // Into:      %xd = ADDI8 %xs, sym@got@tlsgd@l
1057   case PPC::ADDItlsgdL32: {
1058     // Transform: %rd = ADDItlsgdL32 %rs, @sym
1059     // Into:      %rd = ADDI %rs, sym@got@tlsgd
1060     const MachineOperand &MO = MI->getOperand(2);
1061     const GlobalValue *GValue = MO.getGlobal();
1062     MCSymbol *MOSymbol = getSymbol(GValue);
1063     const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1064         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1065                           : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
1066         OutContext);
1067     EmitToStreamer(*OutStreamer,
1068                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1069                    .addReg(MI->getOperand(0).getReg())
1070                    .addReg(MI->getOperand(1).getReg())
1071                    .addExpr(SymGotTlsGD));
1072     return;
1073   }
1074   case PPC::GETtlsADDR:
1075     // Transform: %x3 = GETtlsADDR %x3, @sym
1076     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1077   case PPC::GETtlsADDRPCREL:
1078   case PPC::GETtlsADDR32: {
1079     // Transform: %r3 = GETtlsADDR32 %r3, @sym
1080     // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1081     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1082     return;
1083   }
1084   case PPC::ADDIStlsldHA: {
1085     // Transform: %xd = ADDIStlsldHA %x2, @sym
1086     // Into:      %xd = ADDIS8 %x2, sym@got@tlsld@ha
1087     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1088     const MachineOperand &MO = MI->getOperand(2);
1089     const GlobalValue *GValue = MO.getGlobal();
1090     MCSymbol *MOSymbol = getSymbol(GValue);
1091     const MCExpr *SymGotTlsLD =
1092       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
1093                               OutContext);
1094     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1095                                  .addReg(MI->getOperand(0).getReg())
1096                                  .addReg(MI->getOperand(1).getReg())
1097                                  .addExpr(SymGotTlsLD));
1098     return;
1099   }
1100   case PPC::ADDItlsldL:
1101     // Transform: %xd = ADDItlsldL %xs, @sym
1102     // Into:      %xd = ADDI8 %xs, sym@got@tlsld@l
1103   case PPC::ADDItlsldL32: {
1104     // Transform: %rd = ADDItlsldL32 %rs, @sym
1105     // Into:      %rd = ADDI %rs, sym@got@tlsld
1106     const MachineOperand &MO = MI->getOperand(2);
1107     const GlobalValue *GValue = MO.getGlobal();
1108     MCSymbol *MOSymbol = getSymbol(GValue);
1109     const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1110         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1111                           : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
1112         OutContext);
1113     EmitToStreamer(*OutStreamer,
1114                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1115                        .addReg(MI->getOperand(0).getReg())
1116                        .addReg(MI->getOperand(1).getReg())
1117                        .addExpr(SymGotTlsLD));
1118     return;
1119   }
1120   case PPC::GETtlsldADDR:
1121     // Transform: %x3 = GETtlsldADDR %x3, @sym
1122     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1123   case PPC::GETtlsldADDRPCREL:
1124   case PPC::GETtlsldADDR32: {
1125     // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1126     // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1127     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1128     return;
1129   }
1130   case PPC::ADDISdtprelHA:
1131     // Transform: %xd = ADDISdtprelHA %xs, @sym
1132     // Into:      %xd = ADDIS8 %xs, sym@dtprel@ha
1133   case PPC::ADDISdtprelHA32: {
1134     // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1135     // Into:      %rd = ADDIS %rs, sym@dtprel@ha
1136     const MachineOperand &MO = MI->getOperand(2);
1137     const GlobalValue *GValue = MO.getGlobal();
1138     MCSymbol *MOSymbol = getSymbol(GValue);
1139     const MCExpr *SymDtprel =
1140       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
1141                               OutContext);
1142     EmitToStreamer(
1143         *OutStreamer,
1144         MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1145             .addReg(MI->getOperand(0).getReg())
1146             .addReg(MI->getOperand(1).getReg())
1147             .addExpr(SymDtprel));
1148     return;
1149   }
1150   case PPC::PADDIdtprel: {
1151     // Transform: %rd = PADDIdtprel %rs, @sym
1152     // Into:      %rd = PADDI8 %rs, sym@dtprel
1153     const MachineOperand &MO = MI->getOperand(2);
1154     const GlobalValue *GValue = MO.getGlobal();
1155     MCSymbol *MOSymbol = getSymbol(GValue);
1156     const MCExpr *SymDtprel = MCSymbolRefExpr::create(
1157         MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext);
1158     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8)
1159                                      .addReg(MI->getOperand(0).getReg())
1160                                      .addReg(MI->getOperand(1).getReg())
1161                                      .addExpr(SymDtprel));
1162     return;
1163   }
1164 
1165   case PPC::ADDIdtprelL:
1166     // Transform: %xd = ADDIdtprelL %xs, @sym
1167     // Into:      %xd = ADDI8 %xs, sym@dtprel@l
1168   case PPC::ADDIdtprelL32: {
1169     // Transform: %rd = ADDIdtprelL32 %rs, @sym
1170     // Into:      %rd = ADDI %rs, sym@dtprel@l
1171     const MachineOperand &MO = MI->getOperand(2);
1172     const GlobalValue *GValue = MO.getGlobal();
1173     MCSymbol *MOSymbol = getSymbol(GValue);
1174     const MCExpr *SymDtprel =
1175       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
1176                               OutContext);
1177     EmitToStreamer(*OutStreamer,
1178                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1179                        .addReg(MI->getOperand(0).getReg())
1180                        .addReg(MI->getOperand(1).getReg())
1181                        .addExpr(SymDtprel));
1182     return;
1183   }
1184   case PPC::MFOCRF:
1185   case PPC::MFOCRF8:
1186     if (!Subtarget->hasMFOCRF()) {
1187       // Transform: %r3 = MFOCRF %cr7
1188       // Into:      %r3 = MFCR   ;; cr7
1189       unsigned NewOpcode =
1190         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1191       OutStreamer->AddComment(PPCInstPrinter::
1192                               getRegisterName(MI->getOperand(1).getReg()));
1193       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1194                                   .addReg(MI->getOperand(0).getReg()));
1195       return;
1196     }
1197     break;
1198   case PPC::MTOCRF:
1199   case PPC::MTOCRF8:
1200     if (!Subtarget->hasMFOCRF()) {
1201       // Transform: %cr7 = MTOCRF %r3
1202       // Into:      MTCRF mask, %r3 ;; cr7
1203       unsigned NewOpcode =
1204         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1205       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1206                               ->getEncodingValue(MI->getOperand(0).getReg());
1207       OutStreamer->AddComment(PPCInstPrinter::
1208                               getRegisterName(MI->getOperand(0).getReg()));
1209       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1210                                      .addImm(Mask)
1211                                      .addReg(MI->getOperand(1).getReg()));
1212       return;
1213     }
1214     break;
1215   case PPC::LD:
1216   case PPC::STD:
1217   case PPC::LWA_32:
1218   case PPC::LWA: {
1219     // Verify alignment is legal, so we don't create relocations
1220     // that can't be supported.
1221     unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1222     const MachineOperand &MO = MI->getOperand(OpNum);
1223     if (MO.isGlobal()) {
1224       const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
1225       if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1226         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1227     }
1228     // Now process the instruction normally.
1229     break;
1230   }
1231   }
1232 
1233   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1234   EmitToStreamer(*OutStreamer, TmpInst);
1235 }
1236 
1237 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1238   if (!Subtarget->isPPC64())
1239     return PPCAsmPrinter::emitInstruction(MI);
1240 
1241   switch (MI->getOpcode()) {
1242   default:
1243     return PPCAsmPrinter::emitInstruction(MI);
1244   case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1245     // .begin:
1246     //   b .end # lis 0, FuncId[16..32]
1247     //   nop    # li  0, FuncId[0..15]
1248     //   std 0, -8(1)
1249     //   mflr 0
1250     //   bl __xray_FunctionEntry
1251     //   mtlr 0
1252     // .end:
1253     //
1254     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1255     // of instructions change.
1256     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1257     MCSymbol *EndOfSled = OutContext.createTempSymbol();
1258     OutStreamer->emitLabel(BeginOfSled);
1259     EmitToStreamer(*OutStreamer,
1260                    MCInstBuilder(PPC::B).addExpr(
1261                        MCSymbolRefExpr::create(EndOfSled, OutContext)));
1262     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1263     EmitToStreamer(
1264         *OutStreamer,
1265         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1266     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1267     EmitToStreamer(*OutStreamer,
1268                    MCInstBuilder(PPC::BL8_NOP)
1269                        .addExpr(MCSymbolRefExpr::create(
1270                            OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1271                            OutContext)));
1272     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1273     OutStreamer->emitLabel(EndOfSled);
1274     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1275     break;
1276   }
1277   case TargetOpcode::PATCHABLE_RET: {
1278     unsigned RetOpcode = MI->getOperand(0).getImm();
1279     MCInst RetInst;
1280     RetInst.setOpcode(RetOpcode);
1281     for (const auto &MO :
1282          make_range(std::next(MI->operands_begin()), MI->operands_end())) {
1283       MCOperand MCOp;
1284       if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1285         RetInst.addOperand(MCOp);
1286     }
1287 
1288     bool IsConditional;
1289     if (RetOpcode == PPC::BCCLR) {
1290       IsConditional = true;
1291     } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1292                RetOpcode == PPC::TCRETURNai8) {
1293       break;
1294     } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1295       IsConditional = false;
1296     } else {
1297       EmitToStreamer(*OutStreamer, RetInst);
1298       break;
1299     }
1300 
1301     MCSymbol *FallthroughLabel;
1302     if (IsConditional) {
1303       // Before:
1304       //   bgtlr cr0
1305       //
1306       // After:
1307       //   ble cr0, .end
1308       // .p2align 3
1309       // .begin:
1310       //   blr    # lis 0, FuncId[16..32]
1311       //   nop    # li  0, FuncId[0..15]
1312       //   std 0, -8(1)
1313       //   mflr 0
1314       //   bl __xray_FunctionExit
1315       //   mtlr 0
1316       //   blr
1317       // .end:
1318       //
1319       // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1320       // of instructions change.
1321       FallthroughLabel = OutContext.createTempSymbol();
1322       EmitToStreamer(
1323           *OutStreamer,
1324           MCInstBuilder(PPC::BCC)
1325               .addImm(PPC::InvertPredicate(
1326                   static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1327               .addReg(MI->getOperand(2).getReg())
1328               .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1329       RetInst = MCInst();
1330       RetInst.setOpcode(PPC::BLR8);
1331     }
1332     // .p2align 3
1333     // .begin:
1334     //   b(lr)? # lis 0, FuncId[16..32]
1335     //   nop    # li  0, FuncId[0..15]
1336     //   std 0, -8(1)
1337     //   mflr 0
1338     //   bl __xray_FunctionExit
1339     //   mtlr 0
1340     //   b(lr)?
1341     //
1342     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1343     // of instructions change.
1344     OutStreamer->emitCodeAlignment(8);
1345     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1346     OutStreamer->emitLabel(BeginOfSled);
1347     EmitToStreamer(*OutStreamer, RetInst);
1348     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1349     EmitToStreamer(
1350         *OutStreamer,
1351         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1352     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1353     EmitToStreamer(*OutStreamer,
1354                    MCInstBuilder(PPC::BL8_NOP)
1355                        .addExpr(MCSymbolRefExpr::create(
1356                            OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1357                            OutContext)));
1358     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1359     EmitToStreamer(*OutStreamer, RetInst);
1360     if (IsConditional)
1361       OutStreamer->emitLabel(FallthroughLabel);
1362     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1363     break;
1364   }
1365   case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1366     llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1367   case TargetOpcode::PATCHABLE_TAIL_CALL:
1368     // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1369     // normal function exit from a tail exit.
1370     llvm_unreachable("Tail call is handled in the normal case. See comments "
1371                      "around this assert.");
1372   }
1373 }
1374 
1375 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1376   if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1377     PPCTargetStreamer *TS =
1378       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1379 
1380     if (TS)
1381       TS->emitAbiVersion(2);
1382   }
1383 
1384   if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1385       !isPositionIndependent())
1386     return AsmPrinter::emitStartOfAsmFile(M);
1387 
1388   if (M.getPICLevel() == PICLevel::SmallPIC)
1389     return AsmPrinter::emitStartOfAsmFile(M);
1390 
1391   OutStreamer->SwitchSection(OutContext.getELFSection(
1392       ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1393 
1394   MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1395   MCSymbol *CurrentPos = OutContext.createTempSymbol();
1396 
1397   OutStreamer->emitLabel(CurrentPos);
1398 
1399   // The GOT pointer points to the middle of the GOT, in order to reference the
1400   // entire 64kB range.  0x8000 is the midpoint.
1401   const MCExpr *tocExpr =
1402     MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1403                             MCConstantExpr::create(0x8000, OutContext),
1404                             OutContext);
1405 
1406   OutStreamer->emitAssignment(TOCSym, tocExpr);
1407 
1408   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1409 }
1410 
1411 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1412   // linux/ppc32 - Normal entry label.
1413   if (!Subtarget->isPPC64() &&
1414       (!isPositionIndependent() ||
1415        MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1416     return AsmPrinter::emitFunctionEntryLabel();
1417 
1418   if (!Subtarget->isPPC64()) {
1419     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1420     if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1421       MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1422       MCSymbol *PICBase = MF->getPICBaseSymbol();
1423       OutStreamer->emitLabel(RelocSymbol);
1424 
1425       const MCExpr *OffsExpr =
1426         MCBinaryExpr::createSub(
1427           MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1428                                                                OutContext),
1429                                   MCSymbolRefExpr::create(PICBase, OutContext),
1430           OutContext);
1431       OutStreamer->emitValue(OffsExpr, 4);
1432       OutStreamer->emitLabel(CurrentFnSym);
1433       return;
1434     } else
1435       return AsmPrinter::emitFunctionEntryLabel();
1436   }
1437 
1438   // ELFv2 ABI - Normal entry label.
1439   if (Subtarget->isELFv2ABI()) {
1440     // In the Large code model, we allow arbitrary displacements between
1441     // the text section and its associated TOC section.  We place the
1442     // full 8-byte offset to the TOC in memory immediately preceding
1443     // the function global entry point.
1444     if (TM.getCodeModel() == CodeModel::Large
1445         && !MF->getRegInfo().use_empty(PPC::X2)) {
1446       const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1447 
1448       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1449       MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1450       const MCExpr *TOCDeltaExpr =
1451         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1452                                 MCSymbolRefExpr::create(GlobalEPSymbol,
1453                                                         OutContext),
1454                                 OutContext);
1455 
1456       OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1457       OutStreamer->emitValue(TOCDeltaExpr, 8);
1458     }
1459     return AsmPrinter::emitFunctionEntryLabel();
1460   }
1461 
1462   // Emit an official procedure descriptor.
1463   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1464   MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1465       ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1466   OutStreamer->SwitchSection(Section);
1467   OutStreamer->emitLabel(CurrentFnSym);
1468   OutStreamer->emitValueToAlignment(8);
1469   MCSymbol *Symbol1 = CurrentFnSymForSize;
1470   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1471   // entry point.
1472   OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1473                          8 /*size*/);
1474   MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1475   // Generates a R_PPC64_TOC relocation for TOC base insertion.
1476   OutStreamer->emitValue(
1477     MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1478     8/*size*/);
1479   // Emit a null environment pointer.
1480   OutStreamer->emitIntValue(0, 8 /* size */);
1481   OutStreamer->SwitchSection(Current.first, Current.second);
1482 }
1483 
1484 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
1485   const DataLayout &DL = getDataLayout();
1486 
1487   bool isPPC64 = DL.getPointerSizeInBits() == 64;
1488 
1489   PPCTargetStreamer *TS =
1490       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1491 
1492   if (!TOC.empty()) {
1493     const char *Name = isPPC64 ? ".toc" : ".got2";
1494     MCSectionELF *Section = OutContext.getELFSection(
1495         Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1496     OutStreamer->SwitchSection(Section);
1497     if (!isPPC64)
1498       OutStreamer->emitValueToAlignment(4);
1499 
1500     for (const auto &TOCMapPair : TOC) {
1501       const MCSymbol *const TOCEntryTarget = TOCMapPair.first;
1502       MCSymbol *const TOCEntryLabel = TOCMapPair.second;
1503 
1504       OutStreamer->emitLabel(TOCEntryLabel);
1505       if (isPPC64 && TS != nullptr)
1506         TS->emitTCEntry(*TOCEntryTarget);
1507       else
1508         OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
1509     }
1510   }
1511 
1512   PPCAsmPrinter::emitEndOfAsmFile(M);
1513 }
1514 
1515 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1516 void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
1517   // In the ELFv2 ABI, in functions that use the TOC register, we need to
1518   // provide two entry points.  The ABI guarantees that when calling the
1519   // local entry point, r2 is set up by the caller to contain the TOC base
1520   // for this function, and when calling the global entry point, r12 is set
1521   // up by the caller to hold the address of the global entry point.  We
1522   // thus emit a prefix sequence along the following lines:
1523   //
1524   // func:
1525   // .Lfunc_gepNN:
1526   //         # global entry point
1527   //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1528   //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1529   // .Lfunc_lepNN:
1530   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1531   //         # local entry point, followed by function body
1532   //
1533   // For the Large code model, we create
1534   //
1535   // .Lfunc_tocNN:
1536   //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1537   // func:
1538   // .Lfunc_gepNN:
1539   //         # global entry point
1540   //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1541   //         add   r2,r2,r12
1542   // .Lfunc_lepNN:
1543   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1544   //         # local entry point, followed by function body
1545   //
1546   // This ensures we have r2 set up correctly while executing the function
1547   // body, no matter which entry point is called.
1548   const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1549   const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
1550                           !MF->getRegInfo().use_empty(PPC::R2);
1551   const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
1552                                 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
1553   const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
1554                                    Subtarget->isELFv2ABI() && UsesX2OrR2;
1555 
1556   // Only do all that if the function uses R2 as the TOC pointer
1557   // in the first place. We don't need the global entry point if the
1558   // function uses R2 as an allocatable register.
1559   if (NonPCrelGEPRequired || PCrelGEPRequired) {
1560     // Note: The logic here must be synchronized with the code in the
1561     // branch-selection pass which sets the offset of the first block in the
1562     // function. This matters because it affects the alignment.
1563     MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
1564     OutStreamer->emitLabel(GlobalEntryLabel);
1565     const MCSymbolRefExpr *GlobalEntryLabelExp =
1566       MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1567 
1568     if (TM.getCodeModel() != CodeModel::Large) {
1569       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1570       const MCExpr *TOCDeltaExpr =
1571         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1572                                 GlobalEntryLabelExp, OutContext);
1573 
1574       const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
1575       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1576                                    .addReg(PPC::X2)
1577                                    .addReg(PPC::X12)
1578                                    .addExpr(TOCDeltaHi));
1579 
1580       const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
1581       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1582                                    .addReg(PPC::X2)
1583                                    .addReg(PPC::X2)
1584                                    .addExpr(TOCDeltaLo));
1585     } else {
1586       MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
1587       const MCExpr *TOCOffsetDeltaExpr =
1588         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1589                                 GlobalEntryLabelExp, OutContext);
1590 
1591       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1592                                    .addReg(PPC::X2)
1593                                    .addExpr(TOCOffsetDeltaExpr)
1594                                    .addReg(PPC::X12));
1595       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1596                                    .addReg(PPC::X2)
1597                                    .addReg(PPC::X2)
1598                                    .addReg(PPC::X12));
1599     }
1600 
1601     MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
1602     OutStreamer->emitLabel(LocalEntryLabel);
1603     const MCSymbolRefExpr *LocalEntryLabelExp =
1604        MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1605     const MCExpr *LocalOffsetExp =
1606       MCBinaryExpr::createSub(LocalEntryLabelExp,
1607                               GlobalEntryLabelExp, OutContext);
1608 
1609     PPCTargetStreamer *TS =
1610       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1611 
1612     if (TS)
1613       TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1614   } else if (Subtarget->isUsingPCRelativeCalls()) {
1615     // When generating the entry point for a function we have a few scenarios
1616     // based on whether or not that function uses R2 and whether or not that
1617     // function makes calls (or is a leaf function).
1618     // 1) A leaf function that does not use R2 (or treats it as callee-saved
1619     //    and preserves it). In this case st_other=0 and both
1620     //    the local and global entry points for the function are the same.
1621     //    No special entry point code is required.
1622     // 2) A function uses the TOC pointer R2. This function may or may not have
1623     //    calls. In this case st_other=[2,6] and the global and local entry
1624     //    points are different. Code to correctly setup the TOC pointer in R2
1625     //    is put between the global and local entry points. This case is
1626     //    covered by the if statatement above.
1627     // 3) A function does not use the TOC pointer R2 but does have calls.
1628     //    In this case st_other=1 since we do not know whether or not any
1629     //    of the callees clobber R2. This case is dealt with in this else if
1630     //    block. Tail calls are considered calls and the st_other should also
1631     //    be set to 1 in that case as well.
1632     // 4) The function does not use the TOC pointer but R2 is used inside
1633     //    the function. In this case st_other=1 once again.
1634     // 5) This function uses inline asm. We mark R2 as reserved if the function
1635     //    has inline asm as we have to assume that it may be used.
1636     if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
1637         MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
1638       PPCTargetStreamer *TS =
1639           static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1640       if (TS)
1641         TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
1642                            MCConstantExpr::create(1, OutContext));
1643     }
1644   }
1645 }
1646 
1647 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1648 /// directive.
1649 ///
1650 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
1651   // Only the 64-bit target requires a traceback table.  For now,
1652   // we only emit the word of zeroes that GDB requires to find
1653   // the end of the function, and zeroes for the eight-byte
1654   // mandatory fields.
1655   // FIXME: We should fill in the eight-byte mandatory fields as described in
1656   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1657   // currently make use of these fields).
1658   if (Subtarget->isPPC64()) {
1659     OutStreamer->emitIntValue(0, 4/*size*/);
1660     OutStreamer->emitIntValue(0, 8/*size*/);
1661   }
1662 }
1663 
1664 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
1665                                    MCSymbol *GVSym) const {
1666 
1667   assert(MAI->hasVisibilityOnlyWithLinkage() &&
1668          "AIX's linkage directives take a visibility setting.");
1669 
1670   MCSymbolAttr LinkageAttr = MCSA_Invalid;
1671   switch (GV->getLinkage()) {
1672   case GlobalValue::ExternalLinkage:
1673     LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
1674     break;
1675   case GlobalValue::LinkOnceAnyLinkage:
1676   case GlobalValue::LinkOnceODRLinkage:
1677   case GlobalValue::WeakAnyLinkage:
1678   case GlobalValue::WeakODRLinkage:
1679   case GlobalValue::ExternalWeakLinkage:
1680     LinkageAttr = MCSA_Weak;
1681     break;
1682   case GlobalValue::AvailableExternallyLinkage:
1683     LinkageAttr = MCSA_Extern;
1684     break;
1685   case GlobalValue::PrivateLinkage:
1686     return;
1687   case GlobalValue::InternalLinkage:
1688     assert(GV->getVisibility() == GlobalValue::DefaultVisibility &&
1689            "InternalLinkage should not have other visibility setting.");
1690     LinkageAttr = MCSA_LGlobal;
1691     break;
1692   case GlobalValue::AppendingLinkage:
1693     llvm_unreachable("Should never emit this");
1694   case GlobalValue::CommonLinkage:
1695     llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
1696   }
1697 
1698   assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
1699 
1700   MCSymbolAttr VisibilityAttr = MCSA_Invalid;
1701   if (!TM.getIgnoreXCOFFVisibility()) {
1702     switch (GV->getVisibility()) {
1703 
1704     // TODO: "exported" and "internal" Visibility needs to go here.
1705     case GlobalValue::DefaultVisibility:
1706       break;
1707     case GlobalValue::HiddenVisibility:
1708       VisibilityAttr = MAI->getHiddenVisibilityAttr();
1709       break;
1710     case GlobalValue::ProtectedVisibility:
1711       VisibilityAttr = MAI->getProtectedVisibilityAttr();
1712       break;
1713     }
1714   }
1715 
1716   OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
1717                                                     VisibilityAttr);
1718 }
1719 
1720 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1721   // Setup CurrentFnDescSym and its containing csect.
1722   MCSectionXCOFF *FnDescSec =
1723       cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
1724           &MF.getFunction(), TM));
1725   FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
1726 
1727   CurrentFnDescSym = FnDescSec->getQualNameSymbol();
1728 
1729   return AsmPrinter::SetupMachineFunction(MF);
1730 }
1731 
1732 void PPCAIXAsmPrinter::ValidateGV(const GlobalVariable *GV) {
1733   // Early error checking limiting what is supported.
1734   if (GV->isThreadLocal())
1735     report_fatal_error("Thread local not yet supported on AIX.");
1736 
1737   if (GV->hasComdat())
1738     report_fatal_error("COMDAT not yet supported by AIX.");
1739 }
1740 
1741 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) {
1742   return GV->hasAppendingLinkage() &&
1743          StringSwitch<bool>(GV->getName())
1744              // TODO: Linker could still eliminate the GV if we just skip
1745              // handling llvm.used array. Skipping them for now until we or the
1746              // AIX OS team come up with a good solution.
1747              .Case("llvm.used", true)
1748              // It's correct to just skip llvm.compiler.used array here.
1749              .Case("llvm.compiler.used", true)
1750              .Default(false);
1751 }
1752 
1753 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) {
1754   return StringSwitch<bool>(GV->getName())
1755       .Cases("llvm.global_ctors", "llvm.global_dtors", true)
1756       .Default(false);
1757 }
1758 
1759 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
1760   // Special LLVM global arrays have been handled at the initialization.
1761   if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV))
1762     return;
1763 
1764   assert(!GV->getName().startswith("llvm.") &&
1765          "Unhandled intrinsic global variable.");
1766   ValidateGV(GV);
1767 
1768   MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
1769 
1770   if (GV->isDeclarationForLinker()) {
1771     emitLinkage(GV, GVSym);
1772     return;
1773   }
1774 
1775   SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
1776   if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly())
1777     report_fatal_error("Encountered a global variable kind that is "
1778                        "not supported yet.");
1779 
1780   MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1781       getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
1782 
1783   // Switch to the containing csect.
1784   OutStreamer->SwitchSection(Csect);
1785 
1786   const DataLayout &DL = GV->getParent()->getDataLayout();
1787 
1788   // Handle common symbols.
1789   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
1790     Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV));
1791     uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
1792     GVSym->setStorageClass(
1793         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV));
1794 
1795     if (GVKind.isBSSLocal())
1796       OutStreamer->emitXCOFFLocalCommonSymbol(
1797           OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
1798           GVSym, Alignment.value());
1799     else
1800       OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value());
1801     return;
1802   }
1803 
1804   MCSymbol *EmittedInitSym = GVSym;
1805   emitLinkage(GV, EmittedInitSym);
1806   emitAlignment(getGVAlignment(GV, DL), GV);
1807 
1808   // When -fdata-sections is enabled, every GlobalVariable will
1809   // be put into its own csect; therefore, label is not necessary here.
1810   if (!TM.getDataSections() || GV->hasSection()) {
1811     OutStreamer->emitLabel(EmittedInitSym);
1812   }
1813 
1814   // Emit aliasing label for global variable.
1815   llvm::for_each(GOAliasMap[GV], [this](const GlobalAlias *Alias) {
1816     OutStreamer->emitLabel(getSymbol(Alias));
1817   });
1818 
1819   emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
1820 }
1821 
1822 void PPCAIXAsmPrinter::emitFunctionDescriptor() {
1823   const DataLayout &DL = getDataLayout();
1824   const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
1825 
1826   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1827   // Emit function descriptor.
1828   OutStreamer->SwitchSection(
1829       cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
1830 
1831   // Emit aliasing label for function descriptor csect.
1832   llvm::for_each(GOAliasMap[&MF->getFunction()],
1833                  [this](const GlobalAlias *Alias) {
1834                    OutStreamer->emitLabel(getSymbol(Alias));
1835                  });
1836 
1837   // Emit function entry point address.
1838   OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
1839                          PointerSize);
1840   // Emit TOC base address.
1841   const MCSymbol *TOCBaseSym =
1842       cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
1843           ->getQualNameSymbol();
1844   OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
1845                          PointerSize);
1846   // Emit a null environment pointer.
1847   OutStreamer->emitIntValue(0, PointerSize);
1848 
1849   OutStreamer->SwitchSection(Current.first, Current.second);
1850 }
1851 
1852 void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
1853   // It's not necessary to emit the label when we have individual
1854   // function in its own csect.
1855   if (!TM.getFunctionSections())
1856     PPCAsmPrinter::emitFunctionEntryLabel();
1857 
1858   // Emit aliasing label for function entry point label.
1859   llvm::for_each(
1860       GOAliasMap[&MF->getFunction()], [this](const GlobalAlias *Alias) {
1861         OutStreamer->emitLabel(
1862             getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
1863       });
1864 }
1865 
1866 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
1867   // If there are no functions in this module, we will never need to reference
1868   // the TOC base.
1869   if (M.empty())
1870     return;
1871 
1872   // Switch to section to emit TOC base.
1873   OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection());
1874 
1875   PPCTargetStreamer *TS =
1876       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1877 
1878   for (auto &I : TOC) {
1879     // Setup the csect for the current TC entry.
1880     MCSectionXCOFF *TCEntry = cast<MCSectionXCOFF>(
1881         getObjFileLowering().getSectionForTOCEntry(I.first, TM));
1882     OutStreamer->SwitchSection(TCEntry);
1883 
1884     OutStreamer->emitLabel(I.second);
1885     if (TS != nullptr)
1886       TS->emitTCEntry(*I.first);
1887   }
1888 }
1889 
1890 bool PPCAIXAsmPrinter::doInitialization(Module &M) {
1891   const bool Result = PPCAsmPrinter::doInitialization(M);
1892 
1893   auto setCsectAlignment = [this](const GlobalObject *GO) {
1894     // Declarations have 0 alignment which is set by default.
1895     if (GO->isDeclarationForLinker())
1896       return;
1897 
1898     SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
1899     MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1900         getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
1901 
1902     Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
1903     if (GOAlign > Csect->getAlignment())
1904       Csect->setAlignment(GOAlign);
1905   };
1906 
1907   // We need to know, up front, the alignment of csects for the assembly path,
1908   // because once a .csect directive gets emitted, we could not change the
1909   // alignment value on it.
1910   for (const auto &G : M.globals()) {
1911     if (isSpecialLLVMGlobalArrayToSkip(&G))
1912       continue;
1913 
1914     if (isSpecialLLVMGlobalArrayForStaticInit(&G)) {
1915       // Generate a format indicator and a unique module id to be a part of
1916       // the sinit and sterm function names.
1917       if (FormatIndicatorAndUniqueModId.empty()) {
1918         std::string UniqueModuleId = getUniqueModuleId(&M);
1919         if (UniqueModuleId.compare("") != 0)
1920           // TODO: Use source file full path to generate the unique module id
1921           // and add a format indicator as a part of function name in case we
1922           // will support more than one format.
1923           FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
1924         else
1925           // Use the Pid and current time as the unique module id when we cannot
1926           // generate one based on a module's strong external symbols.
1927           // FIXME: Adjust the comment accordingly after we use source file full
1928           // path instead.
1929           FormatIndicatorAndUniqueModId =
1930               "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) +
1931               "_" + llvm::itostr(time(nullptr));
1932       }
1933 
1934       emitSpecialLLVMGlobal(&G);
1935       continue;
1936     }
1937 
1938     setCsectAlignment(&G);
1939   }
1940 
1941   for (const auto &F : M)
1942     setCsectAlignment(&F);
1943 
1944   // Construct an aliasing list for each GlobalObject.
1945   for (const auto &Alias : M.aliases()) {
1946     const GlobalObject *Base = Alias.getBaseObject();
1947     if (!Base)
1948       report_fatal_error(
1949           "alias without a base object is not yet supported on AIX");
1950     GOAliasMap[Base].push_back(&Alias);
1951   }
1952 
1953   return Result;
1954 }
1955 
1956 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
1957   switch (MI->getOpcode()) {
1958   default:
1959     break;
1960   case PPC::BL8:
1961   case PPC::BL:
1962   case PPC::BL8_NOP:
1963   case PPC::BL_NOP: {
1964     const MachineOperand &MO = MI->getOperand(0);
1965     if (MO.isSymbol()) {
1966       MCSymbolXCOFF *S =
1967           cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
1968       ExtSymSDNodeSymbols.insert(S);
1969     }
1970   } break;
1971   case PPC::BL_TLS:
1972   case PPC::BL8_TLS:
1973   case PPC::BL8_TLS_:
1974   case PPC::BL8_NOP_TLS:
1975     report_fatal_error("TLS call not yet implemented");
1976   case PPC::TAILB:
1977   case PPC::TAILB8:
1978   case PPC::TAILBA:
1979   case PPC::TAILBA8:
1980   case PPC::TAILBCTR:
1981   case PPC::TAILBCTR8:
1982     if (MI->getOperand(0).isSymbol())
1983       report_fatal_error("Tail call for extern symbol not yet supported.");
1984     break;
1985   }
1986   return PPCAsmPrinter::emitInstruction(MI);
1987 }
1988 
1989 bool PPCAIXAsmPrinter::doFinalization(Module &M) {
1990   for (MCSymbol *Sym : ExtSymSDNodeSymbols)
1991     OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
1992   return PPCAsmPrinter::doFinalization(M);
1993 }
1994 
1995 static unsigned mapToSinitPriority(int P) {
1996   if (P < 0 || P > 65535)
1997     report_fatal_error("invalid init priority");
1998 
1999   if (P <= 20)
2000     return P;
2001 
2002   if (P < 81)
2003     return 20 + (P - 20) * 16;
2004 
2005   if (P <= 1124)
2006     return 1004 + (P - 81);
2007 
2008   if (P < 64512)
2009     return 2047 + (P - 1124) * 33878;
2010 
2011   return 2147482625u + (P - 64512);
2012 }
2013 
2014 static std::string convertToSinitPriority(int Priority) {
2015   // This helper function converts clang init priority to values used in sinit
2016   // and sterm functions.
2017   //
2018   // The conversion strategies are:
2019   // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm
2020   // reserved priority range [0, 1023] by
2021   // - directly mapping the first 21 and the last 20 elements of the ranges
2022   // - linear interpolating the intermediate values with a step size of 16.
2023   //
2024   // We map the non reserved clang/gnu priority range of [101, 65535] into the
2025   // sinit/sterm priority range [1024, 2147483648] by:
2026   // - directly mapping the first and the last 1024 elements of the ranges
2027   // - linear interpolating the intermediate values with a step size of 33878.
2028   unsigned int P = mapToSinitPriority(Priority);
2029 
2030   std::string PrioritySuffix;
2031   llvm::raw_string_ostream os(PrioritySuffix);
2032   os << llvm::format_hex_no_prefix(P, 8);
2033   os.flush();
2034   return PrioritySuffix;
2035 }
2036 
2037 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
2038                                           const Constant *List, bool IsCtor) {
2039   SmallVector<Structor, 8> Structors;
2040   preprocessXXStructorList(DL, List, Structors);
2041   if (Structors.empty())
2042     return;
2043 
2044   unsigned Index = 0;
2045   for (Structor &S : Structors) {
2046     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func))
2047       S.Func = CE->getOperand(0);
2048 
2049     llvm::GlobalAlias::create(
2050         GlobalValue::ExternalLinkage,
2051         (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
2052             llvm::Twine(convertToSinitPriority(S.Priority)) +
2053             llvm::Twine("_", FormatIndicatorAndUniqueModId) +
2054             llvm::Twine("_", llvm::utostr(Index++)),
2055         cast<Function>(S.Func));
2056   }
2057 }
2058 
2059 // Return a pass that prints the PPC assembly code for a MachineFunction to the
2060 // given output stream.
2061 static AsmPrinter *
2062 createPPCAsmPrinterPass(TargetMachine &tm,
2063                         std::unique_ptr<MCStreamer> &&Streamer) {
2064   if (tm.getTargetTriple().isOSAIX())
2065     return new PPCAIXAsmPrinter(tm, std::move(Streamer));
2066 
2067   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
2068 }
2069 
2070 // Force static initialization.
2071 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
2072   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
2073                                      createPPCAsmPrinterPass);
2074   TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
2075                                      createPPCAsmPrinterPass);
2076   TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
2077                                      createPPCAsmPrinterPass);
2078 }
2079