AsmPrinter.cpp revision 5fda434b0d4932d63b21ce3b5dd72c18e855da26
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 {
923    llvm_unreachable("Unknown constant value!");
924  }
925}
926
927/// printAsCString - Print the specified array as a C compatible string, only if
928/// the predicate isString is true.
929///
930static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
931                           unsigned LastElt) {
932  assert(CVA->isString() && "Array is not string compatible!");
933
934  O << '\"';
935  for (unsigned i = 0; i != LastElt; ++i) {
936    unsigned char C =
937        (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
938    printStringChar(O, C);
939  }
940  O << '\"';
941}
942
943/// EmitString - Emit a zero-byte-terminated string constant.
944///
945void AsmPrinter::EmitString(const ConstantArray *CVA) const {
946  unsigned NumElts = CVA->getNumOperands();
947  if (MAI->getAscizDirective() && NumElts &&
948      cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
949    O << MAI->getAscizDirective();
950    printAsCString(O, CVA, NumElts-1);
951  } else {
952    O << MAI->getAsciiDirective();
953    printAsCString(O, CVA, NumElts);
954  }
955  O << '\n';
956}
957
958void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
959                                         unsigned AddrSpace) {
960  if (CVA->isString()) {
961    EmitString(CVA);
962  } else { // Not a string.  Print the values in successive locations
963    for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
964      EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
965  }
966}
967
968void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
969  const VectorType *PTy = CP->getType();
970
971  for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
972    EmitGlobalConstant(CP->getOperand(I));
973}
974
975void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
976                                          unsigned AddrSpace) {
977  // Print the fields in successive locations. Pad to align if needed!
978  const TargetData *TD = TM.getTargetData();
979  unsigned Size = TD->getTypeAllocSize(CVS->getType());
980  const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
981  uint64_t sizeSoFar = 0;
982  for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
983    const Constant* field = CVS->getOperand(i);
984
985    // Check if padding is needed and insert one or more 0s.
986    uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
987    uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
988                        - cvsLayout->getElementOffset(i)) - fieldSize;
989    sizeSoFar += fieldSize + padSize;
990
991    // Now print the actual field value.
992    EmitGlobalConstant(field, AddrSpace);
993
994    // Insert padding - this may include padding to increase the size of the
995    // current field up to the ABI size (if the struct is not packed) as well
996    // as padding to ensure that the next field starts at the right offset.
997    EmitZeros(padSize, AddrSpace);
998  }
999  assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1000         "Layout of constant struct may be incorrect!");
1001}
1002
1003void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1004                                      unsigned AddrSpace) {
1005  // FP Constants are printed as integer constants to avoid losing
1006  // precision...
1007  LLVMContext &Context = CFP->getContext();
1008  const TargetData *TD = TM.getTargetData();
1009  if (CFP->getType()->isDoubleTy()) {
1010    double Val = CFP->getValueAPF().convertToDouble();  // for comment only
1011    uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1012    if (MAI->getData64bitsDirective(AddrSpace)) {
1013      O << MAI->getData64bitsDirective(AddrSpace) << i;
1014      if (VerboseAsm) {
1015        O.PadToColumn(MAI->getCommentColumn());
1016        O << MAI->getCommentString() << " double " << Val;
1017      }
1018      O << '\n';
1019    } else if (TD->isBigEndian()) {
1020      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1021      if (VerboseAsm) {
1022        O.PadToColumn(MAI->getCommentColumn());
1023        O << MAI->getCommentString()
1024          << " most significant word of double " << Val;
1025      }
1026      O << '\n';
1027      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1028      if (VerboseAsm) {
1029        O.PadToColumn(MAI->getCommentColumn());
1030        O << MAI->getCommentString()
1031          << " least significant word of double " << Val;
1032      }
1033      O << '\n';
1034    } else {
1035      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1036      if (VerboseAsm) {
1037        O.PadToColumn(MAI->getCommentColumn());
1038        O << MAI->getCommentString()
1039          << " least significant word of double " << Val;
1040      }
1041      O << '\n';
1042      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1043      if (VerboseAsm) {
1044        O.PadToColumn(MAI->getCommentColumn());
1045        O << MAI->getCommentString()
1046          << " most significant word of double " << Val;
1047      }
1048      O << '\n';
1049    }
1050    return;
1051  }
1052
1053  if (CFP->getType()->isFloatTy()) {
1054    float Val = CFP->getValueAPF().convertToFloat();  // for comment only
1055    O << MAI->getData32bitsDirective(AddrSpace)
1056      << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1057    if (VerboseAsm) {
1058      O.PadToColumn(MAI->getCommentColumn());
1059      O << MAI->getCommentString() << " float " << Val;
1060    }
1061    O << '\n';
1062    return;
1063  }
1064
1065  if (CFP->getType()->isX86_FP80Ty()) {
1066    // all long double variants are printed as hex
1067    // api needed to prevent premature destruction
1068    APInt api = CFP->getValueAPF().bitcastToAPInt();
1069    const uint64_t *p = api.getRawData();
1070    // Convert to double so we can print the approximate val as a comment.
1071    APFloat DoubleVal = CFP->getValueAPF();
1072    bool ignored;
1073    DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1074                      &ignored);
1075    if (TD->isBigEndian()) {
1076      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1077      if (VerboseAsm) {
1078        O.PadToColumn(MAI->getCommentColumn());
1079        O << MAI->getCommentString()
1080          << " most significant halfword of x86_fp80 ~"
1081          << DoubleVal.convertToDouble();
1082      }
1083      O << '\n';
1084      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1085      if (VerboseAsm) {
1086        O.PadToColumn(MAI->getCommentColumn());
1087        O << MAI->getCommentString() << " next halfword";
1088      }
1089      O << '\n';
1090      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1091      if (VerboseAsm) {
1092        O.PadToColumn(MAI->getCommentColumn());
1093        O << MAI->getCommentString() << " next halfword";
1094      }
1095      O << '\n';
1096      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1097      if (VerboseAsm) {
1098        O.PadToColumn(MAI->getCommentColumn());
1099        O << MAI->getCommentString() << " next halfword";
1100      }
1101      O << '\n';
1102      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1103      if (VerboseAsm) {
1104        O.PadToColumn(MAI->getCommentColumn());
1105        O << MAI->getCommentString()
1106          << " least significant halfword";
1107      }
1108      O << '\n';
1109     } else {
1110      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1111      if (VerboseAsm) {
1112        O.PadToColumn(MAI->getCommentColumn());
1113        O << MAI->getCommentString()
1114          << " least significant halfword of x86_fp80 ~"
1115          << DoubleVal.convertToDouble();
1116      }
1117      O << '\n';
1118      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1119      if (VerboseAsm) {
1120        O.PadToColumn(MAI->getCommentColumn());
1121        O << MAI->getCommentString()
1122          << " next halfword";
1123      }
1124      O << '\n';
1125      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1126      if (VerboseAsm) {
1127        O.PadToColumn(MAI->getCommentColumn());
1128        O << MAI->getCommentString()
1129          << " next halfword";
1130      }
1131      O << '\n';
1132      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1133      if (VerboseAsm) {
1134        O.PadToColumn(MAI->getCommentColumn());
1135        O << MAI->getCommentString()
1136          << " next halfword";
1137      }
1138      O << '\n';
1139      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1140      if (VerboseAsm) {
1141        O.PadToColumn(MAI->getCommentColumn());
1142        O << MAI->getCommentString()
1143          << " most significant halfword";
1144      }
1145      O << '\n';
1146    }
1147    EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1148              TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1149    return;
1150  }
1151
1152  if (CFP->getType()->isPPC_FP128Ty()) {
1153    // all long double variants are printed as hex
1154    // api needed to prevent premature destruction
1155    APInt api = CFP->getValueAPF().bitcastToAPInt();
1156    const uint64_t *p = api.getRawData();
1157    if (TD->isBigEndian()) {
1158      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1159      if (VerboseAsm) {
1160        O.PadToColumn(MAI->getCommentColumn());
1161        O << MAI->getCommentString()
1162          << " most significant word of ppc_fp128";
1163      }
1164      O << '\n';
1165      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1166      if (VerboseAsm) {
1167        O.PadToColumn(MAI->getCommentColumn());
1168        O << MAI->getCommentString()
1169        << " next word";
1170      }
1171      O << '\n';
1172      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1173      if (VerboseAsm) {
1174        O.PadToColumn(MAI->getCommentColumn());
1175        O << MAI->getCommentString()
1176          << " next word";
1177      }
1178      O << '\n';
1179      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1180      if (VerboseAsm) {
1181        O.PadToColumn(MAI->getCommentColumn());
1182        O << MAI->getCommentString()
1183          << " least significant word";
1184      }
1185      O << '\n';
1186     } else {
1187      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1188      if (VerboseAsm) {
1189        O.PadToColumn(MAI->getCommentColumn());
1190        O << MAI->getCommentString()
1191          << " least significant word of ppc_fp128";
1192      }
1193      O << '\n';
1194      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1195      if (VerboseAsm) {
1196        O.PadToColumn(MAI->getCommentColumn());
1197        O << MAI->getCommentString()
1198          << " next word";
1199      }
1200      O << '\n';
1201      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1202      if (VerboseAsm) {
1203        O.PadToColumn(MAI->getCommentColumn());
1204        O << MAI->getCommentString()
1205          << " next word";
1206      }
1207      O << '\n';
1208      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1209      if (VerboseAsm) {
1210        O.PadToColumn(MAI->getCommentColumn());
1211        O << MAI->getCommentString()
1212          << " most significant word";
1213      }
1214      O << '\n';
1215    }
1216    return;
1217  } else llvm_unreachable("Floating point constant type not handled");
1218}
1219
1220void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1221                                            unsigned AddrSpace) {
1222  const TargetData *TD = TM.getTargetData();
1223  unsigned BitWidth = CI->getBitWidth();
1224  assert(isPowerOf2_32(BitWidth) &&
1225         "Non-power-of-2-sized integers not handled!");
1226
1227  // We don't expect assemblers to support integer data directives
1228  // for more than 64 bits, so we emit the data in at most 64-bit
1229  // quantities at a time.
1230  const uint64_t *RawData = CI->getValue().getRawData();
1231  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1232    uint64_t Val;
1233    if (TD->isBigEndian())
1234      Val = RawData[e - i - 1];
1235    else
1236      Val = RawData[i];
1237
1238    if (MAI->getData64bitsDirective(AddrSpace))
1239      O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1240    else if (TD->isBigEndian()) {
1241      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1242      if (VerboseAsm) {
1243        O.PadToColumn(MAI->getCommentColumn());
1244        O << MAI->getCommentString()
1245          << " most significant half of i64 " << Val;
1246      }
1247      O << '\n';
1248      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1249      if (VerboseAsm) {
1250        O.PadToColumn(MAI->getCommentColumn());
1251        O << MAI->getCommentString()
1252          << " least significant half of i64 " << Val;
1253      }
1254      O << '\n';
1255    } else {
1256      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1257      if (VerboseAsm) {
1258        O.PadToColumn(MAI->getCommentColumn());
1259        O << MAI->getCommentString()
1260          << " least significant half of i64 " << Val;
1261      }
1262      O << '\n';
1263      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1264      if (VerboseAsm) {
1265        O.PadToColumn(MAI->getCommentColumn());
1266        O << MAI->getCommentString()
1267          << " most significant half of i64 " << Val;
1268      }
1269      O << '\n';
1270    }
1271  }
1272}
1273
1274/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1275void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1276  const TargetData *TD = TM.getTargetData();
1277  const Type *type = CV->getType();
1278  unsigned Size = TD->getTypeAllocSize(type);
1279
1280  if (CV->isNullValue() || isa<UndefValue>(CV)) {
1281    EmitZeros(Size, AddrSpace);
1282    return;
1283  } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1284    EmitGlobalConstantArray(CVA , AddrSpace);
1285    return;
1286  } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1287    EmitGlobalConstantStruct(CVS, AddrSpace);
1288    return;
1289  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1290    EmitGlobalConstantFP(CFP, AddrSpace);
1291    return;
1292  } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1293    // Small integers are handled below; large integers are handled here.
1294    if (Size > 4) {
1295      EmitGlobalConstantLargeInt(CI, AddrSpace);
1296      return;
1297    }
1298  } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1299    EmitGlobalConstantVector(CP);
1300    return;
1301  }
1302
1303  printDataDirective(type, AddrSpace);
1304  EmitConstantValueOnly(CV);
1305  if (VerboseAsm) {
1306    if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1307      SmallString<40> S;
1308      CI->getValue().toStringUnsigned(S, 16);
1309      O.PadToColumn(MAI->getCommentColumn());
1310      O << MAI->getCommentString() << " 0x" << S.str();
1311    }
1312  }
1313  O << '\n';
1314}
1315
1316void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1317  // Target doesn't support this yet!
1318  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1319}
1320
1321/// PrintSpecial - Print information related to the specified machine instr
1322/// that is independent of the operand, and may be independent of the instr
1323/// itself.  This can be useful for portably encoding the comment character
1324/// or other bits of target-specific knowledge into the asmstrings.  The
1325/// syntax used is ${:comment}.  Targets can override this to add support
1326/// for their own strange codes.
1327void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1328  if (!strcmp(Code, "private")) {
1329    O << MAI->getPrivateGlobalPrefix();
1330  } else if (!strcmp(Code, "comment")) {
1331    if (VerboseAsm)
1332      O << MAI->getCommentString();
1333  } else if (!strcmp(Code, "uid")) {
1334    // Comparing the address of MI isn't sufficient, because machineinstrs may
1335    // be allocated to the same address across functions.
1336    const Function *ThisF = MI->getParent()->getParent()->getFunction();
1337
1338    // If this is a new LastFn instruction, bump the counter.
1339    if (LastMI != MI || LastFn != ThisF) {
1340      ++Counter;
1341      LastMI = MI;
1342      LastFn = ThisF;
1343    }
1344    O << Counter;
1345  } else {
1346    std::string msg;
1347    raw_string_ostream Msg(msg);
1348    Msg << "Unknown special formatter '" << Code
1349         << "' for machine instr: " << *MI;
1350    llvm_report_error(Msg.str());
1351  }
1352}
1353
1354/// processDebugLoc - Processes the debug information of each machine
1355/// instruction's DebugLoc.
1356void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1357                                 bool BeforePrintingInsn) {
1358  if (!MAI || !DW)
1359    return;
1360  DebugLoc DL = MI->getDebugLoc();
1361  if (MAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1362    if (!DL.isUnknown()) {
1363      DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1364      if (BeforePrintingInsn) {
1365        if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
1366          printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1367                                          CurDLT.CompileUnit));
1368          O << '\n';
1369        }
1370      }
1371
1372      PrevDLT = CurDLT;
1373    }
1374  }
1375}
1376
1377/// printInlineAsm - This method formats and prints the specified machine
1378/// instruction that is an inline asm.
1379void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1380  unsigned NumOperands = MI->getNumOperands();
1381
1382  // Count the number of register definitions.
1383  unsigned NumDefs = 0;
1384  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1385       ++NumDefs)
1386    assert(NumDefs != NumOperands-1 && "No asm string?");
1387
1388  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1389
1390  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1391  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1392
1393  // If this asmstr is empty, just print the #APP/#NOAPP markers.
1394  // These are useful to see where empty asm's wound up.
1395  if (AsmStr[0] == 0) {
1396    O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1397    O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1398    return;
1399  }
1400
1401  O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1402
1403  // The variant of the current asmprinter.
1404  int AsmPrinterVariant = MAI->getAssemblerDialect();
1405
1406  int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1407  const char *LastEmitted = AsmStr; // One past the last character emitted.
1408
1409  while (*LastEmitted) {
1410    switch (*LastEmitted) {
1411    default: {
1412      // Not a special case, emit the string section literally.
1413      const char *LiteralEnd = LastEmitted+1;
1414      while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1415             *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1416        ++LiteralEnd;
1417      if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1418        O.write(LastEmitted, LiteralEnd-LastEmitted);
1419      LastEmitted = LiteralEnd;
1420      break;
1421    }
1422    case '\n':
1423      ++LastEmitted;   // Consume newline character.
1424      O << '\n';       // Indent code with newline.
1425      break;
1426    case '$': {
1427      ++LastEmitted;   // Consume '$' character.
1428      bool Done = true;
1429
1430      // Handle escapes.
1431      switch (*LastEmitted) {
1432      default: Done = false; break;
1433      case '$':     // $$ -> $
1434        if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1435          O << '$';
1436        ++LastEmitted;  // Consume second '$' character.
1437        break;
1438      case '(':             // $( -> same as GCC's { character.
1439        ++LastEmitted;      // Consume '(' character.
1440        if (CurVariant != -1) {
1441          llvm_report_error("Nested variants found in inline asm string: '"
1442                            + std::string(AsmStr) + "'");
1443        }
1444        CurVariant = 0;     // We're in the first variant now.
1445        break;
1446      case '|':
1447        ++LastEmitted;  // consume '|' character.
1448        if (CurVariant == -1)
1449          O << '|';       // this is gcc's behavior for | outside a variant
1450        else
1451          ++CurVariant;   // We're in the next variant.
1452        break;
1453      case ')':         // $) -> same as GCC's } char.
1454        ++LastEmitted;  // consume ')' character.
1455        if (CurVariant == -1)
1456          O << '}';     // this is gcc's behavior for } outside a variant
1457        else
1458          CurVariant = -1;
1459        break;
1460      }
1461      if (Done) break;
1462
1463      bool HasCurlyBraces = false;
1464      if (*LastEmitted == '{') {     // ${variable}
1465        ++LastEmitted;               // Consume '{' character.
1466        HasCurlyBraces = true;
1467      }
1468
1469      // If we have ${:foo}, then this is not a real operand reference, it is a
1470      // "magic" string reference, just like in .td files.  Arrange to call
1471      // PrintSpecial.
1472      if (HasCurlyBraces && *LastEmitted == ':') {
1473        ++LastEmitted;
1474        const char *StrStart = LastEmitted;
1475        const char *StrEnd = strchr(StrStart, '}');
1476        if (StrEnd == 0) {
1477          llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1478                            + std::string(AsmStr) + "'");
1479        }
1480
1481        std::string Val(StrStart, StrEnd);
1482        PrintSpecial(MI, Val.c_str());
1483        LastEmitted = StrEnd+1;
1484        break;
1485      }
1486
1487      const char *IDStart = LastEmitted;
1488      char *IDEnd;
1489      errno = 0;
1490      long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1491      if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1492        llvm_report_error("Bad $ operand number in inline asm string: '"
1493                          + std::string(AsmStr) + "'");
1494      }
1495      LastEmitted = IDEnd;
1496
1497      char Modifier[2] = { 0, 0 };
1498
1499      if (HasCurlyBraces) {
1500        // If we have curly braces, check for a modifier character.  This
1501        // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1502        if (*LastEmitted == ':') {
1503          ++LastEmitted;    // Consume ':' character.
1504          if (*LastEmitted == 0) {
1505            llvm_report_error("Bad ${:} expression in inline asm string: '"
1506                              + std::string(AsmStr) + "'");
1507          }
1508
1509          Modifier[0] = *LastEmitted;
1510          ++LastEmitted;    // Consume modifier character.
1511        }
1512
1513        if (*LastEmitted != '}') {
1514          llvm_report_error("Bad ${} expression in inline asm string: '"
1515                            + std::string(AsmStr) + "'");
1516        }
1517        ++LastEmitted;    // Consume '}' character.
1518      }
1519
1520      if ((unsigned)Val >= NumOperands-1) {
1521        llvm_report_error("Invalid $ operand number in inline asm string: '"
1522                          + std::string(AsmStr) + "'");
1523      }
1524
1525      // Okay, we finally have a value number.  Ask the target to print this
1526      // operand!
1527      if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1528        unsigned OpNo = 1;
1529
1530        bool Error = false;
1531
1532        // Scan to find the machine operand number for the operand.
1533        for (; Val; --Val) {
1534          if (OpNo >= MI->getNumOperands()) break;
1535          unsigned OpFlags = MI->getOperand(OpNo).getImm();
1536          OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1537        }
1538
1539        if (OpNo >= MI->getNumOperands()) {
1540          Error = true;
1541        } else {
1542          unsigned OpFlags = MI->getOperand(OpNo).getImm();
1543          ++OpNo;  // Skip over the ID number.
1544
1545          if (Modifier[0]=='l')  // labels are target independent
1546            GetMBBSymbol(MI->getOperand(OpNo).getMBB()
1547                           ->getNumber())->print(O, MAI);
1548          else {
1549            AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1550            if ((OpFlags & 7) == 4) {
1551              Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1552                                                Modifier[0] ? Modifier : 0);
1553            } else {
1554              Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1555                                          Modifier[0] ? Modifier : 0);
1556            }
1557          }
1558        }
1559        if (Error) {
1560          std::string msg;
1561          raw_string_ostream Msg(msg);
1562          Msg << "Invalid operand found in inline asm: '"
1563               << AsmStr << "'\n";
1564          MI->print(Msg);
1565          llvm_report_error(Msg.str());
1566        }
1567      }
1568      break;
1569    }
1570    }
1571  }
1572  O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1573}
1574
1575/// printImplicitDef - This method prints the specified machine instruction
1576/// that is an implicit def.
1577void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1578  if (!VerboseAsm) return;
1579  O.PadToColumn(MAI->getCommentColumn());
1580  O << MAI->getCommentString() << " implicit-def: "
1581    << TRI->getName(MI->getOperand(0).getReg());
1582}
1583
1584/// printLabel - This method prints a local label used by debug and
1585/// exception handling tables.
1586void AsmPrinter::printLabel(const MachineInstr *MI) const {
1587  printLabel(MI->getOperand(0).getImm());
1588}
1589
1590void AsmPrinter::printLabel(unsigned Id) const {
1591  O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1592}
1593
1594/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1595/// instruction, using the specified assembler variant.  Targets should
1596/// overried this to format as appropriate.
1597bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1598                                 unsigned AsmVariant, const char *ExtraCode) {
1599  // Target doesn't support this yet!
1600  return true;
1601}
1602
1603bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1604                                       unsigned AsmVariant,
1605                                       const char *ExtraCode) {
1606  // Target doesn't support this yet!
1607  return true;
1608}
1609
1610MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1611  SmallString<60> Name;
1612  raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1613    << getFunctionNumber() << '_' << MBBID;
1614
1615  return OutContext.GetOrCreateSymbol(Name.str());
1616}
1617
1618
1619/// EmitBasicBlockStart - This method prints the label for the specified
1620/// MachineBasicBlock, an alignment (if present) and a comment describing
1621/// it if appropriate.
1622void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1623  if (unsigned Align = MBB->getAlignment())
1624    EmitAlignment(Log2_32(Align));
1625
1626  if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1627    if (VerboseAsm)
1628      O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1629  } else {
1630    GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1631    O << ':';
1632    if (!VerboseAsm)
1633      O << '\n';
1634  }
1635
1636  if (VerboseAsm) {
1637    if (const BasicBlock *BB = MBB->getBasicBlock())
1638      if (BB->hasName()) {
1639        O.PadToColumn(MAI->getCommentColumn());
1640        O << MAI->getCommentString() << ' ';
1641        WriteAsOperand(O, BB, /*PrintType=*/false);
1642      }
1643
1644    EmitComments(*MBB);
1645    O << '\n';
1646  }
1647}
1648
1649/// printPICJumpTableSetLabel - This method prints a set label for the
1650/// specified MachineBasicBlock for a jumptable entry.
1651void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1652                                           const MachineBasicBlock *MBB) const {
1653  if (!MAI->getSetDirective())
1654    return;
1655
1656  O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1657    << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1658  GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1659  O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1660    << '_' << uid << '\n';
1661}
1662
1663void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1664                                           const MachineBasicBlock *MBB) const {
1665  if (!MAI->getSetDirective())
1666    return;
1667
1668  O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1669    << getFunctionNumber() << '_' << uid << '_' << uid2
1670    << "_set_" << MBB->getNumber() << ',';
1671  GetMBBSymbol(MBB->getNumber())->print(O, MAI);
1672  O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1673    << '_' << uid << '_' << uid2 << '\n';
1674}
1675
1676/// printDataDirective - This method prints the asm directive for the
1677/// specified type.
1678void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1679  const TargetData *TD = TM.getTargetData();
1680  switch (type->getTypeID()) {
1681  case Type::FloatTyID: case Type::DoubleTyID:
1682  case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1683    assert(0 && "Should have already output floating point constant.");
1684  default:
1685    assert(0 && "Can't handle printing this type of thing");
1686  case Type::IntegerTyID: {
1687    unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1688    if (BitWidth <= 8)
1689      O << MAI->getData8bitsDirective(AddrSpace);
1690    else if (BitWidth <= 16)
1691      O << MAI->getData16bitsDirective(AddrSpace);
1692    else if (BitWidth <= 32)
1693      O << MAI->getData32bitsDirective(AddrSpace);
1694    else if (BitWidth <= 64) {
1695      assert(MAI->getData64bitsDirective(AddrSpace) &&
1696             "Target cannot handle 64-bit constant exprs!");
1697      O << MAI->getData64bitsDirective(AddrSpace);
1698    } else {
1699      llvm_unreachable("Target cannot handle given data directive width!");
1700    }
1701    break;
1702  }
1703  case Type::PointerTyID:
1704    if (TD->getPointerSize() == 8) {
1705      assert(MAI->getData64bitsDirective(AddrSpace) &&
1706             "Target cannot handle 64-bit pointer exprs!");
1707      O << MAI->getData64bitsDirective(AddrSpace);
1708    } else if (TD->getPointerSize() == 2) {
1709      O << MAI->getData16bitsDirective(AddrSpace);
1710    } else if (TD->getPointerSize() == 1) {
1711      O << MAI->getData8bitsDirective(AddrSpace);
1712    } else {
1713      O << MAI->getData32bitsDirective(AddrSpace);
1714    }
1715    break;
1716  }
1717}
1718
1719void AsmPrinter::printVisibility(const std::string& Name,
1720                                 unsigned Visibility) const {
1721  if (Visibility == GlobalValue::HiddenVisibility) {
1722    if (const char *Directive = MAI->getHiddenDirective())
1723      O << Directive << Name << '\n';
1724  } else if (Visibility == GlobalValue::ProtectedVisibility) {
1725    if (const char *Directive = MAI->getProtectedDirective())
1726      O << Directive << Name << '\n';
1727  }
1728}
1729
1730void AsmPrinter::printOffset(int64_t Offset) const {
1731  if (Offset > 0)
1732    O << '+' << Offset;
1733  else if (Offset < 0)
1734    O << Offset;
1735}
1736
1737GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1738  if (!S->usesMetadata())
1739    return 0;
1740
1741  gcp_iterator GCPI = GCMetadataPrinters.find(S);
1742  if (GCPI != GCMetadataPrinters.end())
1743    return GCPI->second;
1744
1745  const char *Name = S->getName().c_str();
1746
1747  for (GCMetadataPrinterRegistry::iterator
1748         I = GCMetadataPrinterRegistry::begin(),
1749         E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1750    if (strcmp(Name, I->getName()) == 0) {
1751      GCMetadataPrinter *GMP = I->instantiate();
1752      GMP->S = S;
1753      GCMetadataPrinters.insert(std::make_pair(S, GMP));
1754      return GMP;
1755    }
1756
1757  errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1758  llvm_unreachable(0);
1759}
1760
1761/// EmitComments - Pretty-print comments for instructions
1762void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1763  assert(VerboseAsm && !MI.getDebugLoc().isUnknown());
1764
1765  DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1766
1767  // Print source line info.
1768  O.PadToColumn(MAI->getCommentColumn());
1769  O << MAI->getCommentString() << " SrcLine ";
1770  if (DLT.CompileUnit) {
1771    DICompileUnit CU(DLT.CompileUnit);
1772    O << CU.getFilename() << " ";
1773  }
1774  O << DLT.Line;
1775  if (DLT.Col != 0)
1776    O << ":" << DLT.Col;
1777}
1778
1779/// PrintChildLoopComment - Print comments about child loops within
1780/// the loop for this basic block, with nesting.
1781///
1782static void PrintChildLoopComment(formatted_raw_ostream &O,
1783                                  const MachineLoop *loop,
1784                                  const MCAsmInfo *MAI,
1785                                  int FunctionNumber) {
1786  // Add child loop information
1787  for(MachineLoop::iterator cl = loop->begin(),
1788        clend = loop->end();
1789      cl != clend;
1790      ++cl) {
1791    MachineBasicBlock *Header = (*cl)->getHeader();
1792    assert(Header && "No header for loop");
1793
1794    O << '\n';
1795    O.PadToColumn(MAI->getCommentColumn());
1796
1797    O << MAI->getCommentString();
1798    O.indent(((*cl)->getLoopDepth()-1)*2)
1799      << " Child Loop BB" << FunctionNumber << "_"
1800      << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1801
1802    PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1803  }
1804}
1805
1806/// EmitComments - Pretty-print comments for basic blocks
1807void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1808{
1809  if (VerboseAsm) {
1810    // Add loop depth information
1811    const MachineLoop *loop = LI->getLoopFor(&MBB);
1812
1813    if (loop) {
1814      // Print a newline after bb# annotation.
1815      O << "\n";
1816      O.PadToColumn(MAI->getCommentColumn());
1817      O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1818        << '\n';
1819
1820      O.PadToColumn(MAI->getCommentColumn());
1821
1822      MachineBasicBlock *Header = loop->getHeader();
1823      assert(Header && "No header for loop");
1824
1825      if (Header == &MBB) {
1826        O << MAI->getCommentString() << " Loop Header";
1827        PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1828      }
1829      else {
1830        O << MAI->getCommentString() << " Loop Header is BB"
1831          << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1832      }
1833
1834      if (loop->empty()) {
1835        O << '\n';
1836        O.PadToColumn(MAI->getCommentColumn());
1837        O << MAI->getCommentString() << " Inner Loop";
1838      }
1839
1840      // Add parent loop information
1841      for (const MachineLoop *CurLoop = loop->getParentLoop();
1842           CurLoop;
1843           CurLoop = CurLoop->getParentLoop()) {
1844        MachineBasicBlock *Header = CurLoop->getHeader();
1845        assert(Header && "No header for loop");
1846
1847        O << '\n';
1848        O.PadToColumn(MAI->getCommentColumn());
1849        O << MAI->getCommentString();
1850        O.indent((CurLoop->getLoopDepth()-1)*2)
1851          << " Inside Loop BB" << getFunctionNumber() << "_"
1852          << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();
1853      }
1854    }
1855  }
1856}
1857