PPCAsmPrinter.cpp revision 0ea3171fbfaf78672264a9299c33c81c63b2a522
1//===-- PPC32AsmPrinter.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 "PowerPCInstrInfo.h"
22#include "PowerPCTargetMachine.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/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/CodeGen/ValueTypes.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Support/Mangler.h"
33#include "Support/CommandLine.h"
34#include "Support/Debug.h"
35#include "Support/Statistic.h"
36#include "Support/StringExtras.h"
37#include <set>
38
39namespace llvm {
40
41namespace {
42  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
43
44  struct PowerPCAsmPrinter : public MachineFunctionPass {
45    /// Output stream on which we're printing assembly code.
46    ///
47    std::ostream &O;
48
49    /// Target machine description which we query for reg. names, data
50    /// layout, etc.
51    ///
52    PowerPCTargetMachine &TM;
53
54    /// Name-mangler for global names.
55    ///
56    Mangler *Mang;
57    std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
58    std::set<std::string> Strings;
59
60    PowerPCAsmPrinter(std::ostream &o, TargetMachine &tm) : O(o),
61      TM(reinterpret_cast<PowerPCTargetMachine&>(tm)), LabelNumber(0) {}
62
63    /// Cache of mangled name for current function. This is
64    /// recalculated at the beginning of each call to
65    /// runOnMachineFunction().
66    ///
67    std::string CurrentFnName;
68
69    /// Unique incrementer for label values for referencing Global values.
70    ///
71    unsigned LabelNumber;
72
73    virtual const char *getPassName() const {
74      return "PowerPC Assembly Printer";
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, bool LoadAddrOp = false);
85    void printImmOp(const MachineOperand &MO, unsigned ArgType);
86
87    void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
88      const MachineOperand &MO = MI->getOperand(OpNo);
89      if (MO.getType() == MachineOperand::MO_MachineRegister) {
90        assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
91        O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
92      } else if (MO.isImmediate()) {
93        O << MO.getImmedValue();
94      } else {
95        printOp(MO);
96      }
97    }
98
99    void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
100                            MVT::ValueType VT) {
101      O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
102    }
103
104    void printConstantPool(MachineConstantPool *MCP);
105    bool runOnMachineFunction(MachineFunction &F);
106    bool doInitialization(Module &M);
107    bool doFinalization(Module &M);
108    void emitGlobalConstant(const Constant* CV);
109    void emitConstantValueOnly(const Constant *CV);
110  };
111} // end of anonymous namespace
112
113/// createPPC32AsmPrinterPass - Returns a pass that prints the PPC
114/// assembly code for a MachineFunction to the given output stream,
115/// using the given target machine description.  This should work
116/// regardless of whether the function is in SSA form or not.
117///
118FunctionPass *createPPCAsmPrinter(std::ostream &o,TargetMachine &tm) {
119  return new PowerPCAsmPrinter(o, tm);
120}
121
122// Include the auto-generated portion of the assembly writer
123#include "PowerPCGenAsmWriter.inc"
124
125/// isStringCompatible - Can we treat the specified array as a string?
126/// Only if it is an array of ubytes or non-negative sbytes.
127///
128static bool isStringCompatible(const ConstantArray *CVA) {
129  const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
130  if (ETy == Type::UByteTy) return true;
131  if (ETy != Type::SByteTy) return false;
132
133  for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
134    if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
135      return false;
136
137  return true;
138}
139
140/// toOctal - Convert the low order bits of X into an octal digit.
141///
142static inline char toOctal(int X) {
143  return (X&7)+'0';
144}
145
146/// getAsCString - Return the specified array as a C compatible
147/// string, only if the predicate isStringCompatible is true.
148///
149static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
150  assert(isStringCompatible(CVA) && "Array is not string compatible!");
151
152  O << "\"";
153  for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
154    unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
155
156    if (C == '"') {
157      O << "\\\"";
158    } else if (C == '\\') {
159      O << "\\\\";
160    } else if (isprint(C)) {
161      O << C;
162    } else {
163      switch (C) {
164      case '\b': O << "\\b"; break;
165      case '\f': O << "\\f"; break;
166      case '\n': O << "\\n"; break;
167      case '\r': O << "\\r"; break;
168      case '\t': O << "\\t"; break;
169      default:
170        O << '\\';
171        O << toOctal(C >> 6);
172        O << toOctal(C >> 3);
173        O << toOctal(C >> 0);
174        break;
175      }
176    }
177  }
178  O << "\"";
179}
180
181// Print out the specified constant, without a storage class.  Only the
182// constants valid in constant expressions can occur here.
183void PowerPCAsmPrinter::emitConstantValueOnly(const Constant *CV) {
184  if (CV->isNullValue())
185    O << "0";
186  else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
187    assert(CB == ConstantBool::True);
188    O << "1";
189  } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
190    O << CI->getValue();
191  else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
192    O << CI->getValue();
193  else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
194    // This is a constant address for a global variable or function.  Use the
195    // name of the variable or function as the address value.
196    O << Mang->getValueName(GV);
197  else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
198    const TargetData &TD = TM.getTargetData();
199    switch (CE->getOpcode()) {
200    case Instruction::GetElementPtr: {
201      // generate a symbolic expression for the byte address
202      const Constant *ptrVal = CE->getOperand(0);
203      std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
204      if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
205        O << "(";
206        emitConstantValueOnly(ptrVal);
207        O << ") + " << Offset;
208      } else {
209        emitConstantValueOnly(ptrVal);
210      }
211      break;
212    }
213    case Instruction::Cast: {
214      // Support only non-converting or widening casts for now, that is, ones
215      // that do not involve a change in value.  This assertion is really gross,
216      // and may not even be a complete check.
217      Constant *Op = CE->getOperand(0);
218      const Type *OpTy = Op->getType(), *Ty = CE->getType();
219
220      // Remember, kids, pointers on x86 can be losslessly converted back and
221      // forth into 32-bit or wider integers, regardless of signedness. :-P
222      assert(((isa<PointerType>(OpTy)
223               && (Ty == Type::LongTy || Ty == Type::ULongTy
224                   || Ty == Type::IntTy || Ty == Type::UIntTy))
225              || (isa<PointerType>(Ty)
226                  && (OpTy == Type::LongTy || OpTy == Type::ULongTy
227                      || OpTy == Type::IntTy || OpTy == Type::UIntTy))
228              || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
229                   && OpTy->isLosslesslyConvertibleTo(Ty))))
230             && "FIXME: Don't yet support this kind of constant cast expr");
231      O << "(";
232      emitConstantValueOnly(Op);
233      O << ")";
234      break;
235    }
236    case Instruction::Add:
237      O << "(";
238      emitConstantValueOnly(CE->getOperand(0));
239      O << ") + (";
240      emitConstantValueOnly(CE->getOperand(1));
241      O << ")";
242      break;
243    default:
244      assert(0 && "Unsupported operator!");
245    }
246  } else {
247    assert(0 && "Unknown constant value!");
248  }
249}
250
251// Print a constant value or values, with the appropriate storage class as a
252// prefix.
253void PowerPCAsmPrinter::emitGlobalConstant(const Constant *CV) {
254  const TargetData &TD = TM.getTargetData();
255
256  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
257    if (isStringCompatible(CVA)) {
258      O << "\t.ascii ";
259      printAsCString(O, CVA);
260      O << "\n";
261    } else { // Not a string.  Print the values in successive locations
262      for (unsigned i=0, e = CVA->getNumOperands(); i != e; i++)
263        emitGlobalConstant(CVA->getOperand(i));
264    }
265    return;
266  } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
267    // Print the fields in successive locations. Pad to align if needed!
268    const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
269    unsigned sizeSoFar = 0;
270    for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
271      const Constant* field = CVS->getOperand(i);
272
273      // Check if padding is needed and insert one or more 0s.
274      unsigned fieldSize = TD.getTypeSize(field->getType());
275      unsigned padSize = ((i == e-1? cvsLayout->StructSize
276                           : cvsLayout->MemberOffsets[i+1])
277                          - cvsLayout->MemberOffsets[i]) - fieldSize;
278      sizeSoFar += fieldSize + padSize;
279
280      // Now print the actual field value
281      emitGlobalConstant(field);
282
283      // Insert the field padding unless it's zero bytes...
284      if (padSize)
285        O << "\t.space\t " << padSize << "\n";
286    }
287    assert(sizeSoFar == cvsLayout->StructSize &&
288           "Layout of constant struct may be incorrect!");
289    return;
290  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
291    // FP Constants are printed as integer constants to avoid losing
292    // precision...
293    double Val = CFP->getValue();
294    union DU {                            // Abide by C TBAA rules
295      double FVal;
296      uint64_t UVal;
297      struct {
298        uint32_t MSWord;
299        uint32_t LSWord;
300      } T;
301    } U;
302    U.FVal = Val;
303
304    O << ".long\t" << U.T.MSWord << "\t; double most significant word "
305      << Val << "\n";
306    O << ".long\t" << U.T.LSWord << "\t; double least significant word "
307      << Val << "\n";
308    return;
309  } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
310    if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
311      union DU {                            // Abide by C TBAA rules
312        int64_t UVal;
313        struct {
314          uint32_t MSWord;
315          uint32_t LSWord;
316        } T;
317      } U;
318      U.UVal = CI->getRawValue();
319
320      O << ".long\t" << U.T.MSWord << "\t; Double-word most significant word "
321        << U.UVal << "\n";
322      O << ".long\t" << U.T.LSWord << "\t; Double-word least significant word "
323        << U.UVal << "\n";
324      return;
325    }
326  }
327
328  const Type *type = CV->getType();
329  O << "\t";
330  switch (type->getTypeID()) {
331  case Type::UByteTyID: case Type::SByteTyID:
332    O << ".byte";
333    break;
334  case Type::UShortTyID: case Type::ShortTyID:
335    O << ".short";
336    break;
337  case Type::BoolTyID:
338  case Type::PointerTyID:
339  case Type::UIntTyID: case Type::IntTyID:
340    O << ".long";
341    break;
342  case Type::ULongTyID: case Type::LongTyID:
343    assert (0 && "Should have already output double-word constant.");
344  case Type::FloatTyID: case Type::DoubleTyID:
345    assert (0 && "Should have already output floating point constant.");
346  default:
347    if (CV == Constant::getNullValue(type)) {  // Zero initializer?
348      O << ".space\t" << TD.getTypeSize(type) << "\n";
349      return;
350    }
351    std::cerr << "Can't handle printing: " << *CV;
352    abort();
353    break;
354  }
355  O << "\t";
356  emitConstantValueOnly(CV);
357  O << "\n";
358}
359
360/// printConstantPool - Print to the current output stream assembly
361/// representations of the constants in the constant pool MCP. This is
362/// used to print out constants which have been "spilled to memory" by
363/// the code generator.
364///
365void PowerPCAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
366  const std::vector<Constant*> &CP = MCP->getConstants();
367  const TargetData &TD = TM.getTargetData();
368
369  if (CP.empty()) return;
370
371  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
372    O << "\t.const\n";
373    O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
374      << "\n";
375    O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
376      << *CP[i] << "\n";
377    emitGlobalConstant(CP[i]);
378  }
379}
380
381/// runOnMachineFunction - This uses the printMachineInstruction()
382/// method to print assembly for each instruction.
383///
384bool PowerPCAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
385  O << "\n\n";
386  // What's my mangled name?
387  CurrentFnName = Mang->getValueName(MF.getFunction());
388
389  // Print out constants referenced by the function
390  printConstantPool(MF.getConstantPool());
391
392  // Print out labels for the function.
393  O << "\t.text\n";
394  O << "\t.globl\t" << CurrentFnName << "\n";
395  O << "\t.align 2\n";
396  O << CurrentFnName << ":\n";
397
398  // Print out code for the function.
399  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
400       I != E; ++I) {
401    // Print a label for the basic block.
402    O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
403      << I->getBasicBlock()->getName() << "\n";
404    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
405      II != E; ++II) {
406      // Print the assembly for the instruction.
407      O << "\t";
408      printMachineInstruction(II);
409    }
410  }
411  ++LabelNumber;
412
413  // We didn't modify anything.
414  return false;
415}
416
417void PowerPCAsmPrinter::printOp(const MachineOperand &MO,
418                      bool LoadAddrOp /* = false */) {
419  const MRegisterInfo &RI = *TM.getRegisterInfo();
420  int new_symbol;
421
422  switch (MO.getType()) {
423  case MachineOperand::MO_VirtualRegister:
424    if (Value *V = MO.getVRegValueOrNull()) {
425      O << "<" << V->getName() << ">";
426      return;
427    }
428    // FALLTHROUGH
429  case MachineOperand::MO_MachineRegister:
430  case MachineOperand::MO_CCRegister:
431    O << LowercaseString(RI.get(MO.getReg()).Name);
432    return;
433
434  case MachineOperand::MO_SignExtendedImmed:
435  case MachineOperand::MO_UnextendedImmed:
436    std::cerr << "printOp() does not handle immediate values\n";
437    abort();
438    return;
439
440  case MachineOperand::MO_PCRelativeDisp:
441    std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
442    abort();
443    return;
444
445  case MachineOperand::MO_MachineBasicBlock: {
446    MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
447    O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
448      << "_" << MBBOp->getNumber() << "\t; "
449      << MBBOp->getBasicBlock()->getName();
450    return;
451  }
452
453  case MachineOperand::MO_ConstantPoolIndex:
454    O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
455    return;
456
457  case MachineOperand::MO_ExternalSymbol:
458    O << MO.getSymbolName();
459    return;
460
461  case MachineOperand::MO_GlobalAddress: {
462    GlobalValue *GV = MO.getGlobal();
463    std::string Name = Mang->getValueName(GV);
464
465    // Dynamically-resolved functions need a stub for the function.  Be
466    // wary however not to output $stub for external functions whose addresses
467    // are taken.  Those should be emitted as $non_lazy_ptr below.
468    Function *F = dyn_cast<Function>(GV);
469    if (F && F->isExternal() && !LoadAddrOp &&
470        TM.CalledFunctions.find(F) != TM.CalledFunctions.end()) {
471      FnStubs.insert(Name);
472      O << "L" << Name << "$stub";
473      return;
474    }
475
476    // External global variables need a non-lazily-resolved stub
477    if (GV->isExternal() && TM.AddressTaken.find(GV) != TM.AddressTaken.end()) {
478      GVStubs.insert(Name);
479      O << "L" << Name << "$non_lazy_ptr";
480      return;
481    }
482
483    if (F && LoadAddrOp && TM.AddressTaken.find(GV) != TM.AddressTaken.end()) {
484      LinkOnceStubs.insert(Name);
485      O << "L" << Name << "$non_lazy_ptr";
486      return;
487    }
488
489    O << Mang->getValueName(GV);
490    return;
491  }
492
493  default:
494    O << "<unknown operand type: " << MO.getType() << ">";
495    return;
496  }
497}
498
499void PowerPCAsmPrinter::printImmOp(const MachineOperand &MO, unsigned ArgType) {
500  int Imm = MO.getImmedValue();
501  if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
502    O << (short)Imm;
503  } else if (ArgType == PPCII::Zimm16) {
504    O << (unsigned short)Imm;
505  } else {
506    O << Imm;
507  }
508}
509
510/// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
511/// the current output stream.
512///
513void PowerPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
514  ++EmittedInsts;
515  if (printInstruction(MI))
516    return; // Printer was automatically generated
517
518  unsigned Opcode = MI->getOpcode();
519  const TargetInstrInfo &TII = *TM.getInstrInfo();
520  const TargetInstrDescriptor &Desc = TII.get(Opcode);
521  unsigned i;
522
523  unsigned ArgCount = MI->getNumOperands();
524  unsigned ArgType[] = {
525    (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
526    (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
527    (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
528    (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
529    (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
530  };
531  assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
532         "Instruction requires VMX support");
533  assert(((Desc.TSFlags & PPCII::PPC64) == 0) &&
534         "Instruction requires 64 bit support");
535
536  // CALLpcrel and CALLindirect are handled specially here to print only the
537  // appropriate number of args that the assembler expects.  This is because
538  // may have many arguments appended to record the uses of registers that are
539  // holding arguments to the called function.
540  if (Opcode == PPC::COND_BRANCH) {
541    std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
542    abort();
543  } else if (Opcode == PPC::IMPLICIT_DEF) {
544    O << "; IMPLICIT DEF ";
545    printOp(MI->getOperand(0));
546    O << "\n";
547    return;
548  } else if (Opcode == PPC::CALLpcrel) {
549    O << TII.getName(Opcode) << " ";
550    printOp(MI->getOperand(0));
551    O << "\n";
552    return;
553  } else if (Opcode == PPC::CALLindirect) {
554    O << TII.getName(Opcode) << " ";
555    printImmOp(MI->getOperand(0), ArgType[0]);
556    O << ", ";
557    printImmOp(MI->getOperand(1), ArgType[0]);
558    O << "\n";
559    return;
560  } else if (Opcode == PPC::MovePCtoLR) {
561    // FIXME: should probably be converted to cout.width and cout.fill
562    O << "bl \"L0000" << LabelNumber << "$pb\"\n";
563    O << "\"L0000" << LabelNumber << "$pb\":\n";
564    O << "\tmflr ";
565    printOp(MI->getOperand(0));
566    O << "\n";
567    return;
568  }
569
570  O << TII.getName(Opcode) << " ";
571  if (Opcode == PPC::LOADLoDirect || Opcode == PPC::LOADLoIndirect) {
572    printOp(MI->getOperand(0));
573    O << ", lo16(";
574    printOp(MI->getOperand(2), true /* LoadAddrOp */);
575    O << "-\"L0000" << LabelNumber << "$pb\")";
576    O << "(";
577    if (MI->getOperand(1).getReg() == PPC::R0)
578      O << "0";
579    else
580      printOp(MI->getOperand(1));
581    O << ")\n";
582  } else if (Opcode == PPC::LOADHiAddr) {
583    printOp(MI->getOperand(0));
584    O << ", ";
585    if (MI->getOperand(1).getReg() == PPC::R0)
586      O << "0";
587    else
588      printOp(MI->getOperand(1));
589    O << ", ha16(" ;
590    printOp(MI->getOperand(2), true /* LoadAddrOp */);
591     O << "-\"L0000" << LabelNumber << "$pb\")\n";
592  } else if (ArgCount == 3 && ArgType[1] == PPCII::Disimm16) {
593    printOp(MI->getOperand(0));
594    O << ", ";
595    printImmOp(MI->getOperand(1), ArgType[1]);
596    O << "(";
597    if (MI->getOperand(2).hasAllocatedReg() &&
598        MI->getOperand(2).getReg() == PPC::R0)
599      O << "0";
600    else
601      printOp(MI->getOperand(2));
602    O << ")\n";
603  } else {
604    for (i = 0; i < ArgCount; ++i) {
605      // addi and friends
606      if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
607          MI->getOperand(1).hasAllocatedReg() &&
608          MI->getOperand(1).getReg() == PPC::R0) {
609        O << "0";
610      // for long branch support, bc $+8
611      } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
612                 TII.isBranch(MI->getOpcode())) {
613        O << "$+8";
614        assert(8 == MI->getOperand(i).getImmedValue()
615          && "branch off PC not to pc+8?");
616        //printOp(MI->getOperand(i));
617      } else if (MI->getOperand(i).isImmediate()) {
618        printImmOp(MI->getOperand(i), ArgType[i]);
619      } else {
620        printOp(MI->getOperand(i));
621      }
622      if (ArgCount - 1 == i)
623        O << "\n";
624      else
625        O << ", ";
626    }
627  }
628  return;
629}
630
631bool PowerPCAsmPrinter::doInitialization(Module &M) {
632  Mang = new Mangler(M, true);
633  return false; // success
634}
635
636// SwitchSection - Switch to the specified section of the executable if we are
637// not already in it!
638//
639static void SwitchSection(std::ostream &OS, std::string &CurSection,
640                          const char *NewSection) {
641  if (CurSection != NewSection) {
642    CurSection = NewSection;
643    if (!CurSection.empty())
644      OS << "\t" << NewSection << "\n";
645  }
646}
647
648bool PowerPCAsmPrinter::doFinalization(Module &M) {
649  const TargetData &TD = TM.getTargetData();
650  std::string CurSection;
651
652  // Print out module-level global variables here.
653  for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
654    if (I->hasInitializer()) {   // External global require no code
655      O << "\n\n";
656      std::string name = Mang->getValueName(I);
657      Constant *C = I->getInitializer();
658      unsigned Size = TD.getTypeSize(C->getType());
659      unsigned Align = TD.getTypeAlignment(C->getType());
660
661      if (C->isNullValue() && /* FIXME: Verify correct */
662          (I->hasInternalLinkage() || I->hasWeakLinkage())) {
663        SwitchSection(O, CurSection, ".data");
664        if (I->hasInternalLinkage())
665          O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
666            << "," << (unsigned)TD.getTypeAlignment(C->getType());
667        else
668          O << ".comm " << name << "," << TD.getTypeSize(C->getType());
669        O << "\t\t; ";
670        WriteAsOperand(O, I, true, true, &M);
671        O << "\n";
672      } else {
673        switch (I->getLinkage()) {
674        case GlobalValue::LinkOnceLinkage:
675          O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
676            << ".weak_definition " << name << '\n'
677            << ".private_extern " << name << '\n'
678            << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
679          LinkOnceStubs.insert(name);
680          break;
681        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
682          // Nonnull linkonce -> weak
683          O << "\t.weak " << name << "\n";
684          SwitchSection(O, CurSection, "");
685          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
686          break;
687        case GlobalValue::AppendingLinkage:
688          // FIXME: appending linkage variables should go into a section of
689          // their name or something.  For now, just emit them as external.
690        case GlobalValue::ExternalLinkage:
691          // If external or appending, declare as a global symbol
692          O << "\t.globl " << name << "\n";
693          // FALL THROUGH
694        case GlobalValue::InternalLinkage:
695          SwitchSection(O, CurSection, ".data");
696          break;
697        }
698
699        O << "\t.align " << Align << "\n";
700        O << name << ":\t\t\t\t; ";
701        WriteAsOperand(O, I, true, true, &M);
702        O << " = ";
703        WriteAsOperand(O, C, false, false, &M);
704        O << "\n";
705        emitGlobalConstant(C);
706      }
707    }
708
709  // Output stubs for dynamically-linked functions
710  for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
711       i != e; ++i)
712  {
713    O << ".data\n";
714    O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
715    O << "\t.align 2\n";
716    O << "L" << *i << "$stub:\n";
717    O << "\t.indirect_symbol " << *i << "\n";
718    O << "\tmflr r0\n";
719    O << "\tbcl 20,31,L0$" << *i << "\n";
720    O << "L0$" << *i << ":\n";
721    O << "\tmflr r11\n";
722    O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
723    O << "\tmtlr r0\n";
724    O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
725    O << "\tmtctr r12\n";
726    O << "\tbctr\n";
727    O << ".data\n";
728    O << ".lazy_symbol_pointer\n";
729    O << "L" << *i << "$lazy_ptr:\n";
730    O << "\t.indirect_symbol " << *i << "\n";
731    O << "\t.long dyld_stub_binding_helper\n";
732  }
733
734  O << "\n";
735
736  // Output stubs for external global variables
737  if (GVStubs.begin() != GVStubs.end())
738    O << ".data\n.non_lazy_symbol_pointer\n";
739  for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
740       i != e; ++i) {
741    O << "L" << *i << "$non_lazy_ptr:\n";
742    O << "\t.indirect_symbol " << *i << "\n";
743    O << "\t.long\t0\n";
744  }
745
746  // Output stubs for link-once variables
747  if (LinkOnceStubs.begin() != LinkOnceStubs.end())
748    O << ".data\n.align 2\n";
749  for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
750         e = LinkOnceStubs.end(); i != e; ++i) {
751    O << "L" << *i << "$non_lazy_ptr:\n"
752      << "\t.long\t" << *i << '\n';
753  }
754
755  delete Mang;
756  return false; // success
757}
758
759} // End llvm namespace
760