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