PPCAsmPrinter.cpp revision 815ef5b3dd7536e62038c091f6bf17f7badbfe5a
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>
42using namespace llvm;
43
44namespace {
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      {
251      CommentString = ";";
252      GlobalPrefix = "_";
253      PrivateGlobalPrefix = "L";     // Marker for constant pool idxs
254      ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
255      Data64bitsDirective = 0;       // we can't emit a 64-bit unit
256      AlignmentIsInBytes = false;    // Alignment is by power of 2.
257      ConstantPoolSection = "\t.const\t";
258      LCOMMDirective = "\t.lcomm\t";
259      StaticCtorsSection = ".mod_init_func";
260      StaticDtorsSection = ".mod_term_func";
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///
310FunctionPass *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///
318FunctionPass *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
325void 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///
402void 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  }
426
427  if (printInstruction(MI))
428    return; // Printer was automatically generated
429
430  assert(0 && "Unhandled instruction in asm writer!");
431  abort();
432  return;
433}
434
435
436/// runOnMachineFunction - This uses the printMachineInstruction()
437/// method to print assembly for each instruction.
438///
439bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
440  // FIXME - is this the earliest this can be set?
441  DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
442
443  SetupMachineFunction(MF);
444  O << "\n\n";
445
446  // Emit pre-function debug information.
447  DW.BeginFunction(MF);
448
449  // Print out constants referenced by the function
450  EmitConstantPool(MF.getConstantPool());
451
452  // Print out labels for the function.
453  const Function *F = MF.getFunction();
454  switch (F->getLinkage()) {
455  default: assert(0 && "Unknown linkage type!");
456  case Function::InternalLinkage:  // Symbols default to internal.
457    SwitchSection(".text", F);
458    EmitAlignment(4, F);
459    break;
460  case Function::ExternalLinkage:
461    SwitchSection(".text", F);
462    EmitAlignment(4, F);
463    O << "\t.globl\t" << CurrentFnName << "\n";
464    break;
465  case Function::WeakLinkage:
466  case Function::LinkOnceLinkage:
467    SwitchSection(".section __TEXT,__textcoal_nt,coalesced,pure_instructions",
468                  F);
469    O << "\t.globl\t" << CurrentFnName << "\n";
470    O << "\t.weak_definition\t" << CurrentFnName << "\n";
471    break;
472  }
473  O << CurrentFnName << ":\n";
474
475  // Print out code for the function.
476  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
477       I != E; ++I) {
478    // Print a label for the basic block.
479    if (I != MF.begin()) {
480      O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
481        << I->getNumber() << ":\t";
482      if (!I->getBasicBlock()->getName().empty())
483        O << CommentString << " " << I->getBasicBlock()->getName();
484      O << "\n";
485    }
486    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
487         II != E; ++II) {
488      // Print the assembly for the instruction.
489      O << "\t";
490      printMachineInstruction(II);
491    }
492  }
493
494  // Emit post-function debug information.
495  DW.EndFunction(MF);
496
497  // We didn't modify anything.
498  return false;
499}
500
501
502bool DarwinAsmPrinter::doInitialization(Module &M) {
503  if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
504    O << "\t.machine ppc970\n";
505  AsmPrinter::doInitialization(M);
506
507  // Darwin wants symbols to be quoted if they have complex names.
508  Mang->setUseQuotes(true);
509
510  // Emit initial debug information.
511  DW.BeginModule(M);
512  return false;
513}
514
515bool DarwinAsmPrinter::doFinalization(Module &M) {
516  const TargetData &TD = TM.getTargetData();
517
518  // Print out module-level global variables here.
519  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
520       I != E; ++I) {
521    if (!I->hasInitializer()) continue;   // External global require no code
522
523    // Check to see if this is a special global used by LLVM, if so, emit it.
524    if (I->hasAppendingLinkage() && EmitSpecialLLVMGlobal(I))
525      continue;
526
527    std::string name = Mang->getValueName(I);
528    Constant *C = I->getInitializer();
529    unsigned Size = TD.getTypeSize(C->getType());
530    unsigned Align = getPreferredAlignmentLog(I);
531
532    if (C->isNullValue() && /* FIXME: Verify correct */
533        (I->hasInternalLinkage() || I->hasWeakLinkage() ||
534         I->hasLinkOnceLinkage())) {
535      SwitchSection(".data", I);
536      if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
537      if (I->hasInternalLinkage())
538        O << LCOMMDirective << name << "," << Size << "," << Align;
539      else
540        O << ".comm " << name << "," << Size;
541      O << "\t\t; '" << I->getName() << "'\n";
542    } else {
543      switch (I->getLinkage()) {
544      case GlobalValue::LinkOnceLinkage:
545      case GlobalValue::WeakLinkage:
546        O << "\t.globl " << name << '\n'
547          << "\t.weak_definition " << name << '\n';
548        SwitchSection(".section __DATA,__datacoal_nt,coalesced", I);
549        break;
550      case GlobalValue::AppendingLinkage:
551        // FIXME: appending linkage variables should go into a section of
552        // their name or something.  For now, just emit them as external.
553      case GlobalValue::ExternalLinkage:
554        // If external or appending, declare as a global symbol
555        O << "\t.globl " << name << "\n";
556        // FALL THROUGH
557      case GlobalValue::InternalLinkage:
558        SwitchSection(".data", I);
559        break;
560      default:
561        std::cerr << "Unknown linkage type!";
562        abort();
563      }
564
565      EmitAlignment(Align, I);
566      O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
567      EmitGlobalConstant(C);
568      O << '\n';
569    }
570  }
571
572  // Output stubs for dynamically-linked functions
573  if (PICEnabled) {
574    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
575         i != e; ++i) {
576      SwitchSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
577                    "pure_instructions,32", 0);
578      EmitAlignment(2);
579      O << "L" << *i << "$stub:\n";
580      O << "\t.indirect_symbol " << *i << "\n";
581      O << "\tmflr r0\n";
582      O << "\tbcl 20,31,L0$" << *i << "\n";
583      O << "L0$" << *i << ":\n";
584      O << "\tmflr r11\n";
585      O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
586      O << "\tmtlr r0\n";
587      O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
588      O << "\tmtctr r12\n";
589      O << "\tbctr\n";
590      SwitchSection(".lazy_symbol_pointer", 0);
591      O << "L" << *i << "$lazy_ptr:\n";
592      O << "\t.indirect_symbol " << *i << "\n";
593      O << "\t.long dyld_stub_binding_helper\n";
594    }
595  } else {
596    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
597         i != e; ++i) {
598      SwitchSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
599                    "pure_instructions,16", 0);
600      EmitAlignment(4);
601      O << "L" << *i << "$stub:\n";
602      O << "\t.indirect_symbol " << *i << "\n";
603      O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
604      O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
605      O << "\tmtctr r12\n";
606      O << "\tbctr\n";
607      SwitchSection(".lazy_symbol_pointer", 0);
608      O << "L" << *i << "$lazy_ptr:\n";
609      O << "\t.indirect_symbol " << *i << "\n";
610      O << "\t.long dyld_stub_binding_helper\n";
611    }
612  }
613
614  O << "\n";
615
616  // Output stubs for external and common global variables.
617  if (GVStubs.begin() != GVStubs.end()) {
618    SwitchSection(".non_lazy_symbol_pointer", 0);
619    for (std::set<std::string>::iterator I = GVStubs.begin(),
620         E = GVStubs.end(); I != E; ++I) {
621      O << "L" << *I << "$non_lazy_ptr:\n";
622      O << "\t.indirect_symbol " << *I << "\n";
623      O << "\t.long\t0\n";
624    }
625  }
626
627  // Emit initial debug information.
628  DW.EndModule(M);
629
630  // Funny Darwin hack: This flag tells the linker that no global symbols
631  // contain code that falls through to other global symbols (e.g. the obvious
632  // implementation of multiple entry points).  If this doesn't occur, the
633  // linker can safely perform dead code stripping.  Since LLVM never generates
634  // code that does this, it is always safe to set.
635  O << "\t.subsections_via_symbols\n";
636
637  AsmPrinter::doFinalization(M);
638  return false; // success
639}
640
641/// runOnMachineFunction - This uses the e()
642/// method to print assembly for each instruction.
643///
644bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
645  SetupMachineFunction(MF);
646
647  // Print out constants referenced by the function
648  EmitConstantPool(MF.getConstantPool());
649
650  // Print out header for the function.
651  O << "\t.csect .text[PR]\n"
652    << "\t.align 2\n"
653    << "\t.globl "  << CurrentFnName << '\n'
654    << "\t.globl ." << CurrentFnName << '\n'
655    << "\t.csect "  << CurrentFnName << "[DS],3\n"
656    << CurrentFnName << ":\n"
657    << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
658    << "\t.csect .text[PR]\n"
659    << '.' << CurrentFnName << ":\n";
660
661  // Print out code for the function.
662  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
663       I != E; ++I) {
664    // Print a label for the basic block.
665    O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
666      << I->getNumber()
667      << ":\t" << CommentString << I->getBasicBlock()->getName() << '\n';
668    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
669      II != E; ++II) {
670      // Print the assembly for the instruction.
671      O << "\t";
672      printMachineInstruction(II);
673    }
674  }
675
676  O << "LT.." << CurrentFnName << ":\n"
677    << "\t.long 0\n"
678    << "\t.byte 0,0,32,65,128,0,0,0\n"
679    << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
680    << "\t.short 3\n"
681    << "\t.byte \"" << CurrentFnName << "\"\n"
682    << "\t.align 2\n";
683
684  // We didn't modify anything.
685  return false;
686}
687
688bool AIXAsmPrinter::doInitialization(Module &M) {
689  SwitchSection("", 0);
690  const TargetData &TD = TM.getTargetData();
691
692  O << "\t.machine \"ppc64\"\n"
693    << "\t.toc\n"
694    << "\t.csect .text[PR]\n";
695
696  // Print out module-level global variables
697  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
698       I != E; ++I) {
699    if (!I->hasInitializer())
700      continue;
701
702    std::string Name = I->getName();
703    Constant *C = I->getInitializer();
704    // N.B.: We are defaulting to writable strings
705    if (I->hasExternalLinkage()) {
706      O << "\t.globl " << Name << '\n'
707        << "\t.csect .data[RW],3\n";
708    } else {
709      O << "\t.csect _global.rw_c[RW],3\n";
710    }
711    O << Name << ":\n";
712    EmitGlobalConstant(C);
713  }
714
715  // Output labels for globals
716  if (M.global_begin() != M.global_end()) O << "\t.toc\n";
717  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
718       I != E; ++I) {
719    const GlobalVariable *GV = I;
720    // Do not output labels for unused variables
721    if (GV->isExternal() && GV->use_begin() == GV->use_end())
722      continue;
723
724    IncrementFunctionNumber();
725    std::string Name = GV->getName();
726    std::string Label = "LC.." + utostr(getFunctionNumber());
727    GVToLabelMap[GV] = Label;
728    O << Label << ":\n"
729      << "\t.tc " << Name << "[TC]," << Name;
730    if (GV->isExternal()) O << "[RW]";
731    O << '\n';
732   }
733
734  AsmPrinter::doInitialization(M);
735  return false; // success
736}
737
738bool AIXAsmPrinter::doFinalization(Module &M) {
739  const TargetData &TD = TM.getTargetData();
740  // Print out module-level global variables
741  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
742       I != E; ++I) {
743    if (I->hasInitializer() || I->hasExternalLinkage())
744      continue;
745
746    std::string Name = I->getName();
747    if (I->hasInternalLinkage()) {
748      O << "\t.lcomm " << Name << ",16,_global.bss_c";
749    } else {
750      O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
751        << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
752    }
753    O << "\t\t" << CommentString << " ";
754    WriteAsOperand(O, I, false, true, &M);
755    O << "\n";
756  }
757
758  O << "_section_.text:\n"
759    << "\t.csect .data[RW],3\n"
760    << "\t.llong _section_.text\n";
761  AsmPrinter::doFinalization(M);
762  return false; // success
763}
764