]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/AsmPrinter/AsmPrinter.cpp
Revert r196270, "Generalize debug info / EH emission in AsmPrinter"
[opencl/llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
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 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/ConstantFolding.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CodeGen/GCMetadataPrinter.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/DebugInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/MCExpr.h"
36 #include "llvm/MC/MCInst.h"
37 #include "llvm/MC/MCSection.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Transforms/Utils/GlobalStatus.h"
52 using namespace llvm;
54 static const char *const DWARFGroupName = "DWARF Emission";
55 static const char *const DbgTimerName = "DWARF Debug Writer";
56 static const char *const EHTimerName = "DWARF Exception Writer";
58 STATISTIC(EmittedInsts, "Number of machine instrs printed");
60 char AsmPrinter::ID = 0;
62 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
63 static gcp_map_type &getGCMap(void *&P) {
64   if (P == 0)
65     P = new gcp_map_type();
66   return *(gcp_map_type*)P;
67 }
70 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
71 /// value in log2 form.  This rounds up to the preferred alignment if possible
72 /// and legal.
73 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
74                                    unsigned InBits = 0) {
75   unsigned NumBits = 0;
76   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
77     NumBits = TD.getPreferredAlignmentLog(GVar);
79   // If InBits is specified, round it to it.
80   if (InBits > NumBits)
81     NumBits = InBits;
83   // If the GV has a specified alignment, take it into account.
84   if (GV->getAlignment() == 0)
85     return NumBits;
87   unsigned GVAlign = Log2_32(GV->getAlignment());
89   // If the GVAlign is larger than NumBits, or if we are required to obey
90   // NumBits because the GV has an assigned section, obey it.
91   if (GVAlign > NumBits || GV->hasSection())
92     NumBits = GVAlign;
93   return NumBits;
94 }
96 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
97   : MachineFunctionPass(ID),
98     TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
99     OutContext(Streamer.getContext()),
100     OutStreamer(Streamer),
101     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
102   DD = 0; DE = 0; MMI = 0; LI = 0; MF = 0;
103   CurrentFnSym = CurrentFnSymForSize = 0;
104   GCMetadataPrinters = 0;
105   VerboseAsm = Streamer.isVerboseAsm();
108 AsmPrinter::~AsmPrinter() {
109   assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
111   if (GCMetadataPrinters != 0) {
112     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
114     for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
115       delete I->second;
116     delete &GCMap;
117     GCMetadataPrinters = 0;
118   }
120   delete &OutStreamer;
123 /// getFunctionNumber - Return a unique ID for the current function.
124 ///
125 unsigned AsmPrinter::getFunctionNumber() const {
126   return MF->getFunctionNumber();
129 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
130   return TM.getTargetLowering()->getObjFileLowering();
133 /// getDataLayout - Return information about data layout.
134 const DataLayout &AsmPrinter::getDataLayout() const {
135   return *TM.getDataLayout();
138 StringRef AsmPrinter::getTargetTriple() const {
139   return TM.getTargetTriple();
142 /// getCurrentSection() - Return the current section we are emitting to.
143 const MCSection *AsmPrinter::getCurrentSection() const {
144   return OutStreamer.getCurrentSection().first;
149 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
150   AU.setPreservesAll();
151   MachineFunctionPass::getAnalysisUsage(AU);
152   AU.addRequired<MachineModuleInfo>();
153   AU.addRequired<GCModuleInfo>();
154   if (isVerbose())
155     AU.addRequired<MachineLoopInfo>();
158 bool AsmPrinter::doInitialization(Module &M) {
159   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
160   MMI->AnalyzeModule(M);
162   // Initialize TargetLoweringObjectFile.
163   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
164     .Initialize(OutContext, TM);
166   OutStreamer.InitStreamer();
168   Mang = new Mangler(&TM);
170   // Allow the target to emit any magic that it wants at the start of the file.
171   EmitStartOfAsmFile(M);
173   // Very minimal debug info. It is ignored if we emit actual debug info. If we
174   // don't, this at least helps the user find where a global came from.
175   if (MAI->hasSingleParameterDotFile()) {
176     // .file "foo.c"
177     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
178   }
180   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
181   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
182   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
183     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
184       MP->beginAssembly(*this);
186   // Emit module-level inline asm if it exists.
187   if (!M.getModuleInlineAsm().empty()) {
188     OutStreamer.AddComment("Start of file scope inline assembly");
189     OutStreamer.AddBlankLine();
190     EmitInlineAsm(M.getModuleInlineAsm()+"\n");
191     OutStreamer.AddComment("End of file scope inline assembly");
192     OutStreamer.AddBlankLine();
193   }
195   if (MAI->doesSupportDebugInformation())
196     DD = new DwarfDebug(this, &M);
198   switch (MAI->getExceptionHandlingType()) {
199   case ExceptionHandling::None:
200     return false;
201   case ExceptionHandling::SjLj:
202   case ExceptionHandling::DwarfCFI:
203     DE = new DwarfCFIException(this);
204     return false;
205   case ExceptionHandling::ARM:
206     DE = new ARMException(this);
207     return false;
208   case ExceptionHandling::Win64:
209     DE = new Win64Exception(this);
210     return false;
211   }
213   llvm_unreachable("Unknown exception type.");
216 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
217   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
218   switch (Linkage) {
219   case GlobalValue::CommonLinkage:
220   case GlobalValue::LinkOnceAnyLinkage:
221   case GlobalValue::LinkOnceODRLinkage:
222   case GlobalValue::WeakAnyLinkage:
223   case GlobalValue::WeakODRLinkage:
224   case GlobalValue::LinkerPrivateWeakLinkage:
225     if (MAI->hasWeakDefDirective()) {
226       // .globl _foo
227       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
229       bool CanBeHidden = false;
231       if (Linkage == GlobalValue::LinkOnceODRLinkage) {
232         if (GV->hasUnnamedAddr()) {
233           CanBeHidden = true;
234         } else {
235           GlobalStatus GS;
236           if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
237             CanBeHidden = true;
238         }
239       }
241       if (!CanBeHidden)
242         // .weak_definition _foo
243         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
244       else
245         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
246     } else if (MAI->hasLinkOnceDirective()) {
247       // .globl _foo
248       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
249       //NOTE: linkonce is handled by the section the symbol was assigned to.
250     } else {
251       // .weak _foo
252       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
253     }
254     return;
255   case GlobalValue::DLLExportLinkage:
256   case GlobalValue::AppendingLinkage:
257     // FIXME: appending linkage variables should go into a section of
258     // their name or something.  For now, just emit them as external.
259   case GlobalValue::ExternalLinkage:
260     // If external or appending, declare as a global symbol.
261     // .globl _foo
262     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
263     return;
264   case GlobalValue::PrivateLinkage:
265   case GlobalValue::InternalLinkage:
266   case GlobalValue::LinkerPrivateLinkage:
267     return;
268   case GlobalValue::AvailableExternallyLinkage:
269     llvm_unreachable("Should never emit this");
270   case GlobalValue::DLLImportLinkage:
271   case GlobalValue::ExternalWeakLinkage:
272     llvm_unreachable("Don't know how to emit these");
273   }
274   llvm_unreachable("Unknown linkage type!");
277 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
278   return getObjFileLowering().getSymbol(*Mang, GV);
281 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
282 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
283   if (GV->hasInitializer()) {
284     // Check to see if this is a special global used by LLVM, if so, emit it.
285     if (EmitSpecialLLVMGlobal(GV))
286       return;
288     if (isVerbose()) {
289       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
290                      /*PrintType=*/false, GV->getParent());
291       OutStreamer.GetCommentOS() << '\n';
292     }
293   }
295   MCSymbol *GVSym = getSymbol(GV);
296   EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
298   if (!GV->hasInitializer())   // External globals require no extra code.
299     return;
301   if (MAI->hasDotTypeDotSizeDirective())
302     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
304   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
306   const DataLayout *DL = TM.getDataLayout();
307   uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
309   // If the alignment is specified, we *must* obey it.  Overaligning a global
310   // with a specified alignment is a prompt way to break globals emitted to
311   // sections and expected to be contiguous (e.g. ObjC metadata).
312   unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
314   if (DD)
315     DD->setSymbolSize(GVSym, Size);
317   // Handle common and BSS local symbols (.lcomm).
318   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
319     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
320     unsigned Align = 1 << AlignLog;
322     // Handle common symbols.
323     if (GVKind.isCommon()) {
324       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
325         Align = 0;
327       // .comm _foo, 42, 4
328       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
329       return;
330     }
332     // Handle local BSS symbols.
333     if (MAI->hasMachoZeroFillDirective()) {
334       const MCSection *TheSection =
335         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
336       // .zerofill __DATA, __bss, _foo, 400, 5
337       OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
338       return;
339     }
341     // Use .lcomm only if it supports user-specified alignment.
342     // Otherwise, while it would still be correct to use .lcomm in some
343     // cases (e.g. when Align == 1), the external assembler might enfore
344     // some -unknown- default alignment behavior, which could cause
345     // spurious differences between external and integrated assembler.
346     // Prefer to simply fall back to .local / .comm in this case.
347     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
348       // .lcomm _foo, 42
349       OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
350       return;
351     }
353     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
354       Align = 0;
356     // .local _foo
357     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
358     // .comm _foo, 42, 4
359     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
360     return;
361   }
363   const MCSection *TheSection =
364     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
366   // Handle the zerofill directive on darwin, which is a special form of BSS
367   // emission.
368   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
369     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
371     // .globl _foo
372     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
373     // .zerofill __DATA, __common, _foo, 400, 5
374     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
375     return;
376   }
378   // Handle thread local data for mach-o which requires us to output an
379   // additional structure of data and mangle the original symbol so that we
380   // can reference it later.
381   //
382   // TODO: This should become an "emit thread local global" method on TLOF.
383   // All of this macho specific stuff should be sunk down into TLOFMachO and
384   // stuff like "TLSExtraDataSection" should no longer be part of the parent
385   // TLOF class.  This will also make it more obvious that stuff like
386   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
387   // specific code.
388   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
389     // Emit the .tbss symbol
390     MCSymbol *MangSym =
391       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
393     if (GVKind.isThreadBSS()) {
394       TheSection = getObjFileLowering().getTLSBSSSection();
395       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
396     } else if (GVKind.isThreadData()) {
397       OutStreamer.SwitchSection(TheSection);
399       EmitAlignment(AlignLog, GV);
400       OutStreamer.EmitLabel(MangSym);
402       EmitGlobalConstant(GV->getInitializer());
403     }
405     OutStreamer.AddBlankLine();
407     // Emit the variable struct for the runtime.
408     const MCSection *TLVSect
409       = getObjFileLowering().getTLSExtraDataSection();
411     OutStreamer.SwitchSection(TLVSect);
412     // Emit the linkage here.
413     EmitLinkage(GV, GVSym);
414     OutStreamer.EmitLabel(GVSym);
416     // Three pointers in size:
417     //   - __tlv_bootstrap - used to make sure support exists
418     //   - spare pointer, used when mapped by the runtime
419     //   - pointer to mangled symbol above with initializer
420     unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
421     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
422                                 PtrSize);
423     OutStreamer.EmitIntValue(0, PtrSize);
424     OutStreamer.EmitSymbolValue(MangSym, PtrSize);
426     OutStreamer.AddBlankLine();
427     return;
428   }
430   OutStreamer.SwitchSection(TheSection);
432   EmitLinkage(GV, GVSym);
433   EmitAlignment(AlignLog, GV);
435   OutStreamer.EmitLabel(GVSym);
437   EmitGlobalConstant(GV->getInitializer());
439   if (MAI->hasDotTypeDotSizeDirective())
440     // .size foo, 42
441     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
443   OutStreamer.AddBlankLine();
446 /// EmitFunctionHeader - This method emits the header for the current
447 /// function.
448 void AsmPrinter::EmitFunctionHeader() {
449   // Print out constants referenced by the function
450   EmitConstantPool();
452   // Print the 'header' of function.
453   const Function *F = MF->getFunction();
455   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
456   EmitVisibility(CurrentFnSym, F->getVisibility());
458   EmitLinkage(F, CurrentFnSym);
459   EmitAlignment(MF->getAlignment(), F);
461   if (MAI->hasDotTypeDotSizeDirective())
462     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
464   if (isVerbose()) {
465     WriteAsOperand(OutStreamer.GetCommentOS(), F,
466                    /*PrintType=*/false, F->getParent());
467     OutStreamer.GetCommentOS() << '\n';
468   }
470   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
471   // do their wild and crazy things as required.
472   EmitFunctionEntryLabel();
474   // If the function had address-taken blocks that got deleted, then we have
475   // references to the dangling symbols.  Emit them at the start of the function
476   // so that we don't get references to undefined symbols.
477   std::vector<MCSymbol*> DeadBlockSyms;
478   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
479   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
480     OutStreamer.AddComment("Address taken block that was later removed");
481     OutStreamer.EmitLabel(DeadBlockSyms[i]);
482   }
484   // Emit pre-function debug and/or EH information.
485   if (DE) {
486     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
487     DE->beginFunction(MF);
488   }
489   if (DD) {
490     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
491     DD->beginFunction(MF);
492   }
494   // Emit the prefix data.
495   if (F->hasPrefixData())
496     EmitGlobalConstant(F->getPrefixData());
499 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
500 /// function.  This can be overridden by targets as required to do custom stuff.
501 void AsmPrinter::EmitFunctionEntryLabel() {
502   // The function label could have already been emitted if two symbols end up
503   // conflicting due to asm renaming.  Detect this and emit an error.
504   if (CurrentFnSym->isUndefined())
505     return OutStreamer.EmitLabel(CurrentFnSym);
507   report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
508                      "' label emitted multiple times to assembly file");
511 /// emitComments - Pretty-print comments for instructions.
512 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
513   const MachineFunction *MF = MI.getParent()->getParent();
514   const TargetMachine &TM = MF->getTarget();
516   // Check for spills and reloads
517   int FI;
519   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
521   // We assume a single instruction only has a spill or reload, not
522   // both.
523   const MachineMemOperand *MMO;
524   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
525     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
526       MMO = *MI.memoperands_begin();
527       CommentOS << MMO->getSize() << "-byte Reload\n";
528     }
529   } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
530     if (FrameInfo->isSpillSlotObjectIndex(FI))
531       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
532   } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
533     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
534       MMO = *MI.memoperands_begin();
535       CommentOS << MMO->getSize() << "-byte Spill\n";
536     }
537   } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
538     if (FrameInfo->isSpillSlotObjectIndex(FI))
539       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
540   }
542   // Check for spill-induced copies
543   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
544     CommentOS << " Reload Reuse\n";
547 /// emitImplicitDef - This method emits the specified machine instruction
548 /// that is an implicit def.
549 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
550   unsigned RegNo = MI->getOperand(0).getReg();
551   OutStreamer.AddComment(Twine("implicit-def: ") +
552                          TM.getRegisterInfo()->getName(RegNo));
553   OutStreamer.AddBlankLine();
556 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
557   std::string Str = "kill:";
558   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
559     const MachineOperand &Op = MI->getOperand(i);
560     assert(Op.isReg() && "KILL instruction must have only register operands");
561     Str += ' ';
562     Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
563     Str += (Op.isDef() ? "<def>" : "<kill>");
564   }
565   AP.OutStreamer.AddComment(Str);
566   AP.OutStreamer.AddBlankLine();
569 /// emitDebugValueComment - This method handles the target-independent form
570 /// of DBG_VALUE, returning true if it was able to do so.  A false return
571 /// means the target will need to handle MI in EmitInstruction.
572 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
573   // This code handles only the 3-operand target-independent form.
574   if (MI->getNumOperands() != 3)
575     return false;
577   SmallString<128> Str;
578   raw_svector_ostream OS(Str);
579   OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
581   // cast away const; DIetc do not take const operands for some reason.
582   DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
583   if (V.getContext().isSubprogram()) {
584     StringRef Name = DISubprogram(V.getContext()).getDisplayName();
585     if (!Name.empty())
586       OS << Name << ":";
587   }
588   OS << V.getName() << " <- ";
590   // The second operand is only an offset if it's an immediate.
591   bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
592   int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
594   // Register or immediate value. Register 0 means undef.
595   if (MI->getOperand(0).isFPImm()) {
596     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
597     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
598       OS << (double)APF.convertToFloat();
599     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
600       OS << APF.convertToDouble();
601     } else {
602       // There is no good way to print long double.  Convert a copy to
603       // double.  Ah well, it's only a comment.
604       bool ignored;
605       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
606                   &ignored);
607       OS << "(long double) " << APF.convertToDouble();
608     }
609   } else if (MI->getOperand(0).isImm()) {
610     OS << MI->getOperand(0).getImm();
611   } else if (MI->getOperand(0).isCImm()) {
612     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
613   } else {
614     unsigned Reg;
615     if (MI->getOperand(0).isReg()) {
616       Reg = MI->getOperand(0).getReg();
617     } else {
618       assert(MI->getOperand(0).isFI() && "Unknown operand type");
619       const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
620       Offset += TFI->getFrameIndexReference(*AP.MF,
621                                             MI->getOperand(0).getIndex(), Reg);
622       Deref = true;
623     }
624     if (Reg == 0) {
625       // Suppress offset, it is not meaningful here.
626       OS << "undef";
627       // NOTE: Want this comment at start of line, don't emit with AddComment.
628       AP.OutStreamer.EmitRawText(OS.str());
629       return true;
630     }
631     if (Deref)
632       OS << '[';
633     OS << AP.TM.getRegisterInfo()->getName(Reg);
634   }
636   if (Deref)
637     OS << '+' << Offset << ']';
639   // NOTE: Want this comment at start of line, don't emit with AddComment.
640   AP.OutStreamer.EmitRawText(OS.str());
641   return true;
644 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
645   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
646       MF->getFunction()->needsUnwindTableEntry())
647     return CFI_M_EH;
649   if (MMI->hasDebugInfo())
650     return CFI_M_Debug;
652   return CFI_M_None;
655 bool AsmPrinter::needsSEHMoves() {
656   return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
657     MF->getFunction()->needsUnwindTableEntry();
660 bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
661   return MAI->doesDwarfUseRelocationsAcrossSections();
664 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
665   const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
667   if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
668     return;
670   if (needsCFIMoves() == CFI_M_None)
671     return;
673   if (MMI->getCompactUnwindEncoding() != 0)
674     OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
676   const MachineModuleInfo &MMI = MF->getMMI();
677   const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
678   bool FoundOne = false;
679   (void)FoundOne;
680   for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
681          E = Instrs.end(); I != E; ++I) {
682     if (I->getLabel() == Label) {
683       emitCFIInstruction(*I);
684       FoundOne = true;
685     }
686   }
687   assert(FoundOne);
690 /// EmitFunctionBody - This method emits the body and trailer for a
691 /// function.
692 void AsmPrinter::EmitFunctionBody() {
693   // Emit target-specific gunk before the function body.
694   EmitFunctionBodyStart();
696   bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
698   // Print out code for the function.
699   bool HasAnyRealCode = false;
700   const MachineInstr *LastMI = 0;
701   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
702        I != E; ++I) {
703     // Print a label for the basic block.
704     EmitBasicBlockStart(I);
705     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
706          II != IE; ++II) {
707       LastMI = II;
709       // Print the assembly for the instruction.
710       if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
711           !II->isDebugValue()) {
712         HasAnyRealCode = true;
713         ++EmittedInsts;
714       }
716       if (ShouldPrintDebugScopes) {
717         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
718         DD->beginInstruction(II);
719       }
721       if (isVerbose())
722         emitComments(*II, OutStreamer.GetCommentOS());
724       switch (II->getOpcode()) {
725       case TargetOpcode::PROLOG_LABEL:
726         emitPrologLabel(*II);
727         break;
729       case TargetOpcode::EH_LABEL:
730       case TargetOpcode::GC_LABEL:
731         OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
732         break;
733       case TargetOpcode::INLINEASM:
734         EmitInlineAsm(II);
735         break;
736       case TargetOpcode::DBG_VALUE:
737         if (isVerbose()) {
738           if (!emitDebugValueComment(II, *this))
739             EmitInstruction(II);
740         }
741         break;
742       case TargetOpcode::IMPLICIT_DEF:
743         if (isVerbose()) emitImplicitDef(II);
744         break;
745       case TargetOpcode::KILL:
746         if (isVerbose()) emitKill(II, *this);
747         break;
748       default:
749         if (!TM.hasMCUseLoc())
750           MCLineEntry::Make(&OutStreamer, getCurrentSection());
752         EmitInstruction(II);
753         break;
754       }
756       if (ShouldPrintDebugScopes) {
757         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
758         DD->endInstruction(II);
759       }
760     }
761   }
763   // If the last instruction was a prolog label, then we have a situation where
764   // we emitted a prolog but no function body. This results in the ending prolog
765   // label equaling the end of function label and an invalid "row" in the
766   // FDE. We need to emit a noop in this situation so that the FDE's rows are
767   // valid.
768   bool RequiresNoop = LastMI && LastMI->isPrologLabel();
770   // If the function is empty and the object file uses .subsections_via_symbols,
771   // then we need to emit *something* to the function body to prevent the
772   // labels from collapsing together.  Just emit a noop.
773   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
774     MCInst Noop;
775     TM.getInstrInfo()->getNoopForMachoTarget(Noop);
776     if (Noop.getOpcode()) {
777       OutStreamer.AddComment("avoids zero-length function");
778       OutStreamer.EmitInstruction(Noop);
779     } else  // Target not mc-ized yet.
780       OutStreamer.EmitRawText(StringRef("\tnop\n"));
781   }
783   const Function *F = MF->getFunction();
784   for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
785     const BasicBlock *BB = i;
786     if (!BB->hasAddressTaken())
787       continue;
788     MCSymbol *Sym = GetBlockAddressSymbol(BB);
789     if (Sym->isDefined())
790       continue;
791     OutStreamer.AddComment("Address of block that was removed by CodeGen");
792     OutStreamer.EmitLabel(Sym);
793   }
795   // Emit target-specific gunk after the function body.
796   EmitFunctionBodyEnd();
798   // If the target wants a .size directive for the size of the function, emit
799   // it.
800   if (MAI->hasDotTypeDotSizeDirective()) {
801     // Create a symbol for the end of function, so we can get the size as
802     // difference between the function label and the temp label.
803     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
804     OutStreamer.EmitLabel(FnEndLabel);
806     const MCExpr *SizeExp =
807       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
808                               MCSymbolRefExpr::Create(CurrentFnSymForSize,
809                                                       OutContext),
810                               OutContext);
811     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
812   }
814   // Emit post-function debug information.
815   if (DD) {
816     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
817     DD->endFunction(MF);
818   }
819   if (DE) {
820     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
821     DE->endFunction();
822   }
823   MMI->EndFunction();
825   // Print out jump tables referenced by the function.
826   EmitJumpTableInfo();
828   OutStreamer.AddBlankLine();
831 /// EmitDwarfRegOp - Emit dwarf register operation.
832 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
833                                 bool Indirect) const {
834   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
835   int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
837   for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
838        ++SR) {
839     Reg = TRI->getDwarfRegNum(*SR, false);
840     // FIXME: Get the bit range this register uses of the superregister
841     // so that we can produce a DW_OP_bit_piece
842   }
844   // FIXME: Handle cases like a super register being encoded as
845   // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
847   // FIXME: We have no reasonable way of handling errors in here. The
848   // caller might be in the middle of an dwarf expression. We should
849   // probably assert that Reg >= 0 once debug info generation is more mature.
851   if (MLoc.isIndirect() || Indirect) {
852     if (Reg < 32) {
853       OutStreamer.AddComment(
854         dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
855       EmitInt8(dwarf::DW_OP_breg0 + Reg);
856     } else {
857       OutStreamer.AddComment("DW_OP_bregx");
858       EmitInt8(dwarf::DW_OP_bregx);
859       OutStreamer.AddComment(Twine(Reg));
860       EmitULEB128(Reg);
861     }
862     EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
863     if (MLoc.isIndirect() && Indirect)
864       EmitInt8(dwarf::DW_OP_deref);
865   } else {
866     if (Reg < 32) {
867       OutStreamer.AddComment(
868         dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
869       EmitInt8(dwarf::DW_OP_reg0 + Reg);
870     } else {
871       OutStreamer.AddComment("DW_OP_regx");
872       EmitInt8(dwarf::DW_OP_regx);
873       OutStreamer.AddComment(Twine(Reg));
874       EmitULEB128(Reg);
875     }
876   }
878   // FIXME: Produce a DW_OP_bit_piece if we used a superregister
881 bool AsmPrinter::doFinalization(Module &M) {
882   // Emit global variables.
883   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
884        I != E; ++I)
885     EmitGlobalVariable(I);
887   // Emit visibility info for declarations
888   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
889     const Function &F = *I;
890     if (!F.isDeclaration())
891       continue;
892     GlobalValue::VisibilityTypes V = F.getVisibility();
893     if (V == GlobalValue::DefaultVisibility)
894       continue;
896     MCSymbol *Name = getSymbol(&F);
897     EmitVisibility(Name, V, false);
898   }
900   // Emit module flags.
901   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
902   M.getModuleFlagsMetadata(ModuleFlags);
903   if (!ModuleFlags.empty())
904     getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
906   // Make sure we wrote out everything we need.
907   OutStreamer.Flush();
909   // Finalize debug and EH information.
910   if (DE) {
911     {
912       NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
913       DE->endModule();
914     }
915     delete DE; DE = 0;
916   }
917   if (DD) {
918     {
919       NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
920       DD->endModule();
921     }
922     delete DD; DD = 0;
923   }
925   // If the target wants to know about weak references, print them all.
926   if (MAI->getWeakRefDirective()) {
927     // FIXME: This is not lazy, it would be nice to only print weak references
928     // to stuff that is actually used.  Note that doing so would require targets
929     // to notice uses in operands (due to constant exprs etc).  This should
930     // happen with the MC stuff eventually.
932     // Print out module-level global variables here.
933     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
934          I != E; ++I) {
935       if (!I->hasExternalWeakLinkage()) continue;
936       OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
937     }
939     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
940       if (!I->hasExternalWeakLinkage()) continue;
941       OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
942     }
943   }
945   if (MAI->hasSetDirective()) {
946     OutStreamer.AddBlankLine();
947     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
948          I != E; ++I) {
949       MCSymbol *Name = getSymbol(I);
951       const GlobalValue *GV = I->getAliasedGlobal();
952       if (GV->isDeclaration()) {
953         report_fatal_error(Name->getName() +
954                            ": Target doesn't support aliases to declarations");
955       }
957       MCSymbol *Target = getSymbol(GV);
959       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
960         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
961       else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
962         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
963       else
964         assert(I->hasLocalLinkage() && "Invalid alias linkage");
966       EmitVisibility(Name, I->getVisibility());
968       // Emit the directives as assignments aka .set:
969       OutStreamer.EmitAssignment(Name,
970                                  MCSymbolRefExpr::Create(Target, OutContext));
971     }
972   }
974   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
975   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
976   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
977     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
978       MP->finishAssembly(*this);
980   // Emit llvm.ident metadata in an '.ident' directive.
981   EmitModuleIdents(M);
983   // If we don't have any trampolines, then we don't require stack memory
984   // to be executable. Some targets have a directive to declare this.
985   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
986   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
987     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
988       OutStreamer.SwitchSection(S);
990   // Allow the target to emit any magic that it wants at the end of the file,
991   // after everything else has gone out.
992   EmitEndOfAsmFile(M);
994   delete Mang; Mang = 0;
995   MMI = 0;
997   OutStreamer.Finish();
998   OutStreamer.reset();
1000   return false;
1003 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1004   this->MF = &MF;
1005   // Get the function symbol.
1006   CurrentFnSym = getSymbol(MF.getFunction());
1007   CurrentFnSymForSize = CurrentFnSym;
1009   if (isVerbose())
1010     LI = &getAnalysis<MachineLoopInfo>();
1013 namespace {
1014   // SectionCPs - Keep track the alignment, constpool entries per Section.
1015   struct SectionCPs {
1016     const MCSection *S;
1017     unsigned Alignment;
1018     SmallVector<unsigned, 4> CPEs;
1019     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1020   };
1023 /// EmitConstantPool - Print to the current output stream assembly
1024 /// representations of the constants in the constant pool MCP. This is
1025 /// used to print out constants which have been "spilled to memory" by
1026 /// the code generator.
1027 ///
1028 void AsmPrinter::EmitConstantPool() {
1029   const MachineConstantPool *MCP = MF->getConstantPool();
1030   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1031   if (CP.empty()) return;
1033   // Calculate sections for constant pool entries. We collect entries to go into
1034   // the same section together to reduce amount of section switch statements.
1035   SmallVector<SectionCPs, 4> CPSections;
1036   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1037     const MachineConstantPoolEntry &CPE = CP[i];
1038     unsigned Align = CPE.getAlignment();
1040     SectionKind Kind;
1041     switch (CPE.getRelocationInfo()) {
1042     default: llvm_unreachable("Unknown section kind");
1043     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1044     case 1:
1045       Kind = SectionKind::getReadOnlyWithRelLocal();
1046       break;
1047     case 0:
1048     switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1049     case 4:  Kind = SectionKind::getMergeableConst4(); break;
1050     case 8:  Kind = SectionKind::getMergeableConst8(); break;
1051     case 16: Kind = SectionKind::getMergeableConst16();break;
1052     default: Kind = SectionKind::getMergeableConst(); break;
1053     }
1054     }
1056     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1058     // The number of sections are small, just do a linear search from the
1059     // last section to the first.
1060     bool Found = false;
1061     unsigned SecIdx = CPSections.size();
1062     while (SecIdx != 0) {
1063       if (CPSections[--SecIdx].S == S) {
1064         Found = true;
1065         break;
1066       }
1067     }
1068     if (!Found) {
1069       SecIdx = CPSections.size();
1070       CPSections.push_back(SectionCPs(S, Align));
1071     }
1073     if (Align > CPSections[SecIdx].Alignment)
1074       CPSections[SecIdx].Alignment = Align;
1075     CPSections[SecIdx].CPEs.push_back(i);
1076   }
1078   // Now print stuff into the calculated sections.
1079   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1080     OutStreamer.SwitchSection(CPSections[i].S);
1081     EmitAlignment(Log2_32(CPSections[i].Alignment));
1083     unsigned Offset = 0;
1084     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1085       unsigned CPI = CPSections[i].CPEs[j];
1086       MachineConstantPoolEntry CPE = CP[CPI];
1088       // Emit inter-object padding for alignment.
1089       unsigned AlignMask = CPE.getAlignment() - 1;
1090       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1091       OutStreamer.EmitZeros(NewOffset - Offset);
1093       Type *Ty = CPE.getType();
1094       Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1095       OutStreamer.EmitLabel(GetCPISymbol(CPI));
1097       if (CPE.isMachineConstantPoolEntry())
1098         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1099       else
1100         EmitGlobalConstant(CPE.Val.ConstVal);
1101     }
1102   }
1105 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1106 /// by the current function to the current output stream.
1107 ///
1108 void AsmPrinter::EmitJumpTableInfo() {
1109   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1110   if (MJTI == 0) return;
1111   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1112   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1113   if (JT.empty()) return;
1115   // Pick the directive to use to print the jump table entries, and switch to
1116   // the appropriate section.
1117   const Function *F = MF->getFunction();
1118   bool JTInDiffSection = false;
1119   if (// In PIC mode, we need to emit the jump table to the same section as the
1120       // function body itself, otherwise the label differences won't make sense.
1121       // FIXME: Need a better predicate for this: what about custom entries?
1122       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1123       // We should also do if the section name is NULL or function is declared
1124       // in discardable section
1125       // FIXME: this isn't the right predicate, should be based on the MCSection
1126       // for the function.
1127       F->isWeakForLinker()) {
1128     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1129   } else {
1130     // Otherwise, drop it in the readonly section.
1131     const MCSection *ReadOnlySection =
1132       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1133     OutStreamer.SwitchSection(ReadOnlySection);
1134     JTInDiffSection = true;
1135   }
1137   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1139   // Jump tables in code sections are marked with a data_region directive
1140   // where that's supported.
1141   if (!JTInDiffSection)
1142     OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1144   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1145     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1147     // If this jump table was deleted, ignore it.
1148     if (JTBBs.empty()) continue;
1150     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1151     // .set directive for each unique entry.  This reduces the number of
1152     // relocations the assembler will generate for the jump table.
1153     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1154         MAI->hasSetDirective()) {
1155       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1156       const TargetLowering *TLI = TM.getTargetLowering();
1157       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1158       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1159         const MachineBasicBlock *MBB = JTBBs[ii];
1160         if (!EmittedSets.insert(MBB)) continue;
1162         // .set LJTSet, LBB32-base
1163         const MCExpr *LHS =
1164           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1165         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1166                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1167       }
1168     }
1170     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1171     // before each jump table.  The first label is never referenced, but tells
1172     // the assembler and linker the extents of the jump table object.  The
1173     // second label is actually referenced by the code.
1174     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1175       // FIXME: This doesn't have to have any specific name, just any randomly
1176       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1177       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1179     OutStreamer.EmitLabel(GetJTISymbol(JTI));
1181     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1182       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1183   }
1184   if (!JTInDiffSection)
1185     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1188 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1189 /// current stream.
1190 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1191                                     const MachineBasicBlock *MBB,
1192                                     unsigned UID) const {
1193   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1194   const MCExpr *Value = 0;
1195   switch (MJTI->getEntryKind()) {
1196   case MachineJumpTableInfo::EK_Inline:
1197     llvm_unreachable("Cannot emit EK_Inline jump table entry");
1198   case MachineJumpTableInfo::EK_Custom32:
1199     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1200                                                               OutContext);
1201     break;
1202   case MachineJumpTableInfo::EK_BlockAddress:
1203     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1204     //     .word LBB123
1205     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1206     break;
1207   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1208     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1209     // with a relocation as gp-relative, e.g.:
1210     //     .gprel32 LBB123
1211     MCSymbol *MBBSym = MBB->getSymbol();
1212     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1213     return;
1214   }
1216   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1217     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1218     // with a relocation as gp-relative, e.g.:
1219     //     .gpdword LBB123
1220     MCSymbol *MBBSym = MBB->getSymbol();
1221     OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1222     return;
1223   }
1225   case MachineJumpTableInfo::EK_LabelDifference32: {
1226     // EK_LabelDifference32 - Each entry is the address of the block minus
1227     // the address of the jump table.  This is used for PIC jump tables where
1228     // gprel32 is not supported.  e.g.:
1229     //      .word LBB123 - LJTI1_2
1230     // If the .set directive is supported, this is emitted as:
1231     //      .set L4_5_set_123, LBB123 - LJTI1_2
1232     //      .word L4_5_set_123
1234     // If we have emitted set directives for the jump table entries, print
1235     // them rather than the entries themselves.  If we're emitting PIC, then
1236     // emit the table entries as differences between two text section labels.
1237     if (MAI->hasSetDirective()) {
1238       // If we used .set, reference the .set's symbol.
1239       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1240                                       OutContext);
1241       break;
1242     }
1243     // Otherwise, use the difference as the jump table entry.
1244     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1245     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1246     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1247     break;
1248   }
1249   }
1251   assert(Value && "Unknown entry kind!");
1253   unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1254   OutStreamer.EmitValue(Value, EntrySize);
1258 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1259 /// special global used by LLVM.  If so, emit it and return true, otherwise
1260 /// do nothing and return false.
1261 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1262   if (GV->getName() == "llvm.used") {
1263     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1264       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1265     return true;
1266   }
1268   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1269   if (GV->getSection() == "llvm.metadata" ||
1270       GV->hasAvailableExternallyLinkage())
1271     return true;
1273   if (!GV->hasAppendingLinkage()) return false;
1275   assert(GV->hasInitializer() && "Not a special LLVM global!");
1277   if (GV->getName() == "llvm.global_ctors") {
1278     EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1280     if (TM.getRelocationModel() == Reloc::Static &&
1281         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1282       StringRef Sym(".constructors_used");
1283       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1284                                       MCSA_Reference);
1285     }
1286     return true;
1287   }
1289   if (GV->getName() == "llvm.global_dtors") {
1290     EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1292     if (TM.getRelocationModel() == Reloc::Static &&
1293         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1294       StringRef Sym(".destructors_used");
1295       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1296                                       MCSA_Reference);
1297     }
1298     return true;
1299   }
1301   return false;
1304 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1305 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1306 /// is true, as being used with this directive.
1307 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1308   // Should be an array of 'i8*'.
1309   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1310     const GlobalValue *GV =
1311       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1312     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1313       OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1314   }
1317 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1318 /// priority.
1319 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1320   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1321   // init priority.
1322   if (!isa<ConstantArray>(List)) return;
1324   // Sanity check the structors list.
1325   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1326   if (!InitList) return; // Not an array!
1327   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1328   if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1329   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1330       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1332   // Gather the structors in a form that's convenient for sorting by priority.
1333   typedef std::pair<unsigned, Constant *> Structor;
1334   SmallVector<Structor, 8> Structors;
1335   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1336     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1337     if (!CS) continue; // Malformed.
1338     if (CS->getOperand(1)->isNullValue())
1339       break;  // Found a null terminator, skip the rest.
1340     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1341     if (!Priority) continue; // Malformed.
1342     Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1343                                        CS->getOperand(1)));
1344   }
1346   // Emit the function pointers in the target-specific order
1347   const DataLayout *DL = TM.getDataLayout();
1348   unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1349   std::stable_sort(Structors.begin(), Structors.end(), less_first());
1350   for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1351     const MCSection *OutputSection =
1352       (isCtor ?
1353        getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1354        getObjFileLowering().getStaticDtorSection(Structors[i].first));
1355     OutStreamer.SwitchSection(OutputSection);
1356     if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1357       EmitAlignment(Align);
1358     EmitXXStructor(Structors[i].second);
1359   }
1362 void AsmPrinter::EmitModuleIdents(Module &M) {
1363   if (!MAI->hasIdentDirective())
1364     return;
1366   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1367     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1368       const MDNode *N = NMD->getOperand(i);
1369       assert(N->getNumOperands() == 1 && 
1370              "llvm.ident metadata entry can have only one operand");
1371       const MDString *S = cast<MDString>(N->getOperand(0));
1372       OutStreamer.EmitIdent(S->getString());
1373     }
1374   }
1377 //===--------------------------------------------------------------------===//
1378 // Emission and print routines
1379 //
1381 /// EmitInt8 - Emit a byte directive and value.
1382 ///
1383 void AsmPrinter::EmitInt8(int Value) const {
1384   OutStreamer.EmitIntValue(Value, 1);
1387 /// EmitInt16 - Emit a short directive and value.
1388 ///
1389 void AsmPrinter::EmitInt16(int Value) const {
1390   OutStreamer.EmitIntValue(Value, 2);
1393 /// EmitInt32 - Emit a long directive and value.
1394 ///
1395 void AsmPrinter::EmitInt32(int Value) const {
1396   OutStreamer.EmitIntValue(Value, 4);
1399 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1400 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1401 /// labels.  This implicitly uses .set if it is available.
1402 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1403                                      unsigned Size) const {
1404   // Get the Hi-Lo expression.
1405   const MCExpr *Diff =
1406     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1407                             MCSymbolRefExpr::Create(Lo, OutContext),
1408                             OutContext);
1410   if (!MAI->hasSetDirective()) {
1411     OutStreamer.EmitValue(Diff, Size);
1412     return;
1413   }
1415   // Otherwise, emit with .set (aka assignment).
1416   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1417   OutStreamer.EmitAssignment(SetLabel, Diff);
1418   OutStreamer.EmitSymbolValue(SetLabel, Size);
1421 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1422 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1423 /// specify the labels.  This implicitly uses .set if it is available.
1424 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1425                                            const MCSymbol *Lo, unsigned Size)
1426   const {
1428   // Emit Hi+Offset - Lo
1429   // Get the Hi+Offset expression.
1430   const MCExpr *Plus =
1431     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1432                             MCConstantExpr::Create(Offset, OutContext),
1433                             OutContext);
1435   // Get the Hi+Offset-Lo expression.
1436   const MCExpr *Diff =
1437     MCBinaryExpr::CreateSub(Plus,
1438                             MCSymbolRefExpr::Create(Lo, OutContext),
1439                             OutContext);
1441   if (!MAI->hasSetDirective())
1442     OutStreamer.EmitValue(Diff, Size);
1443   else {
1444     // Otherwise, emit with .set (aka assignment).
1445     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1446     OutStreamer.EmitAssignment(SetLabel, Diff);
1447     OutStreamer.EmitSymbolValue(SetLabel, Size);
1448   }
1451 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1452 /// where the size in bytes of the directive is specified by Size and Label
1453 /// specifies the label.  This implicitly uses .set if it is available.
1454 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1455                                      unsigned Size,
1456                                      bool IsSectionRelative) const {
1457   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1458     OutStreamer.EmitCOFFSecRel32(Label);
1459     return;
1460   }
1462   // Emit Label+Offset (or just Label if Offset is zero)
1463   const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1464   if (Offset)
1465     Expr = MCBinaryExpr::CreateAdd(
1466         Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1468   OutStreamer.EmitValue(Expr, Size);
1471 //===----------------------------------------------------------------------===//
1473 // EmitAlignment - Emit an alignment directive to the specified power of
1474 // two boundary.  For example, if you pass in 3 here, you will get an 8
1475 // byte alignment.  If a global value is specified, and if that global has
1476 // an explicit alignment requested, it will override the alignment request
1477 // if required for correctness.
1478 //
1479 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1480   if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1482   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1484   if (getCurrentSection()->getKind().isText())
1485     OutStreamer.EmitCodeAlignment(1 << NumBits);
1486   else
1487     OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1490 //===----------------------------------------------------------------------===//
1491 // Constant emission.
1492 //===----------------------------------------------------------------------===//
1494 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1495 ///
1496 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1497   MCContext &Ctx = AP.OutContext;
1499   if (CV->isNullValue() || isa<UndefValue>(CV))
1500     return MCConstantExpr::Create(0, Ctx);
1502   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1503     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1505   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1506     return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1508   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1509     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1511   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1512   if (CE == 0) {
1513     llvm_unreachable("Unknown constant value to lower!");
1514   }
1516   switch (CE->getOpcode()) {
1517   default:
1518     // If the code isn't optimized, there may be outstanding folding
1519     // opportunities. Attempt to fold the expression using DataLayout as a
1520     // last resort before giving up.
1521     if (Constant *C =
1522           ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1523       if (C != CE)
1524         return lowerConstant(C, AP);
1526     // Otherwise report the problem to the user.
1527     {
1528       std::string S;
1529       raw_string_ostream OS(S);
1530       OS << "Unsupported expression in static initializer: ";
1531       WriteAsOperand(OS, CE, /*PrintType=*/false,
1532                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1533       report_fatal_error(OS.str());
1534     }
1535   case Instruction::GetElementPtr: {
1536     const DataLayout &DL = *AP.TM.getDataLayout();
1537     // Generate a symbolic expression for the byte address
1538     APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1539     cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1541     const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1542     if (!OffsetAI)
1543       return Base;
1545     int64_t Offset = OffsetAI.getSExtValue();
1546     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1547                                    Ctx);
1548   }
1550   case Instruction::Trunc:
1551     // We emit the value and depend on the assembler to truncate the generated
1552     // expression properly.  This is important for differences between
1553     // blockaddress labels.  Since the two labels are in the same function, it
1554     // is reasonable to treat their delta as a 32-bit value.
1555     // FALL THROUGH.
1556   case Instruction::BitCast:
1557     return lowerConstant(CE->getOperand(0), AP);
1559   case Instruction::IntToPtr: {
1560     const DataLayout &DL = *AP.TM.getDataLayout();
1561     // Handle casts to pointers by changing them into casts to the appropriate
1562     // integer type.  This promotes constant folding and simplifies this code.
1563     Constant *Op = CE->getOperand(0);
1564     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1565                                       false/*ZExt*/);
1566     return lowerConstant(Op, AP);
1567   }
1569   case Instruction::PtrToInt: {
1570     const DataLayout &DL = *AP.TM.getDataLayout();
1571     // Support only foldable casts to/from pointers that can be eliminated by
1572     // changing the pointer to the appropriately sized integer type.
1573     Constant *Op = CE->getOperand(0);
1574     Type *Ty = CE->getType();
1576     const MCExpr *OpExpr = lowerConstant(Op, AP);
1578     // We can emit the pointer value into this slot if the slot is an
1579     // integer slot equal to the size of the pointer.
1580     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1581       return OpExpr;
1583     // Otherwise the pointer is smaller than the resultant integer, mask off
1584     // the high bits so we are sure to get a proper truncation if the input is
1585     // a constant expr.
1586     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1587     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1588     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1589   }
1591   // The MC library also has a right-shift operator, but it isn't consistently
1592   // signed or unsigned between different targets.
1593   case Instruction::Add:
1594   case Instruction::Sub:
1595   case Instruction::Mul:
1596   case Instruction::SDiv:
1597   case Instruction::SRem:
1598   case Instruction::Shl:
1599   case Instruction::And:
1600   case Instruction::Or:
1601   case Instruction::Xor: {
1602     const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1603     const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1604     switch (CE->getOpcode()) {
1605     default: llvm_unreachable("Unknown binary operator constant cast expr");
1606     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1607     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1608     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1609     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1610     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1611     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1612     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1613     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1614     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1615     }
1616   }
1617   }
1620 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1622 /// isRepeatedByteSequence - Determine whether the given value is
1623 /// composed of a repeated sequence of identical bytes and return the
1624 /// byte value.  If it is not a repeated sequence, return -1.
1625 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1626   StringRef Data = V->getRawDataValues();
1627   assert(!Data.empty() && "Empty aggregates should be CAZ node");
1628   char C = Data[0];
1629   for (unsigned i = 1, e = Data.size(); i != e; ++i)
1630     if (Data[i] != C) return -1;
1631   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1635 /// isRepeatedByteSequence - Determine whether the given value is
1636 /// composed of a repeated sequence of identical bytes and return the
1637 /// byte value.  If it is not a repeated sequence, return -1.
1638 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1640   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1641     if (CI->getBitWidth() > 64) return -1;
1643     uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1644     uint64_t Value = CI->getZExtValue();
1646     // Make sure the constant is at least 8 bits long and has a power
1647     // of 2 bit width.  This guarantees the constant bit width is
1648     // always a multiple of 8 bits, avoiding issues with padding out
1649     // to Size and other such corner cases.
1650     if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1652     uint8_t Byte = static_cast<uint8_t>(Value);
1654     for (unsigned i = 1; i < Size; ++i) {
1655       Value >>= 8;
1656       if (static_cast<uint8_t>(Value) != Byte) return -1;
1657     }
1658     return Byte;
1659   }
1660   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1661     // Make sure all array elements are sequences of the same repeated
1662     // byte.
1663     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1664     int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1665     if (Byte == -1) return -1;
1667     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1668       int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1669       if (ThisByte == -1) return -1;
1670       if (Byte != ThisByte) return -1;
1671     }
1672     return Byte;
1673   }
1675   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1676     return isRepeatedByteSequence(CDS);
1678   return -1;
1681 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1682                                              AsmPrinter &AP){
1684   // See if we can aggregate this into a .fill, if so, emit it as such.
1685   int Value = isRepeatedByteSequence(CDS, AP.TM);
1686   if (Value != -1) {
1687     uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1688     // Don't emit a 1-byte object as a .fill.
1689     if (Bytes > 1)
1690       return AP.OutStreamer.EmitFill(Bytes, Value);
1691   }
1693   // If this can be emitted with .ascii/.asciz, emit it as such.
1694   if (CDS->isString())
1695     return AP.OutStreamer.EmitBytes(CDS->getAsString());
1697   // Otherwise, emit the values in successive locations.
1698   unsigned ElementByteSize = CDS->getElementByteSize();
1699   if (isa<IntegerType>(CDS->getElementType())) {
1700     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1701       if (AP.isVerbose())
1702         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1703                                                 CDS->getElementAsInteger(i));
1704       AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1705                                   ElementByteSize);
1706     }
1707   } else if (ElementByteSize == 4) {
1708     // FP Constants are printed as integer constants to avoid losing
1709     // precision.
1710     assert(CDS->getElementType()->isFloatTy());
1711     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1712       union {
1713         float F;
1714         uint32_t I;
1715       };
1717       F = CDS->getElementAsFloat(i);
1718       if (AP.isVerbose())
1719         AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1720       AP.OutStreamer.EmitIntValue(I, 4);
1721     }
1722   } else {
1723     assert(CDS->getElementType()->isDoubleTy());
1724     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1725       union {
1726         double F;
1727         uint64_t I;
1728       };
1730       F = CDS->getElementAsDouble(i);
1731       if (AP.isVerbose())
1732         AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1733       AP.OutStreamer.EmitIntValue(I, 8);
1734     }
1735   }
1737   const DataLayout &DL = *AP.TM.getDataLayout();
1738   unsigned Size = DL.getTypeAllocSize(CDS->getType());
1739   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1740                         CDS->getNumElements();
1741   if (unsigned Padding = Size - EmittedSize)
1742     AP.OutStreamer.EmitZeros(Padding);
1746 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1747   // See if we can aggregate some values.  Make sure it can be
1748   // represented as a series of bytes of the constant value.
1749   int Value = isRepeatedByteSequence(CA, AP.TM);
1751   if (Value != -1) {
1752     uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1753     AP.OutStreamer.EmitFill(Bytes, Value);
1754   }
1755   else {
1756     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1757       emitGlobalConstantImpl(CA->getOperand(i), AP);
1758   }
1761 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1762   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1763     emitGlobalConstantImpl(CV->getOperand(i), AP);
1765   const DataLayout &DL = *AP.TM.getDataLayout();
1766   unsigned Size = DL.getTypeAllocSize(CV->getType());
1767   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1768                          CV->getType()->getNumElements();
1769   if (unsigned Padding = Size - EmittedSize)
1770     AP.OutStreamer.EmitZeros(Padding);
1773 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1774   // Print the fields in successive locations. Pad to align if needed!
1775   const DataLayout *DL = AP.TM.getDataLayout();
1776   unsigned Size = DL->getTypeAllocSize(CS->getType());
1777   const StructLayout *Layout = DL->getStructLayout(CS->getType());
1778   uint64_t SizeSoFar = 0;
1779   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1780     const Constant *Field = CS->getOperand(i);
1782     // Check if padding is needed and insert one or more 0s.
1783     uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1784     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1785                         - Layout->getElementOffset(i)) - FieldSize;
1786     SizeSoFar += FieldSize + PadSize;
1788     // Now print the actual field value.
1789     emitGlobalConstantImpl(Field, AP);
1791     // Insert padding - this may include padding to increase the size of the
1792     // current field up to the ABI size (if the struct is not packed) as well
1793     // as padding to ensure that the next field starts at the right offset.
1794     AP.OutStreamer.EmitZeros(PadSize);
1795   }
1796   assert(SizeSoFar == Layout->getSizeInBytes() &&
1797          "Layout of constant struct may be incorrect!");
1800 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1801   APInt API = CFP->getValueAPF().bitcastToAPInt();
1803   // First print a comment with what we think the original floating-point value
1804   // should have been.
1805   if (AP.isVerbose()) {
1806     SmallString<8> StrVal;
1807     CFP->getValueAPF().toString(StrVal);
1809     CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1810     AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1811   }
1813   // Now iterate through the APInt chunks, emitting them in endian-correct
1814   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1815   // floats).
1816   unsigned NumBytes = API.getBitWidth() / 8;
1817   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1818   const uint64_t *p = API.getRawData();
1820   // PPC's long double has odd notions of endianness compared to how LLVM
1821   // handles it: p[0] goes first for *big* endian on PPC.
1822   if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1823     int Chunk = API.getNumWords() - 1;
1825     if (TrailingBytes)
1826       AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1828     for (; Chunk >= 0; --Chunk)
1829       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1830   } else {
1831     unsigned Chunk;
1832     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1833       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1835     if (TrailingBytes)
1836       AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1837   }
1839   // Emit the tail padding for the long double.
1840   const DataLayout &DL = *AP.TM.getDataLayout();
1841   AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1842                            DL.getTypeStoreSize(CFP->getType()));
1845 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1846   const DataLayout *DL = AP.TM.getDataLayout();
1847   unsigned BitWidth = CI->getBitWidth();
1849   // Copy the value as we may massage the layout for constants whose bit width
1850   // is not a multiple of 64-bits.
1851   APInt Realigned(CI->getValue());
1852   uint64_t ExtraBits = 0;
1853   unsigned ExtraBitsSize = BitWidth & 63;
1855   if (ExtraBitsSize) {
1856     // The bit width of the data is not a multiple of 64-bits.
1857     // The extra bits are expected to be at the end of the chunk of the memory.
1858     // Little endian:
1859     // * Nothing to be done, just record the extra bits to emit.
1860     // Big endian:
1861     // * Record the extra bits to emit.
1862     // * Realign the raw data to emit the chunks of 64-bits.
1863     if (DL->isBigEndian()) {
1864       // Basically the structure of the raw data is a chunk of 64-bits cells:
1865       //    0        1         BitWidth / 64
1866       // [chunk1][chunk2] ... [chunkN].
1867       // The most significant chunk is chunkN and it should be emitted first.
1868       // However, due to the alignment issue chunkN contains useless bits.
1869       // Realign the chunks so that they contain only useless information:
1870       // ExtraBits     0       1       (BitWidth / 64) - 1
1871       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1872       ExtraBits = Realigned.getRawData()[0] &
1873         (((uint64_t)-1) >> (64 - ExtraBitsSize));
1874       Realigned = Realigned.lshr(ExtraBitsSize);
1875     } else
1876       ExtraBits = Realigned.getRawData()[BitWidth / 64];
1877   }
1879   // We don't expect assemblers to support integer data directives
1880   // for more than 64 bits, so we emit the data in at most 64-bit
1881   // quantities at a time.
1882   const uint64_t *RawData = Realigned.getRawData();
1883   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1884     uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1885     AP.OutStreamer.EmitIntValue(Val, 8);
1886   }
1888   if (ExtraBitsSize) {
1889     // Emit the extra bits after the 64-bits chunks.
1891     // Emit a directive that fills the expected size.
1892     uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1893     Size -= (BitWidth / 64) * 8;
1894     assert(Size && Size * 8 >= ExtraBitsSize &&
1895            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1896            == ExtraBits && "Directive too small for extra bits.");
1897     AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1898   }
1901 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1902   const DataLayout *DL = AP.TM.getDataLayout();
1903   uint64_t Size = DL->getTypeAllocSize(CV->getType());
1904   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1905     return AP.OutStreamer.EmitZeros(Size);
1907   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1908     switch (Size) {
1909     case 1:
1910     case 2:
1911     case 4:
1912     case 8:
1913       if (AP.isVerbose())
1914         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1915                                                 CI->getZExtValue());
1916       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1917       return;
1918     default:
1919       emitGlobalConstantLargeInt(CI, AP);
1920       return;
1921     }
1922   }
1924   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1925     return emitGlobalConstantFP(CFP, AP);
1927   if (isa<ConstantPointerNull>(CV)) {
1928     AP.OutStreamer.EmitIntValue(0, Size);
1929     return;
1930   }
1932   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1933     return emitGlobalConstantDataSequential(CDS, AP);
1935   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1936     return emitGlobalConstantArray(CVA, AP);
1938   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1939     return emitGlobalConstantStruct(CVS, AP);
1941   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1942     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1943     // vectors).
1944     if (CE->getOpcode() == Instruction::BitCast)
1945       return emitGlobalConstantImpl(CE->getOperand(0), AP);
1947     if (Size > 8) {
1948       // If the constant expression's size is greater than 64-bits, then we have
1949       // to emit the value in chunks. Try to constant fold the value and emit it
1950       // that way.
1951       Constant *New = ConstantFoldConstantExpression(CE, DL);
1952       if (New && New != CE)
1953         return emitGlobalConstantImpl(New, AP);
1954     }
1955   }
1957   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1958     return emitGlobalConstantVector(V, AP);
1960   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1961   // thread the streamer with EmitValue.
1962   AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1965 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1966 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1967   uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1968   if (Size)
1969     emitGlobalConstantImpl(CV, *this);
1970   else if (MAI->hasSubsectionsViaSymbols()) {
1971     // If the global has zero size, emit a single byte so that two labels don't
1972     // look like they are at the same location.
1973     OutStreamer.EmitIntValue(0, 1);
1974   }
1977 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1978   // Target doesn't support this yet!
1979   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1982 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1983   if (Offset > 0)
1984     OS << '+' << Offset;
1985   else if (Offset < 0)
1986     OS << Offset;
1989 //===----------------------------------------------------------------------===//
1990 // Symbol Lowering Routines.
1991 //===----------------------------------------------------------------------===//
1993 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1994 /// temporary label with the specified stem and unique ID.
1995 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1996   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1997                                       Name + Twine(ID));
2000 /// GetTempSymbol - Return an assembler temporary label with the specified
2001 /// stem.
2002 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2003   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
2004                                       Name);
2008 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2009   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2012 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2013   return MMI->getAddrLabelSymbol(BB);
2016 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2017 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2018   return OutContext.GetOrCreateSymbol
2019     (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2020      + "_" + Twine(CPID));
2023 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2024 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2025   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2028 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2029 /// FIXME: privatize to AsmPrinter.
2030 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2031   return OutContext.GetOrCreateSymbol
2032   (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2033    Twine(UID) + "_set_" + Twine(MBBID));
2036 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2037                                                    StringRef Suffix) const {
2038   return getObjFileLowering().getSymbolWithGlobalValueBase(*Mang, GV, Suffix);
2041 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2042 /// ExternalSymbol.
2043 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2044   SmallString<60> NameStr;
2045   Mang->getNameWithPrefix(NameStr, Sym);
2046   return OutContext.GetOrCreateSymbol(NameStr.str());
2051 /// PrintParentLoopComment - Print comments about parent loops of this one.
2052 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2053                                    unsigned FunctionNumber) {
2054   if (Loop == 0) return;
2055   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2056   OS.indent(Loop->getLoopDepth()*2)
2057     << "Parent Loop BB" << FunctionNumber << "_"
2058     << Loop->getHeader()->getNumber()
2059     << " Depth=" << Loop->getLoopDepth() << '\n';
2063 /// PrintChildLoopComment - Print comments about child loops within
2064 /// the loop for this basic block, with nesting.
2065 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2066                                   unsigned FunctionNumber) {
2067   // Add child loop information
2068   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2069     OS.indent((*CL)->getLoopDepth()*2)
2070       << "Child Loop BB" << FunctionNumber << "_"
2071       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2072       << '\n';
2073     PrintChildLoopComment(OS, *CL, FunctionNumber);
2074   }
2077 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2078 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2079                                        const MachineLoopInfo *LI,
2080                                        const AsmPrinter &AP) {
2081   // Add loop depth information
2082   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2083   if (Loop == 0) return;
2085   MachineBasicBlock *Header = Loop->getHeader();
2086   assert(Header && "No header for loop");
2088   // If this block is not a loop header, just print out what is the loop header
2089   // and return.
2090   if (Header != &MBB) {
2091     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
2092                               Twine(AP.getFunctionNumber())+"_" +
2093                               Twine(Loop->getHeader()->getNumber())+
2094                               " Depth="+Twine(Loop->getLoopDepth()));
2095     return;
2096   }
2098   // Otherwise, it is a loop header.  Print out information about child and
2099   // parent loops.
2100   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2102   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2104   OS << "=>";
2105   OS.indent(Loop->getLoopDepth()*2-2);
2107   OS << "This ";
2108   if (Loop->empty())
2109     OS << "Inner ";
2110   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2112   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2116 /// EmitBasicBlockStart - This method prints the label for the specified
2117 /// MachineBasicBlock, an alignment (if present) and a comment describing
2118 /// it if appropriate.
2119 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2120   // Emit an alignment directive for this block, if needed.
2121   if (unsigned Align = MBB->getAlignment())
2122     EmitAlignment(Align);
2124   // If the block has its address taken, emit any labels that were used to
2125   // reference the block.  It is possible that there is more than one label
2126   // here, because multiple LLVM BB's may have been RAUW'd to this block after
2127   // the references were generated.
2128   if (MBB->hasAddressTaken()) {
2129     const BasicBlock *BB = MBB->getBasicBlock();
2130     if (isVerbose())
2131       OutStreamer.AddComment("Block address taken");
2133     std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2135     for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2136       OutStreamer.EmitLabel(Syms[i]);
2137   }
2139   // Print some verbose block comments.
2140   if (isVerbose()) {
2141     if (const BasicBlock *BB = MBB->getBasicBlock())
2142       if (BB->hasName())
2143         OutStreamer.AddComment("%" + BB->getName());
2144     emitBasicBlockLoopComments(*MBB, LI, *this);
2145   }
2147   // Print the main label for the block.
2148   if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2149     if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2150       // NOTE: Want this comment at start of line, don't emit with AddComment.
2151       OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2152                               Twine(MBB->getNumber()) + ":");
2153     }
2154   } else {
2155     OutStreamer.EmitLabel(MBB->getSymbol());
2156   }
2159 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2160                                 bool IsDefinition) const {
2161   MCSymbolAttr Attr = MCSA_Invalid;
2163   switch (Visibility) {
2164   default: break;
2165   case GlobalValue::HiddenVisibility:
2166     if (IsDefinition)
2167       Attr = MAI->getHiddenVisibilityAttr();
2168     else
2169       Attr = MAI->getHiddenDeclarationVisibilityAttr();
2170     break;
2171   case GlobalValue::ProtectedVisibility:
2172     Attr = MAI->getProtectedVisibilityAttr();
2173     break;
2174   }
2176   if (Attr != MCSA_Invalid)
2177     OutStreamer.EmitSymbolAttribute(Sym, Attr);
2180 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2181 /// exactly one predecessor and the control transfer mechanism between
2182 /// the predecessor and this block is a fall-through.
2183 bool AsmPrinter::
2184 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2185   // If this is a landing pad, it isn't a fall through.  If it has no preds,
2186   // then nothing falls through to it.
2187   if (MBB->isLandingPad() || MBB->pred_empty())
2188     return false;
2190   // If there isn't exactly one predecessor, it can't be a fall through.
2191   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2192   ++PI2;
2193   if (PI2 != MBB->pred_end())
2194     return false;
2196   // The predecessor has to be immediately before this block.
2197   MachineBasicBlock *Pred = *PI;
2199   if (!Pred->isLayoutSuccessor(MBB))
2200     return false;
2202   // If the block is completely empty, then it definitely does fall through.
2203   if (Pred->empty())
2204     return true;
2206   // Check the terminators in the previous blocks
2207   for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2208          IE = Pred->end(); II != IE; ++II) {
2209     MachineInstr &MI = *II;
2211     // If it is not a simple branch, we are in a table somewhere.
2212     if (!MI.isBranch() || MI.isIndirectBranch())
2213       return false;
2215     // If we are the operands of one of the branches, this is not
2216     // a fall through.
2217     for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2218            OE = MI.operands_end(); OI != OE; ++OI) {
2219       const MachineOperand& OP = *OI;
2220       if (OP.isJTI())
2221         return false;
2222       if (OP.isMBB() && OP.getMBB() == MBB)
2223         return false;
2224     }
2225   }
2227   return true;
2232 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2233   if (!S->usesMetadata())
2234     return 0;
2236   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2237   gcp_map_type::iterator GCPI = GCMap.find(S);
2238   if (GCPI != GCMap.end())
2239     return GCPI->second;
2241   const char *Name = S->getName().c_str();
2243   for (GCMetadataPrinterRegistry::iterator
2244          I = GCMetadataPrinterRegistry::begin(),
2245          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2246     if (strcmp(Name, I->getName()) == 0) {
2247       GCMetadataPrinter *GMP = I->instantiate();
2248       GMP->S = S;
2249       GCMap.insert(std::make_pair(S, GMP));
2250       return GMP;
2251     }
2253   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));