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