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