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