AsmPrinter.cpp revision ff592eced3d70159de10c5a3837e0d0fee7edb8f
1//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/AsmPrinter.h"
15#include "llvm/Assembly/Writer.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Constants.h"
18#include "llvm/Module.h"
19#include "llvm/CodeGen/GCMetadataPrinter.h"
20#include "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineJumpTableInfo.h"
23#include "llvm/CodeGen/MachineLoopInfo.h"
24#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/CodeGen/DwarfWriter.h"
26#include "llvm/Analysis/DebugInfo.h"
27#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCSection.h"
30#include "llvm/MC/MCStreamer.h"
31#include "llvm/MC/MCSymbol.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/FormattedStream.h"
35#include "llvm/Support/Mangler.h"
36#include "llvm/MC/MCAsmInfo.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetLowering.h"
39#include "llvm/Target/TargetLoweringObjectFile.h"
40#include "llvm/Target/TargetOptions.h"
41#include "llvm/Target/TargetRegisterInfo.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallString.h"
44#include "llvm/ADT/StringExtras.h"
45#include <cerrno>
46using namespace llvm;
47
48static cl::opt<cl::boolOrDefault>
49AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
50           cl::init(cl::BOU_UNSET));
51
52char AsmPrinter::ID = 0;
53AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
54                       const MCAsmInfo *T, bool VDef)
55  : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
56    TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
57
58    OutContext(*new MCContext()),
59    // FIXME: Pass instprinter to streamer.
60    OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)),
61
62    LastMI(0), LastFn(0), Counter(~0U),
63    PrevDLT(0, 0, ~0U, ~0U) {
64  DW = 0; MMI = 0;
65  switch (AsmVerbose) {
66  case cl::BOU_UNSET: VerboseAsm = VDef;  break;
67  case cl::BOU_TRUE:  VerboseAsm = true;  break;
68  case cl::BOU_FALSE: VerboseAsm = false; break;
69  }
70}
71
72AsmPrinter::~AsmPrinter() {
73  for (gcp_iterator I = GCMetadataPrinters.begin(),
74                    E = GCMetadataPrinters.end(); I != E; ++I)
75    delete I->second;
76
77  delete &OutStreamer;
78  delete &OutContext;
79}
80
81TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
82  return TM.getTargetLowering()->getObjFileLowering();
83}
84
85/// getCurrentSection() - Return the current section we are emitting to.
86const MCSection *AsmPrinter::getCurrentSection() const {
87  return OutStreamer.getCurrentSection();
88}
89
90
91void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
92  AU.setPreservesAll();
93  MachineFunctionPass::getAnalysisUsage(AU);
94  AU.addRequired<GCModuleInfo>();
95  if (VerboseAsm)
96    AU.addRequired<MachineLoopInfo>();
97}
98
99bool AsmPrinter::doInitialization(Module &M) {
100  // Initialize TargetLoweringObjectFile.
101  const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
102    .Initialize(OutContext, TM);
103
104  Mang = new Mangler(M, MAI->getGlobalPrefix(), MAI->getPrivateGlobalPrefix(),
105                     MAI->getLinkerPrivateGlobalPrefix());
106
107  if (MAI->doesAllowQuotesInName())
108    Mang->setUseQuotes(true);
109
110  if (MAI->doesAllowNameToStartWithDigit())
111    Mang->setSymbolsCanStartWithDigit(true);
112
113  // Allow the target to emit any magic that it wants at the start of the file.
114  EmitStartOfAsmFile(M);
115
116  if (MAI->hasSingleParameterDotFile()) {
117    /* Very minimal debug info. It is ignored if we emit actual
118       debug info. If we don't, this at least helps the user find where
119       a function came from. */
120    O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
121  }
122
123  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
124  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
125  for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
126    if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
127      MP->beginAssembly(O, *this, *MAI);
128
129  if (!M.getModuleInlineAsm().empty())
130    O << MAI->getCommentString() << " Start of file scope inline assembly\n"
131      << M.getModuleInlineAsm()
132      << '\n' << MAI->getCommentString()
133      << " End of file scope inline assembly\n";
134
135  MMI = getAnalysisIfAvailable<MachineModuleInfo>();
136  if (MMI)
137    MMI->AnalyzeModule(M);
138  DW = getAnalysisIfAvailable<DwarfWriter>();
139  if (DW)
140    DW->BeginModule(&M, MMI, O, this, MAI);
141
142  return false;
143}
144
145bool AsmPrinter::doFinalization(Module &M) {
146  // Emit global variables.
147  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
148       I != E; ++I)
149    PrintGlobalVariable(I);
150
151  // Emit final debug information.
152  if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
153    DW->EndModule();
154
155  // If the target wants to know about weak references, print them all.
156  if (MAI->getWeakRefDirective()) {
157    // FIXME: This is not lazy, it would be nice to only print weak references
158    // to stuff that is actually used.  Note that doing so would require targets
159    // to notice uses in operands (due to constant exprs etc).  This should
160    // happen with the MC stuff eventually.
161
162    // Print out module-level global variables here.
163    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
164         I != E; ++I) {
165      if (I->hasExternalWeakLinkage())
166        O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
167    }
168
169    for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
170      if (I->hasExternalWeakLinkage())
171        O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
172    }
173  }
174
175  if (MAI->getSetDirective()) {
176    O << '\n';
177    for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
178         I != E; ++I) {
179      std::string Name = Mang->getMangledName(I);
180
181      const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
182      std::string Target = Mang->getMangledName(GV);
183
184      if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
185        O << "\t.globl\t" << Name << '\n';
186      else if (I->hasWeakLinkage())
187        O << MAI->getWeakRefDirective() << Name << '\n';
188      else if (!I->hasLocalLinkage())
189        llvm_unreachable("Invalid alias linkage");
190
191      printVisibility(Name, I->getVisibility());
192
193      O << MAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
194    }
195  }
196
197  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
198  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
199  for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
200    if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
201      MP->finishAssembly(O, *this, *MAI);
202
203  // If we don't have any trampolines, then we don't require stack memory
204  // to be executable. Some targets have a directive to declare this.
205  Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
206  if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
207    if (MAI->getNonexecutableStackDirective())
208      O << MAI->getNonexecutableStackDirective() << '\n';
209
210
211  // Allow the target to emit any magic that it wants at the end of the file,
212  // after everything else has gone out.
213  EmitEndOfAsmFile(M);
214
215  delete Mang; Mang = 0;
216  DW = 0; MMI = 0;
217
218  OutStreamer.Finish();
219  return false;
220}
221
222void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
223  // What's my mangled name?
224  CurrentFnName = Mang->getMangledName(MF.getFunction());
225  IncrementFunctionNumber();
226
227  if (VerboseAsm)
228    LI = &getAnalysis<MachineLoopInfo>();
229}
230
231namespace {
232  // SectionCPs - Keep track the alignment, constpool entries per Section.
233  struct SectionCPs {
234    const MCSection *S;
235    unsigned Alignment;
236    SmallVector<unsigned, 4> CPEs;
237    SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
238  };
239}
240
241/// EmitConstantPool - Print to the current output stream assembly
242/// representations of the constants in the constant pool MCP. This is
243/// used to print out constants which have been "spilled to memory" by
244/// the code generator.
245///
246void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
247  const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
248  if (CP.empty()) return;
249
250  // Calculate sections for constant pool entries. We collect entries to go into
251  // the same section together to reduce amount of section switch statements.
252  SmallVector<SectionCPs, 4> CPSections;
253  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
254    const MachineConstantPoolEntry &CPE = CP[i];
255    unsigned Align = CPE.getAlignment();
256
257    SectionKind Kind;
258    switch (CPE.getRelocationInfo()) {
259    default: llvm_unreachable("Unknown section kind");
260    case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
261    case 1:
262      Kind = SectionKind::getReadOnlyWithRelLocal();
263      break;
264    case 0:
265    switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
266    case 4:  Kind = SectionKind::getMergeableConst4(); break;
267    case 8:  Kind = SectionKind::getMergeableConst8(); break;
268    case 16: Kind = SectionKind::getMergeableConst16();break;
269    default: Kind = SectionKind::getMergeableConst(); break;
270    }
271    }
272
273    const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
274
275    // The number of sections are small, just do a linear search from the
276    // last section to the first.
277    bool Found = false;
278    unsigned SecIdx = CPSections.size();
279    while (SecIdx != 0) {
280      if (CPSections[--SecIdx].S == S) {
281        Found = true;
282        break;
283      }
284    }
285    if (!Found) {
286      SecIdx = CPSections.size();
287      CPSections.push_back(SectionCPs(S, Align));
288    }
289
290    if (Align > CPSections[SecIdx].Alignment)
291      CPSections[SecIdx].Alignment = Align;
292    CPSections[SecIdx].CPEs.push_back(i);
293  }
294
295  // Now print stuff into the calculated sections.
296  for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
297    OutStreamer.SwitchSection(CPSections[i].S);
298    EmitAlignment(Log2_32(CPSections[i].Alignment));
299
300    unsigned Offset = 0;
301    for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
302      unsigned CPI = CPSections[i].CPEs[j];
303      MachineConstantPoolEntry CPE = CP[CPI];
304
305      // Emit inter-object padding for alignment.
306      unsigned AlignMask = CPE.getAlignment() - 1;
307      unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
308      EmitZeros(NewOffset - Offset);
309
310      const Type *Ty = CPE.getType();
311      Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
312
313      O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
314        << CPI << ':';
315      if (VerboseAsm) {
316        O.PadToColumn(MAI->getCommentColumn());
317        O << MAI->getCommentString() << " constant ";
318        WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
319      }
320      O << '\n';
321      if (CPE.isMachineConstantPoolEntry())
322        EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
323      else
324        EmitGlobalConstant(CPE.Val.ConstVal);
325    }
326  }
327}
328
329/// EmitJumpTableInfo - Print assembly representations of the jump tables used
330/// by the current function to the current output stream.
331///
332void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
333                                   MachineFunction &MF) {
334  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
335  if (JT.empty()) return;
336
337  bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
338
339  // Pick the directive to use to print the jump table entries, and switch to
340  // the appropriate section.
341  TargetLowering *LoweringInfo = TM.getTargetLowering();
342
343  const Function *F = MF.getFunction();
344  bool JTInDiffSection = false;
345  if (F->isWeakForLinker() ||
346      (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
347    // In PIC mode, we need to emit the jump table to the same section as the
348    // function body itself, otherwise the label differences won't make sense.
349    // We should also do if the section name is NULL or function is declared in
350    // discardable section.
351    OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
352                                                                    TM));
353  } else {
354    // Otherwise, drop it in the readonly section.
355    const MCSection *ReadOnlySection =
356      getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
357    OutStreamer.SwitchSection(ReadOnlySection);
358    JTInDiffSection = true;
359  }
360
361  EmitAlignment(Log2_32(MJTI->getAlignment()));
362
363  for (unsigned i = 0, e = JT.size(); i != e; ++i) {
364    const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
365
366    // If this jump table was deleted, ignore it.
367    if (JTBBs.empty()) continue;
368
369    // For PIC codegen, if possible we want to use the SetDirective to reduce
370    // the number of relocations the assembler will generate for the jump table.
371    // Set directives are all printed before the jump table itself.
372    SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
373    if (MAI->getSetDirective() && IsPic)
374      for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
375        if (EmittedSets.insert(JTBBs[ii]))
376          printPICJumpTableSetLabel(i, JTBBs[ii]);
377
378    // On some targets (e.g. Darwin) we want to emit two consequtive labels
379    // before each jump table.  The first label is never referenced, but tells
380    // the assembler and linker the extents of the jump table object.  The
381    // second label is actually referenced by the code.
382    if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
383      O << MAI->getLinkerPrivateGlobalPrefix()
384        << "JTI" << getFunctionNumber() << '_' << i << ":\n";
385    }
386
387    O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
388      << '_' << i << ":\n";
389
390    for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
391      printPICJumpTableEntry(MJTI, JTBBs[ii], i);
392      O << '\n';
393    }
394  }
395}
396
397void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
398                                        const MachineBasicBlock *MBB,
399                                        unsigned uid)  const {
400  bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
401
402  // Use JumpTableDirective otherwise honor the entry size from the jump table
403  // info.
404  const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
405  bool HadJTEntryDirective = JTEntryDirective != NULL;
406  if (!HadJTEntryDirective) {
407    JTEntryDirective = MJTI->getEntrySize() == 4 ?
408      MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
409  }
410
411  O << JTEntryDirective << ' ';
412
413  // If we have emitted set directives for the jump table entries, print
414  // them rather than the entries themselves.  If we're emitting PIC, then
415  // emit the table entries as differences between two text section labels.
416  // If we're emitting non-PIC code, then emit the entries as direct
417  // references to the target basic blocks.
418  if (!isPIC) {
419    GetMBBSymbol(MBB->getNumber())->print(O, MAI);
420  } else if (MAI->getSetDirective()) {
421    O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
422      << '_' << uid << "_set_" << MBB->getNumber();
423  } else {
424    GetMBBSymbol(MBB->getNumber())->print(O, MAI);
425    // If the arch uses custom Jump Table directives, don't calc relative to
426    // JT
427    if (!HadJTEntryDirective)
428      O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
429        << getFunctionNumber() << '_' << uid;
430  }
431}
432
433
434/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
435/// special global used by LLVM.  If so, emit it and return true, otherwise
436/// do nothing and return false.
437bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
438  if (GV->getName() == "llvm.used") {
439    if (MAI->getUsedDirective() != 0)    // No need to emit this at all.
440      EmitLLVMUsedList(GV->getInitializer());
441    return true;
442  }
443
444  // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
445  if (GV->getSection() == "llvm.metadata" ||
446      GV->hasAvailableExternallyLinkage())
447    return true;
448
449  if (!GV->hasAppendingLinkage()) return false;
450
451  assert(GV->hasInitializer() && "Not a special LLVM global!");
452
453  const TargetData *TD = TM.getTargetData();
454  unsigned Align = Log2_32(TD->getPointerPrefAlignment());
455  if (GV->getName() == "llvm.global_ctors") {
456    OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
457    EmitAlignment(Align, 0);
458    EmitXXStructorList(GV->getInitializer());
459    return true;
460  }
461
462  if (GV->getName() == "llvm.global_dtors") {
463    OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
464    EmitAlignment(Align, 0);
465    EmitXXStructorList(GV->getInitializer());
466    return true;
467  }
468
469  return false;
470}
471
472/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
473/// global in the specified llvm.used list for which emitUsedDirectiveFor
474/// is true, as being used with this directive.
475void AsmPrinter::EmitLLVMUsedList(Constant *List) {
476  const char *Directive = MAI->getUsedDirective();
477
478  // Should be an array of 'i8*'.
479  ConstantArray *InitList = dyn_cast<ConstantArray>(List);
480  if (InitList == 0) return;
481
482  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
483    const GlobalValue *GV =
484      dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
485    if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
486      O << Directive;
487      EmitConstantValueOnly(InitList->getOperand(i));
488      O << '\n';
489    }
490  }
491}
492
493/// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the
494/// function pointers, ignoring the init priority.
495void AsmPrinter::EmitXXStructorList(Constant *List) {
496  // Should be an array of '{ int, void ()* }' structs.  The first value is the
497  // init priority, which we ignore.
498  if (!isa<ConstantArray>(List)) return;
499  ConstantArray *InitList = cast<ConstantArray>(List);
500  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
501    if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
502      if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
503
504      if (CS->getOperand(1)->isNullValue())
505        return;  // Found a null terminator, exit printing.
506      // Emit the function pointer.
507      EmitGlobalConstant(CS->getOperand(1));
508    }
509}
510
511
512//===----------------------------------------------------------------------===//
513/// LEB 128 number encoding.
514
515/// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
516/// representing an unsigned leb128 value.
517void AsmPrinter::PrintULEB128(unsigned Value) const {
518  char Buffer[20];
519  do {
520    unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
521    Value >>= 7;
522    if (Value) Byte |= 0x80;
523    O << "0x" << utohex_buffer(Byte, Buffer+20);
524    if (Value) O << ", ";
525  } while (Value);
526}
527
528/// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
529/// representing a signed leb128 value.
530void AsmPrinter::PrintSLEB128(int Value) const {
531  int Sign = Value >> (8 * sizeof(Value) - 1);
532  bool IsMore;
533  char Buffer[20];
534
535  do {
536    unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
537    Value >>= 7;
538    IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
539    if (IsMore) Byte |= 0x80;
540    O << "0x" << utohex_buffer(Byte, Buffer+20);
541    if (IsMore) O << ", ";
542  } while (IsMore);
543}
544
545//===--------------------------------------------------------------------===//
546// Emission and print routines
547//
548
549/// PrintHex - Print a value as a hexidecimal value.
550///
551void AsmPrinter::PrintHex(int Value) const {
552  char Buffer[20];
553  O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
554}
555
556/// EOL - Print a newline character to asm stream.  If a comment is present
557/// then it will be printed first.  Comments should not contain '\n'.
558void AsmPrinter::EOL() const {
559  O << '\n';
560}
561
562void AsmPrinter::EOL(const std::string &Comment) const {
563  if (VerboseAsm && !Comment.empty()) {
564    O.PadToColumn(MAI->getCommentColumn());
565    O << MAI->getCommentString()
566      << ' '
567      << Comment;
568  }
569  O << '\n';
570}
571
572void AsmPrinter::EOL(const char* Comment) const {
573  if (VerboseAsm && *Comment) {
574    O.PadToColumn(MAI->getCommentColumn());
575    O << MAI->getCommentString()
576      << ' '
577      << Comment;
578  }
579  O << '\n';
580}
581
582static const char *DecodeDWARFEncoding(unsigned Encoding) {
583  switch (Encoding) {
584  case dwarf::DW_EH_PE_absptr:
585    return "absptr";
586  case dwarf::DW_EH_PE_omit:
587    return "omit";
588  case dwarf::DW_EH_PE_pcrel:
589    return "pcrel";
590  case dwarf::DW_EH_PE_udata4:
591    return "udata4";
592  case dwarf::DW_EH_PE_udata8:
593    return "udata8";
594  case dwarf::DW_EH_PE_sdata4:
595    return "sdata4";
596  case dwarf::DW_EH_PE_sdata8:
597    return "sdata8";
598  case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
599    return "pcrel udata4";
600  case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
601    return "pcrel sdata4";
602  case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
603    return "pcrel udata8";
604  case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
605    return "pcrel sdata8";
606  case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
607    return "indirect pcrel udata4";
608  case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
609    return "indirect pcrel sdata4";
610  case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
611    return "indirect pcrel udata8";
612  case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
613    return "indirect pcrel sdata8";
614  }
615
616  return 0;
617}
618
619void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
620  if (VerboseAsm && *Comment) {
621    O.PadToColumn(MAI->getCommentColumn());
622    O << MAI->getCommentString()
623      << ' '
624      << Comment;
625
626    if (const char *EncStr = DecodeDWARFEncoding(Encoding))
627      O << " (" << EncStr << ')';
628  }
629  O << '\n';
630}
631
632/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
633/// unsigned leb128 value.
634void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
635  if (MAI->hasLEB128()) {
636    O << "\t.uleb128\t"
637      << Value;
638  } else {
639    O << MAI->getData8bitsDirective();
640    PrintULEB128(Value);
641  }
642}
643
644/// EmitSLEB128Bytes - print an assembler byte data directive to compose a
645/// signed leb128 value.
646void AsmPrinter::EmitSLEB128Bytes(int Value) const {
647  if (MAI->hasLEB128()) {
648    O << "\t.sleb128\t"
649      << Value;
650  } else {
651    O << MAI->getData8bitsDirective();
652    PrintSLEB128(Value);
653  }
654}
655
656/// EmitInt8 - Emit a byte directive and value.
657///
658void AsmPrinter::EmitInt8(int Value) const {
659  O << MAI->getData8bitsDirective();
660  PrintHex(Value & 0xFF);
661}
662
663/// EmitInt16 - Emit a short directive and value.
664///
665void AsmPrinter::EmitInt16(int Value) const {
666  O << MAI->getData16bitsDirective();
667  PrintHex(Value & 0xFFFF);
668}
669
670/// EmitInt32 - Emit a long directive and value.
671///
672void AsmPrinter::EmitInt32(int Value) const {
673  O << MAI->getData32bitsDirective();
674  PrintHex(Value);
675}
676
677/// EmitInt64 - Emit a long long directive and value.
678///
679void AsmPrinter::EmitInt64(uint64_t Value) const {
680  if (MAI->getData64bitsDirective()) {
681    O << MAI->getData64bitsDirective();
682    PrintHex(Value);
683  } else {
684    if (TM.getTargetData()->isBigEndian()) {
685      EmitInt32(unsigned(Value >> 32)); O << '\n';
686      EmitInt32(unsigned(Value));
687    } else {
688      EmitInt32(unsigned(Value)); O << '\n';
689      EmitInt32(unsigned(Value >> 32));
690    }
691  }
692}
693
694/// toOctal - Convert the low order bits of X into an octal digit.
695///
696static inline char toOctal(int X) {
697  return (X&7)+'0';
698}
699
700/// printStringChar - Print a char, escaped if necessary.
701///
702static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
703  if (C == '"') {
704    O << "\\\"";
705  } else if (C == '\\') {
706    O << "\\\\";
707  } else if (isprint((unsigned char)C)) {
708    O << C;
709  } else {
710    switch(C) {
711    case '\b': O << "\\b"; break;
712    case '\f': O << "\\f"; break;
713    case '\n': O << "\\n"; break;
714    case '\r': O << "\\r"; break;
715    case '\t': O << "\\t"; break;
716    default:
717      O << '\\';
718      O << toOctal(C >> 6);
719      O << toOctal(C >> 3);
720      O << toOctal(C >> 0);
721      break;
722    }
723  }
724}
725
726/// EmitString - Emit a string with quotes and a null terminator.
727/// Special characters are emitted properly.
728/// \literal (Eg. '\t') \endliteral
729void AsmPrinter::EmitString(const std::string &String) const {
730  EmitString(String.c_str(), String.size());
731}
732
733void AsmPrinter::EmitString(const char *String, unsigned Size) const {
734  const char* AscizDirective = MAI->getAscizDirective();
735  if (AscizDirective)
736    O << AscizDirective;
737  else
738    O << MAI->getAsciiDirective();
739  O << '\"';
740  for (unsigned i = 0; i < Size; ++i)
741    printStringChar(O, String[i]);
742  if (AscizDirective)
743    O << '\"';
744  else
745    O << "\\0\"";
746}
747
748
749/// EmitFile - Emit a .file directive.
750void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
751  O << "\t.file\t" << Number << " \"";
752  for (unsigned i = 0, N = Name.size(); i < N; ++i)
753    printStringChar(O, Name[i]);
754  O << '\"';
755}
756
757
758//===----------------------------------------------------------------------===//
759
760// EmitAlignment - Emit an alignment directive to the specified power of
761// two boundary.  For example, if you pass in 3 here, you will get an 8
762// byte alignment.  If a global value is specified, and if that global has
763// an explicit alignment requested, it will unconditionally override the
764// alignment request.  However, if ForcedAlignBits is specified, this value
765// has final say: the ultimate alignment will be the max of ForcedAlignBits
766// and the alignment computed with NumBits and the global.
767//
768// The algorithm is:
769//     Align = NumBits;
770//     if (GV && GV->hasalignment) Align = GV->getalignment();
771//     Align = std::max(Align, ForcedAlignBits);
772//
773void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
774                               unsigned ForcedAlignBits,
775                               bool UseFillExpr) const {
776  if (GV && GV->getAlignment())
777    NumBits = Log2_32(GV->getAlignment());
778  NumBits = std::max(NumBits, ForcedAlignBits);
779
780  if (NumBits == 0) return;   // No need to emit alignment.
781
782  unsigned FillValue = 0;
783  if (getCurrentSection()->getKind().isText())
784    FillValue = MAI->getTextAlignFillValue();
785
786  OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
787}
788
789/// EmitZeros - Emit a block of zeros.
790///
791void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
792  if (NumZeros) {
793    if (MAI->getZeroDirective()) {
794      O << MAI->getZeroDirective() << NumZeros;
795      if (MAI->getZeroDirectiveSuffix())
796        O << MAI->getZeroDirectiveSuffix();
797      O << '\n';
798    } else {
799      for (; NumZeros; --NumZeros)
800        O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
801    }
802  }
803}
804
805// Print out the specified constant, without a storage class.  Only the
806// constants valid in constant expressions can occur here.
807void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
808  if (CV->isNullValue() || isa<UndefValue>(CV))
809    O << '0';
810  else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
811    O << CI->getZExtValue();
812  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
813    // This is a constant address for a global variable or function. Use the
814    // name of the variable or function as the address value.
815    O << Mang->getMangledName(GV);
816  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
817    const TargetData *TD = TM.getTargetData();
818    unsigned Opcode = CE->getOpcode();
819    switch (Opcode) {
820    case Instruction::Trunc:
821    case Instruction::ZExt:
822    case Instruction::SExt:
823    case Instruction::FPTrunc:
824    case Instruction::FPExt:
825    case Instruction::UIToFP:
826    case Instruction::SIToFP:
827    case Instruction::FPToUI:
828    case Instruction::FPToSI:
829      llvm_unreachable("FIXME: Don't support this constant cast expr");
830    case Instruction::GetElementPtr: {
831      // generate a symbolic expression for the byte address
832      const Constant *ptrVal = CE->getOperand(0);
833      SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
834      if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
835                                                idxVec.size())) {
836        // Truncate/sext the offset to the pointer size.
837        if (TD->getPointerSizeInBits() != 64) {
838          int SExtAmount = 64-TD->getPointerSizeInBits();
839          Offset = (Offset << SExtAmount) >> SExtAmount;
840        }
841
842        if (Offset)
843          O << '(';
844        EmitConstantValueOnly(ptrVal);
845        if (Offset > 0)
846          O << ") + " << Offset;
847        else if (Offset < 0)
848          O << ") - " << -Offset;
849      } else {
850        EmitConstantValueOnly(ptrVal);
851      }
852      break;
853    }
854    case Instruction::BitCast:
855      return EmitConstantValueOnly(CE->getOperand(0));
856
857    case Instruction::IntToPtr: {
858      // Handle casts to pointers by changing them into casts to the appropriate
859      // integer type.  This promotes constant folding and simplifies this code.
860      Constant *Op = CE->getOperand(0);
861      Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
862                                        false/*ZExt*/);
863      return EmitConstantValueOnly(Op);
864    }
865
866
867    case Instruction::PtrToInt: {
868      // Support only foldable casts to/from pointers that can be eliminated by
869      // changing the pointer to the appropriately sized integer type.
870      Constant *Op = CE->getOperand(0);
871      const Type *Ty = CE->getType();
872
873      // We can emit the pointer value into this slot if the slot is an
874      // integer slot greater or equal to the size of the pointer.
875      if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
876        return EmitConstantValueOnly(Op);
877
878      O << "((";
879      EmitConstantValueOnly(Op);
880      APInt ptrMask =
881        APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
882
883      SmallString<40> S;
884      ptrMask.toStringUnsigned(S);
885      O << ") & " << S.str() << ')';
886      break;
887    }
888    case Instruction::Add:
889    case Instruction::Sub:
890    case Instruction::And:
891    case Instruction::Or:
892    case Instruction::Xor:
893      O << '(';
894      EmitConstantValueOnly(CE->getOperand(0));
895      O << ')';
896      switch (Opcode) {
897      case Instruction::Add:
898       O << " + ";
899       break;
900      case Instruction::Sub:
901       O << " - ";
902       break;
903      case Instruction::And:
904       O << " & ";
905       break;
906      case Instruction::Or:
907       O << " | ";
908       break;
909      case Instruction::Xor:
910       O << " ^ ";
911       break;
912      default:
913       break;
914      }
915      O << '(';
916      EmitConstantValueOnly(CE->getOperand(1));
917      O << ')';
918      break;
919    default:
920      llvm_unreachable("Unsupported operator!");
921    }
922  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
923    GetBlockAddressSymbol(BA)->print(O, MAI);
924  } else {
925    llvm_unreachable("Unknown constant value!");
926  }
927}
928
929/// printAsCString - Print the specified array as a C compatible string, only if
930/// the predicate isString is true.
931///
932static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
933                           unsigned LastElt) {
934  assert(CVA->isString() && "Array is not string compatible!");
935
936  O << '\"';
937  for (unsigned i = 0; i != LastElt; ++i) {
938    unsigned char C =
939        (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
940    printStringChar(O, C);
941  }
942  O << '\"';
943}
944
945/// EmitString - Emit a zero-byte-terminated string constant.
946///
947void AsmPrinter::EmitString(const ConstantArray *CVA) const {
948  unsigned NumElts = CVA->getNumOperands();
949  if (MAI->getAscizDirective() && NumElts &&
950      cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
951    O << MAI->getAscizDirective();
952    printAsCString(O, CVA, NumElts-1);
953  } else {
954    O << MAI->getAsciiDirective();
955    printAsCString(O, CVA, NumElts);
956  }
957  O << '\n';
958}
959
960void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
961                                         unsigned AddrSpace) {
962  if (CVA->isString()) {
963    EmitString(CVA);
964  } else { // Not a string.  Print the values in successive locations
965    for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
966      EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
967  }
968}
969
970void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
971  const VectorType *PTy = CP->getType();
972
973  for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
974    EmitGlobalConstant(CP->getOperand(I));
975}
976
977void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
978                                          unsigned AddrSpace) {
979  // Print the fields in successive locations. Pad to align if needed!
980  const TargetData *TD = TM.getTargetData();
981  unsigned Size = TD->getTypeAllocSize(CVS->getType());
982  const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
983  uint64_t sizeSoFar = 0;
984  for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
985    const Constant* field = CVS->getOperand(i);
986
987    // Check if padding is needed and insert one or more 0s.
988    uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
989    uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
990                        - cvsLayout->getElementOffset(i)) - fieldSize;
991    sizeSoFar += fieldSize + padSize;
992
993    // Now print the actual field value.
994    EmitGlobalConstant(field, AddrSpace);
995
996    // Insert padding - this may include padding to increase the size of the
997    // current field up to the ABI size (if the struct is not packed) as well
998    // as padding to ensure that the next field starts at the right offset.
999    EmitZeros(padSize, AddrSpace);
1000  }
1001  assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1002         "Layout of constant struct may be incorrect!");
1003}
1004
1005void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1006                                      unsigned AddrSpace) {
1007  // FP Constants are printed as integer constants to avoid losing
1008  // precision...
1009  LLVMContext &Context = CFP->getContext();
1010  const TargetData *TD = TM.getTargetData();
1011  if (CFP->getType()->isDoubleTy()) {
1012    double Val = CFP->getValueAPF().convertToDouble();  // for comment only
1013    uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1014    if (MAI->getData64bitsDirective(AddrSpace)) {
1015      O << MAI->getData64bitsDirective(AddrSpace) << i;
1016      if (VerboseAsm) {
1017        O.PadToColumn(MAI->getCommentColumn());
1018        O << MAI->getCommentString() << " double " << Val;
1019      }
1020      O << '\n';
1021    } else if (TD->isBigEndian()) {
1022      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1023      if (VerboseAsm) {
1024        O.PadToColumn(MAI->getCommentColumn());
1025        O << MAI->getCommentString()
1026          << " most significant word of double " << Val;
1027      }
1028      O << '\n';
1029      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1030      if (VerboseAsm) {
1031        O.PadToColumn(MAI->getCommentColumn());
1032        O << MAI->getCommentString()
1033          << " least significant word of double " << Val;
1034      }
1035      O << '\n';
1036    } else {
1037      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1038      if (VerboseAsm) {
1039        O.PadToColumn(MAI->getCommentColumn());
1040        O << MAI->getCommentString()
1041          << " least significant word of double " << Val;
1042      }
1043      O << '\n';
1044      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1045      if (VerboseAsm) {
1046        O.PadToColumn(MAI->getCommentColumn());
1047        O << MAI->getCommentString()
1048          << " most significant word of double " << Val;
1049      }
1050      O << '\n';
1051    }
1052    return;
1053  }
1054
1055  if (CFP->getType()->isFloatTy()) {
1056    float Val = CFP->getValueAPF().convertToFloat();  // for comment only
1057    O << MAI->getData32bitsDirective(AddrSpace)
1058      << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1059    if (VerboseAsm) {
1060      O.PadToColumn(MAI->getCommentColumn());
1061      O << MAI->getCommentString() << " float " << Val;
1062    }
1063    O << '\n';
1064    return;
1065  }
1066
1067  if (CFP->getType()->isX86_FP80Ty()) {
1068    // all long double variants are printed as hex
1069    // api needed to prevent premature destruction
1070    APInt api = CFP->getValueAPF().bitcastToAPInt();
1071    const uint64_t *p = api.getRawData();
1072    // Convert to double so we can print the approximate val as a comment.
1073    APFloat DoubleVal = CFP->getValueAPF();
1074    bool ignored;
1075    DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1076                      &ignored);
1077    if (TD->isBigEndian()) {
1078      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1079      if (VerboseAsm) {
1080        O.PadToColumn(MAI->getCommentColumn());
1081        O << MAI->getCommentString()
1082          << " most significant halfword of x86_fp80 ~"
1083          << DoubleVal.convertToDouble();
1084      }
1085      O << '\n';
1086      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1087      if (VerboseAsm) {
1088        O.PadToColumn(MAI->getCommentColumn());
1089        O << MAI->getCommentString() << " next halfword";
1090      }
1091      O << '\n';
1092      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1093      if (VerboseAsm) {
1094        O.PadToColumn(MAI->getCommentColumn());
1095        O << MAI->getCommentString() << " next halfword";
1096      }
1097      O << '\n';
1098      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1099      if (VerboseAsm) {
1100        O.PadToColumn(MAI->getCommentColumn());
1101        O << MAI->getCommentString() << " next halfword";
1102      }
1103      O << '\n';
1104      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1105      if (VerboseAsm) {
1106        O.PadToColumn(MAI->getCommentColumn());
1107        O << MAI->getCommentString()
1108          << " least significant halfword";
1109      }
1110      O << '\n';
1111     } else {
1112      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1113      if (VerboseAsm) {
1114        O.PadToColumn(MAI->getCommentColumn());
1115        O << MAI->getCommentString()
1116          << " least significant halfword of x86_fp80 ~"
1117          << DoubleVal.convertToDouble();
1118      }
1119      O << '\n';
1120      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1121      if (VerboseAsm) {
1122        O.PadToColumn(MAI->getCommentColumn());
1123        O << MAI->getCommentString()
1124          << " next halfword";
1125      }
1126      O << '\n';
1127      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1128      if (VerboseAsm) {
1129        O.PadToColumn(MAI->getCommentColumn());
1130        O << MAI->getCommentString()
1131          << " next halfword";
1132      }
1133      O << '\n';
1134      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1135      if (VerboseAsm) {
1136        O.PadToColumn(MAI->getCommentColumn());
1137        O << MAI->getCommentString()
1138          << " next halfword";
1139      }
1140      O << '\n';
1141      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1142      if (VerboseAsm) {
1143        O.PadToColumn(MAI->getCommentColumn());
1144        O << MAI->getCommentString()
1145          << " most significant halfword";
1146      }
1147      O << '\n';
1148    }
1149    EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1150              TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1151    return;
1152  }
1153
1154  if (CFP->getType()->isPPC_FP128Ty()) {
1155    // all long double variants are printed as hex
1156    // api needed to prevent premature destruction
1157    APInt api = CFP->getValueAPF().bitcastToAPInt();
1158    const uint64_t *p = api.getRawData();
1159    if (TD->isBigEndian()) {
1160      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1161      if (VerboseAsm) {
1162        O.PadToColumn(MAI->getCommentColumn());
1163        O << MAI->getCommentString()
1164          << " most significant word of ppc_fp128";
1165      }
1166      O << '\n';
1167      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1168      if (VerboseAsm) {
1169        O.PadToColumn(MAI->getCommentColumn());
1170        O << MAI->getCommentString()
1171        << " next word";
1172      }
1173      O << '\n';
1174      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1175      if (VerboseAsm) {
1176        O.PadToColumn(MAI->getCommentColumn());
1177        O << MAI->getCommentString()
1178          << " next word";
1179      }
1180      O << '\n';
1181      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1182      if (VerboseAsm) {
1183        O.PadToColumn(MAI->getCommentColumn());
1184        O << MAI->getCommentString()
1185          << " least significant word";
1186      }
1187      O << '\n';
1188     } else {
1189      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1190      if (VerboseAsm) {
1191        O.PadToColumn(MAI->getCommentColumn());
1192        O << MAI->getCommentString()
1193          << " least significant word of ppc_fp128";
1194      }
1195      O << '\n';
1196      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1197      if (VerboseAsm) {
1198        O.PadToColumn(MAI->getCommentColumn());
1199        O << MAI->getCommentString()
1200          << " next word";
1201      }
1202      O << '\n';
1203      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1204      if (VerboseAsm) {
1205        O.PadToColumn(MAI->getCommentColumn());
1206        O << MAI->getCommentString()
1207          << " next word";
1208      }
1209      O << '\n';
1210      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1211      if (VerboseAsm) {
1212        O.PadToColumn(MAI->getCommentColumn());
1213        O << MAI->getCommentString()
1214          << " most significant word";
1215      }
1216      O << '\n';
1217    }
1218    return;
1219  } else llvm_unreachable("Floating point constant type not handled");
1220}
1221
1222void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1223                                            unsigned AddrSpace) {
1224  const TargetData *TD = TM.getTargetData();
1225  unsigned BitWidth = CI->getBitWidth();
1226  assert(isPowerOf2_32(BitWidth) &&
1227         "Non-power-of-2-sized integers not handled!");
1228
1229  // We don't expect assemblers to support integer data directives
1230  // for more than 64 bits, so we emit the data in at most 64-bit
1231  // quantities at a time.
1232  const uint64_t *RawData = CI->getValue().getRawData();
1233  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1234    uint64_t Val;
1235    if (TD->isBigEndian())
1236      Val = RawData[e - i - 1];
1237    else
1238      Val = RawData[i];
1239
1240    if (MAI->getData64bitsDirective(AddrSpace))
1241      O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1242    else if (TD->isBigEndian()) {
1243      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1244      if (VerboseAsm) {
1245        O.PadToColumn(MAI->getCommentColumn());
1246        O << MAI->getCommentString()
1247          << " most significant half of i64 " << Val;
1248      }
1249      O << '\n';
1250      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1251      if (VerboseAsm) {
1252        O.PadToColumn(MAI->getCommentColumn());
1253        O << MAI->getCommentString()
1254          << " least significant half of i64 " << Val;
1255      }
1256      O << '\n';
1257    } else {
1258      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1259      if (VerboseAsm) {
1260        O.PadToColumn(MAI->getCommentColumn());
1261        O << MAI->getCommentString()
1262          << " least significant half of i64 " << Val;
1263      }
1264      O << '\n';
1265      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1266      if (VerboseAsm) {
1267        O.PadToColumn(MAI->getCommentColumn());
1268        O << MAI->getCommentString()
1269          << " most significant half of i64 " << Val;
1270      }
1271      O << '\n';
1272    }
1273  }
1274}
1275
1276/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1277void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1278  const TargetData *TD = TM.getTargetData();
1279  const Type *type = CV->getType();
1280  unsigned Size = TD->getTypeAllocSize(type);
1281
1282  if (CV->isNullValue() || isa<UndefValue>(CV)) {
1283    EmitZeros(Size, AddrSpace);
1284    return;
1285  } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1286    EmitGlobalConstantArray(CVA , AddrSpace);
1287    return;
1288  } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1289    EmitGlobalConstantStruct(CVS, AddrSpace);
1290    return;
1291  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1292    EmitGlobalConstantFP(CFP, AddrSpace);
1293    return;
1294  } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1295    // Small integers are handled below; large integers are handled here.
1296    if (Size > 4) {
1297      EmitGlobalConstantLargeInt(CI, AddrSpace);
1298      return;
1299    }
1300  } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1301    EmitGlobalConstantVector(CP);
1302    return;
1303  }
1304
1305  printDataDirective(type, AddrSpace);
1306  EmitConstantValueOnly(CV);
1307  if (VerboseAsm) {
1308    if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1309      SmallString<40> S;
1310      CI->getValue().toStringUnsigned(S, 16);
1311      O.PadToColumn(MAI->getCommentColumn());
1312      O << MAI->getCommentString() << " 0x" << S.str();
1313    }
1314  }
1315  O << '\n';
1316}
1317
1318void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1319  // Target doesn't support this yet!
1320  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1321}
1322
1323/// PrintSpecial - Print information related to the specified machine instr
1324/// that is independent of the operand, and may be independent of the instr
1325/// itself.  This can be useful for portably encoding the comment character
1326/// or other bits of target-specific knowledge into the asmstrings.  The
1327/// syntax used is ${:comment}.  Targets can override this to add support
1328/// for their own strange codes.
1329void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1330  if (!strcmp(Code, "private")) {
1331    O << MAI->getPrivateGlobalPrefix();
1332  } else if (!strcmp(Code, "comment")) {
1333    if (VerboseAsm)
1334      O << MAI->getCommentString();
1335  } else if (!strcmp(Code, "uid")) {
1336    // Comparing the address of MI isn't sufficient, because machineinstrs may
1337    // be allocated to the same address across functions.
1338    const Function *ThisF = MI->getParent()->getParent()->getFunction();
1339
1340    // If this is a new LastFn instruction, bump the counter.
1341    if (LastMI != MI || LastFn != ThisF) {
1342      ++Counter;
1343      LastMI = MI;
1344      LastFn = ThisF;
1345    }
1346    O << Counter;
1347  } else {
1348    std::string msg;
1349    raw_string_ostream Msg(msg);
1350    Msg << "Unknown special formatter '" << Code
1351         << "' for machine instr: " << *MI;
1352    llvm_report_error(Msg.str());
1353  }
1354}
1355
1356/// processDebugLoc - Processes the debug information of each machine
1357/// instruction's DebugLoc.
1358void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1359                                 bool BeforePrintingInsn) {
1360  if (!MAI || !DW)
1361    return;
1362  DebugLoc DL = MI->getDebugLoc();
1363  if (MAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1364    if (!DL.isUnknown()) {
1365      DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1366      if (BeforePrintingInsn) {
1367        if (CurDLT.Scope != 0 && PrevDLT != CurDLT) {
1368	  unsigned L = DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1369	  				    CurDLT.Scope);
1370          printLabel(L);
1371          O << '\n';
1372#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1373          DW->SetDbgScopeBeginLabels(MI, L);
1374#endif
1375        } else {
1376#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
1377          DW->SetDbgScopeEndLabels(MI, 0);
1378#endif
1379        }
1380      }
1381      PrevDLT = CurDLT;
1382    }
1383  }
1384}
1385
1386/// printInlineAsm - This method formats and prints the specified machine
1387/// instruction that is an inline asm.
1388void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1389  unsigned NumOperands = MI->getNumOperands();
1390
1391  // Count the number of register definitions.
1392  unsigned NumDefs = 0;
1393  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1394       ++NumDefs)
1395    assert(NumDefs != NumOperands-1 && "No asm string?");
1396
1397  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1398
1399  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1400  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1401
1402  // If this asmstr is empty, just print the #APP/#NOAPP markers.
1403  // These are useful to see where empty asm's wound up.
1404  if (AsmStr[0] == 0) {
1405    O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1406    O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1407    return;
1408  }
1409
1410  O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1411
1412  // The variant of the current asmprinter.
1413  int AsmPrinterVariant = MAI->getAssemblerDialect();
1414
1415  int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1416  const char *LastEmitted = AsmStr; // One past the last character emitted.
1417
1418  while (*LastEmitted) {
1419    switch (*LastEmitted) {
1420    default: {
1421      // Not a special case, emit the string section literally.
1422      const char *LiteralEnd = LastEmitted+1;
1423      while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1424             *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1425        ++LiteralEnd;
1426      if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1427        O.write(LastEmitted, LiteralEnd-LastEmitted);
1428      LastEmitted = LiteralEnd;
1429      break;
1430    }
1431    case '\n':
1432      ++LastEmitted;   // Consume newline character.
1433      O << '\n';       // Indent code with newline.
1434      break;
1435    case '$': {
1436      ++LastEmitted;   // Consume '$' character.
1437      bool Done = true;
1438
1439      // Handle escapes.
1440      switch (*LastEmitted) {
1441      default: Done = false; break;
1442      case '$':     // $$ -> $
1443        if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1444          O << '$';
1445        ++LastEmitted;  // Consume second '$' character.
1446        break;
1447      case '(':             // $( -> same as GCC's { character.
1448        ++LastEmitted;      // Consume '(' character.
1449        if (CurVariant != -1) {
1450          llvm_report_error("Nested variants found in inline asm string: '"
1451                            + std::string(AsmStr) + "'");
1452        }
1453        CurVariant = 0;     // We're in the first variant now.
1454        break;
1455      case '|':
1456        ++LastEmitted;  // consume '|' character.
1457        if (CurVariant == -1)
1458          O << '|';       // this is gcc's behavior for | outside a variant
1459        else
1460          ++CurVariant;   // We're in the next variant.
1461        break;
1462      case ')':         // $) -> same as GCC's } char.
1463        ++LastEmitted;  // consume ')' character.
1464        if (CurVariant == -1)
1465          O << '}';     // this is gcc's behavior for } outside a variant
1466        else
1467          CurVariant = -1;
1468        break;
1469      }
1470      if (Done) break;
1471
1472      bool HasCurlyBraces = false;
1473      if (*LastEmitted == '{') {     // ${variable}
1474        ++LastEmitted;               // Consume '{' character.
1475        HasCurlyBraces = true;
1476      }
1477
1478      // If we have ${:foo}, then this is not a real operand reference, it is a
1479      // "magic" string reference, just like in .td files.  Arrange to call
1480      // PrintSpecial.
1481      if (HasCurlyBraces && *LastEmitted == ':') {
1482        ++LastEmitted;
1483        const char *StrStart = LastEmitted;
1484        const char *StrEnd = strchr(StrStart, '}');
1485        if (StrEnd == 0) {
1486          llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1487                            + std::string(AsmStr) + "'");
1488        }
1489
1490        std::string Val(StrStart, StrEnd);
1491        PrintSpecial(MI, Val.c_str());
1492        LastEmitted = StrEnd+1;
1493        break;
1494      }
1495
1496      const char *IDStart = LastEmitted;
1497      char *IDEnd;
1498      errno = 0;
1499      long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1500      if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1501        llvm_report_error("Bad $ operand number in inline asm string: '"
1502                          + std::string(AsmStr) + "'");
1503      }
1504      LastEmitted = IDEnd;
1505
1506      char Modifier[2] = { 0, 0 };
1507
1508      if (HasCurlyBraces) {
1509        // If we have curly braces, check for a modifier character.  This
1510        // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1511        if (*LastEmitted == ':') {
1512          ++LastEmitted;    // Consume ':' character.
1513          if (*LastEmitted == 0) {
1514            llvm_report_error("Bad ${:} expression in inline asm string: '"
1515                              + std::string(AsmStr) + "'");
1516          }
1517
1518          Modifier[0] = *LastEmitted;
1519          ++LastEmitted;    // Consume modifier character.
1520        }
1521
1522        if (*LastEmitted != '}') {
1523          llvm_report_error("Bad ${} expression in inline asm string: '"
1524                            + std::string(AsmStr) + "'");
1525        }
1526        ++LastEmitted;    // Consume '}' character.
1527      }
1528
1529      if ((unsigned)Val >= NumOperands-1) {
1530        llvm_report_error("Invalid $ operand number in inline asm string: '"
1531                          + std::string(AsmStr) + "'");
1532      }
1533
1534      // Okay, we finally have a value number.  Ask the target to print this
1535      // operand!
1536      if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1537        unsigned OpNo = 1;
1538
1539        bool Error = false;
1540
1541        // Scan to find the machine operand number for the operand.
1542        for (; Val; --Val) {
1543          if (OpNo >= MI->getNumOperands()) break;
1544          unsigned OpFlags = MI->getOperand(OpNo).getImm();
1545          OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1546        }
1547
1548        if (OpNo >= MI->getNumOperands()) {
1549          Error = true;
1550        } else {
1551          unsigned OpFlags = MI->getOperand(OpNo).getImm();
1552          ++OpNo;  // Skip over the ID number.
1553
1554          if (Modifier[0]=='l')  // labels are target independent
1555            GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1556                           ->getNumber())->print(O, MAI);
1557          else {
1558            AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1559            if ((OpFlags & 7) == 4) {
1560              Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1561                                                Modifier[0] ? Modifier : 0);
1562            } else {
1563              Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1564                                          Modifier[0] ? Modifier : 0);
1565            }
1566          }
1567        }
1568        if (Error) {
1569          std::string msg;
1570          raw_string_ostream Msg(msg);
1571          Msg << "Invalid operand found in inline asm: '"
1572               << AsmStr << "'\n";
1573          MI->print(Msg);
1574          llvm_report_error(Msg.str());
1575        }
1576      }
1577      break;
1578    }
1579    }
1580  }
1581  O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1582}
1583
1584/// printImplicitDef - This method prints the specified machine instruction
1585/// that is an implicit def.
1586void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1587  if (!VerboseAsm) return;
1588  O.PadToColumn(MAI->getCommentColumn());
1589  O << MAI->getCommentString() << " implicit-def: "
1590    << TRI->getName(MI->getOperand(0).getReg());
1591}
1592
1593void AsmPrinter::printKill(const MachineInstr *MI) const {
1594  if (!VerboseAsm) return;
1595  O.PadToColumn(MAI->getCommentColumn());
1596  O << MAI->getCommentString() << " kill:";
1597  for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1598    const MachineOperand &op = MI->getOperand(n);
1599    assert(op.isReg() && "KILL instruction must have only register operands");
1600    O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1601  }
1602}
1603
1604/// printLabel - This method prints a local label used by debug and
1605/// exception handling tables.
1606void AsmPrinter::printLabel(const MachineInstr *MI) const {
1607  printLabel(MI->getOperand(0).getImm());
1608}
1609
1610void AsmPrinter::printLabel(unsigned Id) const {
1611  O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1612}
1613
1614/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1615/// instruction, using the specified assembler variant.  Targets should
1616/// overried this to format as appropriate.
1617bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1618                                 unsigned AsmVariant, const char *ExtraCode) {
1619  // Target doesn't support this yet!
1620  return true;
1621}
1622
1623bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1624                                       unsigned AsmVariant,
1625                                       const char *ExtraCode) {
1626  // Target doesn't support this yet!
1627  return true;
1628}
1629
1630MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1631  return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock());
1632}
1633
1634MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1635                                            const BasicBlock *BB) const {
1636  assert(BB->hasName() &&
1637         "Address of anonymous basic block not supported yet!");
1638
1639  // This code must use the function name itself, and not the function number,
1640  // since it must be possible to generate the label name from within other
1641  // functions.
1642  std::string FuncName = Mang->getMangledName(F);
1643
1644  SmallString<60> Name;
1645  raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BA"
1646    << FuncName.size() << '_' << FuncName << '_'
1647    << Mang->makeNameProper(BB->getName());
1648
1649  return OutContext.GetOrCreateSymbol(Name.str());
1650}
1651
1652MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1653  SmallString<60> Name;
1654  raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1655    << getFunctionNumber() << '_' << MBBID;
1656
1657  return OutContext.GetOrCreateSymbol(Name.str());
1658}
1659
1660
1661/// EmitBasicBlockStart - This method prints the label for the specified
1662/// MachineBasicBlock, an alignment (if present) and a comment describing
1663/// it if appropriate.
1664void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1665  // Emit an alignment directive for this block, if needed.
1666  if (unsigned Align = MBB->getAlignment())
1667    EmitAlignment(Log2_32(Align));
1668
1669  // If the block has its address taken, emit a special label to satisfy
1670  // references to the block. This is done so that we don't need to
1671  // remember the number of this label, and so that we can make
1672  // forward references to labels without knowing what their numbers
1673  // will be.
1674  if (MBB->hasAddressTaken()) {
1675    GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
1676                          MBB->getBasicBlock())->print(O, MAI);
1677    O << ':';
1678    if (VerboseAsm) {
1679      O.PadToColumn(MAI->getCommentColumn());
1680      O << MAI->getCommentString() << " Address Taken";
1681    }
1682    O << '\n';
1683  }
1684
1685  // Print the main label for the block.
1686  if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1687    if (VerboseAsm)
1688      O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1689  } else {
1690    GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1691    O << ':';
1692    if (!VerboseAsm)
1693      O << '\n';
1694  }
1695
1696  // Print some comments to accompany the label.
1697  if (VerboseAsm) {
1698    if (const BasicBlock *BB = MBB->getBasicBlock())
1699      if (BB->hasName()) {
1700        O.PadToColumn(MAI->getCommentColumn());
1701        O << MAI->getCommentString() << ' ';
1702        WriteAsOperand(O, BB, /*PrintType=*/false);
1703      }
1704
1705    EmitComments(*MBB);
1706    O << '\n';
1707  }
1708}
1709
1710/// printPICJumpTableSetLabel - This method prints a set label for the
1711/// specified MachineBasicBlock for a jumptable entry.
1712void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1713                                           const MachineBasicBlock *MBB) const {
1714  if (!MAI->getSetDirective())
1715    return;
1716
1717  O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1718    << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1719  GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1720  O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1721    << '_' << uid << '\n';
1722}
1723
1724void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1725                                           const MachineBasicBlock *MBB) const {
1726  if (!MAI->getSetDirective())
1727    return;
1728
1729  O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1730    << getFunctionNumber() << '_' << uid << '_' << uid2
1731    << "_set_" << MBB->getNumber() << ',';
1732  GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1733  O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1734    << '_' << uid << '_' << uid2 << '\n';
1735}
1736
1737/// printDataDirective - This method prints the asm directive for the
1738/// specified type.
1739void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1740  const TargetData *TD = TM.getTargetData();
1741  switch (type->getTypeID()) {
1742  case Type::FloatTyID: case Type::DoubleTyID:
1743  case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1744    assert(0 && "Should have already output floating point constant.");
1745  default:
1746    assert(0 && "Can't handle printing this type of thing");
1747  case Type::IntegerTyID: {
1748    unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1749    if (BitWidth <= 8)
1750      O << MAI->getData8bitsDirective(AddrSpace);
1751    else if (BitWidth <= 16)
1752      O << MAI->getData16bitsDirective(AddrSpace);
1753    else if (BitWidth <= 32)
1754      O << MAI->getData32bitsDirective(AddrSpace);
1755    else if (BitWidth <= 64) {
1756      assert(MAI->getData64bitsDirective(AddrSpace) &&
1757             "Target cannot handle 64-bit constant exprs!");
1758      O << MAI->getData64bitsDirective(AddrSpace);
1759    } else {
1760      llvm_unreachable("Target cannot handle given data directive width!");
1761    }
1762    break;
1763  }
1764  case Type::PointerTyID:
1765    if (TD->getPointerSize() == 8) {
1766      assert(MAI->getData64bitsDirective(AddrSpace) &&
1767             "Target cannot handle 64-bit pointer exprs!");
1768      O << MAI->getData64bitsDirective(AddrSpace);
1769    } else if (TD->getPointerSize() == 2) {
1770      O << MAI->getData16bitsDirective(AddrSpace);
1771    } else if (TD->getPointerSize() == 1) {
1772      O << MAI->getData8bitsDirective(AddrSpace);
1773    } else {
1774      O << MAI->getData32bitsDirective(AddrSpace);
1775    }
1776    break;
1777  }
1778}
1779
1780void AsmPrinter::printVisibility(const std::string& Name,
1781                                 unsigned Visibility) const {
1782  if (Visibility == GlobalValue::HiddenVisibility) {
1783    if (const char *Directive = MAI->getHiddenDirective())
1784      O << Directive << Name << '\n';
1785  } else if (Visibility == GlobalValue::ProtectedVisibility) {
1786    if (const char *Directive = MAI->getProtectedDirective())
1787      O << Directive << Name << '\n';
1788  }
1789}
1790
1791void AsmPrinter::printOffset(int64_t Offset) const {
1792  if (Offset > 0)
1793    O << '+' << Offset;
1794  else if (Offset < 0)
1795    O << Offset;
1796}
1797
1798GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1799  if (!S->usesMetadata())
1800    return 0;
1801
1802  gcp_iterator GCPI = GCMetadataPrinters.find(S);
1803  if (GCPI != GCMetadataPrinters.end())
1804    return GCPI->second;
1805
1806  const char *Name = S->getName().c_str();
1807
1808  for (GCMetadataPrinterRegistry::iterator
1809         I = GCMetadataPrinterRegistry::begin(),
1810         E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1811    if (strcmp(Name, I->getName()) == 0) {
1812      GCMetadataPrinter *GMP = I->instantiate();
1813      GMP->S = S;
1814      GCMetadataPrinters.insert(std::make_pair(S, GMP));
1815      return GMP;
1816    }
1817
1818  errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1819  llvm_unreachable(0);
1820}
1821
1822/// EmitComments - Pretty-print comments for instructions
1823void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1824  assert(VerboseAsm && !MI.getDebugLoc().isUnknown());
1825
1826  DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1827
1828  // Print source line info.
1829  O.PadToColumn(MAI->getCommentColumn());
1830  O << MAI->getCommentString() << " SrcLine ";
1831  if (DLT.Scope) {
1832    DICompileUnit CU(DLT.Scope);
1833    if (!CU.isNull())
1834      O << CU.getFilename() << " ";
1835  }
1836  O << DLT.Line;
1837  if (DLT.Col != 0)
1838    O << ":" << DLT.Col;
1839}
1840
1841/// PrintChildLoopComment - Print comments about child loops within
1842/// the loop for this basic block, with nesting.
1843///
1844static void PrintChildLoopComment(formatted_raw_ostream &O,
1845                                  const MachineLoop *loop,
1846                                  const MCAsmInfo *MAI,
1847                                  int FunctionNumber) {
1848  // Add child loop information
1849  for(MachineLoop::iterator cl = loop->begin(),
1850        clend = loop->end();
1851      cl != clend;
1852      ++cl) {
1853    MachineBasicBlock *Header = (*cl)->getHeader();
1854    assert(Header && "No header for loop");
1855
1856    O << '\n';
1857    O.PadToColumn(MAI->getCommentColumn());
1858
1859    O << MAI->getCommentString();
1860    O.indent(((*cl)->getLoopDepth()-1)*2)
1861      << " Child Loop BB" << FunctionNumber << "_"
1862      << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1863
1864    PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1865  }
1866}
1867
1868/// EmitComments - Pretty-print comments for basic blocks
1869void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1870{
1871  if (VerboseAsm) {
1872    // Add loop depth information
1873    const MachineLoop *loop = LI->getLoopFor(&MBB);
1874
1875    if (loop) {
1876      // Print a newline after bb# annotation.
1877      O << "\n";
1878      O.PadToColumn(MAI->getCommentColumn());
1879      O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1880        << '\n';
1881
1882      O.PadToColumn(MAI->getCommentColumn());
1883
1884      MachineBasicBlock *Header = loop->getHeader();
1885      assert(Header && "No header for loop");
1886
1887      if (Header == &MBB) {
1888        O << MAI->getCommentString() << " Loop Header";
1889        PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1890      }
1891      else {
1892        O << MAI->getCommentString() << " Loop Header is BB"
1893          << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1894      }
1895
1896      if (loop->empty()) {
1897        O << '\n';
1898        O.PadToColumn(MAI->getCommentColumn());
1899        O << MAI->getCommentString() << " Inner Loop";
1900      }
1901
1902      // Add parent loop information
1903      for (const MachineLoop *CurLoop = loop->getParentLoop();
1904           CurLoop;
1905           CurLoop = CurLoop->getParentLoop()) {
1906        MachineBasicBlock *Header = CurLoop->getHeader();
1907        assert(Header && "No header for loop");
1908
1909        O << '\n';
1910        O.PadToColumn(MAI->getCommentColumn());
1911        O << MAI->getCommentString();
1912        O.indent((CurLoop->getLoopDepth()-1)*2)
1913          << " Inside Loop BB" << getFunctionNumber() << "_"
1914          << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();
1915      }
1916    }
1917  }
1918}
1919