rip out a ton of old instruction printing junk now that the
[oota-llvm.git] / 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 #define DEBUG_TYPE "asmprinter"
20 #include "PPC.h"
21 #include "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Analysis/DebugInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Module.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
34 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCExpr.h"
38 #include "llvm/MC/MCInst.h"
39 #include "llvm/MC/MCSectionMachO.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/Target/Mangler.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegistry.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/ADT/StringSet.h"
54 #include "llvm/ADT/SmallString.h"
55 #include "InstPrinter/PPCInstPrinter.h"
56 using namespace llvm;
57
58 namespace {
59   class PPCAsmPrinter : public AsmPrinter {
60   protected:
61     DenseMap<MCSymbol*, MCSymbol*> TOC;
62     const PPCSubtarget &Subtarget;
63     uint64_t LabelID;
64   public:
65     explicit PPCAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
66       : AsmPrinter(TM, Streamer),
67         Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
68
69     virtual const char *getPassName() const {
70       return "PowerPC Assembly Printer";
71     }
72
73
74     virtual void EmitInstruction(const MachineInstr *MI);
75
76     void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
77
78     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
79                          unsigned AsmVariant, const char *ExtraCode,
80                          raw_ostream &O);
81     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
82                                unsigned AsmVariant, const char *ExtraCode,
83                                raw_ostream &O);
84
85     MachineLocation getDebugValueLocation(const MachineInstr *MI) const {
86       MachineLocation Location;
87       assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
88       // Frame address.  Currently handles register +- offset only.
89       if (MI->getOperand(0).isReg() && MI->getOperand(2).isImm())
90         Location.set(MI->getOperand(0).getReg(), MI->getOperand(2).getImm());
91       else {
92         DEBUG(dbgs() << "DBG_VALUE instruction ignored! " << *MI << "\n");
93       }
94       return Location;
95     }
96   };
97
98   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
99   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
100   public:
101     explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
102       : PPCAsmPrinter(TM, Streamer) {}
103
104     virtual const char *getPassName() const {
105       return "Linux PPC Assembly Printer";
106     }
107
108     bool doFinalization(Module &M);
109
110     virtual void EmitFunctionEntryLabel();
111   };
112
113   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
114   /// OS X
115   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
116   public:
117     explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
118       : PPCAsmPrinter(TM, Streamer) {}
119
120     virtual const char *getPassName() const {
121       return "Darwin PPC Assembly Printer";
122     }
123
124     bool doFinalization(Module &M);
125     void EmitStartOfAsmFile(Module &M);
126
127     void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
128   };
129 } // end of anonymous namespace
130
131 /// stripRegisterPrefix - This method strips the character prefix from a
132 /// register name so that only the number is left.  Used by for linux asm.
133 static const char *stripRegisterPrefix(const char *RegName) {
134   switch (RegName[0]) {
135     case 'r':
136     case 'f':
137     case 'v': return RegName + 1;
138     case 'c': if (RegName[1] == 'r') return RegName + 2;
139   }
140   
141   return RegName;
142 }
143
144 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
145                                  raw_ostream &O) {
146   const MachineOperand &MO = MI->getOperand(OpNo);
147   
148   switch (MO.getType()) {
149   case MachineOperand::MO_Register: {
150     const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
151     // Linux assembler (Others?) does not take register mnemonics.
152     // FIXME - What about special registers used in mfspr/mtspr?
153     if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
154     O << RegName;
155     return;
156   }
157   case MachineOperand::MO_Immediate:
158     O << MO.getImm();
159     return;
160
161   case MachineOperand::MO_MachineBasicBlock:
162     O << *MO.getMBB()->getSymbol();
163     return;
164   case MachineOperand::MO_JumpTableIndex:
165     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
166       << '_' << MO.getIndex();
167     // FIXME: PIC relocation model
168     return;
169   case MachineOperand::MO_ConstantPoolIndex:
170     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
171       << '_' << MO.getIndex();
172     return;
173   case MachineOperand::MO_BlockAddress:
174     O << *GetBlockAddressSymbol(MO.getBlockAddress());
175     return;
176   case MachineOperand::MO_ExternalSymbol: {
177     // Computing the address of an external symbol, not calling it.
178     if (TM.getRelocationModel() == Reloc::Static) {
179       O << *GetExternalSymbolSymbol(MO.getSymbolName());
180       return;
181     }
182
183     MCSymbol *NLPSym = 
184       OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
185                                    MO.getSymbolName()+"$non_lazy_ptr");
186     MachineModuleInfoImpl::StubValueTy &StubSym = 
187       MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
188     if (StubSym.getPointer() == 0)
189       StubSym = MachineModuleInfoImpl::
190         StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
191     
192     O << *NLPSym;
193     return;
194   }
195   case MachineOperand::MO_GlobalAddress: {
196     // Computing the address of a global symbol, not calling it.
197     const GlobalValue *GV = MO.getGlobal();
198     MCSymbol *SymToPrint;
199
200     // External or weakly linked global variables need non-lazily-resolved stubs
201     if (TM.getRelocationModel() != Reloc::Static &&
202         (GV->isDeclaration() || GV->isWeakForLinker())) {
203       if (!GV->hasHiddenVisibility()) {
204         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
205         MachineModuleInfoImpl::StubValueTy &StubSym = 
206           MMI->getObjFileInfo<MachineModuleInfoMachO>()
207             .getGVStubEntry(SymToPrint);
208         if (StubSym.getPointer() == 0)
209           StubSym = MachineModuleInfoImpl::
210             StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
211       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
212                  GV->hasAvailableExternallyLinkage()) {
213         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
214         
215         MachineModuleInfoImpl::StubValueTy &StubSym = 
216           MMI->getObjFileInfo<MachineModuleInfoMachO>().
217                     getHiddenGVStubEntry(SymToPrint);
218         if (StubSym.getPointer() == 0)
219           StubSym = MachineModuleInfoImpl::
220             StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
221       } else {
222         SymToPrint = Mang->getSymbol(GV);
223       }
224     } else {
225       SymToPrint = Mang->getSymbol(GV);
226     }
227     
228     O << *SymToPrint;
229
230     printOffset(MO.getOffset(), O);
231     return;
232   }
233
234   default:
235     O << "<unknown operand type: " << MO.getType() << ">";
236     return;
237   }
238 }
239
240 /// PrintAsmOperand - Print out an operand for an inline asm expression.
241 ///
242 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
243                                     unsigned AsmVariant,
244                                     const char *ExtraCode, raw_ostream &O) {
245   // Does this asm operand have a single letter operand modifier?
246   if (ExtraCode && ExtraCode[0]) {
247     if (ExtraCode[1] != 0) return true; // Unknown modifier.
248
249     switch (ExtraCode[0]) {
250     default: return true;  // Unknown modifier.
251     case 'c': // Don't print "$" before a global var name or constant.
252       break; // PPC never has a prefix.
253     case 'L': // Write second word of DImode reference.
254       // Verify that this operand has two consecutive registers.
255       if (!MI->getOperand(OpNo).isReg() ||
256           OpNo+1 == MI->getNumOperands() ||
257           !MI->getOperand(OpNo+1).isReg())
258         return true;
259       ++OpNo;   // Return the high-part.
260       break;
261     case 'I':
262       // Write 'i' if an integer constant, otherwise nothing.  Used to print
263       // addi vs add, etc.
264       if (MI->getOperand(OpNo).isImm())
265         O << "i";
266       return false;
267     }
268   }
269
270   printOperand(MI, OpNo, O);
271   return false;
272 }
273
274 // At the moment, all inline asm memory operands are a single register.
275 // In any case, the output of this routine should always be just one
276 // assembler operand.
277
278 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
279                                           unsigned AsmVariant,
280                                           const char *ExtraCode,
281                                           raw_ostream &O) {
282   if (ExtraCode && ExtraCode[0])
283     return true; // Unknown modifier.
284   assert(MI->getOperand(OpNo).isReg());
285   O << "0(";
286   printOperand(MI, OpNo, O);
287   O << ")";
288   return false;
289 }
290
291
292 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
293 /// the current output stream.
294 ///
295 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
296   MCInst TmpInst;
297   
298   // Lower multi-instruction pseudo operations.
299   switch (MI->getOpcode()) {
300   default: break;
301   case PPC::MovePCtoLR:
302   case PPC::MovePCtoLR8: {
303     // Transform %LR = MovePCtoLR
304     // Into this, where the label is the PIC base: 
305     //     bl L1$pb
306     // L1$pb:
307     MCSymbol *PICBase = MF->getPICBaseSymbol();
308     
309     // Emit the 'bl'.
310     TmpInst.setOpcode(PPC::BL_Darwin); // Darwin vs SVR4 doesn't matter here.
311     
312     
313     // FIXME: We would like an efficient form for this, so we don't have to do
314     // a lot of extra uniquing.
315     TmpInst.addOperand(MCOperand::CreateExpr(MCSymbolRefExpr::
316                                              Create(PICBase, OutContext)));
317     OutStreamer.EmitInstruction(TmpInst);
318     
319     // Emit the label.
320     OutStreamer.EmitLabel(PICBase);
321     return;
322   }
323   case PPC::LDtoc: {
324     // Transform %X3 = LDtoc <ga:@min1>, %X2
325     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
326       
327     // Change the opcode to LD, and the global address operand to be a
328     // reference to the TOC entry we will synthesize later.
329     TmpInst.setOpcode(PPC::LD);
330     const MachineOperand &MO = MI->getOperand(1);
331     assert(MO.isGlobal());
332       
333     // Map symbol -> label of TOC entry.
334     MCSymbol *&TOCEntry = TOC[Mang->getSymbol(MO.getGlobal())];
335     if (TOCEntry == 0) {
336       TOCEntry = OutContext.
337         GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
338                           "C" + Twine(LabelID++));
339     }
340       
341     const MCExpr *Exp =
342       MCSymbolRefExpr::Create(TOCEntry, MCSymbolRefExpr::VK_PPC_TOC,
343                               OutContext);
344     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
345     OutStreamer.EmitInstruction(TmpInst);
346     return;
347   }
348       
349   case PPC::MFCRpseud:
350     // Transform: %R3 = MFCRpseud %CR7
351     // Into:      %R3 = MFCR      ;; cr7
352     OutStreamer.AddComment(PPCInstPrinter::
353                            getRegisterName(MI->getOperand(1).getReg()));
354     TmpInst.setOpcode(PPC::MFCR);
355     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
356     OutStreamer.EmitInstruction(TmpInst);
357     return;
358   }
359
360   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
361   OutStreamer.EmitInstruction(TmpInst);
362 }
363
364 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
365   if (!Subtarget.isPPC64())  // linux/ppc32 - Normal entry label.
366     return AsmPrinter::EmitFunctionEntryLabel();
367     
368   // Emit an official procedure descriptor.
369   // FIXME 64-bit SVR4: Use MCSection here!
370   OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
371   OutStreamer.EmitRawText(StringRef("\t.align 3"));
372   OutStreamer.EmitLabel(CurrentFnSym);
373   OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
374                           ",.TOC.@tocbase");
375   OutStreamer.EmitRawText(StringRef("\t.previous"));
376   OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
377 }
378
379
380 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
381   const TargetData *TD = TM.getTargetData();
382
383   bool isPPC64 = TD->getPointerSizeInBits() == 64;
384
385   if (isPPC64 && !TOC.empty()) {
386     // FIXME 64-bit SVR4: Use MCSection here?
387     OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
388
389     // FIXME: This is nondeterminstic!
390     for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
391          E = TOC.end(); I != E; ++I) {
392       OutStreamer.EmitLabel(I->second);
393       OutStreamer.EmitRawText("\t.tc " + Twine(I->first->getName()) +
394                               "[TC]," + I->first->getName());
395     }
396   }
397
398   return AsmPrinter::doFinalization(M);
399 }
400
401 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
402   static const char *const CPUDirectives[] = {
403     "",
404     "ppc",
405     "ppc601",
406     "ppc602",
407     "ppc603",
408     "ppc7400",
409     "ppc750",
410     "ppc970",
411     "ppc64"
412   };
413
414   unsigned Directive = Subtarget.getDarwinDirective();
415   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
416     Directive = PPC::DIR_970;
417   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
418     Directive = PPC::DIR_7400;
419   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
420     Directive = PPC::DIR_64;
421   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
422   OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
423
424   // Prime text sections so they are adjacent.  This reduces the likelihood a
425   // large data or debug section causes a branch to exceed 16M limit.
426   const TargetLoweringObjectFileMachO &TLOFMacho = 
427     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
428   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
429   if (TM.getRelocationModel() == Reloc::PIC_) {
430     OutStreamer.SwitchSection(
431            OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
432                                       MCSectionMachO::S_SYMBOL_STUBS |
433                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
434                                       32, SectionKind::getText()));
435   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
436     OutStreamer.SwitchSection(
437            OutContext.getMachOSection("__TEXT","__symbol_stub1",
438                                       MCSectionMachO::S_SYMBOL_STUBS |
439                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
440                                       16, SectionKind::getText()));
441   }
442   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
443 }
444
445 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
446   // Remove $stub suffix, add $lazy_ptr.
447   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
448   TmpStr += "$lazy_ptr";
449   return Ctx.GetOrCreateSymbol(TmpStr.str());
450 }
451
452 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
453   // Add $tmp suffix to $stub, yielding $stub$tmp.
454   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
455   TmpStr += "$tmp";
456   return Ctx.GetOrCreateSymbol(TmpStr.str());
457 }
458
459 void PPCDarwinAsmPrinter::
460 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
461   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
462   
463   const TargetLoweringObjectFileMachO &TLOFMacho = 
464     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
465
466   // .lazy_symbol_pointer
467   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
468   
469   // Output stubs for dynamically-linked functions
470   if (TM.getRelocationModel() == Reloc::PIC_) {
471     const MCSection *StubSection = 
472     OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
473                                MCSectionMachO::S_SYMBOL_STUBS |
474                                MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
475                                32, SectionKind::getText());
476     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
477       OutStreamer.SwitchSection(StubSection);
478       EmitAlignment(4);
479       
480       MCSymbol *Stub = Stubs[i].first;
481       MCSymbol *RawSym = Stubs[i].second.getPointer();
482       MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
483       MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
484                                            
485       OutStreamer.EmitLabel(Stub);
486       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
487       // FIXME: MCize this.
488       OutStreamer.EmitRawText(StringRef("\tmflr r0"));
489       OutStreamer.EmitRawText("\tbcl 20,31," + Twine(AnonSymbol->getName()));
490       OutStreamer.EmitLabel(AnonSymbol);
491       OutStreamer.EmitRawText(StringRef("\tmflr r11"));
492       OutStreamer.EmitRawText("\taddis r11,r11,ha16("+Twine(LazyPtr->getName())+
493                               "-" + AnonSymbol->getName() + ")");
494       OutStreamer.EmitRawText(StringRef("\tmtlr r0"));
495       
496       if (isPPC64)
497         OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
498                                 "-" + AnonSymbol->getName() + ")(r11)");
499       else
500         OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
501                                 "-" + AnonSymbol->getName() + ")(r11)");
502       OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
503       OutStreamer.EmitRawText(StringRef("\tbctr"));
504       
505       OutStreamer.SwitchSection(LSPSection);
506       OutStreamer.EmitLabel(LazyPtr);
507       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
508       
509       if (isPPC64)
510         OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
511       else
512         OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
513     }
514     OutStreamer.AddBlankLine();
515     return;
516   }
517   
518   const MCSection *StubSection =
519     OutContext.getMachOSection("__TEXT","__symbol_stub1",
520                                MCSectionMachO::S_SYMBOL_STUBS |
521                                MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
522                                16, SectionKind::getText());
523   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
524     MCSymbol *Stub = Stubs[i].first;
525     MCSymbol *RawSym = Stubs[i].second.getPointer();
526     MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
527
528     OutStreamer.SwitchSection(StubSection);
529     EmitAlignment(4);
530     OutStreamer.EmitLabel(Stub);
531     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
532     OutStreamer.EmitRawText("\tlis r11,ha16(" + Twine(LazyPtr->getName()) +")");
533     if (isPPC64)
534       OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
535                               ")(r11)");
536     else
537       OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
538                               ")(r11)");
539     OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
540     OutStreamer.EmitRawText(StringRef("\tbctr"));
541     OutStreamer.SwitchSection(LSPSection);
542     OutStreamer.EmitLabel(LazyPtr);
543     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
544     
545     if (isPPC64)
546       OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
547     else
548       OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
549   }
550   
551   OutStreamer.AddBlankLine();
552 }
553
554
555 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
556   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
557
558   // Darwin/PPC always uses mach-o.
559   const TargetLoweringObjectFileMachO &TLOFMacho = 
560     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
561   MachineModuleInfoMachO &MMIMacho =
562     MMI->getObjFileInfo<MachineModuleInfoMachO>();
563   
564   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
565   if (!Stubs.empty())
566     EmitFunctionStubs(Stubs);
567
568   if (MAI->doesSupportExceptionHandling() && MMI) {
569     // Add the (possibly multiple) personalities to the set of global values.
570     // Only referenced functions get into the Personalities list.
571     const std::vector<const Function*> &Personalities = MMI->getPersonalities();
572     for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
573          E = Personalities.end(); I != E; ++I) {
574       if (*I) {
575         MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
576         MachineModuleInfoImpl::StubValueTy &StubSym =
577           MMIMacho.getGVStubEntry(NLPSym);
578         StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
579       }
580     }
581   }
582
583   // Output stubs for dynamically-linked functions.
584   Stubs = MMIMacho.GetGVStubList();
585   
586   // Output macho stubs for external and common global variables.
587   if (!Stubs.empty()) {
588     // Switch with ".non_lazy_symbol_pointer" directive.
589     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
590     EmitAlignment(isPPC64 ? 3 : 2);
591     
592     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
593       // L_foo$stub:
594       OutStreamer.EmitLabel(Stubs[i].first);
595       //   .indirect_symbol _foo
596       MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
597       OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
598
599       if (MCSym.getInt())
600         // External to current translation unit.
601         OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
602       else
603         // Internal to current translation unit.
604         //
605         // When we place the LSDA into the TEXT section, the type info pointers
606         // need to be indirect and pc-rel. We accomplish this by using NLPs.
607         // However, sometimes the types are local to the file. So we need to
608         // fill in the value for the NLP in those cases.
609         OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
610                                                       OutContext),
611                               isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
612     }
613
614     Stubs.clear();
615     OutStreamer.AddBlankLine();
616   }
617
618   Stubs = MMIMacho.GetHiddenGVStubList();
619   if (!Stubs.empty()) {
620     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
621     EmitAlignment(isPPC64 ? 3 : 2);
622     
623     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
624       // L_foo$stub:
625       OutStreamer.EmitLabel(Stubs[i].first);
626       //   .long _foo
627       OutStreamer.EmitValue(MCSymbolRefExpr::
628                             Create(Stubs[i].second.getPointer(),
629                                    OutContext),
630                             isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
631     }
632
633     Stubs.clear();
634     OutStreamer.AddBlankLine();
635   }
636
637   // Funny Darwin hack: This flag tells the linker that no global symbols
638   // contain code that falls through to other global symbols (e.g. the obvious
639   // implementation of multiple entry points).  If this doesn't occur, the
640   // linker can safely perform dead code stripping.  Since LLVM never generates
641   // code that does this, it is always safe to set.
642   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
643
644   return AsmPrinter::doFinalization(M);
645 }
646
647 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
648 /// for a MachineFunction to the given output stream, in a format that the
649 /// Darwin assembler can deal with.
650 ///
651 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
652                                            MCStreamer &Streamer) {
653   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
654
655   if (Subtarget->isDarwin())
656     return new PPCDarwinAsmPrinter(tm, Streamer);
657   return new PPCLinuxAsmPrinter(tm, Streamer);
658 }
659
660 static MCInstPrinter *createPPCMCInstPrinter(const Target &T,
661                                              unsigned SyntaxVariant,
662                                              const MCAsmInfo &MAI) {
663   return new PPCInstPrinter(MAI, SyntaxVariant);
664 }
665
666
667 // Force static initialization.
668 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
669   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
670   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
671   
672   TargetRegistry::RegisterMCInstPrinter(ThePPC32Target, createPPCMCInstPrinter);
673   TargetRegistry::RegisterMCInstPrinter(ThePPC64Target, createPPCMCInstPrinter);
674 }