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