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