44ab7f83c2dbdbd89a92307bddc25ea9262698a0
[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   switch (MO.getType()) {
354   case MachineOperand::MO_Immediate:
355     std::cerr << "printOp() does not handle immediate values\n";
356     abort();
357     return;
358
359   case MachineOperand::MO_MachineBasicBlock:
360     printBasicBlockLabel(MO.getMachineBasicBlock());
361     return;
362   case MachineOperand::MO_JumpTableIndex:
363     O << PrivateGlobalPrefix << "JTI" << getFunctionNumber()
364       << '_' << MO.getJumpTableIndex();
365     // FIXME: PIC relocation model
366     return;
367   case MachineOperand::MO_ConstantPoolIndex:
368     O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
369       << '_' << MO.getConstantPoolIndex();
370     return;
371   case MachineOperand::MO_ExternalSymbol:
372     // Computing the address of an external symbol, not calling it.
373     if (TM.getRelocationModel() != Reloc::Static) {
374       std::string Name(GlobalPrefix); Name += MO.getSymbolName();
375       GVStubs.insert(Name);
376       O << "L" << Name << "$non_lazy_ptr";
377       return;
378     }
379     O << GlobalPrefix << MO.getSymbolName();
380     return;
381   case MachineOperand::MO_GlobalAddress: {
382     // Computing the address of a global symbol, not calling it.
383     GlobalValue *GV = MO.getGlobal();
384     std::string Name = Mang->getValueName(GV);
385     int offset = MO.getOffset();
386
387     // External or weakly linked global variables need non-lazily-resolved stubs
388     if (TM.getRelocationModel() != Reloc::Static) {
389       if (((GV->isExternal() || GV->hasWeakLinkage() ||
390             GV->hasLinkOnceLinkage()))) {
391         GVStubs.insert(Name);
392         O << "L" << Name << "$non_lazy_ptr";
393         return;
394       }
395     }
396
397     O << Name;
398     return;
399   }
400
401   default:
402     O << "<unknown operand type: " << MO.getType() << ">";
403     return;
404   }
405 }
406
407 /// PrintAsmOperand - Print out an operand for an inline asm expression.
408 ///
409 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
410                                     unsigned AsmVariant, 
411                                     const char *ExtraCode) {
412   // Does this asm operand have a single letter operand modifier?
413   if (ExtraCode && ExtraCode[0]) {
414     if (ExtraCode[1] != 0) return true; // Unknown modifier.
415     
416     switch (ExtraCode[0]) {
417     default: return true;  // Unknown modifier.
418     case 'L': // Write second word of DImode reference.  
419       // Verify that this operand has two consecutive registers.
420       if (!MI->getOperand(OpNo).isRegister() ||
421           OpNo+1 == MI->getNumOperands() ||
422           !MI->getOperand(OpNo+1).isRegister())
423         return true;
424       ++OpNo;   // Return the high-part.
425       break;
426     }
427   }
428   
429   printOperand(MI, OpNo);
430   return false;
431 }
432
433 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
434                                           unsigned AsmVariant, 
435                                           const char *ExtraCode) {
436   if (ExtraCode && ExtraCode[0])
437     return true; // Unknown modifier.
438   printMemRegReg(MI, OpNo);
439   return false;
440 }
441
442 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
443 /// the current output stream.
444 ///
445 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
446   ++EmittedInsts;
447
448   // Check for slwi/srwi mnemonics.
449   if (MI->getOpcode() == PPC::RLWINM) {
450     bool FoundMnemonic = false;
451     unsigned char SH = MI->getOperand(2).getImmedValue();
452     unsigned char MB = MI->getOperand(3).getImmedValue();
453     unsigned char ME = MI->getOperand(4).getImmedValue();
454     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
455       O << "slwi "; FoundMnemonic = true;
456     }
457     if (SH <= 31 && MB == (32-SH) && ME == 31) {
458       O << "srwi "; FoundMnemonic = true;
459       SH = 32-SH;
460     }
461     if (FoundMnemonic) {
462       printOperand(MI, 0);
463       O << ", ";
464       printOperand(MI, 1);
465       O << ", " << (unsigned int)SH << "\n";
466       return;
467     }
468   } else if (MI->getOpcode() == PPC::OR4 || MI->getOpcode() == PPC::OR8) {
469     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
470       O << "mr ";
471       printOperand(MI, 0);
472       O << ", ";
473       printOperand(MI, 1);
474       O << "\n";
475       return;
476     }
477   }
478
479   if (printInstruction(MI))
480     return; // Printer was automatically generated
481
482   assert(0 && "Unhandled instruction in asm writer!");
483   abort();
484   return;
485 }
486
487 /// runOnMachineFunction - This uses the printMachineInstruction()
488 /// method to print assembly for each instruction.
489 ///
490 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
491   DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
492   // FIXME - should be able to debug coalesced functions.
493   bool IsNormalText = true;
494
495   SetupMachineFunction(MF);
496   O << "\n\n";
497   
498   // Print out constants referenced by the function
499   EmitConstantPool(MF.getConstantPool());
500
501   // Print out jump tables referenced by the function
502   EmitJumpTableInfo(MF.getJumpTableInfo());
503
504   // Print out labels for the function.
505   const Function *F = MF.getFunction();
506   switch (F->getLinkage()) {
507   default: assert(0 && "Unknown linkage type!");
508   case Function::InternalLinkage:  // Symbols default to internal.
509     SwitchToTextSection("\t.text", F);
510     break;
511   case Function::ExternalLinkage:
512     SwitchToTextSection("\t.text", F);
513     O << "\t.globl\t" << CurrentFnName << "\n";
514     break;
515   case Function::WeakLinkage:
516   case Function::LinkOnceLinkage:
517     SwitchToTextSection(
518                 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
519     O << "\t.globl\t" << CurrentFnName << "\n";
520     O << "\t.weak_definition\t" << CurrentFnName << "\n";
521     IsNormalText = false;
522     break;
523   }
524   EmitAlignment(4, F);
525   O << CurrentFnName << ":\n";
526
527   // Emit pre-function debug information.
528   DW.BeginFunction(&MF, IsNormalText);
529
530   // Print out code for the function.
531   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
532        I != E; ++I) {
533     // Print a label for the basic block.
534     if (I != MF.begin()) {
535       printBasicBlockLabel(I, true);
536       O << '\n';
537     }
538     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
539          II != E; ++II) {
540       // Print the assembly for the instruction.
541       O << "\t";
542       printMachineInstruction(II);
543     }
544   }
545
546   // Emit post-function debug information.
547   DW.EndFunction();
548
549   // We didn't modify anything.
550   return false;
551 }
552
553
554 bool DarwinAsmPrinter::doInitialization(Module &M) {
555   if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
556     O << "\t.machine ppc970\n";
557   AsmPrinter::doInitialization(M);
558   
559   // Darwin wants symbols to be quoted if they have complex names.
560   Mang->setUseQuotes(true);
561   
562   // Emit initial debug information.
563   DW.BeginModule(&M);
564   return false;
565 }
566
567 bool DarwinAsmPrinter::doFinalization(Module &M) {
568   const TargetData *TD = TM.getTargetData();
569
570   // Print out module-level global variables here.
571   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
572        I != E; ++I) {
573     if (!I->hasInitializer()) continue;   // External global require no code
574     
575     // Check to see if this is a special global used by LLVM, if so, emit it.
576     if (EmitSpecialLLVMGlobal(I))
577       continue;
578     
579     std::string name = Mang->getValueName(I);
580     Constant *C = I->getInitializer();
581     unsigned Size = TD->getTypeSize(C->getType());
582     unsigned Align = getPreferredAlignmentLog(I);
583
584     if (C->isNullValue() && /* FIXME: Verify correct */
585         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
586          I->hasLinkOnceLinkage() ||
587          (I->hasExternalLinkage() && !I->hasSection()))) {
588       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
589       if (I->hasExternalLinkage()) {
590         O << "\t.globl " << name << '\n';
591         O << "\t.zerofill __DATA, __common, " << name << ", "
592           << Size << ", " << Align;
593       } else if (I->hasInternalLinkage()) {
594         SwitchToDataSection("\t.data", I);
595         O << LCOMMDirective << name << "," << Size << "," << Align;
596       } else {
597         SwitchToDataSection("\t.data", I);
598         O << ".comm " << name << "," << Size;
599       }
600       O << "\t\t; '" << I->getName() << "'\n";
601     } else {
602       switch (I->getLinkage()) {
603       case GlobalValue::LinkOnceLinkage:
604       case GlobalValue::WeakLinkage:
605         O << "\t.globl " << name << '\n'
606           << "\t.weak_definition " << name << '\n';
607         SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
608         break;
609       case GlobalValue::AppendingLinkage:
610         // FIXME: appending linkage variables should go into a section of
611         // their name or something.  For now, just emit them as external.
612       case GlobalValue::ExternalLinkage:
613         // If external or appending, declare as a global symbol
614         O << "\t.globl " << name << "\n";
615         // FALL THROUGH
616       case GlobalValue::InternalLinkage:
617         SwitchToDataSection("\t.data", I);
618         break;
619       default:
620         std::cerr << "Unknown linkage type!";
621         abort();
622       }
623
624       EmitAlignment(Align, I);
625       O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
626       EmitGlobalConstant(C);
627       O << '\n';
628     }
629   }
630
631   // Output stubs for dynamically-linked functions
632   if (TM.getRelocationModel() == Reloc::PIC) {
633     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
634          i != e; ++i) {
635       SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
636                           "pure_instructions,32", 0);
637       EmitAlignment(2);
638       O << "L" << *i << "$stub:\n";
639       O << "\t.indirect_symbol " << *i << "\n";
640       O << "\tmflr r0\n";
641       O << "\tbcl 20,31,L0$" << *i << "\n";
642       O << "L0$" << *i << ":\n";
643       O << "\tmflr r11\n";
644       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
645       O << "\tmtlr r0\n";
646       O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
647       O << "\tmtctr r12\n";
648       O << "\tbctr\n";
649       SwitchToDataSection(".lazy_symbol_pointer", 0);
650       O << "L" << *i << "$lazy_ptr:\n";
651       O << "\t.indirect_symbol " << *i << "\n";
652       O << "\t.long dyld_stub_binding_helper\n";
653     }
654   } else {
655     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
656          i != e; ++i) {
657       SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
658                           "pure_instructions,16", 0);
659       EmitAlignment(4);
660       O << "L" << *i << "$stub:\n";
661       O << "\t.indirect_symbol " << *i << "\n";
662       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
663       O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
664       O << "\tmtctr r12\n";
665       O << "\tbctr\n";
666       SwitchToDataSection(".lazy_symbol_pointer", 0);
667       O << "L" << *i << "$lazy_ptr:\n";
668       O << "\t.indirect_symbol " << *i << "\n";
669       O << "\t.long dyld_stub_binding_helper\n";
670     }
671   }
672
673   O << "\n";
674
675   // Output stubs for external and common global variables.
676   if (GVStubs.begin() != GVStubs.end()) {
677     SwitchToDataSection(".non_lazy_symbol_pointer", 0);
678     for (std::set<std::string>::iterator I = GVStubs.begin(),
679          E = GVStubs.end(); I != E; ++I) {
680       O << "L" << *I << "$non_lazy_ptr:\n";
681       O << "\t.indirect_symbol " << *I << "\n";
682       O << "\t.long\t0\n";
683     }
684   }
685
686   // Emit initial debug information.
687   DW.EndModule();
688
689   // Funny Darwin hack: This flag tells the linker that no global symbols
690   // contain code that falls through to other global symbols (e.g. the obvious
691   // implementation of multiple entry points).  If this doesn't occur, the
692   // linker can safely perform dead code stripping.  Since LLVM never generates
693   // code that does this, it is always safe to set.
694   O << "\t.subsections_via_symbols\n";
695
696   AsmPrinter::doFinalization(M);
697   return false; // success
698 }
699
700 /// runOnMachineFunction - This uses the printMachineInstruction()
701 /// method to print assembly for each instruction.
702 ///
703 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
704   SetupMachineFunction(MF);
705   
706   // Print out constants referenced by the function
707   EmitConstantPool(MF.getConstantPool());
708
709   // Print out header for the function.
710   O << "\t.csect .text[PR]\n"
711     << "\t.align 2\n"
712     << "\t.globl "  << CurrentFnName << '\n'
713     << "\t.globl ." << CurrentFnName << '\n'
714     << "\t.csect "  << CurrentFnName << "[DS],3\n"
715     << CurrentFnName << ":\n"
716     << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
717     << "\t.csect .text[PR]\n"
718     << '.' << CurrentFnName << ":\n";
719
720   // Print out code for the function.
721   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
722        I != E; ++I) {
723     printBasicBlockLabel(I);
724     O << '\n';
725     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
726       II != E; ++II) {
727       // Print the assembly for the instruction.
728       O << "\t";
729       printMachineInstruction(II);
730     }
731   }
732
733   O << "LT.." << CurrentFnName << ":\n"
734     << "\t.long 0\n"
735     << "\t.byte 0,0,32,65,128,0,0,0\n"
736     << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
737     << "\t.short 3\n"
738     << "\t.byte \"" << CurrentFnName << "\"\n"
739     << "\t.align 2\n";
740
741   // We didn't modify anything.
742   return false;
743 }
744
745 bool AIXAsmPrinter::doInitialization(Module &M) {
746   SwitchToDataSection("", 0);
747
748   O << "\t.machine \"ppc64\"\n"
749     << "\t.toc\n"
750     << "\t.csect .text[PR]\n";
751
752   // Print out module-level global variables
753   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
754        I != E; ++I) {
755     if (!I->hasInitializer())
756       continue;
757
758     std::string Name = I->getName();
759     Constant *C = I->getInitializer();
760     // N.B.: We are defaulting to writable strings
761     if (I->hasExternalLinkage()) {
762       O << "\t.globl " << Name << '\n'
763         << "\t.csect .data[RW],3\n";
764     } else {
765       O << "\t.csect _global.rw_c[RW],3\n";
766     }
767     O << Name << ":\n";
768     EmitGlobalConstant(C);
769   }
770
771   // Output labels for globals
772   if (M.global_begin() != M.global_end()) O << "\t.toc\n";
773   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
774        I != E; ++I) {
775     const GlobalVariable *GV = I;
776     // Do not output labels for unused variables
777     if (GV->isExternal() && GV->use_begin() == GV->use_end())
778       continue;
779
780     IncrementFunctionNumber();
781     std::string Name = GV->getName();
782     std::string Label = "LC.." + utostr(getFunctionNumber());
783     GVToLabelMap[GV] = Label;
784     O << Label << ":\n"
785       << "\t.tc " << Name << "[TC]," << Name;
786     if (GV->isExternal()) O << "[RW]";
787     O << '\n';
788    }
789
790   AsmPrinter::doInitialization(M);
791   return false; // success
792 }
793
794 bool AIXAsmPrinter::doFinalization(Module &M) {
795   const TargetData *TD = TM.getTargetData();
796   // Print out module-level global variables
797   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
798        I != E; ++I) {
799     if (I->hasInitializer() || I->hasExternalLinkage())
800       continue;
801
802     std::string Name = I->getName();
803     if (I->hasInternalLinkage()) {
804       O << "\t.lcomm " << Name << ",16,_global.bss_c";
805     } else {
806       O << "\t.comm " << Name << "," << TD->getTypeSize(I->getType())
807         << "," << Log2_32((unsigned)TD->getTypeAlignment(I->getType()));
808     }
809     O << "\t\t" << CommentString << " ";
810     WriteAsOperand(O, I, false, true, &M);
811     O << "\n";
812   }
813
814   O << "_section_.text:\n"
815     << "\t.csect .data[RW],3\n"
816     << "\t.llong _section_.text\n";
817   AsmPrinter::doFinalization(M);
818   return false; // success
819 }