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