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/StringRef.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/BinaryFormat/ELF.h"
34 #include "llvm/BinaryFormat/MachO.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/MCExpr.h"
51 #include "llvm/MC/MCInst.h"
52 #include "llvm/MC/MCInstBuilder.h"
53 #include "llvm/MC/MCSectionELF.h"
54 #include "llvm/MC/MCSectionMachO.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/TargetRegistry.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include <algorithm>
69 #include <cassert>
70 #include <cstdint>
71 #include <memory>
72 #include <new>
73 
74 using namespace llvm;
75 
76 #define DEBUG_TYPE "asmprinter"
77 
78 namespace {
79 
80 class PPCAsmPrinter : public AsmPrinter {
81 protected:
82   MapVector<const MCSymbol *, MCSymbol *> TOC;
83   const PPCSubtarget *Subtarget = nullptr;
84   StackMaps SM;
85 
86   virtual MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO);
87 
88 public:
89   explicit PPCAsmPrinter(TargetMachine &TM,
90                          std::unique_ptr<MCStreamer> Streamer)
91       : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
92 
93   StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
94 
95   MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym);
96 
97   bool doInitialization(Module &M) override {
98     if (!TOC.empty())
99       TOC.clear();
100     return AsmPrinter::doInitialization(M);
101   }
102 
103   void EmitInstruction(const MachineInstr *MI) override;
104 
105   /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
106   /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
107   /// The \p MI would be INLINEASM ONLY.
108   void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
109 
110   void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
111   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
112                        const char *ExtraCode, raw_ostream &O) override;
113   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
114                              const char *ExtraCode, raw_ostream &O) override;
115 
116   void EmitEndOfAsmFile(Module &M) override;
117 
118   void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
119   void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
120   void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
121   bool runOnMachineFunction(MachineFunction &MF) override {
122     Subtarget = &MF.getSubtarget<PPCSubtarget>();
123     bool Changed = AsmPrinter::runOnMachineFunction(MF);
124     emitXRayTable();
125     return Changed;
126   }
127 };
128 
129 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
130 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
131 public:
132   explicit PPCLinuxAsmPrinter(TargetMachine &TM,
133                               std::unique_ptr<MCStreamer> Streamer)
134       : PPCAsmPrinter(TM, std::move(Streamer)) {}
135 
136   StringRef getPassName() const override {
137     return "Linux PPC Assembly Printer";
138   }
139 
140   bool doFinalization(Module &M) override;
141   void EmitStartOfAsmFile(Module &M) override;
142 
143   void EmitFunctionEntryLabel() override;
144 
145   void EmitFunctionBodyStart() override;
146   void EmitFunctionBodyEnd() override;
147   void EmitInstruction(const MachineInstr *MI) override;
148 };
149 
150 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
151 /// OS X
152 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
153 public:
154   explicit PPCDarwinAsmPrinter(TargetMachine &TM,
155                                std::unique_ptr<MCStreamer> Streamer)
156       : PPCAsmPrinter(TM, std::move(Streamer)) {}
157 
158   StringRef getPassName() const override {
159     return "Darwin PPC Assembly Printer";
160   }
161 
162   bool doFinalization(Module &M) override;
163   void EmitStartOfAsmFile(Module &M) override;
164 };
165 
166 class PPCAIXAsmPrinter : public PPCAsmPrinter {
167 private:
168   static void ValidateGV(const GlobalVariable *GV);
169 protected:
170   MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO) override;
171 
172 public:
173   PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
174       : PPCAsmPrinter(TM, std::move(Streamer)) {}
175 
176   StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
177 
178   void SetupMachineFunction(MachineFunction &MF) override;
179 
180   void EmitGlobalVariable(const GlobalVariable *GV) override;
181 
182   void EmitFunctionDescriptor() override;
183 
184   void EmitEndOfAsmFile(Module &) override;
185 };
186 
187 } // end anonymous namespace
188 
189 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
190                                        raw_ostream &O) {
191   // Computing the address of a global symbol, not calling it.
192   const GlobalValue *GV = MO.getGlobal();
193   MCSymbol *SymToPrint;
194 
195   // External or weakly linked global variables need non-lazily-resolved stubs
196   if (Subtarget->hasLazyResolverStub(GV)) {
197     SymToPrint = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
198     MachineModuleInfoImpl::StubValueTy &StubSym =
199         MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(
200             SymToPrint);
201     if (!StubSym.getPointer())
202       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
203                                                    !GV->hasInternalLinkage());
204   } else {
205     SymToPrint = getSymbol(GV);
206   }
207 
208   SymToPrint->print(O, MAI);
209 
210   printOffset(MO.getOffset(), O);
211 }
212 
213 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
214                                  raw_ostream &O) {
215   const DataLayout &DL = getDataLayout();
216   const MachineOperand &MO = MI->getOperand(OpNo);
217 
218   switch (MO.getType()) {
219   case MachineOperand::MO_Register: {
220     // The MI is INLINEASM ONLY and UseVSXReg is always false.
221     const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
222 
223     // Linux assembler (Others?) does not take register mnemonics.
224     // FIXME - What about special registers used in mfspr/mtspr?
225     if (!Subtarget->isDarwin())
226       RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
227     O << 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 'y': // A memory reference for an X-form instruction
316       {
317         const char *RegName = "r0";
318         if (!Subtarget->isDarwin())
319           RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
320         O << RegName << ", ";
321         printOperand(MI, OpNo, O);
322         return false;
323       }
324     case 'U': // Print 'u' for update form.
325     case 'X': // Print 'x' for indexed form.
326     {
327       // FIXME: Currently for PowerPC memory operands are always loaded
328       // into a register, so we never get an update or indexed form.
329       // This is bad even for offset forms, since even if we know we
330       // have a value in -16(r1), we will generate a load into r<n>
331       // and then load from 0(r<n>).  Until that issue is fixed,
332       // tolerate 'U' and 'X' but don't output anything.
333       assert(MI->getOperand(OpNo).isReg());
334       return false;
335     }
336     }
337   }
338 
339   assert(MI->getOperand(OpNo).isReg());
340   O << "0(";
341   printOperand(MI, OpNo, O);
342   O << ")";
343   return false;
344 }
345 
346 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
347 /// exists for it.  If not, create one.  Then return a symbol that references
348 /// the TOC entry.
349 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym) {
350   MCSymbol *&TOCEntry = TOC[Sym];
351   if (!TOCEntry)
352     TOCEntry = createTempSymbol("C");
353   return TOCEntry;
354 }
355 
356 void PPCAsmPrinter::EmitEndOfAsmFile(Module &M) {
357   emitStackMaps(SM);
358 }
359 
360 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
361   unsigned NumNOPBytes = MI.getOperand(1).getImm();
362 
363   auto &Ctx = OutStreamer->getContext();
364   MCSymbol *MILabel = Ctx.createTempSymbol();
365   OutStreamer->EmitLabel(MILabel);
366 
367   SM.recordStackMap(*MILabel, MI);
368   assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
369 
370   // Scan ahead to trim the shadow.
371   const MachineBasicBlock &MBB = *MI.getParent();
372   MachineBasicBlock::const_iterator MII(MI);
373   ++MII;
374   while (NumNOPBytes > 0) {
375     if (MII == MBB.end() || MII->isCall() ||
376         MII->getOpcode() == PPC::DBG_VALUE ||
377         MII->getOpcode() == TargetOpcode::PATCHPOINT ||
378         MII->getOpcode() == TargetOpcode::STACKMAP)
379       break;
380     ++MII;
381     NumNOPBytes -= 4;
382   }
383 
384   // Emit nops.
385   for (unsigned i = 0; i < NumNOPBytes; i += 4)
386     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
387 }
388 
389 // Lower a patchpoint of the form:
390 // [<def>], <id>, <numBytes>, <target>, <numArgs>
391 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
392   auto &Ctx = OutStreamer->getContext();
393   MCSymbol *MILabel = Ctx.createTempSymbol();
394   OutStreamer->EmitLabel(MILabel);
395 
396   SM.recordPatchPoint(*MILabel, MI);
397   PatchPointOpers Opers(&MI);
398 
399   unsigned EncodedBytes = 0;
400   const MachineOperand &CalleeMO = Opers.getCallTarget();
401 
402   if (CalleeMO.isImm()) {
403     int64_t CallTarget = CalleeMO.getImm();
404     if (CallTarget) {
405       assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
406              "High 16 bits of call target should be zero.");
407       Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
408       EncodedBytes = 0;
409       // Materialize the jump address:
410       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
411                                       .addReg(ScratchReg)
412                                       .addImm((CallTarget >> 32) & 0xFFFF));
413       ++EncodedBytes;
414       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
415                                       .addReg(ScratchReg)
416                                       .addReg(ScratchReg)
417                                       .addImm(32).addImm(16));
418       ++EncodedBytes;
419       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
420                                       .addReg(ScratchReg)
421                                       .addReg(ScratchReg)
422                                       .addImm((CallTarget >> 16) & 0xFFFF));
423       ++EncodedBytes;
424       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
425                                       .addReg(ScratchReg)
426                                       .addReg(ScratchReg)
427                                       .addImm(CallTarget & 0xFFFF));
428 
429       // Save the current TOC pointer before the remote call.
430       int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
431       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
432                                       .addReg(PPC::X2)
433                                       .addImm(TOCSaveOffset)
434                                       .addReg(PPC::X1));
435       ++EncodedBytes;
436 
437       // If we're on ELFv1, then we need to load the actual function pointer
438       // from the function descriptor.
439       if (!Subtarget->isELFv2ABI()) {
440         // Load the new TOC pointer and the function address, but not r11
441         // (needing this is rare, and loading it here would prevent passing it
442         // via a 'nest' parameter.
443         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
444                                         .addReg(PPC::X2)
445                                         .addImm(8)
446                                         .addReg(ScratchReg));
447         ++EncodedBytes;
448         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
449                                         .addReg(ScratchReg)
450                                         .addImm(0)
451                                         .addReg(ScratchReg));
452         ++EncodedBytes;
453       }
454 
455       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
456                                       .addReg(ScratchReg));
457       ++EncodedBytes;
458       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
459       ++EncodedBytes;
460 
461       // Restore the TOC pointer after the call.
462       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
463                                       .addReg(PPC::X2)
464                                       .addImm(TOCSaveOffset)
465                                       .addReg(PPC::X1));
466       ++EncodedBytes;
467     }
468   } else if (CalleeMO.isGlobal()) {
469     const GlobalValue *GValue = CalleeMO.getGlobal();
470     MCSymbol *MOSymbol = getSymbol(GValue);
471     const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
472 
473     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
474                                     .addExpr(SymVar));
475     EncodedBytes += 2;
476   }
477 
478   // Each instruction is 4 bytes.
479   EncodedBytes *= 4;
480 
481   // Emit padding.
482   unsigned NumBytes = Opers.getNumPatchBytes();
483   assert(NumBytes >= EncodedBytes &&
484          "Patchpoint can't request size less than the length of a call.");
485   assert((NumBytes - EncodedBytes) % 4 == 0 &&
486          "Invalid number of NOP bytes requested!");
487   for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
488     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
489 }
490 
491 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
492 /// call to __tls_get_addr to the current output stream.
493 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
494                                 MCSymbolRefExpr::VariantKind VK) {
495   StringRef Name = "__tls_get_addr";
496   MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name);
497   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
498   const Module *M = MF->getFunction().getParent();
499 
500   assert(MI->getOperand(0).isReg() &&
501          ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
502           (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
503          "GETtls[ld]ADDR[32] must define GPR3");
504   assert(MI->getOperand(1).isReg() &&
505          ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
506           (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
507          "GETtls[ld]ADDR[32] must read GPR3");
508 
509   if (!Subtarget->isPPC64() && !Subtarget->isDarwin() &&
510       isPositionIndependent())
511     Kind = MCSymbolRefExpr::VK_PLT;
512   const MCExpr *TlsRef =
513     MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
514 
515   // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
516   if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
517       M->getPICLevel() == PICLevel::BigPIC)
518     TlsRef = MCBinaryExpr::createAdd(
519         TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
520   const MachineOperand &MO = MI->getOperand(2);
521   const GlobalValue *GValue = MO.getGlobal();
522   MCSymbol *MOSymbol = getSymbol(GValue);
523   const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
524   EmitToStreamer(*OutStreamer,
525                  MCInstBuilder(Subtarget->isPPC64() ?
526                                PPC::BL8_NOP_TLS : PPC::BL_TLS)
527                  .addExpr(TlsRef)
528                  .addExpr(SymVar));
529 }
530 
531 /// Map a machine operand for a TOC pseudo-machine instruction to its
532 /// corresponding MCSymbol.
533 MCSymbol *PPCAsmPrinter::getMCSymbolForTOCPseudoMO(const MachineOperand &MO) {
534   switch (MO.getType()) {
535   case MachineOperand::MO_GlobalAddress:
536     return getSymbol(MO.getGlobal());
537   case MachineOperand::MO_ConstantPoolIndex:
538     return GetCPISymbol(MO.getIndex());
539   case MachineOperand::MO_JumpTableIndex:
540     return GetJTISymbol(MO.getIndex());
541   case MachineOperand::MO_BlockAddress:
542     return GetBlockAddressSymbol(MO.getBlockAddress());
543   default:
544     llvm_unreachable("Unexpected operand type to get symbol.");
545   }
546 }
547 
548 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
549 /// the current output stream.
550 ///
551 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
552   MCInst TmpInst;
553   const bool IsDarwin = TM.getTargetTriple().isOSDarwin();
554   const bool IsPPC64 = Subtarget->isPPC64();
555   const bool IsAIX = Subtarget->isAIXABI();
556   const Module *M = MF->getFunction().getParent();
557   PICLevel::Level PL = M->getPICLevel();
558 
559 #ifndef NDEBUG
560   // Validate that SPE and FPU are mutually exclusive in codegen
561   if (!MI->isInlineAsm()) {
562     for (const MachineOperand &MO: MI->operands()) {
563       if (MO.isReg()) {
564         Register Reg = MO.getReg();
565         if (Subtarget->hasSPE()) {
566           if (PPC::F4RCRegClass.contains(Reg) ||
567               PPC::F8RCRegClass.contains(Reg) ||
568               PPC::QBRCRegClass.contains(Reg) ||
569               PPC::QFRCRegClass.contains(Reg) ||
570               PPC::QSRCRegClass.contains(Reg) ||
571               PPC::VFRCRegClass.contains(Reg) ||
572               PPC::VRRCRegClass.contains(Reg) ||
573               PPC::VSFRCRegClass.contains(Reg) ||
574               PPC::VSSRCRegClass.contains(Reg)
575               )
576             llvm_unreachable("SPE targets cannot have FPRegs!");
577         } else {
578           if (PPC::SPERCRegClass.contains(Reg))
579             llvm_unreachable("SPE register found in FPU-targeted code!");
580         }
581       }
582     }
583   }
584 #endif
585   // Lower multi-instruction pseudo operations.
586   switch (MI->getOpcode()) {
587   default: break;
588   case TargetOpcode::DBG_VALUE:
589     llvm_unreachable("Should be handled target independently");
590   case TargetOpcode::STACKMAP:
591     return LowerSTACKMAP(SM, *MI);
592   case TargetOpcode::PATCHPOINT:
593     return LowerPATCHPOINT(SM, *MI);
594 
595   case PPC::MoveGOTtoLR: {
596     // Transform %lr = MoveGOTtoLR
597     // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
598     // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
599     // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
600     //      blrl
601     // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
602     MCSymbol *GOTSymbol =
603       OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
604     const MCExpr *OffsExpr =
605       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
606                                                       MCSymbolRefExpr::VK_PPC_LOCAL,
607                                                       OutContext),
608                               MCConstantExpr::create(4, OutContext),
609                               OutContext);
610 
611     // Emit the 'bl'.
612     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
613     return;
614   }
615   case PPC::MovePCtoLR:
616   case PPC::MovePCtoLR8: {
617     // Transform %lr = MovePCtoLR
618     // Into this, where the label is the PIC base:
619     //     bl L1$pb
620     // L1$pb:
621     MCSymbol *PICBase = MF->getPICBaseSymbol();
622 
623     // Emit the 'bl'.
624     EmitToStreamer(*OutStreamer,
625                    MCInstBuilder(PPC::BL)
626                        // FIXME: We would like an efficient form for this, so we
627                        // don't have to do a lot of extra uniquing.
628                        .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
629 
630     // Emit the label.
631     OutStreamer->EmitLabel(PICBase);
632     return;
633   }
634   case PPC::UpdateGBR: {
635     // Transform %rd = UpdateGBR(%rt, %ri)
636     // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
637     //       add %rd, %rt, %ri
638     // or into (if secure plt mode is on):
639     //       addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
640     //       addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
641     // Get the offset from the GOT Base Register to the GOT
642     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
643     if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
644       unsigned PICR = TmpInst.getOperand(0).getReg();
645       MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
646           M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
647                                                  : ".LTOC");
648       const MCExpr *PB =
649           MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
650 
651       const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
652           MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
653 
654       const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, false, OutContext);
655       EmitToStreamer(
656           *OutStreamer,
657           MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
658 
659       const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, false, OutContext);
660       EmitToStreamer(
661           *OutStreamer,
662           MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
663       return;
664     } else {
665       MCSymbol *PICOffset =
666         MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol();
667       TmpInst.setOpcode(PPC::LWZ);
668       const MCExpr *Exp =
669         MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
670       const MCExpr *PB =
671         MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
672                                 MCSymbolRefExpr::VK_None,
673                                 OutContext);
674       const MCOperand TR = TmpInst.getOperand(1);
675       const MCOperand PICR = TmpInst.getOperand(0);
676 
677       // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
678       TmpInst.getOperand(1) =
679           MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
680       TmpInst.getOperand(0) = TR;
681       TmpInst.getOperand(2) = PICR;
682       EmitToStreamer(*OutStreamer, TmpInst);
683 
684       TmpInst.setOpcode(PPC::ADD4);
685       TmpInst.getOperand(0) = PICR;
686       TmpInst.getOperand(1) = TR;
687       TmpInst.getOperand(2) = PICR;
688       EmitToStreamer(*OutStreamer, TmpInst);
689       return;
690     }
691   }
692   case PPC::LWZtoc: {
693     assert(!IsDarwin && "TOC is an ELF/XCOFF construct.");
694 
695     // Transform %rN = LWZtoc @op1, %r2
696     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
697 
698     // Change the opcode to LWZ.
699     TmpInst.setOpcode(PPC::LWZ);
700 
701     const MachineOperand &MO = MI->getOperand(1);
702     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
703            "Invalid operand for LWZtoc.");
704 
705     // Map the operand to its corresponding MCSymbol.
706     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO);
707 
708     // Create a reference to the GOT entry for the symbol. The GOT entry will be
709     // synthesized later.
710     if (PL == PICLevel::SmallPIC && !IsAIX) {
711       const MCExpr *Exp =
712         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
713                                 OutContext);
714       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
715       EmitToStreamer(*OutStreamer, TmpInst);
716       return;
717     }
718 
719     // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
720     // storage allocated in the TOC which contains the address of
721     // 'MOSymbol'. Said TOC entry will be synthesized later.
722     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
723     const MCExpr *Exp =
724         MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
725 
726     // AIX uses the label directly as the lwz displacement operand for
727     // references into the toc section. The displacement value will be generated
728     // relative to the toc-base.
729     if (IsAIX) {
730       assert(
731           TM.getCodeModel() == CodeModel::Small &&
732           "This pseudo should only be selected for 32-bit small code model.");
733       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
734       EmitToStreamer(*OutStreamer, TmpInst);
735       return;
736     }
737 
738     // Create an explicit subtract expression between the local symbol and
739     // '.LTOC' to manifest the toc-relative offset.
740     const MCExpr *PB = MCSymbolRefExpr::create(
741         OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
742     Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
743     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
744     EmitToStreamer(*OutStreamer, TmpInst);
745     return;
746   }
747   case PPC::LDtocJTI:
748   case PPC::LDtocCPT:
749   case PPC::LDtocBA:
750   case PPC::LDtoc: {
751     assert(!IsDarwin && "TOC is an ELF/XCOFF construct");
752 
753     // Transform %x3 = LDtoc @min1, %x2
754     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
755 
756     // Change the opcode to LD.
757     TmpInst.setOpcode(PPC::LD);
758 
759     const MachineOperand &MO = MI->getOperand(1);
760     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
761            "Invalid operand!");
762 
763     // Map the machine operand to its corresponding MCSymbol, then map the
764     // global address operand to be a reference to the TOC entry we will
765     // synthesize later.
766     MCSymbol *TOCEntry =
767         lookUpOrCreateTOCEntry(getMCSymbolForTOCPseudoMO(MO));
768 
769     const MCSymbolRefExpr::VariantKind VK =
770         IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
771     const MCExpr *Exp =
772         MCSymbolRefExpr::create(TOCEntry, VK, OutContext);
773     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
774     EmitToStreamer(*OutStreamer, TmpInst);
775     return;
776   }
777   case PPC::ADDIStocHA: {
778     assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
779            "This pseudo should only be selected for 32-bit large code model on"
780            " AIX.");
781 
782     // Transform %rd = ADDIStocHA %rA, @sym(%r2)
783     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
784 
785     // Change the opcode to ADDIS.
786     TmpInst.setOpcode(PPC::ADDIS);
787 
788     const MachineOperand &MO = MI->getOperand(2);
789     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
790            "Invalid operand for ADDIStocHA.");
791 
792     // Map the machine operand to its corresponding MCSymbol.
793     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO);
794 
795     // Always use TOC on AIX. Map the global address operand to be a reference
796     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
797     // reference the storage allocated in the TOC which contains the address of
798     // 'MOSymbol'.
799     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
800     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
801                                                 MCSymbolRefExpr::VK_PPC_U,
802                                                 OutContext);
803     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
804     EmitToStreamer(*OutStreamer, TmpInst);
805     return;
806   }
807   case PPC::LWZtocL: {
808     assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
809            "This pseudo should only be selected for 32-bit large code model on"
810            " AIX.");
811 
812     // Transform %rd = LWZtocL @sym, %rs.
813     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
814 
815     // Change the opcode to lwz.
816     TmpInst.setOpcode(PPC::LWZ);
817 
818     const MachineOperand &MO = MI->getOperand(1);
819     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
820            "Invalid operand for LWZtocL.");
821 
822     // Map the machine operand to its corresponding MCSymbol.
823     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO);
824 
825     // Always use TOC on AIX. Map the global address operand to be a reference
826     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
827     // reference the storage allocated in the TOC which contains the address of
828     // 'MOSymbol'.
829     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
830     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
831                                                 MCSymbolRefExpr::VK_PPC_L,
832                                                 OutContext);
833     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
834     EmitToStreamer(*OutStreamer, TmpInst);
835     return;
836   }
837   case PPC::ADDIStocHA8: {
838     assert(!IsDarwin && "TOC is an ELF/XCOFF construct");
839 
840     // Transform %xd = ADDIStocHA8 %x2, @sym
841     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
842 
843     // Change the opcode to ADDIS8. If the global address is the address of
844     // an external symbol, is a jump table address, is a block address, or is a
845     // constant pool index with large code model enabled, then generate a TOC
846     // entry and reference that. Otherwise, reference the symbol directly.
847     TmpInst.setOpcode(PPC::ADDIS8);
848 
849     const MachineOperand &MO = MI->getOperand(2);
850     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
851            "Invalid operand for ADDIStocHA8!");
852 
853     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO);
854 
855     const bool GlobalToc =
856         MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
857     if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
858         (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
859       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
860 
861     const MCSymbolRefExpr::VariantKind VK =
862         IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA;
863 
864     const MCExpr *Exp =
865         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
866 
867     if (!MO.isJTI() && MO.getOffset())
868       Exp = MCBinaryExpr::createAdd(Exp,
869                                     MCConstantExpr::create(MO.getOffset(),
870                                                            OutContext),
871                                     OutContext);
872 
873     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
874     EmitToStreamer(*OutStreamer, TmpInst);
875     return;
876   }
877   case PPC::LDtocL: {
878     assert(!IsDarwin && "TOC is an ELF/XCOFF construct");
879 
880     // Transform %xd = LDtocL @sym, %xs
881     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
882 
883     // Change the opcode to LD. If the global address is the address of
884     // an external symbol, is a jump table address, is a block address, or is
885     // a constant pool index with large code model enabled, then generate a
886     // TOC entry and reference that. Otherwise, reference the symbol directly.
887     TmpInst.setOpcode(PPC::LD);
888 
889     const MachineOperand &MO = MI->getOperand(1);
890     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
891             MO.isBlockAddress()) &&
892            "Invalid operand for LDtocL!");
893 
894     LLVM_DEBUG(assert(
895         (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
896         "LDtocL used on symbol that could be accessed directly is "
897         "invalid. Must match ADDIStocHA8."));
898 
899     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO);
900 
901     if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
902       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
903 
904     const MCSymbolRefExpr::VariantKind VK =
905         IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO;
906     const MCExpr *Exp =
907         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
908     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
909     EmitToStreamer(*OutStreamer, TmpInst);
910     return;
911   }
912   case PPC::ADDItocL: {
913     // Transform %xd = ADDItocL %xs, @sym
914     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
915 
916     // Change the opcode to ADDI8. If the global address is external, then
917     // generate a TOC entry and reference that. Otherwise, reference the
918     // symbol directly.
919     TmpInst.setOpcode(PPC::ADDI8);
920 
921     const MachineOperand &MO = MI->getOperand(2);
922     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
923 
924     LLVM_DEBUG(assert(
925         !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
926         "Interposable definitions must use indirect access."));
927 
928     const MCExpr *Exp =
929         MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO),
930                                 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
931     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
932     EmitToStreamer(*OutStreamer, TmpInst);
933     return;
934   }
935   case PPC::ADDISgotTprelHA: {
936     // Transform: %xd = ADDISgotTprelHA %x2, @sym
937     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
938     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
939     const MachineOperand &MO = MI->getOperand(2);
940     const GlobalValue *GValue = MO.getGlobal();
941     MCSymbol *MOSymbol = getSymbol(GValue);
942     const MCExpr *SymGotTprel =
943         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
944                                 OutContext);
945     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
946                                  .addReg(MI->getOperand(0).getReg())
947                                  .addReg(MI->getOperand(1).getReg())
948                                  .addExpr(SymGotTprel));
949     return;
950   }
951   case PPC::LDgotTprelL:
952   case PPC::LDgotTprelL32: {
953     // Transform %xd = LDgotTprelL @sym, %xs
954     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
955 
956     // Change the opcode to LD.
957     TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
958     const MachineOperand &MO = MI->getOperand(1);
959     const GlobalValue *GValue = MO.getGlobal();
960     MCSymbol *MOSymbol = getSymbol(GValue);
961     const MCExpr *Exp = MCSymbolRefExpr::create(
962         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
963                           : MCSymbolRefExpr::VK_PPC_GOT_TPREL,
964         OutContext);
965     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
966     EmitToStreamer(*OutStreamer, TmpInst);
967     return;
968   }
969 
970   case PPC::PPC32PICGOT: {
971     MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
972     MCSymbol *GOTRef = OutContext.createTempSymbol();
973     MCSymbol *NextInstr = OutContext.createTempSymbol();
974 
975     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
976       // FIXME: We would like an efficient form for this, so we don't have to do
977       // a lot of extra uniquing.
978       .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
979     const MCExpr *OffsExpr =
980       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
981                                 MCSymbolRefExpr::create(GOTRef, OutContext),
982         OutContext);
983     OutStreamer->EmitLabel(GOTRef);
984     OutStreamer->EmitValue(OffsExpr, 4);
985     OutStreamer->EmitLabel(NextInstr);
986     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
987                                  .addReg(MI->getOperand(0).getReg()));
988     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
989                                  .addReg(MI->getOperand(1).getReg())
990                                  .addImm(0)
991                                  .addReg(MI->getOperand(0).getReg()));
992     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
993                                  .addReg(MI->getOperand(0).getReg())
994                                  .addReg(MI->getOperand(1).getReg())
995                                  .addReg(MI->getOperand(0).getReg()));
996     return;
997   }
998   case PPC::PPC32GOT: {
999     MCSymbol *GOTSymbol =
1000         OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1001     const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1002         GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1003     const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1004         GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1005     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1006                                  .addReg(MI->getOperand(0).getReg())
1007                                  .addExpr(SymGotTlsL));
1008     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1009                                  .addReg(MI->getOperand(0).getReg())
1010                                  .addReg(MI->getOperand(0).getReg())
1011                                  .addExpr(SymGotTlsHA));
1012     return;
1013   }
1014   case PPC::ADDIStlsgdHA: {
1015     // Transform: %xd = ADDIStlsgdHA %x2, @sym
1016     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1017     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1018     const MachineOperand &MO = MI->getOperand(2);
1019     const GlobalValue *GValue = MO.getGlobal();
1020     MCSymbol *MOSymbol = getSymbol(GValue);
1021     const MCExpr *SymGotTlsGD =
1022       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
1023                               OutContext);
1024     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1025                                  .addReg(MI->getOperand(0).getReg())
1026                                  .addReg(MI->getOperand(1).getReg())
1027                                  .addExpr(SymGotTlsGD));
1028     return;
1029   }
1030   case PPC::ADDItlsgdL:
1031     // Transform: %xd = ADDItlsgdL %xs, @sym
1032     // Into:      %xd = ADDI8 %xs, sym@got@tlsgd@l
1033   case PPC::ADDItlsgdL32: {
1034     // Transform: %rd = ADDItlsgdL32 %rs, @sym
1035     // Into:      %rd = ADDI %rs, sym@got@tlsgd
1036     const MachineOperand &MO = MI->getOperand(2);
1037     const GlobalValue *GValue = MO.getGlobal();
1038     MCSymbol *MOSymbol = getSymbol(GValue);
1039     const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1040         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1041                           : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
1042         OutContext);
1043     EmitToStreamer(*OutStreamer,
1044                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1045                    .addReg(MI->getOperand(0).getReg())
1046                    .addReg(MI->getOperand(1).getReg())
1047                    .addExpr(SymGotTlsGD));
1048     return;
1049   }
1050   case PPC::GETtlsADDR:
1051     // Transform: %x3 = GETtlsADDR %x3, @sym
1052     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1053   case PPC::GETtlsADDR32: {
1054     // Transform: %r3 = GETtlsADDR32 %r3, @sym
1055     // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1056     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1057     return;
1058   }
1059   case PPC::ADDIStlsldHA: {
1060     // Transform: %xd = ADDIStlsldHA %x2, @sym
1061     // Into:      %xd = ADDIS8 %x2, sym@got@tlsld@ha
1062     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1063     const MachineOperand &MO = MI->getOperand(2);
1064     const GlobalValue *GValue = MO.getGlobal();
1065     MCSymbol *MOSymbol = getSymbol(GValue);
1066     const MCExpr *SymGotTlsLD =
1067       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
1068                               OutContext);
1069     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1070                                  .addReg(MI->getOperand(0).getReg())
1071                                  .addReg(MI->getOperand(1).getReg())
1072                                  .addExpr(SymGotTlsLD));
1073     return;
1074   }
1075   case PPC::ADDItlsldL:
1076     // Transform: %xd = ADDItlsldL %xs, @sym
1077     // Into:      %xd = ADDI8 %xs, sym@got@tlsld@l
1078   case PPC::ADDItlsldL32: {
1079     // Transform: %rd = ADDItlsldL32 %rs, @sym
1080     // Into:      %rd = ADDI %rs, sym@got@tlsld
1081     const MachineOperand &MO = MI->getOperand(2);
1082     const GlobalValue *GValue = MO.getGlobal();
1083     MCSymbol *MOSymbol = getSymbol(GValue);
1084     const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1085         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1086                           : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
1087         OutContext);
1088     EmitToStreamer(*OutStreamer,
1089                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1090                        .addReg(MI->getOperand(0).getReg())
1091                        .addReg(MI->getOperand(1).getReg())
1092                        .addExpr(SymGotTlsLD));
1093     return;
1094   }
1095   case PPC::GETtlsldADDR:
1096     // Transform: %x3 = GETtlsldADDR %x3, @sym
1097     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1098   case PPC::GETtlsldADDR32: {
1099     // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1100     // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1101     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1102     return;
1103   }
1104   case PPC::ADDISdtprelHA:
1105     // Transform: %xd = ADDISdtprelHA %xs, @sym
1106     // Into:      %xd = ADDIS8 %xs, sym@dtprel@ha
1107   case PPC::ADDISdtprelHA32: {
1108     // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1109     // Into:      %rd = ADDIS %rs, sym@dtprel@ha
1110     const MachineOperand &MO = MI->getOperand(2);
1111     const GlobalValue *GValue = MO.getGlobal();
1112     MCSymbol *MOSymbol = getSymbol(GValue);
1113     const MCExpr *SymDtprel =
1114       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
1115                               OutContext);
1116     EmitToStreamer(
1117         *OutStreamer,
1118         MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1119             .addReg(MI->getOperand(0).getReg())
1120             .addReg(MI->getOperand(1).getReg())
1121             .addExpr(SymDtprel));
1122     return;
1123   }
1124   case PPC::ADDIdtprelL:
1125     // Transform: %xd = ADDIdtprelL %xs, @sym
1126     // Into:      %xd = ADDI8 %xs, sym@dtprel@l
1127   case PPC::ADDIdtprelL32: {
1128     // Transform: %rd = ADDIdtprelL32 %rs, @sym
1129     // Into:      %rd = ADDI %rs, sym@dtprel@l
1130     const MachineOperand &MO = MI->getOperand(2);
1131     const GlobalValue *GValue = MO.getGlobal();
1132     MCSymbol *MOSymbol = getSymbol(GValue);
1133     const MCExpr *SymDtprel =
1134       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
1135                               OutContext);
1136     EmitToStreamer(*OutStreamer,
1137                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1138                        .addReg(MI->getOperand(0).getReg())
1139                        .addReg(MI->getOperand(1).getReg())
1140                        .addExpr(SymDtprel));
1141     return;
1142   }
1143   case PPC::MFOCRF:
1144   case PPC::MFOCRF8:
1145     if (!Subtarget->hasMFOCRF()) {
1146       // Transform: %r3 = MFOCRF %cr7
1147       // Into:      %r3 = MFCR   ;; cr7
1148       unsigned NewOpcode =
1149         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1150       OutStreamer->AddComment(PPCInstPrinter::
1151                               getRegisterName(MI->getOperand(1).getReg()));
1152       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1153                                   .addReg(MI->getOperand(0).getReg()));
1154       return;
1155     }
1156     break;
1157   case PPC::MTOCRF:
1158   case PPC::MTOCRF8:
1159     if (!Subtarget->hasMFOCRF()) {
1160       // Transform: %cr7 = MTOCRF %r3
1161       // Into:      MTCRF mask, %r3 ;; cr7
1162       unsigned NewOpcode =
1163         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1164       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1165                               ->getEncodingValue(MI->getOperand(0).getReg());
1166       OutStreamer->AddComment(PPCInstPrinter::
1167                               getRegisterName(MI->getOperand(0).getReg()));
1168       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1169                                      .addImm(Mask)
1170                                      .addReg(MI->getOperand(1).getReg()));
1171       return;
1172     }
1173     break;
1174   case PPC::LD:
1175   case PPC::STD:
1176   case PPC::LWA_32:
1177   case PPC::LWA: {
1178     // Verify alignment is legal, so we don't create relocations
1179     // that can't be supported.
1180     // FIXME:  This test is currently disabled for Darwin.  The test
1181     // suite shows a handful of test cases that fail this check for
1182     // Darwin.  Those need to be investigated before this sanity test
1183     // can be enabled for those subtargets.
1184     if (!IsDarwin) {
1185       unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1186       const MachineOperand &MO = MI->getOperand(OpNum);
1187       if (MO.isGlobal() && MO.getGlobal()->getAlignment() < 4)
1188         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1189     }
1190     // Now process the instruction normally.
1191     break;
1192   }
1193   }
1194 
1195   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, IsDarwin);
1196   EmitToStreamer(*OutStreamer, TmpInst);
1197 }
1198 
1199 void PPCLinuxAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1200   if (!Subtarget->isPPC64())
1201     return PPCAsmPrinter::EmitInstruction(MI);
1202 
1203   switch (MI->getOpcode()) {
1204   default:
1205     return PPCAsmPrinter::EmitInstruction(MI);
1206   case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1207     // .begin:
1208     //   b .end # lis 0, FuncId[16..32]
1209     //   nop    # li  0, FuncId[0..15]
1210     //   std 0, -8(1)
1211     //   mflr 0
1212     //   bl __xray_FunctionEntry
1213     //   mtlr 0
1214     // .end:
1215     //
1216     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1217     // of instructions change.
1218     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1219     MCSymbol *EndOfSled = OutContext.createTempSymbol();
1220     OutStreamer->EmitLabel(BeginOfSled);
1221     EmitToStreamer(*OutStreamer,
1222                    MCInstBuilder(PPC::B).addExpr(
1223                        MCSymbolRefExpr::create(EndOfSled, OutContext)));
1224     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1225     EmitToStreamer(
1226         *OutStreamer,
1227         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1228     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1229     EmitToStreamer(*OutStreamer,
1230                    MCInstBuilder(PPC::BL8_NOP)
1231                        .addExpr(MCSymbolRefExpr::create(
1232                            OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1233                            OutContext)));
1234     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1235     OutStreamer->EmitLabel(EndOfSled);
1236     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER);
1237     break;
1238   }
1239   case TargetOpcode::PATCHABLE_RET: {
1240     unsigned RetOpcode = MI->getOperand(0).getImm();
1241     MCInst RetInst;
1242     RetInst.setOpcode(RetOpcode);
1243     for (const auto &MO :
1244          make_range(std::next(MI->operands_begin()), MI->operands_end())) {
1245       MCOperand MCOp;
1246       if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this, false))
1247         RetInst.addOperand(MCOp);
1248     }
1249 
1250     bool IsConditional;
1251     if (RetOpcode == PPC::BCCLR) {
1252       IsConditional = true;
1253     } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1254                RetOpcode == PPC::TCRETURNai8) {
1255       break;
1256     } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1257       IsConditional = false;
1258     } else {
1259       EmitToStreamer(*OutStreamer, RetInst);
1260       break;
1261     }
1262 
1263     MCSymbol *FallthroughLabel;
1264     if (IsConditional) {
1265       // Before:
1266       //   bgtlr cr0
1267       //
1268       // After:
1269       //   ble cr0, .end
1270       // .p2align 3
1271       // .begin:
1272       //   blr    # lis 0, FuncId[16..32]
1273       //   nop    # li  0, FuncId[0..15]
1274       //   std 0, -8(1)
1275       //   mflr 0
1276       //   bl __xray_FunctionExit
1277       //   mtlr 0
1278       //   blr
1279       // .end:
1280       //
1281       // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1282       // of instructions change.
1283       FallthroughLabel = OutContext.createTempSymbol();
1284       EmitToStreamer(
1285           *OutStreamer,
1286           MCInstBuilder(PPC::BCC)
1287               .addImm(PPC::InvertPredicate(
1288                   static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1289               .addReg(MI->getOperand(2).getReg())
1290               .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1291       RetInst = MCInst();
1292       RetInst.setOpcode(PPC::BLR8);
1293     }
1294     // .p2align 3
1295     // .begin:
1296     //   b(lr)? # lis 0, FuncId[16..32]
1297     //   nop    # li  0, FuncId[0..15]
1298     //   std 0, -8(1)
1299     //   mflr 0
1300     //   bl __xray_FunctionExit
1301     //   mtlr 0
1302     //   b(lr)?
1303     //
1304     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1305     // of instructions change.
1306     OutStreamer->EmitCodeAlignment(8);
1307     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1308     OutStreamer->EmitLabel(BeginOfSled);
1309     EmitToStreamer(*OutStreamer, RetInst);
1310     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1311     EmitToStreamer(
1312         *OutStreamer,
1313         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1314     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1315     EmitToStreamer(*OutStreamer,
1316                    MCInstBuilder(PPC::BL8_NOP)
1317                        .addExpr(MCSymbolRefExpr::create(
1318                            OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1319                            OutContext)));
1320     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1321     EmitToStreamer(*OutStreamer, RetInst);
1322     if (IsConditional)
1323       OutStreamer->EmitLabel(FallthroughLabel);
1324     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT);
1325     break;
1326   }
1327   case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1328     llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1329   case TargetOpcode::PATCHABLE_TAIL_CALL:
1330     // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1331     // normal function exit from a tail exit.
1332     llvm_unreachable("Tail call is handled in the normal case. See comments "
1333                      "around this assert.");
1334   }
1335 }
1336 
1337 void PPCLinuxAsmPrinter::EmitStartOfAsmFile(Module &M) {
1338   if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1339     PPCTargetStreamer *TS =
1340       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1341 
1342     if (TS)
1343       TS->emitAbiVersion(2);
1344   }
1345 
1346   if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1347       !isPositionIndependent())
1348     return AsmPrinter::EmitStartOfAsmFile(M);
1349 
1350   if (M.getPICLevel() == PICLevel::SmallPIC)
1351     return AsmPrinter::EmitStartOfAsmFile(M);
1352 
1353   OutStreamer->SwitchSection(OutContext.getELFSection(
1354       ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1355 
1356   MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1357   MCSymbol *CurrentPos = OutContext.createTempSymbol();
1358 
1359   OutStreamer->EmitLabel(CurrentPos);
1360 
1361   // The GOT pointer points to the middle of the GOT, in order to reference the
1362   // entire 64kB range.  0x8000 is the midpoint.
1363   const MCExpr *tocExpr =
1364     MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1365                             MCConstantExpr::create(0x8000, OutContext),
1366                             OutContext);
1367 
1368   OutStreamer->EmitAssignment(TOCSym, tocExpr);
1369 
1370   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1371 }
1372 
1373 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
1374   // linux/ppc32 - Normal entry label.
1375   if (!Subtarget->isPPC64() &&
1376       (!isPositionIndependent() ||
1377        MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1378     return AsmPrinter::EmitFunctionEntryLabel();
1379 
1380   if (!Subtarget->isPPC64()) {
1381     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1382     if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1383       MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol();
1384       MCSymbol *PICBase = MF->getPICBaseSymbol();
1385       OutStreamer->EmitLabel(RelocSymbol);
1386 
1387       const MCExpr *OffsExpr =
1388         MCBinaryExpr::createSub(
1389           MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1390                                                                OutContext),
1391                                   MCSymbolRefExpr::create(PICBase, OutContext),
1392           OutContext);
1393       OutStreamer->EmitValue(OffsExpr, 4);
1394       OutStreamer->EmitLabel(CurrentFnSym);
1395       return;
1396     } else
1397       return AsmPrinter::EmitFunctionEntryLabel();
1398   }
1399 
1400   // ELFv2 ABI - Normal entry label.
1401   if (Subtarget->isELFv2ABI()) {
1402     // In the Large code model, we allow arbitrary displacements between
1403     // the text section and its associated TOC section.  We place the
1404     // full 8-byte offset to the TOC in memory immediately preceding
1405     // the function global entry point.
1406     if (TM.getCodeModel() == CodeModel::Large
1407         && !MF->getRegInfo().use_empty(PPC::X2)) {
1408       const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1409 
1410       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1411       MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol();
1412       const MCExpr *TOCDeltaExpr =
1413         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1414                                 MCSymbolRefExpr::create(GlobalEPSymbol,
1415                                                         OutContext),
1416                                 OutContext);
1417 
1418       OutStreamer->EmitLabel(PPCFI->getTOCOffsetSymbol());
1419       OutStreamer->EmitValue(TOCDeltaExpr, 8);
1420     }
1421     return AsmPrinter::EmitFunctionEntryLabel();
1422   }
1423 
1424   // Emit an official procedure descriptor.
1425   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1426   MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1427       ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1428   OutStreamer->SwitchSection(Section);
1429   OutStreamer->EmitLabel(CurrentFnSym);
1430   OutStreamer->EmitValueToAlignment(8);
1431   MCSymbol *Symbol1 = CurrentFnSymForSize;
1432   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1433   // entry point.
1434   OutStreamer->EmitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1435                          8 /*size*/);
1436   MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1437   // Generates a R_PPC64_TOC relocation for TOC base insertion.
1438   OutStreamer->EmitValue(
1439     MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1440     8/*size*/);
1441   // Emit a null environment pointer.
1442   OutStreamer->EmitIntValue(0, 8 /* size */);
1443   OutStreamer->SwitchSection(Current.first, Current.second);
1444 }
1445 
1446 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
1447   const DataLayout &DL = getDataLayout();
1448 
1449   bool isPPC64 = DL.getPointerSizeInBits() == 64;
1450 
1451   PPCTargetStreamer &TS =
1452       static_cast<PPCTargetStreamer &>(*OutStreamer->getTargetStreamer());
1453 
1454   if (!TOC.empty()) {
1455     MCSectionELF *Section;
1456 
1457     if (isPPC64)
1458       Section = OutStreamer->getContext().getELFSection(
1459           ".toc", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1460         else
1461           Section = OutStreamer->getContext().getELFSection(
1462               ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1463     OutStreamer->SwitchSection(Section);
1464 
1465     for (const auto &TOCMapPair : TOC) {
1466       const MCSymbol *const TOCEntryTarget = TOCMapPair.first;
1467       MCSymbol *const TOCEntryLabel = TOCMapPair.second;
1468 
1469       OutStreamer->EmitLabel(TOCEntryLabel);
1470       if (isPPC64) {
1471         TS.emitTCEntry(*TOCEntryTarget);
1472       } else {
1473         OutStreamer->EmitValueToAlignment(4);
1474         OutStreamer->EmitSymbolValue(TOCEntryTarget, 4);
1475       }
1476     }
1477   }
1478 
1479   return AsmPrinter::doFinalization(M);
1480 }
1481 
1482 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1483 void PPCLinuxAsmPrinter::EmitFunctionBodyStart() {
1484   // In the ELFv2 ABI, in functions that use the TOC register, we need to
1485   // provide two entry points.  The ABI guarantees that when calling the
1486   // local entry point, r2 is set up by the caller to contain the TOC base
1487   // for this function, and when calling the global entry point, r12 is set
1488   // up by the caller to hold the address of the global entry point.  We
1489   // thus emit a prefix sequence along the following lines:
1490   //
1491   // func:
1492   // .Lfunc_gepNN:
1493   //         # global entry point
1494   //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1495   //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1496   // .Lfunc_lepNN:
1497   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1498   //         # local entry point, followed by function body
1499   //
1500   // For the Large code model, we create
1501   //
1502   // .Lfunc_tocNN:
1503   //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1504   // func:
1505   // .Lfunc_gepNN:
1506   //         # global entry point
1507   //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1508   //         add   r2,r2,r12
1509   // .Lfunc_lepNN:
1510   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1511   //         # local entry point, followed by function body
1512   //
1513   // This ensures we have r2 set up correctly while executing the function
1514   // body, no matter which entry point is called.
1515   if (Subtarget->isELFv2ABI()
1516       // Only do all that if the function uses r2 in the first place.
1517       && !MF->getRegInfo().use_empty(PPC::X2)) {
1518     // Note: The logic here must be synchronized with the code in the
1519     // branch-selection pass which sets the offset of the first block in the
1520     // function. This matters because it affects the alignment.
1521     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1522 
1523     MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol();
1524     OutStreamer->EmitLabel(GlobalEntryLabel);
1525     const MCSymbolRefExpr *GlobalEntryLabelExp =
1526       MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1527 
1528     if (TM.getCodeModel() != CodeModel::Large) {
1529       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1530       const MCExpr *TOCDeltaExpr =
1531         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1532                                 GlobalEntryLabelExp, OutContext);
1533 
1534       const MCExpr *TOCDeltaHi =
1535         PPCMCExpr::createHa(TOCDeltaExpr, false, OutContext);
1536       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1537                                    .addReg(PPC::X2)
1538                                    .addReg(PPC::X12)
1539                                    .addExpr(TOCDeltaHi));
1540 
1541       const MCExpr *TOCDeltaLo =
1542         PPCMCExpr::createLo(TOCDeltaExpr, false, OutContext);
1543       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1544                                    .addReg(PPC::X2)
1545                                    .addReg(PPC::X2)
1546                                    .addExpr(TOCDeltaLo));
1547     } else {
1548       MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol();
1549       const MCExpr *TOCOffsetDeltaExpr =
1550         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1551                                 GlobalEntryLabelExp, OutContext);
1552 
1553       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1554                                    .addReg(PPC::X2)
1555                                    .addExpr(TOCOffsetDeltaExpr)
1556                                    .addReg(PPC::X12));
1557       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1558                                    .addReg(PPC::X2)
1559                                    .addReg(PPC::X2)
1560                                    .addReg(PPC::X12));
1561     }
1562 
1563     MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol();
1564     OutStreamer->EmitLabel(LocalEntryLabel);
1565     const MCSymbolRefExpr *LocalEntryLabelExp =
1566        MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1567     const MCExpr *LocalOffsetExp =
1568       MCBinaryExpr::createSub(LocalEntryLabelExp,
1569                               GlobalEntryLabelExp, OutContext);
1570 
1571     PPCTargetStreamer *TS =
1572       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1573 
1574     if (TS)
1575       TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1576   }
1577 }
1578 
1579 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1580 /// directive.
1581 ///
1582 void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
1583   // Only the 64-bit target requires a traceback table.  For now,
1584   // we only emit the word of zeroes that GDB requires to find
1585   // the end of the function, and zeroes for the eight-byte
1586   // mandatory fields.
1587   // FIXME: We should fill in the eight-byte mandatory fields as described in
1588   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1589   // currently make use of these fields).
1590   if (Subtarget->isPPC64()) {
1591     OutStreamer->EmitIntValue(0, 4/*size*/);
1592     OutStreamer->EmitIntValue(0, 8/*size*/);
1593   }
1594 }
1595 
1596 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
1597   static const char *const CPUDirectives[] = {
1598     "",
1599     "ppc",
1600     "ppc440",
1601     "ppc601",
1602     "ppc602",
1603     "ppc603",
1604     "ppc7400",
1605     "ppc750",
1606     "ppc970",
1607     "ppcA2",
1608     "ppce500",
1609     "ppce500mc",
1610     "ppce5500",
1611     "power3",
1612     "power4",
1613     "power5",
1614     "power5x",
1615     "power6",
1616     "power6x",
1617     "power7",
1618     // FIXME: why is power8 missing here?
1619     "ppc64",
1620     "ppc64le",
1621     "power9",
1622     "future"
1623   };
1624 
1625   // Get the numerically largest directive.
1626   // FIXME: How should we merge darwin directives?
1627   unsigned Directive = PPC::DIR_NONE;
1628   for (const Function &F : M) {
1629     const PPCSubtarget &STI = TM.getSubtarget<PPCSubtarget>(F);
1630     unsigned FDir = STI.getCPUDirective();
1631     Directive = Directive > FDir ? FDir : STI.getCPUDirective();
1632     if (STI.hasMFOCRF() && Directive < PPC::DIR_970)
1633       Directive = PPC::DIR_970;
1634     if (STI.hasAltivec() && Directive < PPC::DIR_7400)
1635       Directive = PPC::DIR_7400;
1636     if (STI.isPPC64() && Directive < PPC::DIR_64)
1637       Directive = PPC::DIR_64;
1638   }
1639 
1640   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
1641 
1642   assert(Directive < array_lengthof(CPUDirectives) &&
1643          "CPUDirectives[] might not be up-to-date!");
1644   PPCTargetStreamer &TStreamer =
1645       *static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1646   TStreamer.emitMachine(CPUDirectives[Directive]);
1647 
1648   // Prime text sections so they are adjacent.  This reduces the likelihood a
1649   // large data or debug section causes a branch to exceed 16M limit.
1650   const TargetLoweringObjectFileMachO &TLOFMacho =
1651       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1652   OutStreamer->SwitchSection(TLOFMacho.getTextCoalSection());
1653   if (TM.getRelocationModel() == Reloc::PIC_) {
1654     OutStreamer->SwitchSection(
1655            OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
1656                                       MachO::S_SYMBOL_STUBS |
1657                                       MachO::S_ATTR_PURE_INSTRUCTIONS,
1658                                       32, SectionKind::getText()));
1659   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
1660     OutStreamer->SwitchSection(
1661            OutContext.getMachOSection("__TEXT","__symbol_stub1",
1662                                       MachO::S_SYMBOL_STUBS |
1663                                       MachO::S_ATTR_PURE_INSTRUCTIONS,
1664                                       16, SectionKind::getText()));
1665   }
1666   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1667 }
1668 
1669 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1670   bool isPPC64 = getDataLayout().getPointerSizeInBits() == 64;
1671 
1672   // Darwin/PPC always uses mach-o.
1673   const TargetLoweringObjectFileMachO &TLOFMacho =
1674       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1675   if (MMI) {
1676     MachineModuleInfoMachO &MMIMacho =
1677         MMI->getObjFileInfo<MachineModuleInfoMachO>();
1678 
1679     if (MAI->doesSupportExceptionHandling()) {
1680       // Add the (possibly multiple) personalities to the set of global values.
1681       // Only referenced functions get into the Personalities list.
1682       for (const Function *Personality : MMI->getPersonalities()) {
1683         if (Personality) {
1684           MCSymbol *NLPSym =
1685               getSymbolWithGlobalValueBase(Personality, "$non_lazy_ptr");
1686           MachineModuleInfoImpl::StubValueTy &StubSym =
1687               MMIMacho.getGVStubEntry(NLPSym);
1688           StubSym =
1689               MachineModuleInfoImpl::StubValueTy(getSymbol(Personality), true);
1690         }
1691       }
1692     }
1693 
1694     // Output stubs for dynamically-linked functions.
1695     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
1696 
1697     // Output macho stubs for external and common global variables.
1698     if (!Stubs.empty()) {
1699       // Switch with ".non_lazy_symbol_pointer" directive.
1700       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1701       EmitAlignment(isPPC64 ? Align(8) : Align(4));
1702 
1703       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1704         // L_foo$stub:
1705         OutStreamer->EmitLabel(Stubs[i].first);
1706         //   .indirect_symbol _foo
1707         MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1708         OutStreamer->EmitSymbolAttribute(MCSym.getPointer(),
1709                                          MCSA_IndirectSymbol);
1710 
1711         if (MCSym.getInt())
1712           // External to current translation unit.
1713           OutStreamer->EmitIntValue(0, isPPC64 ? 8 : 4 /*size*/);
1714         else
1715           // Internal to current translation unit.
1716           //
1717           // When we place the LSDA into the TEXT section, the type info
1718           // pointers
1719           // need to be indirect and pc-rel. We accomplish this by using NLPs.
1720           // However, sometimes the types are local to the file. So we need to
1721           // fill in the value for the NLP in those cases.
1722           OutStreamer->EmitValue(
1723               MCSymbolRefExpr::create(MCSym.getPointer(), OutContext),
1724               isPPC64 ? 8 : 4 /*size*/);
1725       }
1726 
1727       Stubs.clear();
1728       OutStreamer->AddBlankLine();
1729     }
1730   }
1731 
1732   // Funny Darwin hack: This flag tells the linker that no global symbols
1733   // contain code that falls through to other global symbols (e.g. the obvious
1734   // implementation of multiple entry points).  If this doesn't occur, the
1735   // linker can safely perform dead code stripping.  Since LLVM never generates
1736   // code that does this, it is always safe to set.
1737   OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1738 
1739   return AsmPrinter::doFinalization(M);
1740 }
1741 
1742 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1743   // Get the function descriptor symbol.
1744   CurrentFnDescSym = getSymbol(&MF.getFunction());
1745   // Set the containing csect.
1746   MCSectionXCOFF *FnDescSec = OutStreamer->getContext().getXCOFFSection(
1747       CurrentFnDescSym->getName(), XCOFF::XMC_DS, XCOFF::XTY_SD,
1748       XCOFF::C_HIDEXT, SectionKind::getData());
1749   cast<MCSymbolXCOFF>(CurrentFnDescSym)->setContainingCsect(FnDescSec);
1750 
1751   return AsmPrinter::SetupMachineFunction(MF);
1752 }
1753 
1754 void PPCAIXAsmPrinter::ValidateGV(const GlobalVariable *GV) {
1755   // Early error checking limiting what is supported.
1756   if (GV->isThreadLocal())
1757     report_fatal_error("Thread local not yet supported on AIX.");
1758 
1759   if (GV->hasSection())
1760     report_fatal_error("Custom section for Data not yet supported.");
1761 
1762   if (GV->hasComdat())
1763     report_fatal_error("COMDAT not yet supported by AIX.");
1764 }
1765 
1766 void PPCAIXAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
1767   ValidateGV(GV);
1768 
1769   // External global variables are already handled.
1770   if (!GV->hasInitializer())
1771     return;
1772 
1773   // Create the symbol, set its storage class.
1774   MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
1775   GVSym->setStorageClass(
1776       TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV));
1777 
1778   SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
1779   if ((!GVKind.isCommon() && !GVKind.isBSS() && !GVKind.isData() &&
1780        !GVKind.isReadOnly()) ||
1781       GVKind.isMergeable2ByteCString() || GVKind.isMergeable4ByteCString() ||
1782       GVKind.isMergeableConst())
1783     report_fatal_error("Encountered a global variable kind that is "
1784                        "not supported yet.");
1785 
1786   // Create the containing csect and switch to it.
1787   MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1788       getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
1789   OutStreamer->SwitchSection(Csect);
1790   GVSym->setContainingCsect(Csect);
1791 
1792   const DataLayout &DL = GV->getParent()->getDataLayout();
1793 
1794   // Handle common symbols.
1795   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
1796     unsigned Align =
1797       GV->getAlignment() ? GV->getAlignment() : DL.getPreferredAlignment(GV);
1798     uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
1799 
1800     if (GVKind.isBSSLocal())
1801       OutStreamer->EmitXCOFFLocalCommonSymbol(
1802           GVSym, Size, Csect->getQualNameSymbol(), Align);
1803     else
1804       OutStreamer->EmitCommonSymbol(Csect->getQualNameSymbol(), Size, Align);
1805     return;
1806   }
1807 
1808   MCSymbol *EmittedInitSym = GVSym;
1809   EmitLinkage(GV, EmittedInitSym);
1810   EmitAlignment(getGVAlignment(GV, DL), GV);
1811   OutStreamer->EmitLabel(EmittedInitSym);
1812   EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
1813 }
1814 
1815 void PPCAIXAsmPrinter::EmitFunctionDescriptor() {
1816   const DataLayout &DL = getDataLayout();
1817   const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
1818 
1819   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1820   // Emit function descriptor.
1821   OutStreamer->SwitchSection(
1822       cast<MCSymbolXCOFF>(CurrentFnDescSym)->getContainingCsect());
1823   OutStreamer->EmitLabel(CurrentFnDescSym);
1824   // Emit function entry point address.
1825   OutStreamer->EmitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
1826                          PointerSize);
1827   // Emit TOC base address.
1828   const MCSectionXCOFF *TOCBaseSec = OutStreamer->getContext().getXCOFFSection(
1829       StringRef("TOC"), XCOFF::XMC_TC0, XCOFF::XTY_SD, XCOFF::C_HIDEXT,
1830       SectionKind::getData());
1831   const MCSymbol *TOCBaseSym = TOCBaseSec->getQualNameSymbol();
1832   OutStreamer->EmitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
1833                          PointerSize);
1834   // Emit a null environment pointer.
1835   OutStreamer->EmitIntValue(0, PointerSize);
1836 
1837   OutStreamer->SwitchSection(Current.first, Current.second);
1838 }
1839 
1840 void PPCAIXAsmPrinter::EmitEndOfAsmFile(Module &M) {
1841   // If there are no functions in this module, we will never need to reference
1842   // the TOC base.
1843   if (M.empty())
1844     return;
1845 
1846   // Emit TOC base.
1847   MCSectionXCOFF *TOCBaseSection = OutStreamer->getContext().getXCOFFSection(
1848       StringRef("TOC"), XCOFF::XMC_TC0, XCOFF::XTY_SD, XCOFF::C_HIDEXT,
1849       SectionKind::getData());
1850   // The TOC-base always has 0 size, but 4 byte alignment.
1851   TOCBaseSection->setAlignment(Align(4));
1852   // Switch to section to emit TOC base.
1853   OutStreamer->SwitchSection(TOCBaseSection);
1854 
1855   PPCTargetStreamer &TS =
1856       static_cast<PPCTargetStreamer &>(*OutStreamer->getTargetStreamer());
1857 
1858   for (auto &I : TOC) {
1859     // Setup the csect for the current TC entry.
1860     MCSectionXCOFF *TCEntry = OutStreamer->getContext().getXCOFFSection(
1861         cast<MCSymbolXCOFF>(I.first)->getUnqualifiedName(), XCOFF::XMC_TC,
1862         XCOFF::XTY_SD, XCOFF::C_HIDEXT, SectionKind::getData());
1863     cast<MCSymbolXCOFF>(I.second)->setContainingCsect(TCEntry);
1864     OutStreamer->SwitchSection(TCEntry);
1865 
1866     OutStreamer->EmitLabel(I.second);
1867     TS.emitTCEntry(*I.first);
1868   }
1869 }
1870 
1871 MCSymbol *
1872 PPCAIXAsmPrinter::getMCSymbolForTOCPseudoMO(const MachineOperand &MO) {
1873   const GlobalObject *GO = nullptr;
1874 
1875   // If the MO is a function or certain kind of globals, we want to make sure to
1876   // refer to the csect symbol, otherwise we can just do the default handling.
1877   if (MO.getType() != MachineOperand::MO_GlobalAddress ||
1878       !(GO = dyn_cast<const GlobalObject>(MO.getGlobal())))
1879     return PPCAsmPrinter::getMCSymbolForTOCPseudoMO(MO);
1880 
1881   // Do an early error check for globals we don't support. This will go away
1882   // eventually.
1883   const auto *GV = dyn_cast<const GlobalVariable>(GO);
1884   if (GV) {
1885     ValidateGV(GV);
1886   }
1887 
1888   MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(getSymbol(GO));
1889 
1890   // If the global object is a global variable without initializer or is a
1891   // declaration of a function, then XSym is an external referenced symbol.
1892   // Hence we may need to explictly create a MCSectionXCOFF for it so that we
1893   // can return its symbol later.
1894   if (GO->isDeclaration()) {
1895     if (!XSym->hasContainingCsect()) {
1896       // Make sure the storage class is set.
1897       const XCOFF::StorageClass SC =
1898           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
1899       XSym->setStorageClass(SC);
1900 
1901       MCSectionXCOFF *Csect = OutStreamer->getContext().getXCOFFSection(
1902           XSym->getName(), isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA,
1903           XCOFF::XTY_ER, SC, SectionKind::getMetadata());
1904       XSym->setContainingCsect(Csect);
1905     }
1906 
1907     return XSym->getContainingCsect()->getQualNameSymbol();
1908   }
1909 
1910   // Handle initialized global variables and defined functions.
1911   SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
1912 
1913   if (GOKind.isText()) {
1914     // If the MO is a function, we want to make sure to refer to the function
1915     // descriptor csect.
1916     return OutStreamer->getContext()
1917         .getXCOFFSection(XSym->getName(), XCOFF::XMC_DS, XCOFF::XTY_SD,
1918                          XCOFF::C_HIDEXT, SectionKind::getData())
1919         ->getQualNameSymbol();
1920   } else if (GOKind.isCommon() || GOKind.isBSSLocal()) {
1921     // If the operand is a common then we should refer to the csect symbol.
1922     return cast<MCSectionXCOFF>(
1923                getObjFileLowering().SectionForGlobal(GO, GOKind, TM))
1924         ->getQualNameSymbol();
1925   }
1926 
1927   // Other global variables are refered to by labels inside of a single csect,
1928   // so refer to the label directly.
1929   return getSymbol(GV);
1930 }
1931 
1932 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1933 /// for a MachineFunction to the given output stream, in a format that the
1934 /// Darwin assembler can deal with.
1935 ///
1936 static AsmPrinter *
1937 createPPCAsmPrinterPass(TargetMachine &tm,
1938                         std::unique_ptr<MCStreamer> &&Streamer) {
1939   if (tm.getTargetTriple().isMacOSX())
1940     return new PPCDarwinAsmPrinter(tm, std::move(Streamer));
1941   if (tm.getTargetTriple().isOSAIX())
1942     return new PPCAIXAsmPrinter(tm, std::move(Streamer));
1943 
1944   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
1945 }
1946 
1947 // Force static initialization.
1948 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1949   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
1950                                      createPPCAsmPrinterPass);
1951   TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
1952                                      createPPCAsmPrinterPass);
1953   TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
1954                                      createPPCAsmPrinterPass);
1955 }
1956