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