PPCAsmPrinter.cpp revision b5f662fa0314f7e7e690aae8ebff7136cc3a5ab0
1//===-- PowerPCAsmPrinter.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 "PowerPC.h"
21#include "PowerPCTargetMachine.h"
22#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Module.h"
25#include "llvm/Assembly/Writer.h"
26#include "llvm/CodeGen/AsmPrinter.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/CodeGen/ValueTypes.h"
31#include "llvm/Support/Mangler.h"
32#include "llvm/Support/MathExtras.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Target/MRegisterInfo.h"
36#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/ADT/Statistic.h"
38#include "llvm/ADT/StringExtras.h"
39#include <set>
40using namespace llvm;
41
42namespace {
43  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
44
45  struct PowerPCAsmPrinter : public AsmPrinter {
46    std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
47    std::set<std::string> Strings;
48
49    PowerPCAsmPrinter(std::ostream &O, TargetMachine &TM)
50      : AsmPrinter(O, TM), LabelNumber(0) {}
51
52    /// Unique incrementer for label values for referencing Global values.
53    ///
54    unsigned LabelNumber;
55
56    virtual const char *getPassName() const {
57      return "PowerPC Assembly Printer";
58    }
59
60    PowerPCTargetMachine &getTM() {
61      return static_cast<PowerPCTargetMachine&>(TM);
62    }
63
64    /// printInstruction - This method is automatically generated by tablegen
65    /// from the instruction set description.  This method returns true if the
66    /// machine instruction was sufficiently described to print it, otherwise it
67    /// returns false.
68    bool printInstruction(const MachineInstr *MI);
69
70    void printMachineInstruction(const MachineInstr *MI);
71    void printOp(const MachineOperand &MO, bool IsCallOp = false);
72
73    void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
74      const MachineOperand &MO = MI->getOperand(OpNo);
75      if (MO.getType() == MachineOperand::MO_MachineRegister) {
76        assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
77        O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
78      } else if (MO.isImmediate()) {
79        O << MO.getImmedValue();
80      } else {
81        printOp(MO);
82      }
83    }
84
85    void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
86                            MVT::ValueType VT) {
87      unsigned char value = MI->getOperand(OpNo).getImmedValue();
88      assert(value <= 31 && "Invalid u5imm argument!");
89      O << (unsigned int)value;
90    }
91    void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
92                            MVT::ValueType VT) {
93      unsigned char value = MI->getOperand(OpNo).getImmedValue();
94      assert(value <= 63 && "Invalid u6imm argument!");
95      O << (unsigned int)value;
96    }
97    void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
98                            MVT::ValueType VT) {
99      O << (short)MI->getOperand(OpNo).getImmedValue();
100    }
101    void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
102                            MVT::ValueType VT) {
103      O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
104    }
105    void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
106                            MVT::ValueType VT) {
107      // Branches can take an immediate operand.  This is used by the branch
108      // selection pass to print $+8, an eight byte displacement from the PC.
109      if (MI->getOperand(OpNo).isImmediate()) {
110        O << "$+" << MI->getOperand(OpNo).getImmedValue();
111      } else {
112        printOp(MI->getOperand(OpNo),
113                TM.getInstrInfo()->isCall(MI->getOpcode()));
114      }
115    }
116    void printPICLabel(const MachineInstr *MI, unsigned OpNo,
117                       MVT::ValueType VT) {
118      // FIXME: should probably be converted to cout.width and cout.fill
119      O << "\"L0000" << LabelNumber << "$pb\"\n";
120      O << "\"L0000" << LabelNumber << "$pb\":";
121    }
122    void printSymbolHi(const MachineInstr *MI, unsigned OpNo,
123                       MVT::ValueType VT) {
124      O << "ha16(";
125      printOp(MI->getOperand(OpNo));
126      O << "-\"L0000" << LabelNumber << "$pb\")";
127    }
128    void printSymbolLo(const MachineInstr *MI, unsigned OpNo,
129                       MVT::ValueType VT) {
130      // FIXME: Because LFS, LFD, and LWZ can be used either with a s16imm or
131      // a lo16 of a global or constant pool operand, we must handle both here.
132      // this isn't a great design, but it works for now.
133      if (MI->getOperand(OpNo).isImmediate()) {
134        O << (short)MI->getOperand(OpNo).getImmedValue();
135      } else {
136        O << "lo16(";
137        printOp(MI->getOperand(OpNo));
138        O << "-\"L0000" << LabelNumber << "$pb\")";
139      }
140    }
141    void printcrbit(const MachineInstr *MI, unsigned OpNo,
142                       MVT::ValueType VT) {
143      unsigned char value = MI->getOperand(OpNo).getImmedValue();
144      assert(value <= 3 && "Invalid crbit argument!");
145      unsigned RegNo, CCReg = MI->getOperand(OpNo-1).getReg();
146      switch (CCReg) {
147      case PPC::CR0:  RegNo = 0; break;
148      case PPC::CR1:  RegNo = 1; break;
149      case PPC::CR2:  RegNo = 2; break;
150      case PPC::CR3:  RegNo = 3; break;
151      case PPC::CR4:  RegNo = 4; break;
152      case PPC::CR5:  RegNo = 5; break;
153      case PPC::CR6:  RegNo = 6; break;
154      case PPC::CR7:  RegNo = 7; break;
155      default:
156        std::cerr << "Unhandled reg in enumRegToRealReg!\n";
157        abort();
158      }
159      O << 4 * RegNo + value;
160    }
161
162    virtual void printConstantPool(MachineConstantPool *MCP) = 0;
163    virtual bool runOnMachineFunction(MachineFunction &F) = 0;
164    virtual bool doFinalization(Module &M) = 0;
165  };
166
167  /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
168  /// X
169  ///
170  struct DarwinAsmPrinter : public PowerPCAsmPrinter {
171
172    DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
173      : PowerPCAsmPrinter(O, TM) {
174      CommentString = ";";
175      GlobalPrefix = "_";
176      ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
177      Data64bitsDirective = 0;       // we can't emit a 64-bit unit
178      AlignmentIsInBytes = false;    // Alignment is by power of 2.
179    }
180
181    virtual const char *getPassName() const {
182      return "Darwin PPC Assembly Printer";
183    }
184
185    void printConstantPool(MachineConstantPool *MCP);
186    bool runOnMachineFunction(MachineFunction &F);
187    bool doFinalization(Module &M);
188  };
189
190  /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
191  ///
192  struct AIXAsmPrinter : public PowerPCAsmPrinter {
193    /// Map for labels corresponding to global variables
194    ///
195    std::map<const GlobalVariable*,std::string> GVToLabelMap;
196
197    AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
198      : PowerPCAsmPrinter(O, TM) {
199      CommentString = "#";
200      GlobalPrefix = "_";
201      ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
202      Data64bitsDirective = 0;       // we can't emit a 64-bit unit
203      AlignmentIsInBytes = false;    // Alignment is by power of 2.
204    }
205
206    virtual const char *getPassName() const {
207      return "AIX PPC Assembly Printer";
208    }
209
210    void printConstantPool(MachineConstantPool *MCP);
211    bool runOnMachineFunction(MachineFunction &F);
212    bool doInitialization(Module &M);
213    bool doFinalization(Module &M);
214  };
215} // end of anonymous namespace
216
217// SwitchSection - Switch to the specified section of the executable if we are
218// not already in it!
219//
220static void SwitchSection(std::ostream &OS, std::string &CurSection,
221                          const char *NewSection) {
222  if (CurSection != NewSection) {
223    CurSection = NewSection;
224    if (!CurSection.empty())
225      OS << "\t" << NewSection << "\n";
226  }
227}
228
229/// isStringCompatible - Can we treat the specified array as a string?
230/// Only if it is an array of ubytes or non-negative sbytes.
231///
232static bool isStringCompatible(const ConstantArray *CVA) {
233  const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
234  if (ETy == Type::UByteTy) return true;
235  if (ETy != Type::SByteTy) return false;
236
237  for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
238    if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
239      return false;
240
241  return true;
242}
243
244/// toOctal - Convert the low order bits of X into an octal digit.
245///
246static inline char toOctal(int X) {
247  return (X&7)+'0';
248}
249
250// Possible states while outputting ASCII strings
251namespace {
252  enum StringSection {
253    None,
254    Alpha,
255    Numeric
256  };
257}
258
259/// SwitchStringSection - manage the changes required to output bytes as
260/// characters in a string vs. numeric decimal values
261///
262static inline void SwitchStringSection(std::ostream &O, StringSection NewSect,
263                                       StringSection &Current) {
264  if (Current == None) {
265    if (NewSect == Alpha)
266      O << "\t.byte \"";
267    else if (NewSect == Numeric)
268      O << "\t.byte ";
269  } else if (Current == Alpha) {
270    if (NewSect == None)
271      O << "\"";
272    else if (NewSect == Numeric)
273      O << "\"\n"
274        << "\t.byte ";
275  } else if (Current == Numeric) {
276    if (NewSect == Alpha)
277      O << '\n'
278        << "\t.byte \"";
279    else if (NewSect == Numeric)
280      O << ", ";
281  }
282
283  Current = NewSect;
284}
285
286/// getAsCString - Return the specified array as a C compatible
287/// string, only if the predicate isStringCompatible is true.
288///
289static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
290  assert(isStringCompatible(CVA) && "Array is not string compatible!");
291
292  if (CVA->getNumOperands() == 0)
293    return;
294
295  StringSection Current = None;
296  for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i) {
297    unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
298    if (C == '"') {
299      SwitchStringSection(O, Alpha, Current);
300      O << "\"\"";
301    } else if (isprint(C)) {
302      SwitchStringSection(O, Alpha, Current);
303      O << C;
304    } else {
305      SwitchStringSection(O, Numeric, Current);
306      O << utostr((unsigned)C);
307    }
308  }
309  SwitchStringSection(O, None, Current);
310  O << '\n';
311}
312
313/// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
314/// code for a MachineFunction to the given output stream, in a format that the
315/// Darwin assembler can deal with.
316///
317FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
318  return new DarwinAsmPrinter(o, tm);
319}
320
321/// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
322/// for a MachineFunction to the given output stream, in a format that the
323/// AIX 5L assembler can deal with.
324///
325FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
326  return new AIXAsmPrinter(o, tm);
327}
328
329// Include the auto-generated portion of the assembly writer
330#include "PowerPCGenAsmWriter.inc"
331
332void PowerPCAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) {
333  const MRegisterInfo &RI = *TM.getRegisterInfo();
334  int new_symbol;
335
336  switch (MO.getType()) {
337  case MachineOperand::MO_VirtualRegister:
338    if (Value *V = MO.getVRegValueOrNull()) {
339      O << "<" << V->getName() << ">";
340      return;
341    }
342    // FALLTHROUGH
343  case MachineOperand::MO_MachineRegister:
344  case MachineOperand::MO_CCRegister:
345    O << LowercaseString(RI.get(MO.getReg()).Name);
346    return;
347
348  case MachineOperand::MO_SignExtendedImmed:
349  case MachineOperand::MO_UnextendedImmed:
350    std::cerr << "printOp() does not handle immediate values\n";
351    abort();
352    return;
353
354  case MachineOperand::MO_PCRelativeDisp:
355    std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
356    abort();
357    return;
358
359  case MachineOperand::MO_MachineBasicBlock: {
360    MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
361    O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
362      << "_" << MBBOp->getNumber() << "\t; "
363      << MBBOp->getBasicBlock()->getName();
364    return;
365  }
366
367  case MachineOperand::MO_ConstantPoolIndex:
368    O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
369    return;
370
371  case MachineOperand::MO_ExternalSymbol:
372    if (IsCallOp) {
373      std::string Name(GlobalPrefix); Name += MO.getSymbolName();
374      FnStubs.insert(Name);
375      O << "L" << Name << "$stub";
376      return;
377    }
378    O << GlobalPrefix << MO.getSymbolName();
379    return;
380
381  case MachineOperand::MO_GlobalAddress: {
382    GlobalValue *GV = MO.getGlobal();
383    std::string Name = Mang->getValueName(GV);
384
385    // Dynamically-resolved functions need a stub for the function.  Be
386    // wary however not to output $stub for external functions whose addresses
387    // are taken.  Those should be emitted as $non_lazy_ptr below.
388    Function *F = dyn_cast<Function>(GV);
389    if (F && IsCallOp && F->isExternal()) {
390      FnStubs.insert(Name);
391      O << "L" << Name << "$stub";
392      return;
393    }
394
395    // External or weakly linked global variables need non-lazily-resolved stubs
396    if ((GV->isExternal() || GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())){
397      if (GV->hasLinkOnceLinkage())
398        LinkOnceStubs.insert(Name);
399      else
400        GVStubs.insert(Name);
401      O << "L" << Name << "$non_lazy_ptr";
402      return;
403    }
404
405    O << Mang->getValueName(GV);
406    return;
407  }
408
409  default:
410    O << "<unknown operand type: " << MO.getType() << ">";
411    return;
412  }
413}
414
415/// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
416/// the current output stream.
417///
418void PowerPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
419  ++EmittedInsts;
420  // Check for slwi/srwi mnemonics.
421  if (MI->getOpcode() == PPC::RLWINM) {
422    bool FoundMnemonic = false;
423    unsigned char SH = MI->getOperand(2).getImmedValue();
424    unsigned char MB = MI->getOperand(3).getImmedValue();
425    unsigned char ME = MI->getOperand(4).getImmedValue();
426    if (SH <= 31 && MB == 0 && ME == (31-SH)) {
427      O << "slwi "; FoundMnemonic = true;
428    }
429    if (SH <= 31 && MB == (32-SH) && ME == 31) {
430      O << "srwi "; FoundMnemonic = true;
431      SH = 32-SH;
432    }
433    if (FoundMnemonic) {
434      printOperand(MI, 0, MVT::i64);
435      O << ", ";
436      printOperand(MI, 1, MVT::i64);
437      O << ", " << (unsigned int)SH << "\n";
438      return;
439    }
440  }
441
442  if (printInstruction(MI))
443    return; // Printer was automatically generated
444
445  assert(0 && "Unhandled instruction in asm writer!");
446  abort();
447  return;
448}
449
450/// runOnMachineFunction - This uses the printMachineInstruction()
451/// method to print assembly for each instruction.
452///
453bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
454  setupMachineFunction(MF);
455  O << "\n\n";
456
457  // Print out constants referenced by the function
458  printConstantPool(MF.getConstantPool());
459
460  // Print out labels for the function.
461  O << "\t.text\n";
462  emitAlignment(2);
463  O << "\t.globl\t" << CurrentFnName << "\n";
464  O << CurrentFnName << ":\n";
465
466  // Print out code for the function.
467  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
468       I != E; ++I) {
469    // Print a label for the basic block.
470    O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
471      << CommentString << " " << I->getBasicBlock()->getName() << "\n";
472    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
473         II != E; ++II) {
474      // Print the assembly for the instruction.
475      O << "\t";
476      printMachineInstruction(II);
477    }
478  }
479  ++LabelNumber;
480
481  // We didn't modify anything.
482  return false;
483}
484
485/// printConstantPool - Print to the current output stream assembly
486/// representations of the constants in the constant pool MCP. This is
487/// used to print out constants which have been "spilled to memory" by
488/// the code generator.
489///
490void DarwinAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
491  const std::vector<Constant*> &CP = MCP->getConstants();
492  const TargetData &TD = TM.getTargetData();
493
494  if (CP.empty()) return;
495
496  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
497    O << "\t.const\n";
498    emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
499    O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
500      << *CP[i] << "\n";
501    emitGlobalConstant(CP[i]);
502  }
503}
504
505bool DarwinAsmPrinter::doFinalization(Module &M) {
506  const TargetData &TD = TM.getTargetData();
507  std::string CurSection;
508
509  // Print out module-level global variables here.
510  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
511    if (I->hasInitializer()) {   // External global require no code
512      O << '\n';
513      std::string name = Mang->getValueName(I);
514      Constant *C = I->getInitializer();
515      unsigned Size = TD.getTypeSize(C->getType());
516      unsigned Align = TD.getTypeAlignmentShift(C->getType());
517
518      if (C->isNullValue() && /* FIXME: Verify correct */
519          (I->hasInternalLinkage() || I->hasWeakLinkage() ||
520           I->hasLinkOnceLinkage())) {
521        SwitchSection(O, CurSection, ".data");
522        if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
523        if (I->hasInternalLinkage())
524          O << ".lcomm " << name << "," << Size << "," << Align;
525        else
526          O << ".comm " << name << "," << Size;
527        O << "\t\t; ";
528        WriteAsOperand(O, I, true, true, &M);
529        O << '\n';
530      } else {
531        switch (I->getLinkage()) {
532        case GlobalValue::LinkOnceLinkage:
533          O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
534            << ".weak_definition " << name << '\n'
535            << ".private_extern " << name << '\n'
536            << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
537          LinkOnceStubs.insert(name);
538          break;
539        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
540          // Nonnull linkonce -> weak
541          O << "\t.weak " << name << "\n";
542          SwitchSection(O, CurSection, "");
543          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
544          break;
545        case GlobalValue::AppendingLinkage:
546          // FIXME: appending linkage variables should go into a section of
547          // their name or something.  For now, just emit them as external.
548        case GlobalValue::ExternalLinkage:
549          // If external or appending, declare as a global symbol
550          O << "\t.globl " << name << "\n";
551          // FALL THROUGH
552        case GlobalValue::InternalLinkage:
553          SwitchSection(O, CurSection, ".data");
554          break;
555        case GlobalValue::GhostLinkage:
556          std::cerr << "Error: unmaterialized (GhostLinkage) function in asm!";
557          abort();
558        }
559
560        emitAlignment(Align);
561        O << name << ":\t\t\t\t; ";
562        WriteAsOperand(O, I, true, true, &M);
563        O << " = ";
564        WriteAsOperand(O, C, false, false, &M);
565        O << "\n";
566        emitGlobalConstant(C);
567      }
568    }
569
570  // Output stubs for dynamically-linked functions
571  for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
572       i != e; ++i)
573  {
574    O << ".data\n";
575    O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
576    emitAlignment(2);
577    O << "L" << *i << "$stub:\n";
578    O << "\t.indirect_symbol " << *i << "\n";
579    O << "\tmflr r0\n";
580    O << "\tbcl 20,31,L0$" << *i << "\n";
581    O << "L0$" << *i << ":\n";
582    O << "\tmflr r11\n";
583    O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
584    O << "\tmtlr r0\n";
585    O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
586    O << "\tmtctr r12\n";
587    O << "\tbctr\n";
588    O << ".data\n";
589    O << ".lazy_symbol_pointer\n";
590    O << "L" << *i << "$lazy_ptr:\n";
591    O << "\t.indirect_symbol " << *i << "\n";
592    O << "\t.long dyld_stub_binding_helper\n";
593  }
594
595  O << "\n";
596
597  // Output stubs for external global variables
598  if (GVStubs.begin() != GVStubs.end())
599    O << ".data\n.non_lazy_symbol_pointer\n";
600  for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
601       i != e; ++i) {
602    O << "L" << *i << "$non_lazy_ptr:\n";
603    O << "\t.indirect_symbol " << *i << "\n";
604    O << "\t.long\t0\n";
605  }
606
607  // Output stubs for link-once variables
608  if (LinkOnceStubs.begin() != LinkOnceStubs.end())
609    O << ".data\n.align 2\n";
610  for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
611         e = LinkOnceStubs.end(); i != e; ++i) {
612    O << "L" << *i << "$non_lazy_ptr:\n"
613      << "\t.long\t" << *i << '\n';
614  }
615
616  AsmPrinter::doFinalization(M);
617  return false; // success
618}
619
620/// runOnMachineFunction - This uses the printMachineInstruction()
621/// method to print assembly for each instruction.
622///
623bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
624  CurrentFnName = MF.getFunction()->getName();
625
626  // Print out constants referenced by the function
627  printConstantPool(MF.getConstantPool());
628
629  // Print out header for the function.
630  O << "\t.csect .text[PR]\n"
631    << "\t.align 2\n"
632    << "\t.globl "  << CurrentFnName << '\n'
633    << "\t.globl ." << CurrentFnName << '\n'
634    << "\t.csect "  << CurrentFnName << "[DS],3\n"
635    << CurrentFnName << ":\n"
636    << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
637    << "\t.csect .text[PR]\n"
638    << '.' << CurrentFnName << ":\n";
639
640  // Print out code for the function.
641  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
642       I != E; ++I) {
643    // Print a label for the basic block.
644    O << "LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
645      << I->getBasicBlock()->getName() << "\n";
646    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
647      II != E; ++II) {
648      // Print the assembly for the instruction.
649      O << "\t";
650      printMachineInstruction(II);
651    }
652  }
653  ++LabelNumber;
654
655  O << "LT.." << CurrentFnName << ":\n"
656    << "\t.long 0\n"
657    << "\t.byte 0,0,32,65,128,0,0,0\n"
658    << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
659    << "\t.short 3\n"
660    << "\t.byte \"" << CurrentFnName << "\"\n"
661    << "\t.align 2\n";
662
663  // We didn't modify anything.
664  return false;
665}
666
667/// printConstantPool - Print to the current output stream assembly
668/// representations of the constants in the constant pool MCP. This is
669/// used to print out constants which have been "spilled to memory" by
670/// the code generator.
671///
672void AIXAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
673  const std::vector<Constant*> &CP = MCP->getConstants();
674  const TargetData &TD = TM.getTargetData();
675
676  if (CP.empty()) return;
677
678  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
679    O << "\t.const\n";
680    O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
681      << "\n";
682    O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
683      << *CP[i] << "\n";
684    emitGlobalConstant(CP[i]);
685  }
686}
687
688bool AIXAsmPrinter::doInitialization(Module &M) {
689  const TargetData &TD = TM.getTargetData();
690  std::string CurSection;
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(); I != E; ++I) {
698    if (!I->hasInitializer())
699      continue;
700
701    std::string Name = I->getName();
702    Constant *C = I->getInitializer();
703    // N.B.: We are defaulting to writable strings
704    if (I->hasExternalLinkage()) {
705      O << "\t.globl " << Name << '\n'
706        << "\t.csect .data[RW],3\n";
707    } else {
708      O << "\t.csect _global.rw_c[RW],3\n";
709    }
710    O << Name << ":\n";
711    emitGlobalConstant(C);
712  }
713
714  // Output labels for globals
715  if (M.global_begin() != M.global_end()) O << "\t.toc\n";
716  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) {
717    const GlobalVariable *GV = I;
718    // Do not output labels for unused variables
719    if (GV->isExternal() && GV->use_begin() == GV->use_end())
720      continue;
721
722    std::string Name = GV->getName();
723    std::string Label = "LC.." + utostr(LabelNumber++);
724    GVToLabelMap[GV] = Label;
725    O << Label << ":\n"
726      << "\t.tc " << Name << "[TC]," << Name;
727    if (GV->isExternal()) O << "[RW]";
728    O << '\n';
729  }
730
731  Mang = new Mangler(M, ".");
732  return false; // success
733}
734
735bool AIXAsmPrinter::doFinalization(Module &M) {
736  const TargetData &TD = TM.getTargetData();
737  // Print out module-level global variables
738  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) {
739    if (I->hasInitializer() || I->hasExternalLinkage())
740      continue;
741
742    std::string Name = I->getName();
743    if (I->hasInternalLinkage()) {
744      O << "\t.lcomm " << Name << ",16,_global.bss_c";
745    } else {
746      O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
747        << "," << log2((unsigned)TD.getTypeAlignment(I->getType()));
748    }
749    O << "\t\t# ";
750    WriteAsOperand(O, I, true, true, &M);
751    O << "\n";
752  }
753
754  O << "_section_.text:\n"
755    << "\t.csect .data[RW],3\n"
756    << "\t.llong _section_.text\n";
757
758  delete Mang;
759  return false; // success
760}
761