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