Give AsmPrinter the most common expected implementation of
[oota-llvm.git] / lib / Target / PowerPC / AsmPrinter / 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/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.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/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSet.h"
52 #include "llvm/ADT/SmallString.h"
53 using namespace llvm;
54
55 namespace {
56   class PPCAsmPrinter : public AsmPrinter {
57   protected:
58     DenseMap<const MCSymbol*, const MCSymbol*> TOC;
59     const PPCSubtarget &Subtarget;
60     uint64_t LabelID;
61   public:
62     explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
63                            const MCAsmInfo *T, bool V)
64       : AsmPrinter(O, TM, T, V),
65         Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
66
67     virtual const char *getPassName() const {
68       return "PowerPC Assembly Printer";
69     }
70
71     PPCTargetMachine &getTM() {
72       return static_cast<PPCTargetMachine&>(TM);
73     }
74
75     unsigned enumRegToMachineReg(unsigned enumReg) {
76       switch (enumReg) {
77       default: llvm_unreachable("Unhandled register!");
78       case PPC::CR0:  return  0;
79       case PPC::CR1:  return  1;
80       case PPC::CR2:  return  2;
81       case PPC::CR3:  return  3;
82       case PPC::CR4:  return  4;
83       case PPC::CR5:  return  5;
84       case PPC::CR6:  return  6;
85       case PPC::CR7:  return  7;
86       }
87       llvm_unreachable(0);
88     }
89
90     /// printInstruction - This method is automatically generated by tablegen
91     /// from the instruction set description.  This method returns true if the
92     /// machine instruction was sufficiently described to print it, otherwise it
93     /// returns false.
94     void printInstruction(const MachineInstr *MI);
95     static const char *getRegisterName(unsigned RegNo);
96
97
98     virtual void EmitInstruction(const MachineInstr *MI);
99     void printOp(const MachineOperand &MO);
100
101     /// stripRegisterPrefix - This method strips the character prefix from a
102     /// register name so that only the number is left.  Used by for linux asm.
103     const char *stripRegisterPrefix(const char *RegName) {
104       switch (RegName[0]) {
105       case 'r':
106       case 'f':
107       case 'v': return RegName + 1;
108       case 'c': if (RegName[1] == 'r') return RegName + 2;
109       }
110
111       return RegName;
112     }
113
114     /// printRegister - Print register according to target requirements.
115     ///
116     void printRegister(const MachineOperand &MO, bool R0AsZero) {
117       unsigned RegNo = MO.getReg();
118       assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
119
120       // If we should use 0 for R0.
121       if (R0AsZero && RegNo == PPC::R0) {
122         O << "0";
123         return;
124       }
125
126       const char *RegName = getRegisterName(RegNo);
127       // Linux assembler (Others?) does not take register mnemonics.
128       // FIXME - What about special registers used in mfspr/mtspr?
129       if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
130       O << RegName;
131     }
132
133     void printOperand(const MachineInstr *MI, unsigned OpNo) {
134       const MachineOperand &MO = MI->getOperand(OpNo);
135       if (MO.isReg()) {
136         printRegister(MO, false);
137       } else if (MO.isImm()) {
138         O << MO.getImm();
139       } else {
140         printOp(MO);
141       }
142     }
143
144     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
145                          unsigned AsmVariant, const char *ExtraCode);
146     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
147                                unsigned AsmVariant, const char *ExtraCode);
148
149
150     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
151       char value = MI->getOperand(OpNo).getImm();
152       value = (value << (32-5)) >> (32-5);
153       O << (int)value;
154     }
155     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
156       unsigned char value = MI->getOperand(OpNo).getImm();
157       assert(value <= 31 && "Invalid u5imm argument!");
158       O << (unsigned int)value;
159     }
160     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
161       unsigned char value = MI->getOperand(OpNo).getImm();
162       assert(value <= 63 && "Invalid u6imm argument!");
163       O << (unsigned int)value;
164     }
165     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
166       O << (short)MI->getOperand(OpNo).getImm();
167     }
168     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
169       O << (unsigned short)MI->getOperand(OpNo).getImm();
170     }
171     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
172       if (MI->getOperand(OpNo).isImm()) {
173         O << (short)(MI->getOperand(OpNo).getImm()*4);
174       } else {
175         O << "lo16(";
176         printOp(MI->getOperand(OpNo));
177         if (TM.getRelocationModel() == Reloc::PIC_)
178           O << "-\"L" << getFunctionNumber() << "$pb\")";
179         else
180           O << ')';
181       }
182     }
183     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
184       // Branches can take an immediate operand.  This is used by the branch
185       // selection pass to print $+8, an eight byte displacement from the PC.
186       if (MI->getOperand(OpNo).isImm()) {
187         O << "$+" << MI->getOperand(OpNo).getImm()*4;
188       } else {
189         printOp(MI->getOperand(OpNo));
190       }
191     }
192     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
193       const MachineOperand &MO = MI->getOperand(OpNo);
194       if (TM.getRelocationModel() != Reloc::Static) {
195         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
196           GlobalValue *GV = MO.getGlobal();
197           if (GV->isDeclaration() || GV->isWeakForLinker()) {
198             // Dynamically-resolved functions need a stub for the function.
199             MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
200             const MCSymbol *&StubSym =
201               MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
202             if (StubSym == 0)
203               StubSym = GetGlobalValueSymbol(GV);
204             O << *Sym;
205             return;
206           }
207         }
208         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
209           SmallString<128> TempNameStr;
210           TempNameStr += StringRef(MO.getSymbolName());
211           TempNameStr += StringRef("$stub");
212           
213           const MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
214           const MCSymbol *&StubSym =
215             MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
216           if (StubSym == 0)
217             StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
218           O << *Sym;
219           return;
220         }
221       }
222
223       printOp(MI->getOperand(OpNo));
224     }
225     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
226      O << (int)MI->getOperand(OpNo).getImm()*4;
227     }
228     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
229       O << "\"L" << getFunctionNumber() << "$pb\"\n";
230       O << "\"L" << getFunctionNumber() << "$pb\":";
231     }
232     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
233       if (MI->getOperand(OpNo).isImm()) {
234         printS16ImmOperand(MI, OpNo);
235       } else {
236         if (Subtarget.isDarwin()) O << "ha16(";
237         printOp(MI->getOperand(OpNo));
238         if (TM.getRelocationModel() == Reloc::PIC_)
239           O << "-\"L" << getFunctionNumber() << "$pb\"";
240         if (Subtarget.isDarwin())
241           O << ')';
242         else
243           O << "@ha";
244       }
245     }
246     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
247       if (MI->getOperand(OpNo).isImm()) {
248         printS16ImmOperand(MI, OpNo);
249       } else {
250         if (Subtarget.isDarwin()) O << "lo16(";
251         printOp(MI->getOperand(OpNo));
252         if (TM.getRelocationModel() == Reloc::PIC_)
253           O << "-\"L" << getFunctionNumber() << "$pb\"";
254         if (Subtarget.isDarwin())
255           O << ')';
256         else
257           O << "@l";
258       }
259     }
260     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
261       unsigned CCReg = MI->getOperand(OpNo).getReg();
262       unsigned RegNo = enumRegToMachineReg(CCReg);
263       O << (0x80 >> RegNo);
264     }
265     // The new addressing mode printers.
266     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
267       printSymbolLo(MI, OpNo);
268       O << '(';
269       if (MI->getOperand(OpNo+1).isReg() &&
270           MI->getOperand(OpNo+1).getReg() == PPC::R0)
271         O << "0";
272       else
273         printOperand(MI, OpNo+1);
274       O << ')';
275     }
276     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
277       if (MI->getOperand(OpNo).isImm())
278         printS16X4ImmOperand(MI, OpNo);
279       else
280         printSymbolLo(MI, OpNo);
281       O << '(';
282       if (MI->getOperand(OpNo+1).isReg() &&
283           MI->getOperand(OpNo+1).getReg() == PPC::R0)
284         O << "0";
285       else
286         printOperand(MI, OpNo+1);
287       O << ')';
288     }
289
290     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
291       // When used as the base register, r0 reads constant zero rather than
292       // the value contained in the register.  For this reason, the darwin
293       // assembler requires that we print r0 as 0 (no r) when used as the base.
294       const MachineOperand &MO = MI->getOperand(OpNo);
295       printRegister(MO, true);
296       O << ", ";
297       printOperand(MI, OpNo+1);
298     }
299
300     void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
301       const MachineOperand &MO = MI->getOperand(OpNo);
302
303       assert(MO.getType() == MachineOperand::MO_GlobalAddress);
304
305       const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
306
307       // Map symbol -> label of TOC entry.
308       const MCSymbol *&TOCEntry = TOC[Sym];
309       if (TOCEntry == 0)
310         TOCEntry = OutContext.
311           GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
312                             Twine(LabelID++));
313
314       O << *TOCEntry << "@toc";
315     }
316
317     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
318                                const char *Modifier);
319   };
320
321   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
322   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
323   public:
324     explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
325                                 const MCAsmInfo *T, bool V)
326       : PPCAsmPrinter(O, TM, T, V){}
327
328     virtual const char *getPassName() const {
329       return "Linux PPC Assembly Printer";
330     }
331
332     bool doFinalization(Module &M);
333
334     virtual void EmitFunctionEntryLabel();
335
336     void getAnalysisUsage(AnalysisUsage &AU) const {
337       AU.setPreservesAll();
338       AU.addRequired<MachineModuleInfo>();
339       AU.addRequired<DwarfWriter>();
340       PPCAsmPrinter::getAnalysisUsage(AU);
341     }
342   };
343
344   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
345   /// OS X
346   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
347     formatted_raw_ostream &OS;
348   public:
349     explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
350                                  const MCAsmInfo *T, bool V)
351       : PPCAsmPrinter(O, TM, T, V), OS(O) {}
352
353     virtual const char *getPassName() const {
354       return "Darwin PPC Assembly Printer";
355     }
356
357     bool doFinalization(Module &M);
358     void EmitStartOfAsmFile(Module &M);
359
360     void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
361     
362     void getAnalysisUsage(AnalysisUsage &AU) const {
363       AU.setPreservesAll();
364       AU.addRequired<MachineModuleInfo>();
365       AU.addRequired<DwarfWriter>();
366       PPCAsmPrinter::getAnalysisUsage(AU);
367     }
368   };
369 } // end of anonymous namespace
370
371 // Include the auto-generated portion of the assembly writer
372 #include "PPCGenAsmWriter.inc"
373
374 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
375   switch (MO.getType()) {
376   case MachineOperand::MO_Immediate:
377     llvm_unreachable("printOp() does not handle immediate values");
378
379   case MachineOperand::MO_MachineBasicBlock:
380     O << *MO.getMBB()->getSymbol(OutContext);
381     return;
382   case MachineOperand::MO_JumpTableIndex:
383     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
384       << '_' << MO.getIndex();
385     // FIXME: PIC relocation model
386     return;
387   case MachineOperand::MO_ConstantPoolIndex:
388     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
389       << '_' << MO.getIndex();
390     return;
391   case MachineOperand::MO_BlockAddress:
392     O << *GetBlockAddressSymbol(MO.getBlockAddress());
393     return;
394   case MachineOperand::MO_ExternalSymbol: {
395     // Computing the address of an external symbol, not calling it.
396     if (TM.getRelocationModel() == Reloc::Static) {
397       O << *GetExternalSymbolSymbol(MO.getSymbolName());
398       return;
399     }
400
401     const MCSymbol *NLPSym = 
402       OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
403                                    MO.getSymbolName()+"$non_lazy_ptr");
404     const MCSymbol *&StubSym = 
405       MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
406     if (StubSym == 0)
407       StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
408     
409     O << *NLPSym;
410     return;
411   }
412   case MachineOperand::MO_GlobalAddress: {
413     // Computing the address of a global symbol, not calling it.
414     GlobalValue *GV = MO.getGlobal();
415     MCSymbol *SymToPrint;
416
417     // External or weakly linked global variables need non-lazily-resolved stubs
418     if (TM.getRelocationModel() != Reloc::Static &&
419         (GV->isDeclaration() || GV->isWeakForLinker())) {
420       if (!GV->hasHiddenVisibility()) {
421         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
422         const MCSymbol *&StubSym = 
423        MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(SymToPrint);
424         if (StubSym == 0)
425           StubSym = GetGlobalValueSymbol(GV);
426       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
427                  GV->hasAvailableExternallyLinkage()) {
428         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
429         
430         const MCSymbol *&StubSym = 
431           MMI->getObjFileInfo<MachineModuleInfoMachO>().
432                     getHiddenGVStubEntry(SymToPrint);
433         if (StubSym == 0)
434           StubSym = GetGlobalValueSymbol(GV);
435       } else {
436         SymToPrint = GetGlobalValueSymbol(GV);
437       }
438     } else {
439       SymToPrint = GetGlobalValueSymbol(GV);
440     }
441     
442     O << *SymToPrint;
443
444     printOffset(MO.getOffset());
445     return;
446   }
447
448   default:
449     O << "<unknown operand type: " << MO.getType() << ">";
450     return;
451   }
452 }
453
454 /// PrintAsmOperand - Print out an operand for an inline asm expression.
455 ///
456 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
457                                     unsigned AsmVariant,
458                                     const char *ExtraCode) {
459   // Does this asm operand have a single letter operand modifier?
460   if (ExtraCode && ExtraCode[0]) {
461     if (ExtraCode[1] != 0) return true; // Unknown modifier.
462
463     switch (ExtraCode[0]) {
464     default: return true;  // Unknown modifier.
465     case 'c': // Don't print "$" before a global var name or constant.
466       // PPC never has a prefix.
467       printOperand(MI, OpNo);
468       return false;
469     case 'L': // Write second word of DImode reference.
470       // Verify that this operand has two consecutive registers.
471       if (!MI->getOperand(OpNo).isReg() ||
472           OpNo+1 == MI->getNumOperands() ||
473           !MI->getOperand(OpNo+1).isReg())
474         return true;
475       ++OpNo;   // Return the high-part.
476       break;
477     case 'I':
478       // Write 'i' if an integer constant, otherwise nothing.  Used to print
479       // addi vs add, etc.
480       if (MI->getOperand(OpNo).isImm())
481         O << "i";
482       return false;
483     }
484   }
485
486   printOperand(MI, OpNo);
487   return false;
488 }
489
490 // At the moment, all inline asm memory operands are a single register.
491 // In any case, the output of this routine should always be just one
492 // assembler operand.
493
494 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
495                                           unsigned AsmVariant,
496                                           const char *ExtraCode) {
497   if (ExtraCode && ExtraCode[0])
498     return true; // Unknown modifier.
499   assert (MI->getOperand(OpNo).isReg());
500   O << "0(";
501   printOperand(MI, OpNo);
502   O << ")";
503   return false;
504 }
505
506 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
507                                           const char *Modifier) {
508   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
509   unsigned Code = MI->getOperand(OpNo).getImm();
510   if (!strcmp(Modifier, "cc")) {
511     switch ((PPC::Predicate)Code) {
512     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
513     case PPC::PRED_LT: O << "lt"; return;
514     case PPC::PRED_LE: O << "le"; return;
515     case PPC::PRED_EQ: O << "eq"; return;
516     case PPC::PRED_GE: O << "ge"; return;
517     case PPC::PRED_GT: O << "gt"; return;
518     case PPC::PRED_NE: O << "ne"; return;
519     case PPC::PRED_UN: O << "un"; return;
520     case PPC::PRED_NU: O << "nu"; return;
521     }
522
523   } else {
524     assert(!strcmp(Modifier, "reg") &&
525            "Need to specify 'cc' or 'reg' as predicate op modifier!");
526     // Don't print the register for 'always'.
527     if (Code == PPC::PRED_ALWAYS) return;
528     printOperand(MI, OpNo+1);
529   }
530 }
531
532
533 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
534 /// the current output stream.
535 ///
536 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
537   // Check for slwi/srwi mnemonics.
538   if (MI->getOpcode() == PPC::RLWINM) {
539     unsigned char SH = MI->getOperand(2).getImm();
540     unsigned char MB = MI->getOperand(3).getImm();
541     unsigned char ME = MI->getOperand(4).getImm();
542     bool useSubstituteMnemonic = false;
543     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
544       O << "\tslwi "; useSubstituteMnemonic = true;
545     }
546     if (SH <= 31 && MB == (32-SH) && ME == 31) {
547       O << "\tsrwi "; useSubstituteMnemonic = true;
548       SH = 32-SH;
549     }
550     if (useSubstituteMnemonic) {
551       printOperand(MI, 0);
552       O << ", ";
553       printOperand(MI, 1);
554       O << ", " << (unsigned int)SH;
555       return;
556     }
557   }
558   
559   if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
560       MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
561     O << "\tmr ";
562     printOperand(MI, 0);
563     O << ", ";
564     printOperand(MI, 1);
565     return;
566   }
567   
568   if (MI->getOpcode() == PPC::RLDICR) {
569     unsigned char SH = MI->getOperand(2).getImm();
570     unsigned char ME = MI->getOperand(3).getImm();
571     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
572     if (63-SH == ME) {
573       O << "\tsldi ";
574       printOperand(MI, 0);
575       O << ", ";
576       printOperand(MI, 1);
577       O << ", " << (unsigned int)SH;
578       return;
579     }
580   }
581
582   printInstruction(MI);
583 }
584
585 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
586   if (!Subtarget.isPPC64())  // linux/ppc32 - Normal entry label.
587     return AsmPrinter::EmitFunctionEntryLabel();
588     
589   // Emit an official procedure descriptor.
590   // FIXME 64-bit SVR4: Use MCSection here!
591   O << "\t.section\t\".opd\",\"aw\"\n";
592   O << "\t.align 3\n";
593   OutStreamer.EmitLabel(CurrentFnSym);
594   O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
595   O << "\t.previous\n";
596   O << ".L." << *CurrentFnSym << ":\n";
597 }
598
599
600 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
601   const TargetData *TD = TM.getTargetData();
602
603   bool isPPC64 = TD->getPointerSizeInBits() == 64;
604
605   if (isPPC64 && !TOC.empty()) {
606     // FIXME 64-bit SVR4: Use MCSection here?
607     O << "\t.section\t\".toc\",\"aw\"\n";
608
609     // FIXME: This is nondeterminstic!
610     for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
611          E = TOC.end(); I != E; ++I) {
612       O << *I->second << ":\n";
613       O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
614     }
615   }
616
617   return AsmPrinter::doFinalization(M);
618 }
619
620 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
621   static const char *const CPUDirectives[] = {
622     "",
623     "ppc",
624     "ppc601",
625     "ppc602",
626     "ppc603",
627     "ppc7400",
628     "ppc750",
629     "ppc970",
630     "ppc64"
631   };
632
633   unsigned Directive = Subtarget.getDarwinDirective();
634   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
635     Directive = PPC::DIR_970;
636   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
637     Directive = PPC::DIR_7400;
638   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
639     Directive = PPC::DIR_64;
640   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
641   O << "\t.machine " << CPUDirectives[Directive] << '\n';
642
643   // Prime text sections so they are adjacent.  This reduces the likelihood a
644   // large data or debug section causes a branch to exceed 16M limit.
645   TargetLoweringObjectFileMachO &TLOFMacho = 
646     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
647   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
648   if (TM.getRelocationModel() == Reloc::PIC_) {
649     OutStreamer.SwitchSection(
650             TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
651                                       MCSectionMachO::S_SYMBOL_STUBS |
652                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
653                                       32, SectionKind::getText()));
654   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
655     OutStreamer.SwitchSection(
656             TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
657                                       MCSectionMachO::S_SYMBOL_STUBS |
658                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
659                                       16, SectionKind::getText()));
660   }
661   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
662 }
663
664 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
665   // Remove $stub suffix, add $lazy_ptr.
666   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
667   TmpStr += "$lazy_ptr";
668   return Ctx.GetOrCreateSymbol(TmpStr.str());
669 }
670
671 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
672   // Add $tmp suffix to $stub, yielding $stub$tmp.
673   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
674   TmpStr += "$tmp";
675   return Ctx.GetOrCreateSymbol(TmpStr.str());
676 }
677
678 void PPCDarwinAsmPrinter::
679 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
680   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
681   
682   TargetLoweringObjectFileMachO &TLOFMacho = 
683     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
684
685   // .lazy_symbol_pointer
686   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
687   
688   // Output stubs for dynamically-linked functions
689   if (TM.getRelocationModel() == Reloc::PIC_) {
690     const MCSection *StubSection = 
691     TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
692                               MCSectionMachO::S_SYMBOL_STUBS |
693                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
694                               32, SectionKind::getText());
695     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
696       OutStreamer.SwitchSection(StubSection);
697       EmitAlignment(4);
698       
699       const MCSymbol *Stub = Stubs[i].first;
700       const MCSymbol *RawSym = Stubs[i].second;
701       const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
702       const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
703                                            
704       O << *Stub << ":\n";
705       O << "\t.indirect_symbol " << *RawSym << '\n';
706       O << "\tmflr r0\n";
707       O << "\tbcl 20,31," << *AnonSymbol << '\n';
708       O << *AnonSymbol << ":\n";
709       O << "\tmflr r11\n";
710       O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
711       << ")\n";
712       O << "\tmtlr r0\n";
713       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
714       << '-' << *AnonSymbol << ")(r11)\n";
715       O << "\tmtctr r12\n";
716       O << "\tbctr\n";
717       
718       OutStreamer.SwitchSection(LSPSection);
719       O << *LazyPtr << ":\n";
720       O << "\t.indirect_symbol " << *RawSym << '\n';
721       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
722     }
723     O << '\n';
724     return;
725   }
726   
727   const MCSection *StubSection =
728     TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
729                               MCSectionMachO::S_SYMBOL_STUBS |
730                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
731                               16, SectionKind::getText());
732   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
733     const MCSymbol *Stub = Stubs[i].first;
734     const MCSymbol *RawSym = Stubs[i].second;
735     const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
736
737     OutStreamer.SwitchSection(StubSection);
738     EmitAlignment(4);
739     O << *Stub << ":\n";
740     O << "\t.indirect_symbol " << *RawSym << '\n';
741     O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
742     O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(" << *LazyPtr
743     << ")(r11)\n";
744     O << "\tmtctr r12\n";
745     O << "\tbctr\n";
746     OutStreamer.SwitchSection(LSPSection);
747     O << *LazyPtr << ":\n";
748     O << "\t.indirect_symbol " << *RawSym << '\n';
749     O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
750   }
751   
752   O << '\n';
753 }
754
755
756 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
757   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
758
759   // Darwin/PPC always uses mach-o.
760   TargetLoweringObjectFileMachO &TLOFMacho = 
761     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
762   MachineModuleInfoMachO &MMIMacho =
763     MMI->getObjFileInfo<MachineModuleInfoMachO>();
764   
765   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
766   if (!Stubs.empty())
767     EmitFunctionStubs(Stubs);
768
769   if (MAI->doesSupportExceptionHandling() && MMI) {
770     // Add the (possibly multiple) personalities to the set of global values.
771     // Only referenced functions get into the Personalities list.
772     const std::vector<Function *> &Personalities = MMI->getPersonalities();
773     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
774          E = Personalities.end(); I != E; ++I) {
775       if (*I) {
776         const MCSymbol *NLPSym = 
777           GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
778         const MCSymbol *&StubSym = MMIMacho.getGVStubEntry(NLPSym);
779         StubSym = GetGlobalValueSymbol(*I);
780       }
781     }
782   }
783
784   // Output stubs for dynamically-linked functions.
785   Stubs = MMIMacho.GetGVStubList();
786   
787   // Output macho stubs for external and common global variables.
788   if (!Stubs.empty()) {
789     // Switch with ".non_lazy_symbol_pointer" directive.
790     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
791     EmitAlignment(isPPC64 ? 3 : 2);
792     
793     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
794       O << *Stubs[i].first << ":\n";
795       O << "\t.indirect_symbol " << *Stubs[i].second << '\n';
796       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
797     }
798   }
799
800   Stubs = MMIMacho.GetHiddenGVStubList();
801   if (!Stubs.empty()) {
802     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
803     EmitAlignment(isPPC64 ? 3 : 2);
804     
805     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
806       O << *Stubs[i].first << ":\n";
807       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *Stubs[i].second << '\n';
808     }
809   }
810
811   // Funny Darwin hack: This flag tells the linker that no global symbols
812   // contain code that falls through to other global symbols (e.g. the obvious
813   // implementation of multiple entry points).  If this doesn't occur, the
814   // linker can safely perform dead code stripping.  Since LLVM never generates
815   // code that does this, it is always safe to set.
816   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
817
818   return AsmPrinter::doFinalization(M);
819 }
820
821
822
823 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
824 /// for a MachineFunction to the given output stream, in a format that the
825 /// Darwin assembler can deal with.
826 ///
827 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
828                                            TargetMachine &tm,
829                                            const MCAsmInfo *tai,
830                                            bool verbose) {
831   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
832
833   if (Subtarget->isDarwin())
834     return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
835   return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
836 }
837
838 // Force static initialization.
839 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
840   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
841   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
842 }