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