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