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