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