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