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