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