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