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