Move all of the header files which are involved in modelling the LLVM IR
[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 "InstPrinter/PPCInstPrinter.h"
22 #include "MCTargetDesc/PPCPredicates.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringExtras.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/DebugInfo.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCInst.h"
43 #include "llvm/MC/MCInstBuilder.h"
44 #include "llvm/MC/MCSectionELF.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/MC/MCStreamer.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ELF.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/TargetRegistry.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/Mangler.h"
56 #include "llvm/Target/TargetInstrInfo.h"
57 #include "llvm/Target/TargetOptions.h"
58 #include "llvm/Target/TargetRegisterInfo.h"
59 using namespace llvm;
60
61 namespace {
62   class PPCAsmPrinter : public AsmPrinter {
63   protected:
64     MapVector<MCSymbol*, MCSymbol*> TOC;
65     const PPCSubtarget &Subtarget;
66     uint64_t TOCLabelID;
67   public:
68     explicit PPCAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
69       : AsmPrinter(TM, Streamer),
70         Subtarget(TM.getSubtarget<PPCSubtarget>()), TOCLabelID(0) {}
71
72     virtual const char *getPassName() const {
73       return "PowerPC Assembly Printer";
74     }
75
76     MCSymbol *lookUpOrCreateTOCEntry(MCSymbol *Sym);
77
78     virtual void EmitInstruction(const MachineInstr *MI);
79
80     void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
81
82     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
83                          unsigned AsmVariant, const char *ExtraCode,
84                          raw_ostream &O);
85     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
86                                unsigned AsmVariant, const char *ExtraCode,
87                                raw_ostream &O);
88
89     MachineLocation getDebugValueLocation(const MachineInstr *MI) const {
90       MachineLocation Location;
91       assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
92       // Frame address.  Currently handles register +- offset only.
93       if (MI->getOperand(0).isReg() && MI->getOperand(2).isImm())
94         Location.set(MI->getOperand(0).getReg(), MI->getOperand(2).getImm());
95       else {
96         DEBUG(dbgs() << "DBG_VALUE instruction ignored! " << *MI << "\n");
97       }
98       return Location;
99     }
100   };
101
102   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
103   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
104   public:
105     explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
106       : PPCAsmPrinter(TM, Streamer) {}
107
108     virtual const char *getPassName() const {
109       return "Linux PPC Assembly Printer";
110     }
111
112     bool doFinalization(Module &M);
113
114     virtual void EmitFunctionEntryLabel();
115
116     void EmitFunctionBodyEnd();
117   };
118
119   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
120   /// OS X
121   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
122   public:
123     explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
124       : PPCAsmPrinter(TM, Streamer) {}
125
126     virtual const char *getPassName() const {
127       return "Darwin PPC Assembly Printer";
128     }
129
130     bool doFinalization(Module &M);
131     void EmitStartOfAsmFile(Module &M);
132
133     void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
134   };
135 } // end of anonymous namespace
136
137 /// stripRegisterPrefix - This method strips the character prefix from a
138 /// register name so that only the number is left.  Used by for linux asm.
139 static const char *stripRegisterPrefix(const char *RegName) {
140   switch (RegName[0]) {
141     case 'r':
142     case 'f':
143     case 'v': return RegName + 1;
144     case 'c': if (RegName[1] == 'r') return RegName + 2;
145   }
146   
147   return RegName;
148 }
149
150 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
151                                  raw_ostream &O) {
152   const MachineOperand &MO = MI->getOperand(OpNo);
153   
154   switch (MO.getType()) {
155   case MachineOperand::MO_Register: {
156     const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
157     // Linux assembler (Others?) does not take register mnemonics.
158     // FIXME - What about special registers used in mfspr/mtspr?
159     if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
160     O << RegName;
161     return;
162   }
163   case MachineOperand::MO_Immediate:
164     O << MO.getImm();
165     return;
166
167   case MachineOperand::MO_MachineBasicBlock:
168     O << *MO.getMBB()->getSymbol();
169     return;
170   case MachineOperand::MO_JumpTableIndex:
171     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
172       << '_' << MO.getIndex();
173     // FIXME: PIC relocation model
174     return;
175   case MachineOperand::MO_ConstantPoolIndex:
176     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
177       << '_' << MO.getIndex();
178     return;
179   case MachineOperand::MO_BlockAddress:
180     O << *GetBlockAddressSymbol(MO.getBlockAddress());
181     return;
182   case MachineOperand::MO_ExternalSymbol: {
183     // Computing the address of an external symbol, not calling it.
184     if (TM.getRelocationModel() == Reloc::Static) {
185       O << *GetExternalSymbolSymbol(MO.getSymbolName());
186       return;
187     }
188
189     MCSymbol *NLPSym = 
190       OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
191                                    MO.getSymbolName()+"$non_lazy_ptr");
192     MachineModuleInfoImpl::StubValueTy &StubSym = 
193       MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
194     if (StubSym.getPointer() == 0)
195       StubSym = MachineModuleInfoImpl::
196         StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
197     
198     O << *NLPSym;
199     return;
200   }
201   case MachineOperand::MO_GlobalAddress: {
202     // Computing the address of a global symbol, not calling it.
203     const GlobalValue *GV = MO.getGlobal();
204     MCSymbol *SymToPrint;
205
206     // External or weakly linked global variables need non-lazily-resolved stubs
207     if (TM.getRelocationModel() != Reloc::Static &&
208         (GV->isDeclaration() || GV->isWeakForLinker())) {
209       if (!GV->hasHiddenVisibility()) {
210         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
211         MachineModuleInfoImpl::StubValueTy &StubSym = 
212           MMI->getObjFileInfo<MachineModuleInfoMachO>()
213             .getGVStubEntry(SymToPrint);
214         if (StubSym.getPointer() == 0)
215           StubSym = MachineModuleInfoImpl::
216             StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
217       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
218                  GV->hasAvailableExternallyLinkage()) {
219         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
220         
221         MachineModuleInfoImpl::StubValueTy &StubSym = 
222           MMI->getObjFileInfo<MachineModuleInfoMachO>().
223                     getHiddenGVStubEntry(SymToPrint);
224         if (StubSym.getPointer() == 0)
225           StubSym = MachineModuleInfoImpl::
226             StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
227       } else {
228         SymToPrint = Mang->getSymbol(GV);
229       }
230     } else {
231       SymToPrint = Mang->getSymbol(GV);
232     }
233     
234     O << *SymToPrint;
235
236     printOffset(MO.getOffset(), O);
237     return;
238   }
239
240   default:
241     O << "<unknown operand type: " << MO.getType() << ">";
242     return;
243   }
244 }
245
246 /// PrintAsmOperand - Print out an operand for an inline asm expression.
247 ///
248 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
249                                     unsigned AsmVariant,
250                                     const char *ExtraCode, raw_ostream &O) {
251   // Does this asm operand have a single letter operand modifier?
252   if (ExtraCode && ExtraCode[0]) {
253     if (ExtraCode[1] != 0) return true; // Unknown modifier.
254
255     switch (ExtraCode[0]) {
256     default:
257       // See if this is a generic print operand
258       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
259     case 'c': // Don't print "$" before a global var name or constant.
260       break; // PPC never has a prefix.
261     case 'L': // Write second word of DImode reference.
262       // Verify that this operand has two consecutive registers.
263       if (!MI->getOperand(OpNo).isReg() ||
264           OpNo+1 == MI->getNumOperands() ||
265           !MI->getOperand(OpNo+1).isReg())
266         return true;
267       ++OpNo;   // Return the high-part.
268       break;
269     case 'I':
270       // Write 'i' if an integer constant, otherwise nothing.  Used to print
271       // addi vs add, etc.
272       if (MI->getOperand(OpNo).isImm())
273         O << "i";
274       return false;
275     }
276   }
277
278   printOperand(MI, OpNo, O);
279   return false;
280 }
281
282 // At the moment, all inline asm memory operands are a single register.
283 // In any case, the output of this routine should always be just one
284 // assembler operand.
285
286 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
287                                           unsigned AsmVariant,
288                                           const char *ExtraCode,
289                                           raw_ostream &O) {
290   if (ExtraCode && ExtraCode[0]) {
291     if (ExtraCode[1] != 0) return true; // Unknown modifier.
292
293     switch (ExtraCode[0]) {
294     default: return true;  // Unknown modifier.
295     case 'y': // A memory reference for an X-form instruction
296       {
297         const char *RegName = "r0";
298         if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
299         O << RegName << ", ";
300         printOperand(MI, OpNo, O);
301         return false;
302       }
303     }
304   }
305
306   assert(MI->getOperand(OpNo).isReg());
307   O << "0(";
308   printOperand(MI, OpNo, O);
309   O << ")";
310   return false;
311 }
312
313
314 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
315 /// exists for it.  If not, create one.  Then return a symbol that references
316 /// the TOC entry.
317 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(MCSymbol *Sym) {
318
319   MCSymbol *&TOCEntry = TOC[Sym];
320
321   // To avoid name clash check if the name already exists.
322   while (TOCEntry == 0) {
323     if (OutContext.LookupSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
324                                 "C" + Twine(TOCLabelID++)) == 0) {
325       TOCEntry = GetTempSymbol("C", TOCLabelID);
326     }
327   }
328
329   return TOCEntry;
330 }
331
332
333 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
334 /// the current output stream.
335 ///
336 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
337   MCInst TmpInst;
338   
339   // Lower multi-instruction pseudo operations.
340   switch (MI->getOpcode()) {
341   default: break;
342   case TargetOpcode::DBG_VALUE: {
343     if (!isVerbose() || !OutStreamer.hasRawTextSupport()) return;
344       
345     SmallString<32> Str;
346     raw_svector_ostream O(Str);
347     unsigned NOps = MI->getNumOperands();
348     assert(NOps==4);
349     O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
350     // cast away const; DIetc do not take const operands for some reason.
351     DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
352     O << V.getName();
353     O << " <- ";
354     // Frame address.  Currently handles register +- offset only.
355     assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm());
356     O << '['; printOperand(MI, 0, O); O << '+'; printOperand(MI, 1, O);
357     O << ']';
358     O << "+";
359     printOperand(MI, NOps-2, O);
360     OutStreamer.EmitRawText(O.str());
361     return;
362   }
363       
364   case PPC::MovePCtoLR:
365   case PPC::MovePCtoLR8: {
366     // Transform %LR = MovePCtoLR
367     // Into this, where the label is the PIC base: 
368     //     bl L1$pb
369     // L1$pb:
370     MCSymbol *PICBase = MF->getPICBaseSymbol();
371     
372     // Emit the 'bl'.
373     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL_Darwin) // Darwin vs SVR4 doesn't matter here.
374       // FIXME: We would like an efficient form for this, so we don't have to do
375       // a lot of extra uniquing.
376       .addExpr(MCSymbolRefExpr::Create(PICBase, OutContext)));
377     
378     // Emit the label.
379     OutStreamer.EmitLabel(PICBase);
380     return;
381   }
382   case PPC::LDtocJTI:
383   case PPC::LDtocCPT:
384   case PPC::LDtoc: {
385     // Transform %X3 = LDtoc <ga:@min1>, %X2
386     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
387
388     // Change the opcode to LD, and the global address operand to be a
389     // reference to the TOC entry we will synthesize later.
390     TmpInst.setOpcode(PPC::LD);
391     const MachineOperand &MO = MI->getOperand(1);
392
393     // Map symbol -> label of TOC entry
394     assert(MO.isGlobal() || MO.isCPI() || MO.isJTI());
395     MCSymbol *MOSymbol = 0;
396     if (MO.isGlobal())
397       MOSymbol = Mang->getSymbol(MO.getGlobal());
398     else if (MO.isCPI())
399       MOSymbol = GetCPISymbol(MO.getIndex());
400     else if (MO.isJTI())
401       MOSymbol = GetJTISymbol(MO.getIndex());
402
403     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
404
405     const MCExpr *Exp =
406       MCSymbolRefExpr::Create(TOCEntry, MCSymbolRefExpr::VK_PPC_TOC_ENTRY,
407                               OutContext);
408     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
409     OutStreamer.EmitInstruction(TmpInst);
410     return;
411   }
412       
413   case PPC::ADDIStocHA: {
414     // Transform %Xd = ADDIStocHA %X2, <ga:@sym>
415     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
416
417     // Change the opcode to ADDIS8.  If the global address is external,
418     // has common linkage, is a function address, or is a jump table
419     // address, then generate a TOC entry and reference that.  Otherwise
420     // reference the symbol directly.
421     TmpInst.setOpcode(PPC::ADDIS8);
422     const MachineOperand &MO = MI->getOperand(2);
423     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI()) &&
424            "Invalid operand for ADDIStocHA!");
425     MCSymbol *MOSymbol = 0;
426     bool IsExternal = false;
427     bool IsFunction = false;
428     bool IsCommon = false;
429
430     if (MO.isGlobal()) {
431       const GlobalValue *GValue = MO.getGlobal();
432       MOSymbol = Mang->getSymbol(GValue);
433       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GValue);
434       IsExternal = GVar && !GVar->hasInitializer();
435       IsCommon = GVar && GValue->hasCommonLinkage();
436       IsFunction = !GVar;
437     } else if (MO.isCPI())
438       MOSymbol = GetCPISymbol(MO.getIndex());
439     else if (MO.isJTI())
440       MOSymbol = GetJTISymbol(MO.getIndex());
441
442     if (IsExternal || IsFunction || IsCommon || MO.isJTI())
443       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
444
445     const MCExpr *Exp =
446       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC16_HA,
447                               OutContext);
448     TmpInst.getOperand(2) = MCOperand::CreateExpr(Exp);
449     OutStreamer.EmitInstruction(TmpInst);
450     return;
451   }
452   case PPC::LDtocL: {
453     // Transform %Xd = LDtocL <ga:@sym>, %Xs
454     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
455
456     // Change the opcode to LDrs, which is a form of LD with the offset
457     // specified by a SymbolLo.  If the global address is external, has
458     // common linkage, or is a jump table address, then reference the
459     // associated TOC entry.  Otherwise reference the symbol directly.
460     TmpInst.setOpcode(PPC::LDrs);
461     const MachineOperand &MO = MI->getOperand(1);
462     assert((MO.isGlobal() || MO.isJTI()) && "Invalid operand for LDtocL!");
463     MCSymbol *MOSymbol = 0;
464
465     if (MO.isJTI())
466       MOSymbol = lookUpOrCreateTOCEntry(GetJTISymbol(MO.getIndex()));
467     else {
468       const GlobalValue *GValue = MO.getGlobal();
469       MOSymbol = Mang->getSymbol(GValue);
470       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GValue);
471     
472       if (!GVar || !GVar->hasInitializer() || GValue->hasCommonLinkage())
473         MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
474     }
475
476     const MCExpr *Exp =
477       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC16_LO,
478                               OutContext);
479     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
480     OutStreamer.EmitInstruction(TmpInst);
481     return;
482   }
483   case PPC::ADDItocL: {
484     // Transform %Xd = ADDItocL %Xs, <ga:@sym>
485     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
486
487     // Change the opcode to ADDI8L.  If the global address is external, then
488     // generate a TOC entry and reference that.  Otherwise reference the
489     // symbol directly.
490     TmpInst.setOpcode(PPC::ADDI8L);
491     const MachineOperand &MO = MI->getOperand(2);
492     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL");
493     MCSymbol *MOSymbol = 0;
494     bool IsExternal = false;
495     bool IsFunction = false;
496
497     if (MO.isGlobal()) {
498       const GlobalValue *GValue = MO.getGlobal();
499       MOSymbol = Mang->getSymbol(GValue);
500       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GValue);
501       IsExternal = GVar && !GVar->hasInitializer();
502       IsFunction = !GVar;
503     } else if (MO.isCPI())
504       MOSymbol = GetCPISymbol(MO.getIndex());
505
506     if (IsFunction || IsExternal)
507       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
508
509     const MCExpr *Exp =
510       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC16_LO,
511                               OutContext);
512     TmpInst.getOperand(2) = MCOperand::CreateExpr(Exp);
513     OutStreamer.EmitInstruction(TmpInst);
514     return;
515   }
516   case PPC::ADDISgotTprelHA: {
517     // Transform: %Xd = ADDISgotTprelHA %X2, <ga:@sym>
518     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
519     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
520     const MachineOperand &MO = MI->getOperand(2);
521     const GlobalValue *GValue = MO.getGlobal();
522     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
523     const MCExpr *SymGotTprel =
524       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL16_HA,
525                               OutContext);
526     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
527                                 .addReg(MI->getOperand(0).getReg())
528                                 .addReg(PPC::X2)
529                                 .addExpr(SymGotTprel));
530     return;
531   }
532   case PPC::LDgotTprelL: {
533     // Transform %Xd = LDgotTprelL <ga:@sym>, %Xs
534     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
535
536     // Change the opcode to LDrs, which is a form of LD with the offset
537     // specified by a SymbolLo.
538     TmpInst.setOpcode(PPC::LDrs);
539     const MachineOperand &MO = MI->getOperand(1);
540     const GlobalValue *GValue = MO.getGlobal();
541     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
542     const MCExpr *Exp =
543       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL16_LO,
544                               OutContext);
545     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
546     OutStreamer.EmitInstruction(TmpInst);
547     return;
548   }
549   case PPC::ADDIStlsgdHA: {
550     // Transform: %Xd = ADDIStlsgdHA %X2, <ga:@sym>
551     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
552     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
553     const MachineOperand &MO = MI->getOperand(2);
554     const GlobalValue *GValue = MO.getGlobal();
555     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
556     const MCExpr *SymGotTlsGD =
557       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD16_HA,
558                               OutContext);
559     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
560                                 .addReg(MI->getOperand(0).getReg())
561                                 .addReg(PPC::X2)
562                                 .addExpr(SymGotTlsGD));
563     return;
564   }
565   case PPC::ADDItlsgdL: {
566     // Transform: %Xd = ADDItlsgdL %Xs, <ga:@sym>
567     // Into:      %Xd = ADDI8L %Xs, sym@got@tlsgd@l
568     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
569     const MachineOperand &MO = MI->getOperand(2);
570     const GlobalValue *GValue = MO.getGlobal();
571     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
572     const MCExpr *SymGotTlsGD =
573       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD16_LO,
574                               OutContext);
575     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8L)
576                                 .addReg(MI->getOperand(0).getReg())
577                                 .addReg(MI->getOperand(1).getReg())
578                                 .addExpr(SymGotTlsGD));
579     return;
580   }
581   case PPC::GETtlsADDR: {
582     // Transform: %X3 = GETtlsADDR %X3, <ga:@sym>
583     // Into:      BL8_NOP_ELF_TLSGD __tls_get_addr(sym@tlsgd)
584     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
585
586     StringRef Name = "__tls_get_addr";
587     MCSymbol *TlsGetAddr = OutContext.GetOrCreateSymbol(Name);
588     const MCSymbolRefExpr *TlsRef = 
589       MCSymbolRefExpr::Create(TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
590     const MachineOperand &MO = MI->getOperand(2);
591     const GlobalValue *GValue = MO.getGlobal();
592     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
593     const MCExpr *SymVar =
594       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TLSGD,
595                               OutContext);
596     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL8_NOP_ELF_TLSGD)
597                                 .addExpr(TlsRef)
598                                 .addExpr(SymVar));
599     return;
600   }
601   case PPC::ADDIStlsldHA: {
602     // Transform: %Xd = ADDIStlsldHA %X2, <ga:@sym>
603     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsld@ha
604     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
605     const MachineOperand &MO = MI->getOperand(2);
606     const GlobalValue *GValue = MO.getGlobal();
607     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
608     const MCExpr *SymGotTlsLD =
609       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD16_HA,
610                               OutContext);
611     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
612                                 .addReg(MI->getOperand(0).getReg())
613                                 .addReg(PPC::X2)
614                                 .addExpr(SymGotTlsLD));
615     return;
616   }
617   case PPC::ADDItlsldL: {
618     // Transform: %Xd = ADDItlsldL %Xs, <ga:@sym>
619     // Into:      %Xd = ADDI8L %Xs, sym@got@tlsld@l
620     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
621     const MachineOperand &MO = MI->getOperand(2);
622     const GlobalValue *GValue = MO.getGlobal();
623     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
624     const MCExpr *SymGotTlsLD =
625       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD16_LO,
626                               OutContext);
627     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8L)
628                                 .addReg(MI->getOperand(0).getReg())
629                                 .addReg(MI->getOperand(1).getReg())
630                                 .addExpr(SymGotTlsLD));
631     return;
632   }
633   case PPC::GETtlsldADDR: {
634     // Transform: %X3 = GETtlsldADDR %X3, <ga:@sym>
635     // Into:      BL8_NOP_ELF_TLSLD __tls_get_addr(sym@tlsld)
636     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
637
638     StringRef Name = "__tls_get_addr";
639     MCSymbol *TlsGetAddr = OutContext.GetOrCreateSymbol(Name);
640     const MCSymbolRefExpr *TlsRef = 
641       MCSymbolRefExpr::Create(TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
642     const MachineOperand &MO = MI->getOperand(2);
643     const GlobalValue *GValue = MO.getGlobal();
644     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
645     const MCExpr *SymVar =
646       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TLSLD,
647                               OutContext);
648     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL8_NOP_ELF_TLSLD)
649                                 .addExpr(TlsRef)
650                                 .addExpr(SymVar));
651     return;
652   }
653   case PPC::ADDISdtprelHA: {
654     // Transform: %Xd = ADDISdtprelHA %X3, <ga:@sym>
655     // Into:      %Xd = ADDIS8 %X3, sym@dtprel@ha
656     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
657     const MachineOperand &MO = MI->getOperand(2);
658     const GlobalValue *GValue = MO.getGlobal();
659     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
660     const MCExpr *SymDtprel =
661       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL16_HA,
662                               OutContext);
663     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
664                                 .addReg(MI->getOperand(0).getReg())
665                                 .addReg(PPC::X3)
666                                 .addExpr(SymDtprel));
667     return;
668   }
669   case PPC::ADDIdtprelL: {
670     // Transform: %Xd = ADDIdtprelL %Xs, <ga:@sym>
671     // Into:      %Xd = ADDI8L %Xs, sym@dtprel@l
672     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
673     const MachineOperand &MO = MI->getOperand(2);
674     const GlobalValue *GValue = MO.getGlobal();
675     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
676     const MCExpr *SymDtprel =
677       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL16_LO,
678                               OutContext);
679     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8L)
680                                 .addReg(MI->getOperand(0).getReg())
681                                 .addReg(MI->getOperand(1).getReg())
682                                 .addExpr(SymDtprel));
683     return;
684   }
685   case PPC::MFCRpseud:
686   case PPC::MFCR8pseud:
687     // Transform: %R3 = MFCRpseud %CR7
688     // Into:      %R3 = MFCR      ;; cr7
689     OutStreamer.AddComment(PPCInstPrinter::
690                            getRegisterName(MI->getOperand(1).getReg()));
691     OutStreamer.EmitInstruction(MCInstBuilder(Subtarget.isPPC64() ? PPC::MFCR8 : PPC::MFCR)
692       .addReg(MI->getOperand(0).getReg()));
693     return;
694   case PPC::SYNC:
695     // In Book E sync is called msync, handle this special case here...
696     if (Subtarget.isBookE()) {
697       OutStreamer.EmitRawText(StringRef("\tmsync"));
698       return;
699     }
700   }
701
702   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
703   OutStreamer.EmitInstruction(TmpInst);
704 }
705
706 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
707   if (!Subtarget.isPPC64())  // linux/ppc32 - Normal entry label.
708     return AsmPrinter::EmitFunctionEntryLabel();
709     
710   // Emit an official procedure descriptor.
711   const MCSection *Current = OutStreamer.getCurrentSection();
712   const MCSectionELF *Section = OutStreamer.getContext().getELFSection(".opd",
713       ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
714       SectionKind::getReadOnly());
715   OutStreamer.SwitchSection(Section);
716   OutStreamer.EmitLabel(CurrentFnSym);
717   OutStreamer.EmitValueToAlignment(8);
718   MCSymbol *Symbol1 = 
719     OutContext.GetOrCreateSymbol(".L." + Twine(CurrentFnSym->getName()));
720   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
721   // entry point.
722   OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol1, OutContext),
723                         8/*size*/, 0/*addrspace*/);
724   MCSymbol *Symbol2 = OutContext.GetOrCreateSymbol(StringRef(".TOC."));
725   // Generates a R_PPC64_TOC relocation for TOC base insertion.
726   OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol2,
727                         MCSymbolRefExpr::VK_PPC_TOC, OutContext),
728                         8/*size*/, 0/*addrspace*/);
729   // Emit a null environment pointer.
730   OutStreamer.EmitIntValue(0, 8 /* size */, 0 /* addrspace */);
731   OutStreamer.SwitchSection(Current);
732
733   MCSymbol *RealFnSym = OutContext.GetOrCreateSymbol(
734                           ".L." + Twine(CurrentFnSym->getName()));
735   OutStreamer.EmitLabel(RealFnSym);
736   CurrentFnSymForSize = RealFnSym;
737 }
738
739
740 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
741   const DataLayout *TD = TM.getDataLayout();
742
743   bool isPPC64 = TD->getPointerSizeInBits() == 64;
744
745   if (isPPC64 && !TOC.empty()) {
746     const MCSectionELF *Section = OutStreamer.getContext().getELFSection(".toc",
747         ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
748         SectionKind::getReadOnly());
749     OutStreamer.SwitchSection(Section);
750
751     for (MapVector<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
752          E = TOC.end(); I != E; ++I) {
753       OutStreamer.EmitLabel(I->second);
754       MCSymbol *S = OutContext.GetOrCreateSymbol(I->first->getName());
755       OutStreamer.EmitTCEntry(*S);
756     }
757   }
758
759   return AsmPrinter::doFinalization(M);
760 }
761
762 /// EmitFunctionBodyEnd - Print the traceback table before the .size
763 /// directive.
764 ///
765 void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
766   // Only the 64-bit target requires a traceback table.  For now,
767   // we only emit the word of zeroes that GDB requires to find
768   // the end of the function, and zeroes for the eight-byte
769   // mandatory fields.
770   // FIXME: We should fill in the eight-byte mandatory fields as described in
771   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
772   // currently make use of these fields).
773   if (Subtarget.isPPC64()) {
774     OutStreamer.EmitIntValue(0, 4/*size*/);
775     OutStreamer.EmitIntValue(0, 8/*size*/);
776   }
777 }
778
779 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
780   static const char *const CPUDirectives[] = {
781     "",
782     "ppc",
783     "ppc440",
784     "ppc601",
785     "ppc602",
786     "ppc603",
787     "ppc7400",
788     "ppc750",
789     "ppc970",
790     "ppcA2",
791     "ppce500mc",
792     "ppce5500",
793     "power6",
794     "power7",
795     "ppc64"
796   };
797
798   unsigned Directive = Subtarget.getDarwinDirective();
799   if (Subtarget.hasMFOCRF() && Directive < PPC::DIR_970)
800     Directive = PPC::DIR_970;
801   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
802     Directive = PPC::DIR_7400;
803   if (Subtarget.isPPC64() && Directive < PPC::DIR_64)
804     Directive = PPC::DIR_64;
805   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
806   
807   // FIXME: This is a total hack, finish mc'izing the PPC backend.
808   if (OutStreamer.hasRawTextSupport())
809     OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
810
811   // Prime text sections so they are adjacent.  This reduces the likelihood a
812   // large data or debug section causes a branch to exceed 16M limit.
813   const TargetLoweringObjectFileMachO &TLOFMacho = 
814     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
815   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
816   if (TM.getRelocationModel() == Reloc::PIC_) {
817     OutStreamer.SwitchSection(
818            OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
819                                       MCSectionMachO::S_SYMBOL_STUBS |
820                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
821                                       32, SectionKind::getText()));
822   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
823     OutStreamer.SwitchSection(
824            OutContext.getMachOSection("__TEXT","__symbol_stub1",
825                                       MCSectionMachO::S_SYMBOL_STUBS |
826                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
827                                       16, SectionKind::getText()));
828   }
829   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
830 }
831
832 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
833   // Remove $stub suffix, add $lazy_ptr.
834   StringRef NoStub = Sym->getName().substr(0, Sym->getName().size()-5);
835   return Ctx.GetOrCreateSymbol(NoStub + "$lazy_ptr");
836 }
837
838 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
839   // Add $tmp suffix to $stub, yielding $stub$tmp.
840   return Ctx.GetOrCreateSymbol(Sym->getName() + "$tmp");
841 }
842
843 void PPCDarwinAsmPrinter::
844 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
845   bool isPPC64 = TM.getDataLayout()->getPointerSizeInBits() == 64;
846   
847   const TargetLoweringObjectFileMachO &TLOFMacho = 
848     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
849
850   // .lazy_symbol_pointer
851   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
852   
853   // Output stubs for dynamically-linked functions
854   if (TM.getRelocationModel() == Reloc::PIC_) {
855     const MCSection *StubSection = 
856     OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
857                                MCSectionMachO::S_SYMBOL_STUBS |
858                                MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
859                                32, SectionKind::getText());
860     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
861       OutStreamer.SwitchSection(StubSection);
862       EmitAlignment(4);
863       
864       MCSymbol *Stub = Stubs[i].first;
865       MCSymbol *RawSym = Stubs[i].second.getPointer();
866       MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
867       MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
868                                            
869       OutStreamer.EmitLabel(Stub);
870       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
871
872       // mflr r0
873       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MFLR).addReg(PPC::R0));
874       // FIXME: MCize this.
875       OutStreamer.EmitRawText("\tbcl 20, 31, " + Twine(AnonSymbol->getName()));
876       OutStreamer.EmitLabel(AnonSymbol);
877       // mflr r11
878       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MFLR).addReg(PPC::R11));
879       // addis r11, r11, ha16(LazyPtr - AnonSymbol)
880       const MCExpr *Sub =
881         MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(LazyPtr, OutContext),
882                                 MCSymbolRefExpr::Create(AnonSymbol, OutContext),
883                                 OutContext);
884       OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS)
885         .addReg(PPC::R11)
886         .addReg(PPC::R11)
887         .addExpr(Sub));
888       // mtlr r0
889       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTLR).addReg(PPC::R0));
890
891       // ldu r12, lo16(LazyPtr - AnonSymbol)(r11)
892       // lwzu r12, lo16(LazyPtr - AnonSymbol)(r11)
893       OutStreamer.EmitInstruction(MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
894         .addReg(PPC::R12)
895         .addExpr(Sub).addExpr(Sub)
896         .addReg(PPC::R11));
897       // mtctr r12
898       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
899       // bctr
900       OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCTR));
901
902       OutStreamer.SwitchSection(LSPSection);
903       OutStreamer.EmitLabel(LazyPtr);
904       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
905
906       MCSymbol *DyldStubBindingHelper =
907         OutContext.GetOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
908       if (isPPC64) {
909         // .quad dyld_stub_binding_helper
910         OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 8);
911       } else {
912         // .long dyld_stub_binding_helper
913         OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 4);
914       }
915     }
916     OutStreamer.AddBlankLine();
917     return;
918   }
919   
920   const MCSection *StubSection =
921     OutContext.getMachOSection("__TEXT","__symbol_stub1",
922                                MCSectionMachO::S_SYMBOL_STUBS |
923                                MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
924                                16, SectionKind::getText());
925   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
926     MCSymbol *Stub = Stubs[i].first;
927     MCSymbol *RawSym = Stubs[i].second.getPointer();
928     MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
929
930     OutStreamer.SwitchSection(StubSection);
931     EmitAlignment(4);
932     OutStreamer.EmitLabel(Stub);
933     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
934     // lis r11, ha16(LazyPtr)
935     const MCExpr *LazyPtrHa16 =
936       MCSymbolRefExpr::Create(LazyPtr, MCSymbolRefExpr::VK_PPC_DARWIN_HA16,
937                               OutContext);
938     OutStreamer.EmitInstruction(MCInstBuilder(PPC::LIS)
939       .addReg(PPC::R11)
940       .addExpr(LazyPtrHa16));
941
942     const MCExpr *LazyPtrLo16 =
943       MCSymbolRefExpr::Create(LazyPtr, MCSymbolRefExpr::VK_PPC_DARWIN_LO16,
944                               OutContext);
945     // ldu r12, lo16(LazyPtr)(r11)
946     // lwzu r12, lo16(LazyPtr)(r11)
947     OutStreamer.EmitInstruction(MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
948       .addReg(PPC::R12)
949       .addExpr(LazyPtrLo16).addExpr(LazyPtrLo16)
950       .addReg(PPC::R11));
951
952     // mtctr r12
953     OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
954     // bctr
955     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCTR));
956
957     OutStreamer.SwitchSection(LSPSection);
958     OutStreamer.EmitLabel(LazyPtr);
959     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
960
961     MCSymbol *DyldStubBindingHelper =
962       OutContext.GetOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
963     if (isPPC64) {
964       // .quad dyld_stub_binding_helper
965       OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 8);
966     } else {
967       // .long dyld_stub_binding_helper
968       OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 4);
969     }
970   }
971   
972   OutStreamer.AddBlankLine();
973 }
974
975
976 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
977   bool isPPC64 = TM.getDataLayout()->getPointerSizeInBits() == 64;
978
979   // Darwin/PPC always uses mach-o.
980   const TargetLoweringObjectFileMachO &TLOFMacho = 
981     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
982   MachineModuleInfoMachO &MMIMacho =
983     MMI->getObjFileInfo<MachineModuleInfoMachO>();
984   
985   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
986   if (!Stubs.empty())
987     EmitFunctionStubs(Stubs);
988
989   if (MAI->doesSupportExceptionHandling() && MMI) {
990     // Add the (possibly multiple) personalities to the set of global values.
991     // Only referenced functions get into the Personalities list.
992     const std::vector<const Function*> &Personalities = MMI->getPersonalities();
993     for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
994          E = Personalities.end(); I != E; ++I) {
995       if (*I) {
996         MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
997         MachineModuleInfoImpl::StubValueTy &StubSym =
998           MMIMacho.getGVStubEntry(NLPSym);
999         StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
1000       }
1001     }
1002   }
1003
1004   // Output stubs for dynamically-linked functions.
1005   Stubs = MMIMacho.GetGVStubList();
1006   
1007   // Output macho stubs for external and common global variables.
1008   if (!Stubs.empty()) {
1009     // Switch with ".non_lazy_symbol_pointer" directive.
1010     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1011     EmitAlignment(isPPC64 ? 3 : 2);
1012     
1013     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1014       // L_foo$stub:
1015       OutStreamer.EmitLabel(Stubs[i].first);
1016       //   .indirect_symbol _foo
1017       MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1018       OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
1019
1020       if (MCSym.getInt())
1021         // External to current translation unit.
1022         OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
1023       else
1024         // Internal to current translation unit.
1025         //
1026         // When we place the LSDA into the TEXT section, the type info pointers
1027         // need to be indirect and pc-rel. We accomplish this by using NLPs.
1028         // However, sometimes the types are local to the file. So we need to
1029         // fill in the value for the NLP in those cases.
1030         OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
1031                                                       OutContext),
1032                               isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
1033     }
1034
1035     Stubs.clear();
1036     OutStreamer.AddBlankLine();
1037   }
1038
1039   Stubs = MMIMacho.GetHiddenGVStubList();
1040   if (!Stubs.empty()) {
1041     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1042     EmitAlignment(isPPC64 ? 3 : 2);
1043     
1044     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1045       // L_foo$stub:
1046       OutStreamer.EmitLabel(Stubs[i].first);
1047       //   .long _foo
1048       OutStreamer.EmitValue(MCSymbolRefExpr::
1049                             Create(Stubs[i].second.getPointer(),
1050                                    OutContext),
1051                             isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
1052     }
1053
1054     Stubs.clear();
1055     OutStreamer.AddBlankLine();
1056   }
1057
1058   // Funny Darwin hack: This flag tells the linker that no global symbols
1059   // contain code that falls through to other global symbols (e.g. the obvious
1060   // implementation of multiple entry points).  If this doesn't occur, the
1061   // linker can safely perform dead code stripping.  Since LLVM never generates
1062   // code that does this, it is always safe to set.
1063   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1064
1065   return AsmPrinter::doFinalization(M);
1066 }
1067
1068 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1069 /// for a MachineFunction to the given output stream, in a format that the
1070 /// Darwin assembler can deal with.
1071 ///
1072 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
1073                                            MCStreamer &Streamer) {
1074   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1075
1076   if (Subtarget->isDarwin())
1077     return new PPCDarwinAsmPrinter(tm, Streamer);
1078   return new PPCLinuxAsmPrinter(tm, Streamer);
1079 }
1080
1081 // Force static initialization.
1082 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
1083   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1084   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1085 }