679c96534bfbe547cf8e6fe567861d1bfa1a615d
[oota-llvm.git] / lib / Target / PowerPC / PPCAsmPrinter.cpp
1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "PPCTargetMachine.h"
22 #include "PPCSubtarget.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/AsmPrinter.h"
28 #include "llvm/CodeGen/DwarfWriter.h"
29 #include "llvm/CodeGen/MachineDebugInfo.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Target/MRegisterInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include <iostream>
42 #include <set>
43 using namespace llvm;
44
45 namespace {
46   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
47
48   class PPCAsmPrinter : public AsmPrinter {
49   public:
50     std::set<std::string> FnStubs, GVStubs;
51     
52     PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
53       : AsmPrinter(O, TM) {}
54
55     virtual const char *getPassName() const {
56       return "PowerPC Assembly Printer";
57     }
58
59     PPCTargetMachine &getTM() {
60       return static_cast<PPCTargetMachine&>(TM);
61     }
62
63     unsigned enumRegToMachineReg(unsigned enumReg) {
64       switch (enumReg) {
65       default: assert(0 && "Unhandled register!"); break;
66       case PPC::CR0:  return  0;
67       case PPC::CR1:  return  1;
68       case PPC::CR2:  return  2;
69       case PPC::CR3:  return  3;
70       case PPC::CR4:  return  4;
71       case PPC::CR5:  return  5;
72       case PPC::CR6:  return  6;
73       case PPC::CR7:  return  7;
74       }
75       abort();
76     }
77
78     /// printInstruction - This method is automatically generated by tablegen
79     /// from the instruction set description.  This method returns true if the
80     /// machine instruction was sufficiently described to print it, otherwise it
81     /// returns false.
82     bool printInstruction(const MachineInstr *MI);
83
84     void printMachineInstruction(const MachineInstr *MI);
85     void printOp(const MachineOperand &MO);
86
87     void printOperand(const MachineInstr *MI, unsigned OpNo) {
88       const MachineOperand &MO = MI->getOperand(OpNo);
89       if (MO.isRegister()) {
90         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
91         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
92       } else if (MO.isImmediate()) {
93         O << MO.getImmedValue();
94       } else {
95         printOp(MO);
96       }
97     }
98     
99     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
100                          unsigned AsmVariant, const char *ExtraCode);
101     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
102                                unsigned AsmVariant, const char *ExtraCode);
103     
104     
105     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
106       char value = MI->getOperand(OpNo).getImmedValue();
107       value = (value << (32-5)) >> (32-5);
108       O << (int)value;
109     }
110     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
111       unsigned char value = MI->getOperand(OpNo).getImmedValue();
112       assert(value <= 31 && "Invalid u5imm argument!");
113       O << (unsigned int)value;
114     }
115     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
116       unsigned char value = MI->getOperand(OpNo).getImmedValue();
117       assert(value <= 63 && "Invalid u6imm argument!");
118       O << (unsigned int)value;
119     }
120     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
121       O << (short)MI->getOperand(OpNo).getImmedValue();
122     }
123     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
124       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
125     }
126     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
127       O << (short)MI->getOperand(OpNo).getImmedValue()*4;
128     }
129     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
130       // Branches can take an immediate operand.  This is used by the branch
131       // selection pass to print $+8, an eight byte displacement from the PC.
132       if (MI->getOperand(OpNo).isImmediate()) {
133         O << "$+" << MI->getOperand(OpNo).getImmedValue();
134       } else {
135         printOp(MI->getOperand(OpNo));
136       }
137     }
138     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
139       const MachineOperand &MO = MI->getOperand(OpNo);
140       if (TM.getRelocationModel() != Reloc::Static) {
141         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
142           GlobalValue *GV = MO.getGlobal();
143           if (((GV->isExternal() || GV->hasWeakLinkage() ||
144                 GV->hasLinkOnceLinkage()))) {
145             // Dynamically-resolved functions need a stub for the function.
146             std::string Name = Mang->getValueName(GV);
147             FnStubs.insert(Name);
148             O << "L" << Name << "$stub";
149             return;
150           }
151         }
152         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
153           std::string Name(GlobalPrefix); Name += MO.getSymbolName();
154           FnStubs.insert(Name);
155           O << "L" << Name << "$stub";
156           return;
157         }
158       }
159       
160       printOp(MI->getOperand(OpNo));
161     }
162     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
163      O << (int)MI->getOperand(OpNo).getImmedValue()*4;
164     }
165     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
166       O << "\"L" << getFunctionNumber() << "$pb\"\n";
167       O << "\"L" << getFunctionNumber() << "$pb\":";
168     }
169     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
170       if (MI->getOperand(OpNo).isImmediate()) {
171         printS16ImmOperand(MI, OpNo);
172       } else {
173         O << "ha16(";
174         printOp(MI->getOperand(OpNo));
175         if (TM.getRelocationModel() == Reloc::PIC)
176           O << "-\"L" << getFunctionNumber() << "$pb\")";
177         else
178           O << ')';
179       }
180     }
181     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
182       if (MI->getOperand(OpNo).isImmediate()) {
183         printS16ImmOperand(MI, OpNo);
184       } else {
185         O << "lo16(";
186         printOp(MI->getOperand(OpNo));
187         if (TM.getRelocationModel() == Reloc::PIC)
188           O << "-\"L" << getFunctionNumber() << "$pb\")";
189         else
190           O << ')';
191       }
192     }
193     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
194       unsigned CCReg = MI->getOperand(OpNo).getReg();
195       unsigned RegNo = enumRegToMachineReg(CCReg);
196       O << (0x80 >> RegNo);
197     }
198     // The new addressing mode printers.
199     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
200       printSymbolLo(MI, OpNo);
201       O << '(';
202       if (MI->getOperand(OpNo+1).isRegister() && 
203           MI->getOperand(OpNo+1).getReg() == PPC::R0)
204         O << "0";
205       else
206         printOperand(MI, OpNo+1);
207       O << ')';
208     }
209     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
210       if (MI->getOperand(OpNo).isImmediate())
211         printS16X4ImmOperand(MI, OpNo);
212       else 
213         printSymbolLo(MI, OpNo);
214       O << '(';
215       if (MI->getOperand(OpNo+1).isRegister() && 
216           MI->getOperand(OpNo+1).getReg() == PPC::R0)
217         O << "0";
218       else
219         printOperand(MI, OpNo+1);
220       O << ')';
221     }
222     
223     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
224       // When used as the base register, r0 reads constant zero rather than
225       // the value contained in the register.  For this reason, the darwin
226       // assembler requires that we print r0 as 0 (no r) when used as the base.
227       const MachineOperand &MO = MI->getOperand(OpNo);
228       if (MO.getReg() == PPC::R0)
229         O << '0';
230       else
231         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
232       O << ", ";
233       printOperand(MI, OpNo+1);
234     }
235     
236     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
237     virtual bool doFinalization(Module &M) = 0;
238     
239   };
240
241   /// DarwinDwarfWriter - Dwarf debug info writer customized for Darwin/Mac OS X
242   ///
243   struct DarwinDwarfWriter : public DwarfWriter {
244     // Ctor.
245     DarwinDwarfWriter(std::ostream &o, AsmPrinter *ap)
246     : DwarfWriter(o, ap)
247     {
248       needsSet = true;
249       DwarfAbbrevSection = ".section __DWARFA,__debug_abbrev";
250       DwarfInfoSection = ".section __DWARFA,__debug_info";
251       DwarfLineSection = ".section __DWARFA,__debug_line";
252       DwarfFrameSection = ".section __DWARFA,__debug_frame";
253       DwarfPubNamesSection = ".section __DWARFA,__debug_pubnames";
254       DwarfPubTypesSection = ".section __DWARFA,__debug_pubtypes";
255       DwarfStrSection = ".section __DWARFA,__debug_str";
256       DwarfLocSection = ".section __DWARFA,__debug_loc";
257       DwarfARangesSection = ".section __DWARFA,__debug_aranges";
258       DwarfRangesSection = ".section __DWARFA,__debug_ranges";
259       DwarfMacInfoSection = ".section __DWARFA,__debug_macinfo";
260       TextSection = ".text";
261       DataSection = ".data";
262     }
263   };
264
265   /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
266   /// X
267   struct DarwinAsmPrinter : public PPCAsmPrinter {
268   
269     DarwinDwarfWriter DW;
270
271     DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
272       : PPCAsmPrinter(O, TM), DW(O, this) {
273       CommentString = ";";
274       GlobalPrefix = "_";
275       PrivateGlobalPrefix = "L";     // Marker for constant pool idxs
276       ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
277       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
278       AlignmentIsInBytes = false;    // Alignment is by power of 2.
279       ConstantPoolSection = "\t.const\t";
280       // FIXME: Conditionalize jump table section based on PIC
281       JumpTableSection = ".const";
282       LCOMMDirective = "\t.lcomm\t";
283       StaticCtorsSection = ".mod_init_func";
284       StaticDtorsSection = ".mod_term_func";
285       InlineAsmStart = "# InlineAsm Start";
286       InlineAsmEnd = "# InlineAsm End";
287     }
288
289     virtual const char *getPassName() const {
290       return "Darwin PPC Assembly Printer";
291     }
292     
293     bool runOnMachineFunction(MachineFunction &F);
294     bool doInitialization(Module &M);
295     bool doFinalization(Module &M);
296     
297     void getAnalysisUsage(AnalysisUsage &AU) const {
298       AU.setPreservesAll();
299       AU.addRequired<MachineDebugInfo>();
300       PPCAsmPrinter::getAnalysisUsage(AU);
301     }
302
303   };
304
305   /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
306   ///
307   struct AIXAsmPrinter : public PPCAsmPrinter {
308     /// Map for labels corresponding to global variables
309     ///
310     std::map<const GlobalVariable*,std::string> GVToLabelMap;
311
312     AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
313       : PPCAsmPrinter(O, TM) {
314       CommentString = "#";
315       GlobalPrefix = ".";
316       ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
317       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
318       AlignmentIsInBytes = false;    // Alignment is by power of 2.
319       ConstantPoolSection = "\t.const\t";
320     }
321
322     virtual const char *getPassName() const {
323       return "AIX PPC Assembly Printer";
324     }
325
326     bool runOnMachineFunction(MachineFunction &F);
327     bool doInitialization(Module &M);
328     bool doFinalization(Module &M);
329   };
330 } // end of anonymous namespace
331
332 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
333 /// code for a MachineFunction to the given output stream, in a format that the
334 /// Darwin assembler can deal with.
335 ///
336 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o,
337                                            PPCTargetMachine &tm) {
338   return new DarwinAsmPrinter(o, tm);
339 }
340
341 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
342 /// for a MachineFunction to the given output stream, in a format that the
343 /// AIX 5L assembler can deal with.
344 ///
345 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, PPCTargetMachine &tm) {
346   return new AIXAsmPrinter(o, tm);
347 }
348
349 // Include the auto-generated portion of the assembly writer
350 #include "PPCGenAsmWriter.inc"
351
352 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
353   const MRegisterInfo &RI = *TM.getRegisterInfo();
354   int new_symbol;
355
356   switch (MO.getType()) {
357     O << RI.get(MO.getReg()).Name;
358     return;
359
360   case MachineOperand::MO_Immediate:
361     std::cerr << "printOp() does not handle immediate values\n";
362     abort();
363     return;
364
365   case MachineOperand::MO_MachineBasicBlock:
366     printBasicBlockLabel(MO.getMachineBasicBlock());
367     return;
368   case MachineOperand::MO_JumpTableIndex:
369     O << PrivateGlobalPrefix << "JTI" << getFunctionNumber()
370       << '_' << MO.getJumpTableIndex();
371     // FIXME: PIC relocation model
372     return;
373   case MachineOperand::MO_ConstantPoolIndex:
374     O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
375       << '_' << MO.getConstantPoolIndex();
376     return;
377   case MachineOperand::MO_ExternalSymbol:
378     // Computing the address of an external symbol, not calling it.
379     if (TM.getRelocationModel() != Reloc::Static) {
380       std::string Name(GlobalPrefix); Name += MO.getSymbolName();
381       GVStubs.insert(Name);
382       O << "L" << Name << "$non_lazy_ptr";
383       return;
384     }
385     O << GlobalPrefix << MO.getSymbolName();
386     return;
387   case MachineOperand::MO_GlobalAddress: {
388     // Computing the address of a global symbol, not calling it.
389     GlobalValue *GV = MO.getGlobal();
390     std::string Name = Mang->getValueName(GV);
391     int offset = MO.getOffset();
392
393     // External or weakly linked global variables need non-lazily-resolved stubs
394     if (TM.getRelocationModel() != Reloc::Static) {
395       if (((GV->isExternal() || GV->hasWeakLinkage() ||
396             GV->hasLinkOnceLinkage()))) {
397         GVStubs.insert(Name);
398         O << "L" << Name << "$non_lazy_ptr";
399         return;
400       }
401     }
402
403     O << Name;
404     return;
405   }
406
407   default:
408     O << "<unknown operand type: " << MO.getType() << ">";
409     return;
410   }
411 }
412
413 /// PrintAsmOperand - Print out an operand for an inline asm expression.
414 ///
415 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
416                                     unsigned AsmVariant, 
417                                     const char *ExtraCode) {
418   // Does this asm operand have a single letter operand modifier?
419   if (ExtraCode && ExtraCode[0]) {
420     if (ExtraCode[1] != 0) return true; // Unknown modifier.
421     
422     switch (ExtraCode[0]) {
423     default: return true;  // Unknown modifier.
424     case 'L': // Write second word of DImode reference.  
425       // Verify that this operand has two consecutive registers.
426       if (!MI->getOperand(OpNo).isRegister() ||
427           OpNo+1 == MI->getNumOperands() ||
428           !MI->getOperand(OpNo+1).isRegister())
429         return true;
430       ++OpNo;   // Return the high-part.
431       break;
432     }
433   }
434   
435   printOperand(MI, OpNo);
436   return false;
437 }
438
439 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
440                                           unsigned AsmVariant, 
441                                           const char *ExtraCode) {
442   if (ExtraCode && ExtraCode[0])
443     return true; // Unknown modifier.
444   printMemRegReg(MI, OpNo);
445   return false;
446 }
447
448 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
449 /// the current output stream.
450 ///
451 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
452   ++EmittedInsts;
453
454   // Check for slwi/srwi mnemonics.
455   if (MI->getOpcode() == PPC::RLWINM) {
456     bool FoundMnemonic = false;
457     unsigned char SH = MI->getOperand(2).getImmedValue();
458     unsigned char MB = MI->getOperand(3).getImmedValue();
459     unsigned char ME = MI->getOperand(4).getImmedValue();
460     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
461       O << "slwi "; FoundMnemonic = true;
462     }
463     if (SH <= 31 && MB == (32-SH) && ME == 31) {
464       O << "srwi "; FoundMnemonic = true;
465       SH = 32-SH;
466     }
467     if (FoundMnemonic) {
468       printOperand(MI, 0);
469       O << ", ";
470       printOperand(MI, 1);
471       O << ", " << (unsigned int)SH << "\n";
472       return;
473     }
474   } else if (MI->getOpcode() == PPC::OR4 || MI->getOpcode() == PPC::OR8) {
475     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
476       O << "mr ";
477       printOperand(MI, 0);
478       O << ", ";
479       printOperand(MI, 1);
480       O << "\n";
481       return;
482     }
483   }
484
485   if (printInstruction(MI))
486     return; // Printer was automatically generated
487
488   assert(0 && "Unhandled instruction in asm writer!");
489   abort();
490   return;
491 }
492
493 /// runOnMachineFunction - This uses the printMachineInstruction()
494 /// method to print assembly for each instruction.
495 ///
496 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
497   // FIXME - is this the earliest this can be set?
498   DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
499
500   SetupMachineFunction(MF);
501   O << "\n\n";
502   
503   // Print out constants referenced by the function
504   EmitConstantPool(MF.getConstantPool());
505
506   // Print out jump tables referenced by the function
507   EmitJumpTableInfo(MF.getJumpTableInfo());
508
509   // Print out labels for the function.
510   const Function *F = MF.getFunction();
511   switch (F->getLinkage()) {
512   default: assert(0 && "Unknown linkage type!");
513   case Function::InternalLinkage:  // Symbols default to internal.
514     SwitchSection(".text", F);
515     break;
516   case Function::ExternalLinkage:
517     SwitchSection(".text", F);
518     O << "\t.globl\t" << CurrentFnName << "\n";
519     break;
520   case Function::WeakLinkage:
521   case Function::LinkOnceLinkage:
522     SwitchSection(".section __TEXT,__textcoal_nt,coalesced,pure_instructions",
523                   F);
524     O << "\t.globl\t" << CurrentFnName << "\n";
525     O << "\t.weak_definition\t" << CurrentFnName << "\n";
526     break;
527   }
528   EmitAlignment(4, F);
529   O << CurrentFnName << ":\n";
530
531   // Emit pre-function debug information.
532   DW.BeginFunction(&MF);
533
534   // Print out code for the function.
535   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
536        I != E; ++I) {
537     // Print a label for the basic block.
538     if (I != MF.begin()) {
539       printBasicBlockLabel(I, true);
540       O << '\n';
541     }
542     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
543          II != E; ++II) {
544       // Print the assembly for the instruction.
545       O << "\t";
546       printMachineInstruction(II);
547     }
548   }
549
550   // Emit post-function debug information.
551   DW.EndFunction();
552
553   // We didn't modify anything.
554   return false;
555 }
556
557
558 bool DarwinAsmPrinter::doInitialization(Module &M) {
559   if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
560     O << "\t.machine ppc970\n";
561   AsmPrinter::doInitialization(M);
562   
563   // Darwin wants symbols to be quoted if they have complex names.
564   Mang->setUseQuotes(true);
565   
566   // Emit initial debug information.
567   DW.BeginModule(&M);
568   return false;
569 }
570
571 bool DarwinAsmPrinter::doFinalization(Module &M) {
572   const TargetData *TD = TM.getTargetData();
573
574   // Print out module-level global variables here.
575   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
576        I != E; ++I) {
577     if (!I->hasInitializer()) continue;   // External global require no code
578     
579     // Check to see if this is a special global used by LLVM, if so, emit it.
580     if (EmitSpecialLLVMGlobal(I))
581       continue;
582     
583     std::string name = Mang->getValueName(I);
584     Constant *C = I->getInitializer();
585     unsigned Size = TD->getTypeSize(C->getType());
586     unsigned Align = getPreferredAlignmentLog(I);
587
588     if (C->isNullValue() && /* FIXME: Verify correct */
589         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
590          I->hasLinkOnceLinkage() ||
591          (I->hasExternalLinkage() && !I->hasSection()))) {
592       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
593       if (I->hasExternalLinkage()) {
594         O << "\t.globl " << name << '\n';
595         O << "\t.zerofill __DATA, __common, " << name << ", "
596           << Size << ", " << Align;
597       } else if (I->hasInternalLinkage()) {
598         SwitchSection(".data", I);
599         O << LCOMMDirective << name << "," << Size << "," << Align;
600       } else {
601         SwitchSection(".data", I);
602         O << ".comm " << name << "," << Size;
603       }
604       O << "\t\t; '" << I->getName() << "'\n";
605     } else {
606       switch (I->getLinkage()) {
607       case GlobalValue::LinkOnceLinkage:
608       case GlobalValue::WeakLinkage:
609         O << "\t.globl " << name << '\n'
610           << "\t.weak_definition " << name << '\n';
611         SwitchSection(".section __DATA,__datacoal_nt,coalesced", I);
612         break;
613       case GlobalValue::AppendingLinkage:
614         // FIXME: appending linkage variables should go into a section of
615         // their name or something.  For now, just emit them as external.
616       case GlobalValue::ExternalLinkage:
617         // If external or appending, declare as a global symbol
618         O << "\t.globl " << name << "\n";
619         // FALL THROUGH
620       case GlobalValue::InternalLinkage:
621         SwitchSection(".data", I);
622         break;
623       default:
624         std::cerr << "Unknown linkage type!";
625         abort();
626       }
627
628       EmitAlignment(Align, I);
629       O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
630       EmitGlobalConstant(C);
631       O << '\n';
632     }
633   }
634
635   // Output stubs for dynamically-linked functions
636   if (TM.getRelocationModel() == Reloc::PIC) {
637     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
638          i != e; ++i) {
639       SwitchSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
640                     "pure_instructions,32", 0);
641       EmitAlignment(2);
642       O << "L" << *i << "$stub:\n";
643       O << "\t.indirect_symbol " << *i << "\n";
644       O << "\tmflr r0\n";
645       O << "\tbcl 20,31,L0$" << *i << "\n";
646       O << "L0$" << *i << ":\n";
647       O << "\tmflr r11\n";
648       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
649       O << "\tmtlr r0\n";
650       O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
651       O << "\tmtctr r12\n";
652       O << "\tbctr\n";
653       SwitchSection(".lazy_symbol_pointer", 0);
654       O << "L" << *i << "$lazy_ptr:\n";
655       O << "\t.indirect_symbol " << *i << "\n";
656       O << "\t.long dyld_stub_binding_helper\n";
657     }
658   } else {
659     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
660          i != e; ++i) {
661       SwitchSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
662                     "pure_instructions,16", 0);
663       EmitAlignment(4);
664       O << "L" << *i << "$stub:\n";
665       O << "\t.indirect_symbol " << *i << "\n";
666       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
667       O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
668       O << "\tmtctr r12\n";
669       O << "\tbctr\n";
670       SwitchSection(".lazy_symbol_pointer", 0);
671       O << "L" << *i << "$lazy_ptr:\n";
672       O << "\t.indirect_symbol " << *i << "\n";
673       O << "\t.long dyld_stub_binding_helper\n";
674     }
675   }
676
677   O << "\n";
678
679   // Output stubs for external and common global variables.
680   if (GVStubs.begin() != GVStubs.end()) {
681     SwitchSection(".non_lazy_symbol_pointer", 0);
682     for (std::set<std::string>::iterator I = GVStubs.begin(),
683          E = GVStubs.end(); I != E; ++I) {
684       O << "L" << *I << "$non_lazy_ptr:\n";
685       O << "\t.indirect_symbol " << *I << "\n";
686       O << "\t.long\t0\n";
687     }
688   }
689
690   // Emit initial debug information.
691   DW.EndModule();
692
693   // Funny Darwin hack: This flag tells the linker that no global symbols
694   // contain code that falls through to other global symbols (e.g. the obvious
695   // implementation of multiple entry points).  If this doesn't occur, the
696   // linker can safely perform dead code stripping.  Since LLVM never generates
697   // code that does this, it is always safe to set.
698   O << "\t.subsections_via_symbols\n";
699
700   AsmPrinter::doFinalization(M);
701   return false; // success
702 }
703
704 /// runOnMachineFunction - This uses the printMachineInstruction()
705 /// method to print assembly for each instruction.
706 ///
707 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
708   SetupMachineFunction(MF);
709   
710   // Print out constants referenced by the function
711   EmitConstantPool(MF.getConstantPool());
712
713   // Print out header for the function.
714   O << "\t.csect .text[PR]\n"
715     << "\t.align 2\n"
716     << "\t.globl "  << CurrentFnName << '\n'
717     << "\t.globl ." << CurrentFnName << '\n'
718     << "\t.csect "  << CurrentFnName << "[DS],3\n"
719     << CurrentFnName << ":\n"
720     << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
721     << "\t.csect .text[PR]\n"
722     << '.' << CurrentFnName << ":\n";
723
724   // Print out code for the function.
725   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
726        I != E; ++I) {
727     printBasicBlockLabel(I);
728     O << '\n';
729     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
730       II != E; ++II) {
731       // Print the assembly for the instruction.
732       O << "\t";
733       printMachineInstruction(II);
734     }
735   }
736
737   O << "LT.." << CurrentFnName << ":\n"
738     << "\t.long 0\n"
739     << "\t.byte 0,0,32,65,128,0,0,0\n"
740     << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
741     << "\t.short 3\n"
742     << "\t.byte \"" << CurrentFnName << "\"\n"
743     << "\t.align 2\n";
744
745   // We didn't modify anything.
746   return false;
747 }
748
749 bool AIXAsmPrinter::doInitialization(Module &M) {
750   SwitchSection("", 0);
751   const TargetData *TD = TM.getTargetData();
752
753   O << "\t.machine \"ppc64\"\n"
754     << "\t.toc\n"
755     << "\t.csect .text[PR]\n";
756
757   // Print out module-level global variables
758   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
759        I != E; ++I) {
760     if (!I->hasInitializer())
761       continue;
762
763     std::string Name = I->getName();
764     Constant *C = I->getInitializer();
765     // N.B.: We are defaulting to writable strings
766     if (I->hasExternalLinkage()) {
767       O << "\t.globl " << Name << '\n'
768         << "\t.csect .data[RW],3\n";
769     } else {
770       O << "\t.csect _global.rw_c[RW],3\n";
771     }
772     O << Name << ":\n";
773     EmitGlobalConstant(C);
774   }
775
776   // Output labels for globals
777   if (M.global_begin() != M.global_end()) O << "\t.toc\n";
778   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
779        I != E; ++I) {
780     const GlobalVariable *GV = I;
781     // Do not output labels for unused variables
782     if (GV->isExternal() && GV->use_begin() == GV->use_end())
783       continue;
784
785     IncrementFunctionNumber();
786     std::string Name = GV->getName();
787     std::string Label = "LC.." + utostr(getFunctionNumber());
788     GVToLabelMap[GV] = Label;
789     O << Label << ":\n"
790       << "\t.tc " << Name << "[TC]," << Name;
791     if (GV->isExternal()) O << "[RW]";
792     O << '\n';
793    }
794
795   AsmPrinter::doInitialization(M);
796   return false; // success
797 }
798
799 bool AIXAsmPrinter::doFinalization(Module &M) {
800   const TargetData *TD = TM.getTargetData();
801   // Print out module-level global variables
802   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
803        I != E; ++I) {
804     if (I->hasInitializer() || I->hasExternalLinkage())
805       continue;
806
807     std::string Name = I->getName();
808     if (I->hasInternalLinkage()) {
809       O << "\t.lcomm " << Name << ",16,_global.bss_c";
810     } else {
811       O << "\t.comm " << Name << "," << TD->getTypeSize(I->getType())
812         << "," << Log2_32((unsigned)TD->getTypeAlignment(I->getType()));
813     }
814     O << "\t\t" << CommentString << " ";
815     WriteAsOperand(O, I, false, true, &M);
816     O << "\n";
817   }
818
819   O << "_section_.text:\n"
820     << "\t.csect .data[RW],3\n"
821     << "\t.llong _section_.text\n";
822   AsmPrinter::doFinalization(M);
823   return false; // success
824 }