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