Rename Mangler linkage enums to something less gross.
[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/MDNode.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.h"
30 #include "llvm/CodeGen/DwarfWriter.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Target/TargetAsmInfo.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegistry.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/ADT/StringSet.h"
50 using namespace llvm;
51
52 STATISTIC(EmittedInsts, "Number of machine instrs printed");
53
54 namespace {
55   class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
56   protected:
57     struct FnStubInfo {
58       std::string Stub, LazyPtr, AnonSymbol;
59       
60       FnStubInfo() {}
61       
62       void Init(const GlobalValue *GV, Mangler *Mang) {
63         // Already initialized.
64         if (!Stub.empty()) return;
65         Stub = Mang->getMangledName(GV, "$stub", true);
66         LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
67         AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
68       }
69
70       void Init(const std::string &GV, Mangler *Mang) {
71         // Already initialized.
72         if (!Stub.empty()) return;
73         Stub = Mang->makeNameProper(GV + "$stub",
74                                     Mangler::Private);
75         LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
76                                        Mangler::Private);
77         AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
78                                           Mangler::Private);
79       }
80     };
81     
82     StringMap<FnStubInfo> FnStubs;
83     StringMap<std::string> GVStubs, HiddenGVStubs;
84     const PPCSubtarget &Subtarget;
85   public:
86     explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
87                            const TargetAsmInfo *T, bool V)
88       : AsmPrinter(O, TM, T, V),
89         Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
90
91     virtual const char *getPassName() const {
92       return "PowerPC Assembly Printer";
93     }
94
95     PPCTargetMachine &getTM() {
96       return static_cast<PPCTargetMachine&>(TM);
97     }
98
99     unsigned enumRegToMachineReg(unsigned enumReg) {
100       switch (enumReg) {
101       default: llvm_unreachable("Unhandled register!");
102       case PPC::CR0:  return  0;
103       case PPC::CR1:  return  1;
104       case PPC::CR2:  return  2;
105       case PPC::CR3:  return  3;
106       case PPC::CR4:  return  4;
107       case PPC::CR5:  return  5;
108       case PPC::CR6:  return  6;
109       case PPC::CR7:  return  7;
110       }
111       llvm_unreachable(0);
112     }
113
114     /// printInstruction - This method is automatically generated by tablegen
115     /// from the instruction set description.  This method returns true if the
116     /// machine instruction was sufficiently described to print it, otherwise it
117     /// returns false.
118     bool printInstruction(const MachineInstr *MI);
119
120     void printMachineInstruction(const MachineInstr *MI);
121     void printOp(const MachineOperand &MO);
122
123     /// stripRegisterPrefix - This method strips the character prefix from a
124     /// register name so that only the number is left.  Used by for linux asm.
125     const char *stripRegisterPrefix(const char *RegName) {
126       switch (RegName[0]) {
127       case 'r':
128       case 'f':
129       case 'v': return RegName + 1;
130       case 'c': if (RegName[1] == 'r') return RegName + 2;
131       }
132
133       return RegName;
134     }
135
136     /// printRegister - Print register according to target requirements.
137     ///
138     void printRegister(const MachineOperand &MO, bool R0AsZero) {
139       unsigned RegNo = MO.getReg();
140       assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
141
142       // If we should use 0 for R0.
143       if (R0AsZero && RegNo == PPC::R0) {
144         O << "0";
145         return;
146       }
147
148       const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
149       // Linux assembler (Others?) does not take register mnemonics.
150       // FIXME - What about special registers used in mfspr/mtspr?
151       if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
152       O << RegName;
153     }
154
155     void printOperand(const MachineInstr *MI, unsigned OpNo) {
156       const MachineOperand &MO = MI->getOperand(OpNo);
157       if (MO.isReg()) {
158         printRegister(MO, false);
159       } else if (MO.isImm()) {
160         O << MO.getImm();
161       } else {
162         printOp(MO);
163       }
164     }
165
166     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
167                          unsigned AsmVariant, const char *ExtraCode);
168     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
169                                unsigned AsmVariant, const char *ExtraCode);
170
171
172     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
173       char value = MI->getOperand(OpNo).getImm();
174       value = (value << (32-5)) >> (32-5);
175       O << (int)value;
176     }
177     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
178       unsigned char value = MI->getOperand(OpNo).getImm();
179       assert(value <= 31 && "Invalid u5imm argument!");
180       O << (unsigned int)value;
181     }
182     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
183       unsigned char value = MI->getOperand(OpNo).getImm();
184       assert(value <= 63 && "Invalid u6imm argument!");
185       O << (unsigned int)value;
186     }
187     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
188       O << (short)MI->getOperand(OpNo).getImm();
189     }
190     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
191       O << (unsigned short)MI->getOperand(OpNo).getImm();
192     }
193     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
194       if (MI->getOperand(OpNo).isImm()) {
195         O << (short)(MI->getOperand(OpNo).getImm()*4);
196       } else {
197         O << "lo16(";
198         printOp(MI->getOperand(OpNo));
199         if (TM.getRelocationModel() == Reloc::PIC_)
200           O << "-\"L" << getFunctionNumber() << "$pb\")";
201         else
202           O << ')';
203       }
204     }
205     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
206       // Branches can take an immediate operand.  This is used by the branch
207       // selection pass to print $+8, an eight byte displacement from the PC.
208       if (MI->getOperand(OpNo).isImm()) {
209         O << "$+" << MI->getOperand(OpNo).getImm()*4;
210       } else {
211         printOp(MI->getOperand(OpNo));
212       }
213     }
214     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
215       const MachineOperand &MO = MI->getOperand(OpNo);
216       if (TM.getRelocationModel() != Reloc::Static) {
217         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
218           GlobalValue *GV = MO.getGlobal();
219           if (GV->isDeclaration() || GV->isWeakForLinker()) {
220             // Dynamically-resolved functions need a stub for the function.
221             FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
222             FnInfo.Init(GV, Mang);
223             O << FnInfo.Stub;
224             return;
225           }
226         }
227         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
228           FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
229           FnInfo.Init(MO.getSymbolName(), Mang);
230           O << FnInfo.Stub;
231           return;
232         }
233       }
234
235       printOp(MI->getOperand(OpNo));
236     }
237     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
238      O << (int)MI->getOperand(OpNo).getImm()*4;
239     }
240     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
241       O << "\"L" << getFunctionNumber() << "$pb\"\n";
242       O << "\"L" << getFunctionNumber() << "$pb\":";
243     }
244     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
245       if (MI->getOperand(OpNo).isImm()) {
246         printS16ImmOperand(MI, OpNo);
247       } else {
248         if (Subtarget.isDarwin()) O << "ha16(";
249         printOp(MI->getOperand(OpNo));
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) {
259       if (MI->getOperand(OpNo).isImm()) {
260         printS16ImmOperand(MI, OpNo);
261       } else {
262         if (Subtarget.isDarwin()) O << "lo16(";
263         printOp(MI->getOperand(OpNo));
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) {
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) {
279       printSymbolLo(MI, OpNo);
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);
286       O << ')';
287     }
288     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
289       if (MI->getOperand(OpNo).isImm())
290         printS16X4ImmOperand(MI, OpNo);
291       else
292         printSymbolLo(MI, OpNo);
293       O << '(';
294       if (MI->getOperand(OpNo+1).isReg() &&
295           MI->getOperand(OpNo+1).getReg() == PPC::R0)
296         O << "0";
297       else
298         printOperand(MI, OpNo+1);
299       O << ')';
300     }
301
302     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
303       // When used as the base register, r0 reads constant zero rather than
304       // the value contained in the register.  For this reason, the darwin
305       // assembler requires that we print r0 as 0 (no r) when used as the base.
306       const MachineOperand &MO = MI->getOperand(OpNo);
307       printRegister(MO, true);
308       O << ", ";
309       printOperand(MI, OpNo+1);
310     }
311
312     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
313                                const char *Modifier);
314
315     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
316     virtual bool doFinalization(Module &M) = 0;
317
318     virtual void EmitExternalGlobal(const GlobalVariable *GV);
319   };
320
321   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
322   class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
323   public:
324     explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
325                                 const TargetAsmInfo *T, bool V)
326       : PPCAsmPrinter(O, TM, T, V){}
327
328     virtual const char *getPassName() const {
329       return "Linux PPC Assembly Printer";
330     }
331
332     bool runOnMachineFunction(MachineFunction &F);
333     bool doFinalization(Module &M);
334
335     void getAnalysisUsage(AnalysisUsage &AU) const {
336       AU.setPreservesAll();
337       AU.addRequired<MachineModuleInfo>();
338       AU.addRequired<DwarfWriter>();
339       PPCAsmPrinter::getAnalysisUsage(AU);
340     }
341
342     void printModuleLevelGV(const GlobalVariable* GVar);
343   };
344
345   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
346   /// OS X
347   class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
348     formatted_raw_ostream &OS;
349   public:
350     explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
351                                  const TargetAsmInfo *T, bool V)
352       : PPCAsmPrinter(O, TM, T, V), OS(O) {}
353
354     virtual const char *getPassName() const {
355       return "Darwin PPC Assembly Printer";
356     }
357
358     bool runOnMachineFunction(MachineFunction &F);
359     bool doInitialization(Module &M);
360     bool doFinalization(Module &M);
361
362     void getAnalysisUsage(AnalysisUsage &AU) const {
363       AU.setPreservesAll();
364       AU.addRequired<MachineModuleInfo>();
365       AU.addRequired<DwarfWriter>();
366       PPCAsmPrinter::getAnalysisUsage(AU);
367     }
368
369     void printModuleLevelGV(const GlobalVariable* GVar);
370   };
371 } // end of anonymous namespace
372
373 // Include the auto-generated portion of the assembly writer
374 #include "PPCGenAsmWriter.inc"
375
376 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
377   switch (MO.getType()) {
378   case MachineOperand::MO_Immediate:
379     llvm_unreachable("printOp() does not handle immediate values");
380
381   case MachineOperand::MO_MachineBasicBlock:
382     printBasicBlockLabel(MO.getMBB());
383     return;
384   case MachineOperand::MO_JumpTableIndex:
385     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
386       << '_' << MO.getIndex();
387     // FIXME: PIC relocation model
388     return;
389   case MachineOperand::MO_ConstantPoolIndex:
390     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
391       << '_' << MO.getIndex();
392     return;
393   case MachineOperand::MO_ExternalSymbol: {
394     // Computing the address of an external symbol, not calling it.
395     std::string Name(TAI->getGlobalPrefix());
396     Name += MO.getSymbolName();
397     
398     if (TM.getRelocationModel() != Reloc::Static) {
399       GVStubs[Name] = Name+"$non_lazy_ptr";
400       Name += "$non_lazy_ptr";
401     }
402     O << Name;
403     return;
404   }
405   case MachineOperand::MO_GlobalAddress: {
406     // Computing the address of a global symbol, not calling it.
407     GlobalValue *GV = MO.getGlobal();
408     std::string Name;
409
410     // External or weakly linked global variables need non-lazily-resolved stubs
411     if (TM.getRelocationModel() != Reloc::Static &&
412         (GV->isDeclaration() || GV->isWeakForLinker())) {
413       if (!GV->hasHiddenVisibility()) {
414         Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
415         GVStubs[Mang->getMangledName(GV)] = Name;
416       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
417                  GV->hasAvailableExternallyLinkage()) {
418         Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
419         HiddenGVStubs[Mang->getMangledName(GV)] = Name;
420       } else {
421         Name = Mang->getMangledName(GV);
422       }
423     } else {
424       Name = Mang->getMangledName(GV);
425     }
426     O << Name;
427
428     printOffset(MO.getOffset());
429     return;
430   }
431
432   default:
433     O << "<unknown operand type: " << MO.getType() << ">";
434     return;
435   }
436 }
437
438 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
439 ///
440 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
441   std::string Name;
442   
443   if (TM.getRelocationModel() != Reloc::Static) {
444     Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
445   } else {
446     Name = Mang->getMangledName(GV);
447   }
448   O << Name;
449 }
450
451 /// PrintAsmOperand - Print out an operand for an inline asm expression.
452 ///
453 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
454                                     unsigned AsmVariant,
455                                     const char *ExtraCode) {
456   // Does this asm operand have a single letter operand modifier?
457   if (ExtraCode && ExtraCode[0]) {
458     if (ExtraCode[1] != 0) return true; // Unknown modifier.
459
460     switch (ExtraCode[0]) {
461     default: return true;  // Unknown modifier.
462     case 'c': // Don't print "$" before a global var name or constant.
463       // PPC never has a prefix.
464       printOperand(MI, OpNo);
465       return false;
466     case 'L': // Write second word of DImode reference.
467       // Verify that this operand has two consecutive registers.
468       if (!MI->getOperand(OpNo).isReg() ||
469           OpNo+1 == MI->getNumOperands() ||
470           !MI->getOperand(OpNo+1).isReg())
471         return true;
472       ++OpNo;   // Return the high-part.
473       break;
474     case 'I':
475       // Write 'i' if an integer constant, otherwise nothing.  Used to print
476       // addi vs add, etc.
477       if (MI->getOperand(OpNo).isImm())
478         O << "i";
479       return false;
480     }
481   }
482
483   printOperand(MI, OpNo);
484   return false;
485 }
486
487 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
488                                           unsigned AsmVariant,
489                                           const char *ExtraCode) {
490   if (ExtraCode && ExtraCode[0])
491     return true; // Unknown modifier.
492   if (MI->getOperand(OpNo).isReg())
493     printMemRegReg(MI, OpNo);
494   else
495     printMemRegImm(MI, OpNo);
496   return false;
497 }
498
499 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
500                                           const char *Modifier) {
501   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
502   unsigned Code = MI->getOperand(OpNo).getImm();
503   if (!strcmp(Modifier, "cc")) {
504     switch ((PPC::Predicate)Code) {
505     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
506     case PPC::PRED_LT: O << "lt"; return;
507     case PPC::PRED_LE: O << "le"; return;
508     case PPC::PRED_EQ: O << "eq"; return;
509     case PPC::PRED_GE: O << "ge"; return;
510     case PPC::PRED_GT: O << "gt"; return;
511     case PPC::PRED_NE: O << "ne"; return;
512     case PPC::PRED_UN: O << "un"; return;
513     case PPC::PRED_NU: O << "nu"; return;
514     }
515
516   } else {
517     assert(!strcmp(Modifier, "reg") &&
518            "Need to specify 'cc' or 'reg' as predicate op modifier!");
519     // Don't print the register for 'always'.
520     if (Code == PPC::PRED_ALWAYS) return;
521     printOperand(MI, OpNo+1);
522   }
523 }
524
525
526 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
527 /// the current output stream.
528 ///
529 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
530   ++EmittedInsts;
531
532   // Check for slwi/srwi mnemonics.
533   if (MI->getOpcode() == PPC::RLWINM) {
534     bool FoundMnemonic = false;
535     unsigned char SH = MI->getOperand(2).getImm();
536     unsigned char MB = MI->getOperand(3).getImm();
537     unsigned char ME = MI->getOperand(4).getImm();
538     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
539       O << "\tslwi "; FoundMnemonic = true;
540     }
541     if (SH <= 31 && MB == (32-SH) && ME == 31) {
542       O << "\tsrwi "; FoundMnemonic = true;
543       SH = 32-SH;
544     }
545     if (FoundMnemonic) {
546       printOperand(MI, 0);
547       O << ", ";
548       printOperand(MI, 1);
549       O << ", " << (unsigned int)SH << '\n';
550       return;
551     }
552   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
553     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
554       O << "\tmr ";
555       printOperand(MI, 0);
556       O << ", ";
557       printOperand(MI, 1);
558       O << '\n';
559       return;
560     }
561   } else if (MI->getOpcode() == PPC::RLDICR) {
562     unsigned char SH = MI->getOperand(2).getImm();
563     unsigned char ME = MI->getOperand(3).getImm();
564     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
565     if (63-SH == ME) {
566       O << "\tsldi ";
567       printOperand(MI, 0);
568       O << ", ";
569       printOperand(MI, 1);
570       O << ", " << (unsigned int)SH << '\n';
571       return;
572     }
573   }
574
575   if (printInstruction(MI))
576     return; // Printer was automatically generated
577
578   llvm_unreachable("Unhandled instruction in asm writer!");
579 }
580
581 /// runOnMachineFunction - This uses the printMachineInstruction()
582 /// method to print assembly for each instruction.
583 ///
584 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
585   this->MF = &MF;
586
587   SetupMachineFunction(MF);
588   O << "\n\n";
589
590   // Print out constants referenced by the function
591   EmitConstantPool(MF.getConstantPool());
592
593   // Print out labels for the function.
594   const Function *F = MF.getFunction();
595   SwitchToSection(TAI->SectionForGlobal(F));
596
597   switch (F->getLinkage()) {
598   default: llvm_unreachable("Unknown linkage type!");
599   case Function::PrivateLinkage:
600   case Function::LinkerPrivateLinkage:
601   case Function::InternalLinkage:  // Symbols default to internal.
602     break;
603   case Function::ExternalLinkage:
604     O << "\t.global\t" << CurrentFnName << '\n'
605       << "\t.type\t" << CurrentFnName << ", @function\n";
606     break;
607   case Function::WeakAnyLinkage:
608   case Function::WeakODRLinkage:
609   case Function::LinkOnceAnyLinkage:
610   case Function::LinkOnceODRLinkage:
611     O << "\t.global\t" << CurrentFnName << '\n';
612     O << "\t.weak\t" << CurrentFnName << '\n';
613     break;
614   }
615
616   printVisibility(CurrentFnName, F->getVisibility());
617
618   EmitAlignment(MF.getAlignment(), F);
619   O << CurrentFnName << ":\n";
620
621   // Emit pre-function debug information.
622   DW->BeginFunction(&MF);
623
624   // Print out code for the function.
625   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
626        I != E; ++I) {
627     // Print a label for the basic block.
628     if (I != MF.begin()) {
629       printBasicBlockLabel(I, true, true);
630       O << '\n';
631     }
632     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
633          II != E; ++II) {
634       // Print the assembly for the instruction.
635       printMachineInstruction(II);
636     }
637   }
638
639   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
640
641   // Print out jump tables referenced by the function.
642   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
643
644   SwitchToSection(TAI->SectionForGlobal(F));
645
646   // Emit post-function debug information.
647   DW->EndFunction(&MF);
648
649   O.flush();
650
651   // We didn't modify anything.
652   return false;
653 }
654
655 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
656 /// Don't print things like \\n or \\0.
657 static void PrintUnmangledNameSafely(const Value *V, formatted_raw_ostream &OS) {
658   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
659        Name != E; ++Name)
660     if (isprint(*Name))
661       OS << *Name;
662 }
663
664 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
665   const TargetData *TD = TM.getTargetData();
666
667   if (!GVar->hasInitializer())
668     return;   // External global require no code
669
670   // Check to see if this is a special global used by LLVM, if so, emit it.
671   if (EmitSpecialLLVMGlobal(GVar))
672     return;
673
674   std::string name = Mang->getMangledName(GVar);
675
676   printVisibility(name, GVar->getVisibility());
677
678   Constant *C = GVar->getInitializer();
679   if (isa<MDNode>(C) || isa<MDString>(C))
680     return;
681   const Type *Type = C->getType();
682   unsigned Size = TD->getTypeAllocSize(Type);
683   unsigned Align = TD->getPreferredAlignmentLog(GVar);
684
685   SwitchToSection(TAI->SectionForGlobal(GVar));
686
687   if (C->isNullValue() && /* FIXME: Verify correct */
688       !GVar->hasSection() &&
689       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
690        GVar->isWeakForLinker())) {
691       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
692
693       if (GVar->hasExternalLinkage()) {
694         O << "\t.global " << name << '\n';
695         O << "\t.type " << name << ", @object\n";
696         O << name << ":\n";
697         O << "\t.zero " << Size << '\n';
698       } else if (GVar->hasLocalLinkage()) {
699         O << TAI->getLCOMMDirective() << name << ',' << Size;
700       } else {
701         O << ".comm " << name << ',' << Size;
702       }
703       if (VerboseAsm) {
704         O << "\t\t" << TAI->getCommentString() << " '";
705         PrintUnmangledNameSafely(GVar, O);
706         O << "'";
707       }
708       O << '\n';
709       return;
710   }
711
712   switch (GVar->getLinkage()) {
713    case GlobalValue::LinkOnceAnyLinkage:
714    case GlobalValue::LinkOnceODRLinkage:
715    case GlobalValue::WeakAnyLinkage:
716    case GlobalValue::WeakODRLinkage:
717    case GlobalValue::CommonLinkage:
718     O << "\t.global " << name << '\n'
719       << "\t.type " << name << ", @object\n"
720       << "\t.weak " << name << '\n';
721     break;
722    case GlobalValue::AppendingLinkage:
723     // FIXME: appending linkage variables should go into a section of
724     // their name or something.  For now, just emit them as external.
725    case GlobalValue::ExternalLinkage:
726     // If external or appending, declare as a global symbol
727     O << "\t.global " << name << '\n'
728       << "\t.type " << name << ", @object\n";
729     // FALL THROUGH
730    case GlobalValue::InternalLinkage:
731    case GlobalValue::PrivateLinkage:
732    case GlobalValue::LinkerPrivateLinkage:
733     break;
734    default:
735     llvm_unreachable("Unknown linkage type!");
736   }
737
738   EmitAlignment(Align, GVar);
739   O << name << ":";
740   if (VerboseAsm) {
741     O << "\t\t\t\t" << TAI->getCommentString() << " '";
742     PrintUnmangledNameSafely(GVar, O);
743     O << "'";
744   }
745   O << '\n';
746
747   EmitGlobalConstant(C);
748   O << '\n';
749 }
750
751 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
752   // Print out module-level global variables here.
753   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
754        I != E; ++I)
755     printModuleLevelGV(I);
756
757   return AsmPrinter::doFinalization(M);
758 }
759
760 /// runOnMachineFunction - This uses the printMachineInstruction()
761 /// method to print assembly for each instruction.
762 ///
763 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
764   this->MF = &MF;
765
766   SetupMachineFunction(MF);
767   O << "\n\n";
768
769   // Print out constants referenced by the function
770   EmitConstantPool(MF.getConstantPool());
771
772   // Print out labels for the function.
773   const Function *F = MF.getFunction();
774   SwitchToSection(TAI->SectionForGlobal(F));
775
776   switch (F->getLinkage()) {
777   default: llvm_unreachable("Unknown linkage type!");
778   case Function::PrivateLinkage:
779   case Function::LinkerPrivateLinkage:
780   case Function::InternalLinkage:  // Symbols default to internal.
781     break;
782   case Function::ExternalLinkage:
783     O << "\t.globl\t" << CurrentFnName << '\n';
784     break;
785   case Function::WeakAnyLinkage:
786   case Function::WeakODRLinkage:
787   case Function::LinkOnceAnyLinkage:
788   case Function::LinkOnceODRLinkage:
789     O << "\t.globl\t" << CurrentFnName << '\n';
790     O << "\t.weak_definition\t" << CurrentFnName << '\n';
791     break;
792   }
793
794   printVisibility(CurrentFnName, F->getVisibility());
795
796   EmitAlignment(MF.getAlignment(), F);
797   O << CurrentFnName << ":\n";
798
799   // Emit pre-function debug information.
800   DW->BeginFunction(&MF);
801
802   // If the function is empty, then we need to emit *something*. Otherwise, the
803   // function's label might be associated with something that it wasn't meant to
804   // be associated with. We emit a noop in this situation.
805   MachineFunction::iterator I = MF.begin();
806
807   if (++I == MF.end() && MF.front().empty())
808     O << "\tnop\n";
809
810   // Print out code for the function.
811   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
812        I != E; ++I) {
813     // Print a label for the basic block.
814     if (I != MF.begin()) {
815       printBasicBlockLabel(I, true, true, VerboseAsm);
816       O << '\n';
817     }
818     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
819          II != IE; ++II) {
820       // Print the assembly for the instruction.
821       printMachineInstruction(II);
822     }
823   }
824
825   // Print out jump tables referenced by the function.
826   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
827
828   // Emit post-function debug information.
829   DW->EndFunction(&MF);
830
831   // We didn't modify anything.
832   return false;
833 }
834
835
836 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
837   static const char *const CPUDirectives[] = {
838     "",
839     "ppc",
840     "ppc601",
841     "ppc602",
842     "ppc603",
843     "ppc7400",
844     "ppc750",
845     "ppc970",
846     "ppc64"
847   };
848
849   unsigned Directive = Subtarget.getDarwinDirective();
850   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
851     Directive = PPC::DIR_970;
852   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
853     Directive = PPC::DIR_7400;
854   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
855     Directive = PPC::DIR_64;
856   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
857   O << "\t.machine " << CPUDirectives[Directive] << '\n';
858
859   bool Result = AsmPrinter::doInitialization(M);
860   assert(MMI);
861
862   // Prime text sections so they are adjacent.  This reduces the likelihood a
863   // large data or debug section causes a branch to exceed 16M limit.
864   SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
865                       "pure_instructions");
866   if (TM.getRelocationModel() == Reloc::PIC_) {
867     SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
868                           "pure_instructions,32");
869   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
870     SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
871                         "pure_instructions,16");
872   }
873   SwitchToSection(TAI->getTextSection());
874
875   return Result;
876 }
877
878 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
879   const TargetData *TD = TM.getTargetData();
880
881   if (!GVar->hasInitializer())
882     return;   // External global require no code
883
884   // Check to see if this is a special global used by LLVM, if so, emit it.
885   if (EmitSpecialLLVMGlobal(GVar)) {
886     if (TM.getRelocationModel() == Reloc::Static) {
887       if (GVar->getName() == "llvm.global_ctors")
888         O << ".reference .constructors_used\n";
889       else if (GVar->getName() == "llvm.global_dtors")
890         O << ".reference .destructors_used\n";
891     }
892     return;
893   }
894
895   std::string name = Mang->getMangledName(GVar);
896   printVisibility(name, GVar->getVisibility());
897
898   Constant *C = GVar->getInitializer();
899   const Type *Type = C->getType();
900   unsigned Size = TD->getTypeAllocSize(Type);
901   unsigned Align = TD->getPreferredAlignmentLog(GVar);
902
903   SwitchToSection(TAI->SectionForGlobal(GVar));
904
905   if (C->isNullValue() && /* FIXME: Verify correct */
906       !GVar->hasSection() &&
907       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
908        GVar->isWeakForLinker()) &&
909       TAI->SectionKindForGlobal(GVar) != SectionKind::RODataMergeStr) {
910     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
911
912     if (GVar->hasExternalLinkage()) {
913       O << "\t.globl " << name << '\n';
914       O << "\t.zerofill __DATA, __common, " << name << ", "
915         << Size << ", " << Align;
916     } else if (GVar->hasLocalLinkage()) {
917       O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
918     } else if (!GVar->hasCommonLinkage()) {
919       O << "\t.globl " << name << '\n'
920         << TAI->getWeakDefDirective() << name << '\n';
921       EmitAlignment(Align, GVar);
922       O << name << ":";
923       if (VerboseAsm) {
924         O << "\t\t\t\t" << TAI->getCommentString() << " ";
925         PrintUnmangledNameSafely(GVar, O);
926       }
927       O << '\n';
928       EmitGlobalConstant(C);
929       return;
930     } else {
931       O << ".comm " << name << ',' << Size;
932       // Darwin 9 and above support aligned common data.
933       if (Subtarget.isDarwin9())
934         O << ',' << Align;
935     }
936     if (VerboseAsm) {
937       O << "\t\t" << TAI->getCommentString() << " '";
938       PrintUnmangledNameSafely(GVar, O);
939       O << "'";
940     }
941     O << '\n';
942     return;
943   }
944
945   switch (GVar->getLinkage()) {
946    case GlobalValue::LinkOnceAnyLinkage:
947    case GlobalValue::LinkOnceODRLinkage:
948    case GlobalValue::WeakAnyLinkage:
949    case GlobalValue::WeakODRLinkage:
950    case GlobalValue::CommonLinkage:
951     O << "\t.globl " << name << '\n'
952       << "\t.weak_definition " << name << '\n';
953     break;
954    case GlobalValue::AppendingLinkage:
955     // FIXME: appending linkage variables should go into a section of
956     // their name or something.  For now, just emit them as external.
957    case GlobalValue::ExternalLinkage:
958     // If external or appending, declare as a global symbol
959     O << "\t.globl " << name << '\n';
960     // FALL THROUGH
961    case GlobalValue::InternalLinkage:
962    case GlobalValue::PrivateLinkage:
963    case GlobalValue::LinkerPrivateLinkage:
964     break;
965    default:
966     llvm_unreachable("Unknown linkage type!");
967   }
968
969   EmitAlignment(Align, GVar);
970   O << name << ":";
971   if (VerboseAsm) {
972     O << "\t\t\t\t" << TAI->getCommentString() << " '";
973     PrintUnmangledNameSafely(GVar, O);
974     O << "'";
975   }
976   O << '\n';
977
978   EmitGlobalConstant(C);
979   O << '\n';
980 }
981
982 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
983   const TargetData *TD = TM.getTargetData();
984
985   // Print out module-level global variables here.
986   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
987        I != E; ++I)
988     printModuleLevelGV(I);
989
990   bool isPPC64 = TD->getPointerSizeInBits() == 64;
991
992   // Output stubs for dynamically-linked functions
993   if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
994     for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
995          I != E; ++I) {
996       SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
997                           "pure_instructions,32");
998       EmitAlignment(4);
999       const FnStubInfo &Info = I->second;
1000       O << Info.Stub << ":\n";
1001       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1002       O << "\tmflr r0\n";
1003       O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1004       O << Info.AnonSymbol << ":\n";
1005       O << "\tmflr r11\n";
1006       O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1007       O << ")\n";
1008       O << "\tmtlr r0\n";
1009       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1010       O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1011       O << "\tmtctr r12\n";
1012       O << "\tbctr\n";
1013       
1014       SwitchToDataSection(".lazy_symbol_pointer");
1015       O << Info.LazyPtr << ":\n";
1016       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1017       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1018     }
1019   } else if (!FnStubs.empty()) {
1020     for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1021          I != E; ++I) {
1022       SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1023                           "pure_instructions,16");
1024       EmitAlignment(4);
1025       const FnStubInfo &Info = I->second;
1026       O << Info.Stub << ":\n";
1027       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1028       O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1029       O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(";
1030       O << Info.LazyPtr << ")(r11)\n";
1031       O << "\tmtctr r12\n";
1032       O << "\tbctr\n";
1033       SwitchToDataSection(".lazy_symbol_pointer");
1034       O << Info.LazyPtr << ":\n";
1035       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1036       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1037     }
1038   }
1039
1040   O << '\n';
1041
1042   if (TAI->doesSupportExceptionHandling() && MMI) {
1043     // Add the (possibly multiple) personalities to the set of global values.
1044     // Only referenced functions get into the Personalities list.
1045     const std::vector<Function *> &Personalities = MMI->getPersonalities();
1046     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1047          E = Personalities.end(); I != E; ++I) {
1048       if (*I)
1049         GVStubs[Mang->getMangledName(*I)] =
1050           Mang->getMangledName(*I, "$non_lazy_ptr", true);
1051     }
1052   }
1053
1054   // Output stubs for external and common global variables.
1055   if (!GVStubs.empty()) {
1056     SwitchToDataSection(".non_lazy_symbol_pointer");
1057     for (StringMap<std::string>::iterator I = GVStubs.begin(),
1058          E = GVStubs.end(); I != E; ++I) {
1059       O << I->second << ":\n";
1060       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1061       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1062     }
1063   }
1064
1065   if (!HiddenGVStubs.empty()) {
1066     SwitchToSection(TAI->getDataSection());
1067     EmitAlignment(isPPC64 ? 3 : 2);
1068     for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1069          E = HiddenGVStubs.end(); I != E; ++I) {
1070       O << I->second << ":\n";
1071       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1072     }
1073   }
1074
1075   // Funny Darwin hack: This flag tells the linker that no global symbols
1076   // contain code that falls through to other global symbols (e.g. the obvious
1077   // implementation of multiple entry points).  If this doesn't occur, the
1078   // linker can safely perform dead code stripping.  Since LLVM never generates
1079   // code that does this, it is always safe to set.
1080   O << "\t.subsections_via_symbols\n";
1081
1082   return AsmPrinter::doFinalization(M);
1083 }
1084
1085
1086
1087 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1088 /// for a MachineFunction to the given output stream, in a format that the
1089 /// Darwin assembler can deal with.
1090 ///
1091 FunctionPass *llvm::createPPCAsmPrinterPass(formatted_raw_ostream &o,
1092                                             TargetMachine &tm,
1093                                             bool verbose) {
1094   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1095
1096   if (Subtarget->isDarwin()) {
1097     return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1098   } else {
1099     return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1100   }
1101 }
1102
1103 // Force static initialization.
1104 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
1105   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1106
1107   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1108 }