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