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