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