]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
Merge ACPICA 20170728.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / PowerPC / PPCAsmPrinter.cpp
1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
13 //
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "InstPrinter/PPCInstPrinter.h"
20 #include "MCTargetDesc/PPCMCExpr.h"
21 #include "MCTargetDesc/PPCMCTargetDesc.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 "llvm/ADT/MapVector.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/BinaryFormat/ELF.h"
33 #include "llvm/BinaryFormat/MachO.h"
34 #include "llvm/CodeGen/AsmPrinter.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/StackMaps.h"
42 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/MC/MCAsmInfo.h"
47 #include "llvm/MC/MCContext.h"
48 #include "llvm/MC/MCExpr.h"
49 #include "llvm/MC/MCInst.h"
50 #include "llvm/MC/MCInstBuilder.h"
51 #include "llvm/MC/MCSectionELF.h"
52 #include "llvm/MC/MCSectionMachO.h"
53 #include "llvm/MC/MCStreamer.h"
54 #include "llvm/MC/MCSymbol.h"
55 #include "llvm/MC/MCSymbolELF.h"
56 #include "llvm/MC/SectionKind.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/CodeGen.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/TargetRegistry.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include <algorithm>
65 #include <cassert>
66 #include <cstdint>
67 #include <memory>
68 #include <new>
69
70 using namespace llvm;
71
72 #define DEBUG_TYPE "asmprinter"
73
74 namespace {
75
76 class PPCAsmPrinter : public AsmPrinter {
77 protected:
78   MapVector<MCSymbol *, MCSymbol *> TOC;
79   const PPCSubtarget *Subtarget;
80   StackMaps SM;
81
82 public:
83   explicit PPCAsmPrinter(TargetMachine &TM,
84                          std::unique_ptr<MCStreamer> Streamer)
85       : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
86
87   StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
88
89   MCSymbol *lookUpOrCreateTOCEntry(MCSymbol *Sym);
90
91   bool doInitialization(Module &M) override {
92     if (!TOC.empty())
93       TOC.clear();
94     return AsmPrinter::doInitialization(M);
95   }
96
97     void EmitInstruction(const MachineInstr *MI) override;
98
99     void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
100
101     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
102                          unsigned AsmVariant, const char *ExtraCode,
103                          raw_ostream &O) override;
104     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
105                                unsigned AsmVariant, const char *ExtraCode,
106                                raw_ostream &O) override;
107
108     void EmitEndOfAsmFile(Module &M) override;
109
110     void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
111     void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
112     void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
113     bool runOnMachineFunction(MachineFunction &MF) override {
114       Subtarget = &MF.getSubtarget<PPCSubtarget>();
115       bool Changed = AsmPrinter::runOnMachineFunction(MF);
116       emitXRayTable();
117       return Changed;
118     }
119   };
120
121   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
122   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
123   public:
124     explicit PPCLinuxAsmPrinter(TargetMachine &TM,
125                                 std::unique_ptr<MCStreamer> Streamer)
126         : PPCAsmPrinter(TM, std::move(Streamer)) {}
127
128     StringRef getPassName() const override {
129       return "Linux PPC Assembly Printer";
130     }
131
132     bool doFinalization(Module &M) override;
133     void EmitStartOfAsmFile(Module &M) override;
134
135     void EmitFunctionEntryLabel() override;
136
137     void EmitFunctionBodyStart() override;
138     void EmitFunctionBodyEnd() override;
139     void EmitInstruction(const MachineInstr *MI) override;
140   };
141
142   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
143   /// OS X
144   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
145   public:
146     explicit PPCDarwinAsmPrinter(TargetMachine &TM,
147                                  std::unique_ptr<MCStreamer> Streamer)
148         : PPCAsmPrinter(TM, std::move(Streamer)) {}
149
150     StringRef getPassName() const override {
151       return "Darwin PPC Assembly Printer";
152     }
153
154     bool doFinalization(Module &M) override;
155     void EmitStartOfAsmFile(Module &M) override;
156   };
157
158 } // end anonymous namespace
159
160 /// stripRegisterPrefix - This method strips the character prefix from a
161 /// register name so that only the number is left.  Used by for linux asm.
162 static const char *stripRegisterPrefix(const char *RegName) {
163   switch (RegName[0]) {
164     case 'r':
165     case 'f':
166     case 'q': // for QPX
167     case 'v':
168       if (RegName[1] == 's')
169         return RegName + 2;
170       return RegName + 1;
171     case 'c': if (RegName[1] == 'r') return RegName + 2;
172   }
173
174   return RegName;
175 }
176
177 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
178                                  raw_ostream &O) {
179   const DataLayout &DL = getDataLayout();
180   const MachineOperand &MO = MI->getOperand(OpNo);
181
182   switch (MO.getType()) {
183   case MachineOperand::MO_Register: {
184     unsigned Reg = MO.getReg();
185
186     // There are VSX instructions that use VSX register numbering (vs0 - vs63)
187     // as well as those that use VMX register numbering (v0 - v31 which
188     // correspond to vs32 - vs63). If we have an instruction that uses VSX
189     // numbering, we need to convert the VMX registers to VSX registers.
190     // Namely, we print 32-63 when the instruction operates on one of the
191     // VMX registers.
192     // (Please synchronize with PPCInstPrinter::printOperand)
193     if (MI->getDesc().TSFlags & PPCII::UseVSXReg) {
194       if (PPCInstrInfo::isVRRegister(Reg))
195         Reg = PPC::VSX32 + (Reg - PPC::V0);
196       else if (PPCInstrInfo::isVFRegister(Reg))
197         Reg = PPC::VSX32 + (Reg - PPC::VF0);
198     }
199     const char *RegName = PPCInstPrinter::getRegisterName(Reg);
200
201     // Linux assembler (Others?) does not take register mnemonics.
202     // FIXME - What about special registers used in mfspr/mtspr?
203     if (!Subtarget->isDarwin())
204       RegName = stripRegisterPrefix(RegName);
205     O << RegName;
206     return;
207   }
208   case MachineOperand::MO_Immediate:
209     O << MO.getImm();
210     return;
211
212   case MachineOperand::MO_MachineBasicBlock:
213     MO.getMBB()->getSymbol()->print(O, MAI);
214     return;
215   case MachineOperand::MO_ConstantPoolIndex:
216     O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
217       << MO.getIndex();
218     return;
219   case MachineOperand::MO_BlockAddress:
220     GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
221     return;
222   case MachineOperand::MO_GlobalAddress: {
223     // Computing the address of a global symbol, not calling it.
224     const GlobalValue *GV = MO.getGlobal();
225     MCSymbol *SymToPrint;
226
227     // External or weakly linked global variables need non-lazily-resolved stubs
228     if (Subtarget->hasLazyResolverStub(GV)) {
229       SymToPrint = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
230       MachineModuleInfoImpl::StubValueTy &StubSym =
231           MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(
232               SymToPrint);
233       if (!StubSym.getPointer())
234         StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
235                                                      !GV->hasInternalLinkage());
236     } else {
237       SymToPrint = getSymbol(GV);
238     }
239
240     SymToPrint->print(O, MAI);
241
242     printOffset(MO.getOffset(), O);
243     return;
244   }
245
246   default:
247     O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
248     return;
249   }
250 }
251
252 /// PrintAsmOperand - Print out an operand for an inline asm expression.
253 ///
254 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
255                                     unsigned AsmVariant,
256                                     const char *ExtraCode, raw_ostream &O) {
257   // Does this asm operand have a single letter operand modifier?
258   if (ExtraCode && ExtraCode[0]) {
259     if (ExtraCode[1] != 0) return true; // Unknown modifier.
260
261     switch (ExtraCode[0]) {
262     default:
263       // See if this is a generic print operand
264       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
265     case 'c': // Don't print "$" before a global var name or constant.
266       break; // PPC never has a prefix.
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     }
282   }
283
284   printOperand(MI, OpNo, O);
285   return false;
286 }
287
288 // At the moment, all inline asm memory operands are a single register.
289 // In any case, the output of this routine should always be just one
290 // assembler operand.
291
292 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
293                                           unsigned AsmVariant,
294                                           const char *ExtraCode,
295                                           raw_ostream &O) {
296   if (ExtraCode && ExtraCode[0]) {
297     if (ExtraCode[1] != 0) return true; // Unknown modifier.
298
299     switch (ExtraCode[0]) {
300     default: return true;  // Unknown modifier.
301     case 'y': // A memory reference for an X-form instruction
302       {
303         const char *RegName = "r0";
304         if (!Subtarget->isDarwin())
305           RegName = stripRegisterPrefix(RegName);
306         O << RegName << ", ";
307         printOperand(MI, OpNo, O);
308         return false;
309       }
310     case 'U': // Print 'u' for update form.
311     case 'X': // Print 'x' for indexed form.
312     {
313       // FIXME: Currently for PowerPC memory operands are always loaded
314       // into a register, so we never get an update or indexed form.
315       // This is bad even for offset forms, since even if we know we
316       // have a value in -16(r1), we will generate a load into r<n>
317       // and then load from 0(r<n>).  Until that issue is fixed,
318       // tolerate 'U' and 'X' but don't output anything.
319       assert(MI->getOperand(OpNo).isReg());
320       return false;
321     }
322     }
323   }
324
325   assert(MI->getOperand(OpNo).isReg());
326   O << "0(";
327   printOperand(MI, OpNo, O);
328   O << ")";
329   return false;
330 }
331
332 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
333 /// exists for it.  If not, create one.  Then return a symbol that references
334 /// the TOC entry.
335 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(MCSymbol *Sym) {
336   MCSymbol *&TOCEntry = TOC[Sym];
337   if (!TOCEntry)
338     TOCEntry = createTempSymbol("C");
339   return TOCEntry;
340 }
341
342 void PPCAsmPrinter::EmitEndOfAsmFile(Module &M) {
343   SM.serializeToStackMapSection();
344 }
345
346 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
347   unsigned NumNOPBytes = MI.getOperand(1).getImm();
348
349   SM.recordStackMap(MI);
350   assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
351
352   // Scan ahead to trim the shadow.
353   const MachineBasicBlock &MBB = *MI.getParent();
354   MachineBasicBlock::const_iterator MII(MI);
355   ++MII;
356   while (NumNOPBytes > 0) {
357     if (MII == MBB.end() || MII->isCall() ||
358         MII->getOpcode() == PPC::DBG_VALUE ||
359         MII->getOpcode() == TargetOpcode::PATCHPOINT ||
360         MII->getOpcode() == TargetOpcode::STACKMAP)
361       break;
362     ++MII;
363     NumNOPBytes -= 4;
364   }
365
366   // Emit nops.
367   for (unsigned i = 0; i < NumNOPBytes; i += 4)
368     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
369 }
370
371 // Lower a patchpoint of the form:
372 // [<def>], <id>, <numBytes>, <target>, <numArgs>
373 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
374   SM.recordPatchPoint(MI);
375   PatchPointOpers Opers(&MI);
376
377   unsigned EncodedBytes = 0;
378   const MachineOperand &CalleeMO = Opers.getCallTarget();
379
380   if (CalleeMO.isImm()) {
381     int64_t CallTarget = CalleeMO.getImm();
382     if (CallTarget) {
383       assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
384              "High 16 bits of call target should be zero.");
385       unsigned ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
386       EncodedBytes = 0;
387       // Materialize the jump address:
388       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
389                                       .addReg(ScratchReg)
390                                       .addImm((CallTarget >> 32) & 0xFFFF));
391       ++EncodedBytes;
392       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
393                                       .addReg(ScratchReg)
394                                       .addReg(ScratchReg)
395                                       .addImm(32).addImm(16));
396       ++EncodedBytes;
397       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
398                                       .addReg(ScratchReg)
399                                       .addReg(ScratchReg)
400                                       .addImm((CallTarget >> 16) & 0xFFFF));
401       ++EncodedBytes;
402       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
403                                       .addReg(ScratchReg)
404                                       .addReg(ScratchReg)
405                                       .addImm(CallTarget & 0xFFFF));
406
407       // Save the current TOC pointer before the remote call.
408       int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
409       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
410                                       .addReg(PPC::X2)
411                                       .addImm(TOCSaveOffset)
412                                       .addReg(PPC::X1));
413       ++EncodedBytes;
414
415       // If we're on ELFv1, then we need to load the actual function pointer
416       // from the function descriptor.
417       if (!Subtarget->isELFv2ABI()) {
418         // Load the new TOC pointer and the function address, but not r11
419         // (needing this is rare, and loading it here would prevent passing it
420         // via a 'nest' parameter.
421         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
422                                         .addReg(PPC::X2)
423                                         .addImm(8)
424                                         .addReg(ScratchReg));
425         ++EncodedBytes;
426         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
427                                         .addReg(ScratchReg)
428                                         .addImm(0)
429                                         .addReg(ScratchReg));
430         ++EncodedBytes;
431       }
432
433       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
434                                       .addReg(ScratchReg));
435       ++EncodedBytes;
436       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
437       ++EncodedBytes;
438
439       // Restore the TOC pointer after the call.
440       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
441                                       .addReg(PPC::X2)
442                                       .addImm(TOCSaveOffset)
443                                       .addReg(PPC::X1));
444       ++EncodedBytes;
445     }
446   } else if (CalleeMO.isGlobal()) {
447     const GlobalValue *GValue = CalleeMO.getGlobal();
448     MCSymbol *MOSymbol = getSymbol(GValue);
449     const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
450
451     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
452                                     .addExpr(SymVar));
453     EncodedBytes += 2;
454   }
455
456   // Each instruction is 4 bytes.
457   EncodedBytes *= 4;
458
459   // Emit padding.
460   unsigned NumBytes = Opers.getNumPatchBytes();
461   assert(NumBytes >= EncodedBytes &&
462          "Patchpoint can't request size less than the length of a call.");
463   assert((NumBytes - EncodedBytes) % 4 == 0 &&
464          "Invalid number of NOP bytes requested!");
465   for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
466     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
467 }
468
469 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
470 /// call to __tls_get_addr to the current output stream.
471 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
472                                 MCSymbolRefExpr::VariantKind VK) {
473   StringRef Name = "__tls_get_addr";
474   MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name);
475   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
476
477   assert(MI->getOperand(0).isReg() &&
478          ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
479           (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
480          "GETtls[ld]ADDR[32] must define GPR3");
481   assert(MI->getOperand(1).isReg() &&
482          ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
483           (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
484          "GETtls[ld]ADDR[32] must read GPR3");
485
486   if (!Subtarget->isPPC64() && !Subtarget->isDarwin() &&
487       isPositionIndependent())
488     Kind = MCSymbolRefExpr::VK_PLT;
489   const MCSymbolRefExpr *TlsRef =
490     MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
491   const MachineOperand &MO = MI->getOperand(2);
492   const GlobalValue *GValue = MO.getGlobal();
493   MCSymbol *MOSymbol = getSymbol(GValue);
494   const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
495   EmitToStreamer(*OutStreamer,
496                  MCInstBuilder(Subtarget->isPPC64() ?
497                                PPC::BL8_NOP_TLS : PPC::BL_TLS)
498                  .addExpr(TlsRef)
499                  .addExpr(SymVar));
500 }
501
502 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
503 /// the current output stream.
504 ///
505 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
506   MCInst TmpInst;
507   bool isPPC64 = Subtarget->isPPC64();
508   bool isDarwin = TM.getTargetTriple().isOSDarwin();
509   const Module *M = MF->getFunction()->getParent();
510   PICLevel::Level PL = M->getPICLevel();
511
512   // Lower multi-instruction pseudo operations.
513   switch (MI->getOpcode()) {
514   default: break;
515   case TargetOpcode::DBG_VALUE:
516     llvm_unreachable("Should be handled target independently");
517   case TargetOpcode::STACKMAP:
518     return LowerSTACKMAP(SM, *MI);
519   case TargetOpcode::PATCHPOINT:
520     return LowerPATCHPOINT(SM, *MI);
521
522   case PPC::MoveGOTtoLR: {
523     // Transform %LR = MoveGOTtoLR
524     // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
525     // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
526     // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
527     //      blrl
528     // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
529     MCSymbol *GOTSymbol =
530       OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
531     const MCExpr *OffsExpr =
532       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
533                                                       MCSymbolRefExpr::VK_PPC_LOCAL,
534                                                       OutContext),
535                               MCConstantExpr::create(4, OutContext),
536                               OutContext);
537
538     // Emit the 'bl'.
539     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
540     return;
541   }
542   case PPC::MovePCtoLR:
543   case PPC::MovePCtoLR8: {
544     // Transform %LR = MovePCtoLR
545     // Into this, where the label is the PIC base:
546     //     bl L1$pb
547     // L1$pb:
548     MCSymbol *PICBase = MF->getPICBaseSymbol();
549
550     // Emit the 'bl'.
551     EmitToStreamer(*OutStreamer,
552                    MCInstBuilder(PPC::BL)
553                        // FIXME: We would like an efficient form for this, so we
554                        // don't have to do a lot of extra uniquing.
555                        .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
556
557     // Emit the label.
558     OutStreamer->EmitLabel(PICBase);
559     return;
560   }
561   case PPC::UpdateGBR: {
562     // Transform %Rd = UpdateGBR(%Rt, %Ri)
563     // Into: lwz %Rt, .L0$poff - .L0$pb(%Ri)
564     //       add %Rd, %Rt, %Ri
565     // Get the offset from the GOT Base Register to the GOT
566     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
567     MCSymbol *PICOffset =
568       MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol();
569     TmpInst.setOpcode(PPC::LWZ);
570     const MCExpr *Exp =
571       MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
572     const MCExpr *PB =
573       MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
574                               MCSymbolRefExpr::VK_None,
575                               OutContext);
576     const MCOperand TR = TmpInst.getOperand(1);
577     const MCOperand PICR = TmpInst.getOperand(0);
578
579     // Step 1: lwz %Rt, .L$poff - .L$pb(%Ri)
580     TmpInst.getOperand(1) =
581         MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
582     TmpInst.getOperand(0) = TR;
583     TmpInst.getOperand(2) = PICR;
584     EmitToStreamer(*OutStreamer, TmpInst);
585
586     TmpInst.setOpcode(PPC::ADD4);
587     TmpInst.getOperand(0) = PICR;
588     TmpInst.getOperand(1) = TR;
589     TmpInst.getOperand(2) = PICR;
590     EmitToStreamer(*OutStreamer, TmpInst);
591     return;
592   }
593   case PPC::LWZtoc: {
594     // Transform %R3 = LWZtoc <ga:@min1>, %R2
595     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
596
597     // Change the opcode to LWZ, and the global address operand to be a
598     // reference to the GOT entry we will synthesize later.
599     TmpInst.setOpcode(PPC::LWZ);
600     const MachineOperand &MO = MI->getOperand(1);
601
602     // Map symbol -> label of TOC entry
603     assert(MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress());
604     MCSymbol *MOSymbol = nullptr;
605     if (MO.isGlobal())
606       MOSymbol = getSymbol(MO.getGlobal());
607     else if (MO.isCPI())
608       MOSymbol = GetCPISymbol(MO.getIndex());
609     else if (MO.isJTI())
610       MOSymbol = GetJTISymbol(MO.getIndex());
611     else if (MO.isBlockAddress())
612       MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
613
614     if (PL == PICLevel::SmallPIC) {
615       const MCExpr *Exp =
616         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
617                                 OutContext);
618       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
619     } else {
620       MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
621
622       const MCExpr *Exp =
623         MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None,
624                                 OutContext);
625       const MCExpr *PB =
626         MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
627                                                              OutContext);
628       Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
629       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
630     }
631     EmitToStreamer(*OutStreamer, TmpInst);
632     return;
633   }
634   case PPC::LDtocJTI:
635   case PPC::LDtocCPT:
636   case PPC::LDtocBA:
637   case PPC::LDtoc: {
638     // Transform %X3 = LDtoc <ga:@min1>, %X2
639     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
640
641     // Change the opcode to LD, and the global address operand to be a
642     // reference to the TOC entry we will synthesize later.
643     TmpInst.setOpcode(PPC::LD);
644     const MachineOperand &MO = MI->getOperand(1);
645
646     // Map symbol -> label of TOC entry
647     assert(MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress());
648     MCSymbol *MOSymbol = nullptr;
649     if (MO.isGlobal())
650       MOSymbol = getSymbol(MO.getGlobal());
651     else if (MO.isCPI())
652       MOSymbol = GetCPISymbol(MO.getIndex());
653     else if (MO.isJTI())
654       MOSymbol = GetJTISymbol(MO.getIndex());
655     else if (MO.isBlockAddress())
656       MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
657
658     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
659
660     const MCExpr *Exp =
661       MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_PPC_TOC,
662                               OutContext);
663     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
664     EmitToStreamer(*OutStreamer, TmpInst);
665     return;
666   }
667
668   case PPC::ADDIStocHA: {
669     // Transform %Xd = ADDIStocHA %X2, <ga:@sym>
670     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
671
672     // Change the opcode to ADDIS8.  If the global address is external, has
673     // common linkage, is a non-local function address, or is a jump table
674     // address, then generate a TOC entry and reference that.  Otherwise
675     // reference the symbol directly.
676     TmpInst.setOpcode(PPC::ADDIS8);
677     const MachineOperand &MO = MI->getOperand(2);
678     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
679             MO.isBlockAddress()) &&
680            "Invalid operand for ADDIStocHA!");
681     MCSymbol *MOSymbol = nullptr;
682     bool GlobalToc = false;
683
684     if (MO.isGlobal()) {
685       const GlobalValue *GV = MO.getGlobal();
686       MOSymbol = getSymbol(GV);
687       unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
688       GlobalToc = (GVFlags & PPCII::MO_NLP_FLAG);
689     } else if (MO.isCPI()) {
690       MOSymbol = GetCPISymbol(MO.getIndex());
691     } else if (MO.isJTI()) {
692       MOSymbol = GetJTISymbol(MO.getIndex());
693     } else if (MO.isBlockAddress()) {
694       MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
695     }
696
697     if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
698         TM.getCodeModel() == CodeModel::Large)
699       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
700
701     const MCExpr *Exp =
702       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_HA,
703                               OutContext);
704
705     if (!MO.isJTI() && MO.getOffset())
706       Exp = MCBinaryExpr::createAdd(Exp,
707                                     MCConstantExpr::create(MO.getOffset(),
708                                                            OutContext),
709                                     OutContext);
710
711     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
712     EmitToStreamer(*OutStreamer, TmpInst);
713     return;
714   }
715   case PPC::LDtocL: {
716     // Transform %Xd = LDtocL <ga:@sym>, %Xs
717     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
718
719     // Change the opcode to LD.  If the global address is external, has
720     // common linkage, or is a jump table address, then reference the
721     // associated TOC entry.  Otherwise reference the symbol directly.
722     TmpInst.setOpcode(PPC::LD);
723     const MachineOperand &MO = MI->getOperand(1);
724     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
725             MO.isBlockAddress()) &&
726            "Invalid operand for LDtocL!");
727     MCSymbol *MOSymbol = nullptr;
728
729     if (MO.isJTI())
730       MOSymbol = lookUpOrCreateTOCEntry(GetJTISymbol(MO.getIndex()));
731     else if (MO.isBlockAddress()) {
732       MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
733       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
734     }
735     else if (MO.isCPI()) {
736       MOSymbol = GetCPISymbol(MO.getIndex());
737       if (TM.getCodeModel() == CodeModel::Large)
738         MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
739     }
740     else if (MO.isGlobal()) {
741       const GlobalValue *GV = MO.getGlobal();
742       MOSymbol = getSymbol(GV);
743       DEBUG(
744         unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
745         assert((GVFlags & PPCII::MO_NLP_FLAG) &&
746                "LDtocL used on symbol that could be accessed directly is "
747                "invalid. Must match ADDIStocHA."));
748       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
749     }
750
751     const MCExpr *Exp =
752       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
753                               OutContext);
754     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
755     EmitToStreamer(*OutStreamer, TmpInst);
756     return;
757   }
758   case PPC::ADDItocL: {
759     // Transform %Xd = ADDItocL %Xs, <ga:@sym>
760     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
761
762     // Change the opcode to ADDI8.  If the global address is external, then
763     // generate a TOC entry and reference that.  Otherwise reference the
764     // symbol directly.
765     TmpInst.setOpcode(PPC::ADDI8);
766     const MachineOperand &MO = MI->getOperand(2);
767     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL");
768     MCSymbol *MOSymbol = nullptr;
769
770     if (MO.isGlobal()) {
771       const GlobalValue *GV = MO.getGlobal();
772       DEBUG(
773         unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
774         assert (
775             !(GVFlags & PPCII::MO_NLP_FLAG) &&
776             "Interposable definitions must use indirect access."));
777       MOSymbol = getSymbol(GV);
778     } else if (MO.isCPI()) {
779       MOSymbol = GetCPISymbol(MO.getIndex());
780     }
781
782     const MCExpr *Exp =
783       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
784                               OutContext);
785     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
786     EmitToStreamer(*OutStreamer, TmpInst);
787     return;
788   }
789   case PPC::ADDISgotTprelHA: {
790     // Transform: %Xd = ADDISgotTprelHA %X2, <ga:@sym>
791     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
792     assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
793     const MachineOperand &MO = MI->getOperand(2);
794     const GlobalValue *GValue = MO.getGlobal();
795     MCSymbol *MOSymbol = getSymbol(GValue);
796     const MCExpr *SymGotTprel =
797       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
798                               OutContext);
799     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
800                                  .addReg(MI->getOperand(0).getReg())
801                                  .addReg(MI->getOperand(1).getReg())
802                                  .addExpr(SymGotTprel));
803     return;
804   }
805   case PPC::LDgotTprelL:
806   case PPC::LDgotTprelL32: {
807     // Transform %Xd = LDgotTprelL <ga:@sym>, %Xs
808     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
809
810     // Change the opcode to LD.
811     TmpInst.setOpcode(isPPC64 ? PPC::LD : PPC::LWZ);
812     const MachineOperand &MO = MI->getOperand(1);
813     const GlobalValue *GValue = MO.getGlobal();
814     MCSymbol *MOSymbol = getSymbol(GValue);
815     const MCExpr *Exp =
816       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO,
817                               OutContext);
818     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
819     EmitToStreamer(*OutStreamer, TmpInst);
820     return;
821   }
822
823   case PPC::PPC32PICGOT: {
824     MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
825     MCSymbol *GOTRef = OutContext.createTempSymbol();
826     MCSymbol *NextInstr = OutContext.createTempSymbol();
827
828     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
829       // FIXME: We would like an efficient form for this, so we don't have to do
830       // a lot of extra uniquing.
831       .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
832     const MCExpr *OffsExpr =
833       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
834                                 MCSymbolRefExpr::create(GOTRef, OutContext),
835         OutContext);
836     OutStreamer->EmitLabel(GOTRef);
837     OutStreamer->EmitValue(OffsExpr, 4);
838     OutStreamer->EmitLabel(NextInstr);
839     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
840                                  .addReg(MI->getOperand(0).getReg()));
841     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
842                                  .addReg(MI->getOperand(1).getReg())
843                                  .addImm(0)
844                                  .addReg(MI->getOperand(0).getReg()));
845     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
846                                  .addReg(MI->getOperand(0).getReg())
847                                  .addReg(MI->getOperand(1).getReg())
848                                  .addReg(MI->getOperand(0).getReg()));
849     return;
850   }
851   case PPC::PPC32GOT: {
852     MCSymbol *GOTSymbol =
853         OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
854     const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
855         GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
856     const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
857         GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
858     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
859                                  .addReg(MI->getOperand(0).getReg())
860                                  .addExpr(SymGotTlsL));
861     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
862                                  .addReg(MI->getOperand(0).getReg())
863                                  .addReg(MI->getOperand(0).getReg())
864                                  .addExpr(SymGotTlsHA));
865     return;
866   }
867   case PPC::ADDIStlsgdHA: {
868     // Transform: %Xd = ADDIStlsgdHA %X2, <ga:@sym>
869     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
870     assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
871     const MachineOperand &MO = MI->getOperand(2);
872     const GlobalValue *GValue = MO.getGlobal();
873     MCSymbol *MOSymbol = getSymbol(GValue);
874     const MCExpr *SymGotTlsGD =
875       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
876                               OutContext);
877     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
878                                  .addReg(MI->getOperand(0).getReg())
879                                  .addReg(MI->getOperand(1).getReg())
880                                  .addExpr(SymGotTlsGD));
881     return;
882   }
883   case PPC::ADDItlsgdL:
884     // Transform: %Xd = ADDItlsgdL %Xs, <ga:@sym>
885     // Into:      %Xd = ADDI8 %Xs, sym@got@tlsgd@l
886   case PPC::ADDItlsgdL32: {
887     // Transform: %Rd = ADDItlsgdL32 %Rs, <ga:@sym>
888     // Into:      %Rd = ADDI %Rs, sym@got@tlsgd
889     const MachineOperand &MO = MI->getOperand(2);
890     const GlobalValue *GValue = MO.getGlobal();
891     MCSymbol *MOSymbol = getSymbol(GValue);
892     const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
893         MOSymbol, Subtarget->isPPC64() ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
894                                        : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
895         OutContext);
896     EmitToStreamer(*OutStreamer,
897                    MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
898                    .addReg(MI->getOperand(0).getReg())
899                    .addReg(MI->getOperand(1).getReg())
900                    .addExpr(SymGotTlsGD));
901     return;
902   }
903   case PPC::GETtlsADDR:
904     // Transform: %X3 = GETtlsADDR %X3, <ga:@sym>
905     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
906   case PPC::GETtlsADDR32: {
907     // Transform: %R3 = GETtlsADDR32 %R3, <ga:@sym>
908     // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
909     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
910     return;
911   }
912   case PPC::ADDIStlsldHA: {
913     // Transform: %Xd = ADDIStlsldHA %X2, <ga:@sym>
914     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsld@ha
915     assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
916     const MachineOperand &MO = MI->getOperand(2);
917     const GlobalValue *GValue = MO.getGlobal();
918     MCSymbol *MOSymbol = getSymbol(GValue);
919     const MCExpr *SymGotTlsLD =
920       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
921                               OutContext);
922     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
923                                  .addReg(MI->getOperand(0).getReg())
924                                  .addReg(MI->getOperand(1).getReg())
925                                  .addExpr(SymGotTlsLD));
926     return;
927   }
928   case PPC::ADDItlsldL:
929     // Transform: %Xd = ADDItlsldL %Xs, <ga:@sym>
930     // Into:      %Xd = ADDI8 %Xs, sym@got@tlsld@l
931   case PPC::ADDItlsldL32: {
932     // Transform: %Rd = ADDItlsldL32 %Rs, <ga:@sym>
933     // Into:      %Rd = ADDI %Rs, sym@got@tlsld
934     const MachineOperand &MO = MI->getOperand(2);
935     const GlobalValue *GValue = MO.getGlobal();
936     MCSymbol *MOSymbol = getSymbol(GValue);
937     const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
938         MOSymbol, Subtarget->isPPC64() ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
939                                        : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
940         OutContext);
941     EmitToStreamer(*OutStreamer,
942                    MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
943                        .addReg(MI->getOperand(0).getReg())
944                        .addReg(MI->getOperand(1).getReg())
945                        .addExpr(SymGotTlsLD));
946     return;
947   }
948   case PPC::GETtlsldADDR:
949     // Transform: %X3 = GETtlsldADDR %X3, <ga:@sym>
950     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
951   case PPC::GETtlsldADDR32: {
952     // Transform: %R3 = GETtlsldADDR32 %R3, <ga:@sym>
953     // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
954     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
955     return;
956   }
957   case PPC::ADDISdtprelHA:
958     // Transform: %Xd = ADDISdtprelHA %Xs, <ga:@sym>
959     // Into:      %Xd = ADDIS8 %Xs, sym@dtprel@ha
960   case PPC::ADDISdtprelHA32: {
961     // Transform: %Rd = ADDISdtprelHA32 %Rs, <ga:@sym>
962     // Into:      %Rd = ADDIS %Rs, sym@dtprel@ha
963     const MachineOperand &MO = MI->getOperand(2);
964     const GlobalValue *GValue = MO.getGlobal();
965     MCSymbol *MOSymbol = getSymbol(GValue);
966     const MCExpr *SymDtprel =
967       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
968                               OutContext);
969     EmitToStreamer(
970         *OutStreamer,
971         MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDIS8 : PPC::ADDIS)
972             .addReg(MI->getOperand(0).getReg())
973             .addReg(MI->getOperand(1).getReg())
974             .addExpr(SymDtprel));
975     return;
976   }
977   case PPC::ADDIdtprelL:
978     // Transform: %Xd = ADDIdtprelL %Xs, <ga:@sym>
979     // Into:      %Xd = ADDI8 %Xs, sym@dtprel@l
980   case PPC::ADDIdtprelL32: {
981     // Transform: %Rd = ADDIdtprelL32 %Rs, <ga:@sym>
982     // Into:      %Rd = ADDI %Rs, sym@dtprel@l
983     const MachineOperand &MO = MI->getOperand(2);
984     const GlobalValue *GValue = MO.getGlobal();
985     MCSymbol *MOSymbol = getSymbol(GValue);
986     const MCExpr *SymDtprel =
987       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
988                               OutContext);
989     EmitToStreamer(*OutStreamer,
990                    MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
991                        .addReg(MI->getOperand(0).getReg())
992                        .addReg(MI->getOperand(1).getReg())
993                        .addExpr(SymDtprel));
994     return;
995   }
996   case PPC::MFOCRF:
997   case PPC::MFOCRF8:
998     if (!Subtarget->hasMFOCRF()) {
999       // Transform: %R3 = MFOCRF %CR7
1000       // Into:      %R3 = MFCR   ;; cr7
1001       unsigned NewOpcode =
1002         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1003       OutStreamer->AddComment(PPCInstPrinter::
1004                               getRegisterName(MI->getOperand(1).getReg()));
1005       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1006                                   .addReg(MI->getOperand(0).getReg()));
1007       return;
1008     }
1009     break;
1010   case PPC::MTOCRF:
1011   case PPC::MTOCRF8:
1012     if (!Subtarget->hasMFOCRF()) {
1013       // Transform: %CR7 = MTOCRF %R3
1014       // Into:      MTCRF mask, %R3 ;; cr7
1015       unsigned NewOpcode =
1016         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1017       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1018                               ->getEncodingValue(MI->getOperand(0).getReg());
1019       OutStreamer->AddComment(PPCInstPrinter::
1020                               getRegisterName(MI->getOperand(0).getReg()));
1021       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1022                                      .addImm(Mask)
1023                                      .addReg(MI->getOperand(1).getReg()));
1024       return;
1025     }
1026     break;
1027   case PPC::LD:
1028   case PPC::STD:
1029   case PPC::LWA_32:
1030   case PPC::LWA: {
1031     // Verify alignment is legal, so we don't create relocations
1032     // that can't be supported.
1033     // FIXME:  This test is currently disabled for Darwin.  The test
1034     // suite shows a handful of test cases that fail this check for
1035     // Darwin.  Those need to be investigated before this sanity test
1036     // can be enabled for those subtargets.
1037     if (!Subtarget->isDarwin()) {
1038       unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1039       const MachineOperand &MO = MI->getOperand(OpNum);
1040       if (MO.isGlobal() && MO.getGlobal()->getAlignment() < 4)
1041         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1042     }
1043     // Now process the instruction normally.
1044     break;
1045   }
1046   }
1047
1048   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
1049   EmitToStreamer(*OutStreamer, TmpInst);
1050 }
1051
1052 void PPCLinuxAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1053   if (!Subtarget->isPPC64())
1054     return PPCAsmPrinter::EmitInstruction(MI);
1055
1056   switch (MI->getOpcode()) {
1057   default:
1058     return PPCAsmPrinter::EmitInstruction(MI);
1059   case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1060     // .begin:
1061     //   b .end # lis 0, FuncId[16..32]
1062     //   nop    # li  0, FuncId[0..15]
1063     //   std 0, -8(1)
1064     //   mflr 0
1065     //   bl __xray_FunctionEntry
1066     //   mtlr 0
1067     // .end:
1068     //
1069     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1070     // of instructions change.
1071     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1072     MCSymbol *EndOfSled = OutContext.createTempSymbol();
1073     OutStreamer->EmitLabel(BeginOfSled);
1074     EmitToStreamer(*OutStreamer,
1075                    MCInstBuilder(PPC::B).addExpr(
1076                        MCSymbolRefExpr::create(EndOfSled, OutContext)));
1077     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1078     EmitToStreamer(
1079         *OutStreamer,
1080         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1081     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1082     EmitToStreamer(*OutStreamer,
1083                    MCInstBuilder(PPC::BL8_NOP)
1084                        .addExpr(MCSymbolRefExpr::create(
1085                            OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1086                            OutContext)));
1087     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1088     OutStreamer->EmitLabel(EndOfSled);
1089     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER);
1090     break;
1091   }
1092   case TargetOpcode::PATCHABLE_FUNCTION_EXIT: {
1093     // .p2align 3
1094     // .begin:
1095     //   b(lr)? # lis 0, FuncId[16..32]
1096     //   nop    # li  0, FuncId[0..15]
1097     //   std 0, -8(1)
1098     //   mflr 0
1099     //   bl __xray_FunctionExit
1100     //   mtlr 0
1101     // .end:
1102     //   b(lr)?
1103     //
1104     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1105     // of instructions change.
1106     const MachineInstr *Next = [&] {
1107       MachineBasicBlock::const_iterator It(MI);
1108       assert(It != MI->getParent()->end());
1109       ++It;
1110       assert(It->isReturn());
1111       return &*It;
1112     }();
1113     OutStreamer->EmitCodeAlignment(8);
1114     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1115     OutStreamer->EmitLabel(BeginOfSled);
1116     MCInst TmpInst;
1117     LowerPPCMachineInstrToMCInst(Next, TmpInst, *this, false);
1118     EmitToStreamer(*OutStreamer, TmpInst);
1119     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1120     EmitToStreamer(
1121         *OutStreamer,
1122         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1123     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1124     EmitToStreamer(*OutStreamer,
1125                    MCInstBuilder(PPC::BL8_NOP)
1126                        .addExpr(MCSymbolRefExpr::create(
1127                            OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1128                            OutContext)));
1129     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1130     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT);
1131     break;
1132   }
1133   case TargetOpcode::PATCHABLE_TAIL_CALL:
1134   case TargetOpcode::PATCHABLE_RET:
1135     // PPC's tail call instruction, e.g. PPC::TCRETURNdi8, doesn't really
1136     // lower to a PPC::B instruction. The PPC::B instruction is generated
1137     // before it, and handled by the normal case.
1138     llvm_unreachable("Tail call is handled in the normal case. See comments"
1139                      "around this assert.");
1140   }
1141 }
1142
1143 void PPCLinuxAsmPrinter::EmitStartOfAsmFile(Module &M) {
1144   if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1145     PPCTargetStreamer *TS =
1146       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1147
1148     if (TS)
1149       TS->emitAbiVersion(2);
1150   }
1151
1152   if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1153       !isPositionIndependent())
1154     return AsmPrinter::EmitStartOfAsmFile(M);
1155
1156   if (M.getPICLevel() == PICLevel::SmallPIC)
1157     return AsmPrinter::EmitStartOfAsmFile(M);
1158
1159   OutStreamer->SwitchSection(OutContext.getELFSection(
1160       ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1161
1162   MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1163   MCSymbol *CurrentPos = OutContext.createTempSymbol();
1164
1165   OutStreamer->EmitLabel(CurrentPos);
1166
1167   // The GOT pointer points to the middle of the GOT, in order to reference the
1168   // entire 64kB range.  0x8000 is the midpoint.
1169   const MCExpr *tocExpr =
1170     MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1171                             MCConstantExpr::create(0x8000, OutContext),
1172                             OutContext);
1173
1174   OutStreamer->EmitAssignment(TOCSym, tocExpr);
1175
1176   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1177 }
1178
1179 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
1180   // linux/ppc32 - Normal entry label.
1181   if (!Subtarget->isPPC64() &&
1182       (!isPositionIndependent() ||
1183        MF->getFunction()->getParent()->getPICLevel() == PICLevel::SmallPIC))
1184     return AsmPrinter::EmitFunctionEntryLabel();
1185
1186   if (!Subtarget->isPPC64()) {
1187     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1188     if (PPCFI->usesPICBase()) {
1189       MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol();
1190       MCSymbol *PICBase = MF->getPICBaseSymbol();
1191       OutStreamer->EmitLabel(RelocSymbol);
1192
1193       const MCExpr *OffsExpr =
1194         MCBinaryExpr::createSub(
1195           MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1196                                                                OutContext),
1197                                   MCSymbolRefExpr::create(PICBase, OutContext),
1198           OutContext);
1199       OutStreamer->EmitValue(OffsExpr, 4);
1200       OutStreamer->EmitLabel(CurrentFnSym);
1201       return;
1202     } else
1203       return AsmPrinter::EmitFunctionEntryLabel();
1204   }
1205
1206   // ELFv2 ABI - Normal entry label.
1207   if (Subtarget->isELFv2ABI()) {
1208     // In the Large code model, we allow arbitrary displacements between
1209     // the text section and its associated TOC section.  We place the
1210     // full 8-byte offset to the TOC in memory immediatedly preceding
1211     // the function global entry point.
1212     if (TM.getCodeModel() == CodeModel::Large
1213         && !MF->getRegInfo().use_empty(PPC::X2)) {
1214       const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1215
1216       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1217       MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol();
1218       const MCExpr *TOCDeltaExpr =
1219         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1220                                 MCSymbolRefExpr::create(GlobalEPSymbol,
1221                                                         OutContext),
1222                                 OutContext);
1223
1224       OutStreamer->EmitLabel(PPCFI->getTOCOffsetSymbol());
1225       OutStreamer->EmitValue(TOCDeltaExpr, 8);
1226     }
1227     return AsmPrinter::EmitFunctionEntryLabel();
1228   }
1229
1230   // Emit an official procedure descriptor.
1231   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1232   MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1233       ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1234   OutStreamer->SwitchSection(Section);
1235   OutStreamer->EmitLabel(CurrentFnSym);
1236   OutStreamer->EmitValueToAlignment(8);
1237   MCSymbol *Symbol1 = CurrentFnSymForSize;
1238   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1239   // entry point.
1240   OutStreamer->EmitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1241                          8 /*size*/);
1242   MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1243   // Generates a R_PPC64_TOC relocation for TOC base insertion.
1244   OutStreamer->EmitValue(
1245     MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1246     8/*size*/);
1247   // Emit a null environment pointer.
1248   OutStreamer->EmitIntValue(0, 8 /* size */);
1249   OutStreamer->SwitchSection(Current.first, Current.second);
1250 }
1251
1252 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
1253   const DataLayout &DL = getDataLayout();
1254
1255   bool isPPC64 = DL.getPointerSizeInBits() == 64;
1256
1257   PPCTargetStreamer &TS =
1258       static_cast<PPCTargetStreamer &>(*OutStreamer->getTargetStreamer());
1259
1260   if (!TOC.empty()) {
1261     MCSectionELF *Section;
1262
1263     if (isPPC64)
1264       Section = OutStreamer->getContext().getELFSection(
1265           ".toc", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1266         else
1267           Section = OutStreamer->getContext().getELFSection(
1268               ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1269     OutStreamer->SwitchSection(Section);
1270
1271     for (MapVector<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
1272          E = TOC.end(); I != E; ++I) {
1273       OutStreamer->EmitLabel(I->second);
1274       MCSymbol *S = I->first;
1275       if (isPPC64) {
1276         TS.emitTCEntry(*S);
1277       } else {
1278         OutStreamer->EmitValueToAlignment(4);
1279         OutStreamer->EmitSymbolValue(S, 4);
1280       }
1281     }
1282   }
1283
1284   return AsmPrinter::doFinalization(M);
1285 }
1286
1287 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1288 void PPCLinuxAsmPrinter::EmitFunctionBodyStart() {
1289   // In the ELFv2 ABI, in functions that use the TOC register, we need to
1290   // provide two entry points.  The ABI guarantees that when calling the
1291   // local entry point, r2 is set up by the caller to contain the TOC base
1292   // for this function, and when calling the global entry point, r12 is set
1293   // up by the caller to hold the address of the global entry point.  We
1294   // thus emit a prefix sequence along the following lines:
1295   //
1296   // func:
1297   // .Lfunc_gepNN:
1298   //         # global entry point
1299   //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1300   //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1301   // .Lfunc_lepNN:
1302   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1303   //         # local entry point, followed by function body
1304   //
1305   // For the Large code model, we create
1306   //
1307   // .Lfunc_tocNN:
1308   //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1309   // func:
1310   // .Lfunc_gepNN:
1311   //         # global entry point
1312   //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1313   //         add   r2,r2,r12
1314   // .Lfunc_lepNN:
1315   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1316   //         # local entry point, followed by function body
1317   //
1318   // This ensures we have r2 set up correctly while executing the function
1319   // body, no matter which entry point is called.
1320   if (Subtarget->isELFv2ABI()
1321       // Only do all that if the function uses r2 in the first place.
1322       && !MF->getRegInfo().use_empty(PPC::X2)) {
1323     // Note: The logic here must be synchronized with the code in the
1324     // branch-selection pass which sets the offset of the first block in the
1325     // function. This matters because it affects the alignment.
1326     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1327
1328     MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol();
1329     OutStreamer->EmitLabel(GlobalEntryLabel);
1330     const MCSymbolRefExpr *GlobalEntryLabelExp =
1331       MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1332
1333     if (TM.getCodeModel() != CodeModel::Large) {
1334       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1335       const MCExpr *TOCDeltaExpr =
1336         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1337                                 GlobalEntryLabelExp, OutContext);
1338
1339       const MCExpr *TOCDeltaHi =
1340         PPCMCExpr::createHa(TOCDeltaExpr, false, OutContext);
1341       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1342                                    .addReg(PPC::X2)
1343                                    .addReg(PPC::X12)
1344                                    .addExpr(TOCDeltaHi));
1345
1346       const MCExpr *TOCDeltaLo =
1347         PPCMCExpr::createLo(TOCDeltaExpr, false, OutContext);
1348       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1349                                    .addReg(PPC::X2)
1350                                    .addReg(PPC::X2)
1351                                    .addExpr(TOCDeltaLo));
1352     } else {
1353       MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol();
1354       const MCExpr *TOCOffsetDeltaExpr =
1355         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1356                                 GlobalEntryLabelExp, OutContext);
1357
1358       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1359                                    .addReg(PPC::X2)
1360                                    .addExpr(TOCOffsetDeltaExpr)
1361                                    .addReg(PPC::X12));
1362       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1363                                    .addReg(PPC::X2)
1364                                    .addReg(PPC::X2)
1365                                    .addReg(PPC::X12));
1366     }
1367
1368     MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol();
1369     OutStreamer->EmitLabel(LocalEntryLabel);
1370     const MCSymbolRefExpr *LocalEntryLabelExp =
1371        MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1372     const MCExpr *LocalOffsetExp =
1373       MCBinaryExpr::createSub(LocalEntryLabelExp,
1374                               GlobalEntryLabelExp, OutContext);
1375
1376     PPCTargetStreamer *TS =
1377       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1378
1379     if (TS)
1380       TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1381   }
1382 }
1383
1384 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1385 /// directive.
1386 ///
1387 void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
1388   // Only the 64-bit target requires a traceback table.  For now,
1389   // we only emit the word of zeroes that GDB requires to find
1390   // the end of the function, and zeroes for the eight-byte
1391   // mandatory fields.
1392   // FIXME: We should fill in the eight-byte mandatory fields as described in
1393   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1394   // currently make use of these fields).
1395   if (Subtarget->isPPC64()) {
1396     OutStreamer->EmitIntValue(0, 4/*size*/);
1397     OutStreamer->EmitIntValue(0, 8/*size*/);
1398   }
1399 }
1400
1401 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
1402   static const char *const CPUDirectives[] = {
1403     "",
1404     "ppc",
1405     "ppc440",
1406     "ppc601",
1407     "ppc602",
1408     "ppc603",
1409     "ppc7400",
1410     "ppc750",
1411     "ppc970",
1412     "ppcA2",
1413     "ppce500mc",
1414     "ppce5500",
1415     "power3",
1416     "power4",
1417     "power5",
1418     "power5x",
1419     "power6",
1420     "power6x",
1421     "power7",
1422     // FIXME: why is power8 missing here?
1423     "ppc64",
1424     "ppc64le",
1425     "power9"
1426   };
1427
1428   // Get the numerically largest directive.
1429   // FIXME: How should we merge darwin directives?
1430   unsigned Directive = PPC::DIR_NONE;
1431   for (const Function &F : M) {
1432     const PPCSubtarget &STI = TM.getSubtarget<PPCSubtarget>(F);
1433     unsigned FDir = STI.getDarwinDirective();
1434     Directive = Directive > FDir ? FDir : STI.getDarwinDirective();
1435     if (STI.hasMFOCRF() && Directive < PPC::DIR_970)
1436       Directive = PPC::DIR_970;
1437     if (STI.hasAltivec() && Directive < PPC::DIR_7400)
1438       Directive = PPC::DIR_7400;
1439     if (STI.isPPC64() && Directive < PPC::DIR_64)
1440       Directive = PPC::DIR_64;
1441   }
1442
1443   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
1444
1445   assert(Directive < array_lengthof(CPUDirectives) &&
1446          "CPUDirectives[] might not be up-to-date!");
1447   PPCTargetStreamer &TStreamer =
1448       *static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1449   TStreamer.emitMachine(CPUDirectives[Directive]);
1450
1451   // Prime text sections so they are adjacent.  This reduces the likelihood a
1452   // large data or debug section causes a branch to exceed 16M limit.
1453   const TargetLoweringObjectFileMachO &TLOFMacho =
1454       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1455   OutStreamer->SwitchSection(TLOFMacho.getTextCoalSection());
1456   if (TM.getRelocationModel() == Reloc::PIC_) {
1457     OutStreamer->SwitchSection(
1458            OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
1459                                       MachO::S_SYMBOL_STUBS |
1460                                       MachO::S_ATTR_PURE_INSTRUCTIONS,
1461                                       32, SectionKind::getText()));
1462   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
1463     OutStreamer->SwitchSection(
1464            OutContext.getMachOSection("__TEXT","__symbol_stub1",
1465                                       MachO::S_SYMBOL_STUBS |
1466                                       MachO::S_ATTR_PURE_INSTRUCTIONS,
1467                                       16, SectionKind::getText()));
1468   }
1469   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1470 }
1471
1472 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1473   bool isPPC64 = getDataLayout().getPointerSizeInBits() == 64;
1474
1475   // Darwin/PPC always uses mach-o.
1476   const TargetLoweringObjectFileMachO &TLOFMacho =
1477       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1478   if (MMI) {
1479     MachineModuleInfoMachO &MMIMacho =
1480         MMI->getObjFileInfo<MachineModuleInfoMachO>();
1481
1482     if (MAI->doesSupportExceptionHandling()) {
1483       // Add the (possibly multiple) personalities to the set of global values.
1484       // Only referenced functions get into the Personalities list.
1485       for (const Function *Personality : MMI->getPersonalities()) {
1486         if (Personality) {
1487           MCSymbol *NLPSym =
1488               getSymbolWithGlobalValueBase(Personality, "$non_lazy_ptr");
1489           MachineModuleInfoImpl::StubValueTy &StubSym =
1490               MMIMacho.getGVStubEntry(NLPSym);
1491           StubSym =
1492               MachineModuleInfoImpl::StubValueTy(getSymbol(Personality), true);
1493         }
1494       }
1495     }
1496
1497     // Output stubs for dynamically-linked functions.
1498     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
1499
1500     // Output macho stubs for external and common global variables.
1501     if (!Stubs.empty()) {
1502       // Switch with ".non_lazy_symbol_pointer" directive.
1503       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1504       EmitAlignment(isPPC64 ? 3 : 2);
1505
1506       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1507         // L_foo$stub:
1508         OutStreamer->EmitLabel(Stubs[i].first);
1509         //   .indirect_symbol _foo
1510         MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1511         OutStreamer->EmitSymbolAttribute(MCSym.getPointer(),
1512                                          MCSA_IndirectSymbol);
1513
1514         if (MCSym.getInt())
1515           // External to current translation unit.
1516           OutStreamer->EmitIntValue(0, isPPC64 ? 8 : 4 /*size*/);
1517         else
1518           // Internal to current translation unit.
1519           //
1520           // When we place the LSDA into the TEXT section, the type info
1521           // pointers
1522           // need to be indirect and pc-rel. We accomplish this by using NLPs.
1523           // However, sometimes the types are local to the file. So we need to
1524           // fill in the value for the NLP in those cases.
1525           OutStreamer->EmitValue(
1526               MCSymbolRefExpr::create(MCSym.getPointer(), OutContext),
1527               isPPC64 ? 8 : 4 /*size*/);
1528       }
1529
1530       Stubs.clear();
1531       OutStreamer->AddBlankLine();
1532     }
1533   }
1534
1535   // Funny Darwin hack: This flag tells the linker that no global symbols
1536   // contain code that falls through to other global symbols (e.g. the obvious
1537   // implementation of multiple entry points).  If this doesn't occur, the
1538   // linker can safely perform dead code stripping.  Since LLVM never generates
1539   // code that does this, it is always safe to set.
1540   OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1541
1542   return AsmPrinter::doFinalization(M);
1543 }
1544
1545 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1546 /// for a MachineFunction to the given output stream, in a format that the
1547 /// Darwin assembler can deal with.
1548 ///
1549 static AsmPrinter *
1550 createPPCAsmPrinterPass(TargetMachine &tm,
1551                         std::unique_ptr<MCStreamer> &&Streamer) {
1552   if (tm.getTargetTriple().isMacOSX())
1553     return new PPCDarwinAsmPrinter(tm, std::move(Streamer));
1554   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
1555 }
1556
1557 // Force static initialization.
1558 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1559   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
1560                                      createPPCAsmPrinterPass);
1561   TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
1562                                      createPPCAsmPrinterPass);
1563   TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
1564                                      createPPCAsmPrinterPass);
1565 }