1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "Win64Exception.h"
18 #include "WinCodeViewLineTables.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/JumpInstrTableInfo.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/GCMetadataPrinter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBundle.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCSection.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/MCValue.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Target/TargetFrameLowering.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetLoweringObjectFile.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
58 #define DEBUG_TYPE "asm-printer"
60 static const char *const DWARFGroupName = "DWARF Emission";
61 static const char *const DbgTimerName = "Debug Info Emission";
62 static const char *const EHTimerName = "DWARF Exception Writer";
63 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
65 STATISTIC(EmittedInsts, "Number of machine instrs printed");
67 char AsmPrinter::ID = 0;
69 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
70 static gcp_map_type &getGCMap(void *&P) {
72 P = new gcp_map_type();
73 return *(gcp_map_type*)P;
77 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
78 /// value in log2 form. This rounds up to the preferred alignment if possible
80 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
81 unsigned InBits = 0) {
83 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
84 NumBits = TD.getPreferredAlignmentLog(GVar);
86 // If InBits is specified, round it to it.
90 // If the GV has a specified alignment, take it into account.
91 if (GV->getAlignment() == 0)
94 unsigned GVAlign = Log2_32(GV->getAlignment());
96 // If the GVAlign is larger than NumBits, or if we are required to obey
97 // NumBits because the GV has an assigned section, obey it.
98 if (GVAlign > NumBits || GV->hasSection())
103 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
104 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
105 OutContext(Streamer->getContext()), OutStreamer(*Streamer.release()),
106 LastMI(nullptr), LastFn(0), Counter(~0U), SetCounter(0) {
111 CurrentFnSym = CurrentFnSymForSize = nullptr;
112 CurrentFnBegin = nullptr;
113 CurrentFnEnd = nullptr;
114 GCMetadataPrinters = nullptr;
115 VerboseAsm = OutStreamer.isVerboseAsm();
118 AsmPrinter::~AsmPrinter() {
119 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
121 if (GCMetadataPrinters) {
122 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
125 GCMetadataPrinters = nullptr;
131 /// getFunctionNumber - Return a unique ID for the current function.
133 unsigned AsmPrinter::getFunctionNumber() const {
134 return MF->getFunctionNumber();
137 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
138 return *TM.getObjFileLowering();
141 /// getDataLayout - Return information about data layout.
142 const DataLayout &AsmPrinter::getDataLayout() const {
143 return *TM.getDataLayout();
146 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
147 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
148 return MF->getSubtarget<MCSubtargetInfo>();
151 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
152 S.EmitInstruction(Inst, getSubtargetInfo());
155 StringRef AsmPrinter::getTargetTriple() const {
156 return TM.getTargetTriple();
159 /// getCurrentSection() - Return the current section we are emitting to.
160 const MCSection *AsmPrinter::getCurrentSection() const {
161 return OutStreamer.getCurrentSection().first;
166 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
167 AU.setPreservesAll();
168 MachineFunctionPass::getAnalysisUsage(AU);
169 AU.addRequired<MachineModuleInfo>();
170 AU.addRequired<GCModuleInfo>();
172 AU.addRequired<MachineLoopInfo>();
175 bool AsmPrinter::doInitialization(Module &M) {
176 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
177 MMI->AnalyzeModule(M);
179 // Initialize TargetLoweringObjectFile.
180 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
181 .Initialize(OutContext, TM);
183 OutStreamer.InitSections(false);
185 Mang = new Mangler(TM.getDataLayout());
187 // Emit the version-min deplyment target directive if needed.
189 // FIXME: If we end up with a collection of these sorts of Darwin-specific
190 // or ELF-specific things, it may make sense to have a platform helper class
191 // that will work with the target helper class. For now keep it here, as the
192 // alternative is duplicated code in each of the target asm printers that
193 // use the directive, where it would need the same conditionalization
195 Triple TT(getTargetTriple());
196 if (TT.isOSDarwin()) {
197 unsigned Major, Minor, Update;
198 TT.getOSVersion(Major, Minor, Update);
199 // If there is a version specified, Major will be non-zero.
201 OutStreamer.EmitVersionMin((TT.isMacOSX() ?
202 MCVM_OSXVersionMin : MCVM_IOSVersionMin),
203 Major, Minor, Update);
206 // Allow the target to emit any magic that it wants at the start of the file.
207 EmitStartOfAsmFile(M);
209 // Very minimal debug info. It is ignored if we emit actual debug info. If we
210 // don't, this at least helps the user find where a global came from.
211 if (MAI->hasSingleParameterDotFile()) {
213 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
216 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
217 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
219 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
220 MP->beginAssembly(M, *MI, *this);
222 // Emit module-level inline asm if it exists.
223 if (!M.getModuleInlineAsm().empty()) {
224 OutStreamer.AddComment("Start of file scope inline assembly");
225 OutStreamer.AddBlankLine();
226 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
227 OutStreamer.AddComment("End of file scope inline assembly");
228 OutStreamer.AddBlankLine();
231 if (MAI->doesSupportDebugInformation()) {
232 bool skip_dwarf = false;
233 if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
234 Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
236 CodeViewLineTablesGroupName));
237 // FIXME: Don't emit DWARF debug info if there's at least one function
238 // with AddressSanitizer instrumentation.
239 // This is a band-aid fix for PR22032.
240 for (auto &F : M.functions()) {
241 if (F.hasFnAttribute(Attribute::SanitizeAddress)) {
248 DD = new DwarfDebug(this, &M);
249 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
253 EHStreamer *ES = nullptr;
254 switch (MAI->getExceptionHandlingType()) {
255 case ExceptionHandling::None:
257 case ExceptionHandling::SjLj:
258 case ExceptionHandling::DwarfCFI:
259 ES = new DwarfCFIException(this);
261 case ExceptionHandling::ARM:
262 ES = new ARMException(this);
264 case ExceptionHandling::WinEH:
265 switch (MAI->getWinEHEncodingType()) {
266 default: llvm_unreachable("unsupported unwinding information encoding");
267 case WinEH::EncodingType::Itanium:
268 ES = new Win64Exception(this);
274 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
278 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
279 if (!MAI.hasWeakDefCanBeHiddenDirective())
282 return canBeOmittedFromSymbolTable(GV);
285 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
286 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
288 case GlobalValue::CommonLinkage:
289 case GlobalValue::LinkOnceAnyLinkage:
290 case GlobalValue::LinkOnceODRLinkage:
291 case GlobalValue::WeakAnyLinkage:
292 case GlobalValue::WeakODRLinkage:
293 if (MAI->hasWeakDefDirective()) {
295 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
297 if (!canBeHidden(GV, *MAI))
298 // .weak_definition _foo
299 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
301 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
302 } else if (MAI->hasLinkOnceDirective()) {
304 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
305 //NOTE: linkonce is handled by the section the symbol was assigned to.
308 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
311 case GlobalValue::AppendingLinkage:
312 // FIXME: appending linkage variables should go into a section of
313 // their name or something. For now, just emit them as external.
314 case GlobalValue::ExternalLinkage:
315 // If external or appending, declare as a global symbol.
317 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
319 case GlobalValue::PrivateLinkage:
320 case GlobalValue::InternalLinkage:
322 case GlobalValue::AvailableExternallyLinkage:
323 llvm_unreachable("Should never emit this");
324 case GlobalValue::ExternalWeakLinkage:
325 llvm_unreachable("Don't know how to emit these");
327 llvm_unreachable("Unknown linkage type!");
330 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
331 const GlobalValue *GV) const {
332 TM.getNameWithPrefix(Name, GV, *Mang);
335 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
336 return TM.getSymbol(GV, *Mang);
339 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
340 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
341 if (GV->hasInitializer()) {
342 // Check to see if this is a special global used by LLVM, if so, emit it.
343 if (EmitSpecialLLVMGlobal(GV))
346 // Skip the emission of global equivalents. The symbol can be emitted later
347 // on by emitGlobalGOTEquivs in case it turns out to be needed.
348 if (GlobalGOTEquivs.count(getSymbol(GV)))
352 GV->printAsOperand(OutStreamer.GetCommentOS(),
353 /*PrintType=*/false, GV->getParent());
354 OutStreamer.GetCommentOS() << '\n';
358 MCSymbol *GVSym = getSymbol(GV);
359 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
361 if (!GV->hasInitializer()) // External globals require no extra code.
364 GVSym->redefineIfPossible();
365 if (GVSym->isDefined() || GVSym->isVariable())
366 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
367 "' is already defined");
369 if (MAI->hasDotTypeDotSizeDirective())
370 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
372 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
374 const DataLayout *DL = TM.getDataLayout();
375 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
377 // If the alignment is specified, we *must* obey it. Overaligning a global
378 // with a specified alignment is a prompt way to break globals emitted to
379 // sections and expected to be contiguous (e.g. ObjC metadata).
380 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
382 for (const HandlerInfo &HI : Handlers) {
383 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
384 HI.Handler->setSymbolSize(GVSym, Size);
387 // Handle common and BSS local symbols (.lcomm).
388 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
389 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
390 unsigned Align = 1 << AlignLog;
392 // Handle common symbols.
393 if (GVKind.isCommon()) {
394 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
398 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
402 // Handle local BSS symbols.
403 if (MAI->hasMachoZeroFillDirective()) {
404 const MCSection *TheSection =
405 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
406 // .zerofill __DATA, __bss, _foo, 400, 5
407 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
411 // Use .lcomm only if it supports user-specified alignment.
412 // Otherwise, while it would still be correct to use .lcomm in some
413 // cases (e.g. when Align == 1), the external assembler might enfore
414 // some -unknown- default alignment behavior, which could cause
415 // spurious differences between external and integrated assembler.
416 // Prefer to simply fall back to .local / .comm in this case.
417 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
419 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
423 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
427 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
429 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
433 const MCSection *TheSection =
434 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
436 // Handle the zerofill directive on darwin, which is a special form of BSS
438 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
439 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
442 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
443 // .zerofill __DATA, __common, _foo, 400, 5
444 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
448 // Handle thread local data for mach-o which requires us to output an
449 // additional structure of data and mangle the original symbol so that we
450 // can reference it later.
452 // TODO: This should become an "emit thread local global" method on TLOF.
453 // All of this macho specific stuff should be sunk down into TLOFMachO and
454 // stuff like "TLSExtraDataSection" should no longer be part of the parent
455 // TLOF class. This will also make it more obvious that stuff like
456 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
458 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
459 // Emit the .tbss symbol
461 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
463 if (GVKind.isThreadBSS()) {
464 TheSection = getObjFileLowering().getTLSBSSSection();
465 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
466 } else if (GVKind.isThreadData()) {
467 OutStreamer.SwitchSection(TheSection);
469 EmitAlignment(AlignLog, GV);
470 OutStreamer.EmitLabel(MangSym);
472 EmitGlobalConstant(GV->getInitializer());
475 OutStreamer.AddBlankLine();
477 // Emit the variable struct for the runtime.
478 const MCSection *TLVSect
479 = getObjFileLowering().getTLSExtraDataSection();
481 OutStreamer.SwitchSection(TLVSect);
482 // Emit the linkage here.
483 EmitLinkage(GV, GVSym);
484 OutStreamer.EmitLabel(GVSym);
486 // Three pointers in size:
487 // - __tlv_bootstrap - used to make sure support exists
488 // - spare pointer, used when mapped by the runtime
489 // - pointer to mangled symbol above with initializer
490 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
491 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
493 OutStreamer.EmitIntValue(0, PtrSize);
494 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
496 OutStreamer.AddBlankLine();
500 OutStreamer.SwitchSection(TheSection);
502 EmitLinkage(GV, GVSym);
503 EmitAlignment(AlignLog, GV);
505 OutStreamer.EmitLabel(GVSym);
507 EmitGlobalConstant(GV->getInitializer());
509 if (MAI->hasDotTypeDotSizeDirective())
511 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
513 OutStreamer.AddBlankLine();
516 /// EmitFunctionHeader - This method emits the header for the current
518 void AsmPrinter::EmitFunctionHeader() {
519 // Print out constants referenced by the function
522 // Print the 'header' of function.
523 const Function *F = MF->getFunction();
525 OutStreamer.SwitchSection(
526 getObjFileLowering().SectionForGlobal(F, *Mang, TM));
527 EmitVisibility(CurrentFnSym, F->getVisibility());
529 EmitLinkage(F, CurrentFnSym);
530 EmitAlignment(MF->getAlignment(), F);
532 if (MAI->hasDotTypeDotSizeDirective())
533 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
536 F->printAsOperand(OutStreamer.GetCommentOS(),
537 /*PrintType=*/false, F->getParent());
538 OutStreamer.GetCommentOS() << '\n';
541 // Emit the prefix data.
542 if (F->hasPrefixData())
543 EmitGlobalConstant(F->getPrefixData());
545 // Emit the CurrentFnSym. This is a virtual function to allow targets to
546 // do their wild and crazy things as required.
547 EmitFunctionEntryLabel();
549 // If the function had address-taken blocks that got deleted, then we have
550 // references to the dangling symbols. Emit them at the start of the function
551 // so that we don't get references to undefined symbols.
552 std::vector<MCSymbol*> DeadBlockSyms;
553 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
554 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
555 OutStreamer.AddComment("Address taken block that was later removed");
556 OutStreamer.EmitLabel(DeadBlockSyms[i]);
559 bool NeedsLocalForSize = MAI->needsLocalForSize();
560 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
562 CurrentFnBegin = createTempSymbol("func_begin", getFunctionNumber());
563 if (NeedsLocalForSize)
564 CurrentFnSymForSize = CurrentFnBegin;
566 if (MAI->useAssignmentForEHBegin()) {
567 MCSymbol *CurPos = OutContext.CreateTempSymbol();
568 OutStreamer.EmitLabel(CurPos);
569 OutStreamer.EmitAssignment(CurrentFnBegin,
570 MCSymbolRefExpr::Create(CurPos, OutContext));
572 OutStreamer.EmitLabel(CurrentFnBegin);
576 // Emit pre-function debug and/or EH information.
577 for (const HandlerInfo &HI : Handlers) {
578 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
579 HI.Handler->beginFunction(MF);
582 // Emit the prologue data.
583 if (F->hasPrologueData())
584 EmitGlobalConstant(F->getPrologueData());
587 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
588 /// function. This can be overridden by targets as required to do custom stuff.
589 void AsmPrinter::EmitFunctionEntryLabel() {
590 CurrentFnSym->redefineIfPossible();
592 // The function label could have already been emitted if two symbols end up
593 // conflicting due to asm renaming. Detect this and emit an error.
594 if (CurrentFnSym->isVariable())
595 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
596 "' is a protected alias");
597 if (CurrentFnSym->isDefined())
598 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
599 "' label emitted multiple times to assembly file");
601 return OutStreamer.EmitLabel(CurrentFnSym);
604 /// emitComments - Pretty-print comments for instructions.
605 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
606 const MachineFunction *MF = MI.getParent()->getParent();
607 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
609 // Check for spills and reloads
612 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
614 // We assume a single instruction only has a spill or reload, not
616 const MachineMemOperand *MMO;
617 if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
618 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
619 MMO = *MI.memoperands_begin();
620 CommentOS << MMO->getSize() << "-byte Reload\n";
622 } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
623 if (FrameInfo->isSpillSlotObjectIndex(FI))
624 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
625 } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
626 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
627 MMO = *MI.memoperands_begin();
628 CommentOS << MMO->getSize() << "-byte Spill\n";
630 } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
631 if (FrameInfo->isSpillSlotObjectIndex(FI))
632 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
635 // Check for spill-induced copies
636 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
637 CommentOS << " Reload Reuse\n";
640 /// emitImplicitDef - This method emits the specified machine instruction
641 /// that is an implicit def.
642 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
643 unsigned RegNo = MI->getOperand(0).getReg();
644 OutStreamer.AddComment(Twine("implicit-def: ") +
645 MMI->getContext().getRegisterInfo()->getName(RegNo));
646 OutStreamer.AddBlankLine();
649 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
650 std::string Str = "kill:";
651 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
652 const MachineOperand &Op = MI->getOperand(i);
653 assert(Op.isReg() && "KILL instruction must have only register operands");
655 Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
656 Str += (Op.isDef() ? "<def>" : "<kill>");
658 AP.OutStreamer.AddComment(Str);
659 AP.OutStreamer.AddBlankLine();
662 /// emitDebugValueComment - This method handles the target-independent form
663 /// of DBG_VALUE, returning true if it was able to do so. A false return
664 /// means the target will need to handle MI in EmitInstruction.
665 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
666 // This code handles only the 4-operand target-independent form.
667 if (MI->getNumOperands() != 4)
670 SmallString<128> Str;
671 raw_svector_ostream OS(Str);
672 OS << "DEBUG_VALUE: ";
674 DIVariable V = MI->getDebugVariable();
675 if (V.getContext().isSubprogram()) {
676 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
682 DIExpression Expr = MI->getDebugExpression();
683 if (Expr.isBitPiece())
684 OS << " [bit_piece offset=" << Expr.getBitPieceOffset()
685 << " size=" << Expr.getBitPieceSize() << "]";
688 // The second operand is only an offset if it's an immediate.
689 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
690 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
692 // Register or immediate value. Register 0 means undef.
693 if (MI->getOperand(0).isFPImm()) {
694 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
695 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
696 OS << (double)APF.convertToFloat();
697 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
698 OS << APF.convertToDouble();
700 // There is no good way to print long double. Convert a copy to
701 // double. Ah well, it's only a comment.
703 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
705 OS << "(long double) " << APF.convertToDouble();
707 } else if (MI->getOperand(0).isImm()) {
708 OS << MI->getOperand(0).getImm();
709 } else if (MI->getOperand(0).isCImm()) {
710 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
713 if (MI->getOperand(0).isReg()) {
714 Reg = MI->getOperand(0).getReg();
716 assert(MI->getOperand(0).isFI() && "Unknown operand type");
717 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
718 Offset += TFI->getFrameIndexReference(*AP.MF,
719 MI->getOperand(0).getIndex(), Reg);
723 // Suppress offset, it is not meaningful here.
725 // NOTE: Want this comment at start of line, don't emit with AddComment.
726 AP.OutStreamer.emitRawComment(OS.str());
731 OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
735 OS << '+' << Offset << ']';
737 // NOTE: Want this comment at start of line, don't emit with AddComment.
738 AP.OutStreamer.emitRawComment(OS.str());
742 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
743 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
744 MF->getFunction()->needsUnwindTableEntry())
747 if (MMI->hasDebugInfo())
753 bool AsmPrinter::needsSEHMoves() {
754 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
757 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
758 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
759 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
760 ExceptionHandlingType != ExceptionHandling::ARM)
763 if (needsCFIMoves() == CFI_M_None)
766 const MachineModuleInfo &MMI = MF->getMMI();
767 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
768 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
769 const MCCFIInstruction &CFI = Instrs[CFIIndex];
770 emitCFIInstruction(CFI);
773 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
774 // The operands are the MCSymbol and the frame offset of the allocation.
775 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
776 int FrameOffset = MI.getOperand(1).getImm();
778 // Emit a symbol assignment.
779 OutStreamer.EmitAssignment(FrameAllocSym,
780 MCConstantExpr::Create(FrameOffset, OutContext));
783 /// EmitFunctionBody - This method emits the body and trailer for a
785 void AsmPrinter::EmitFunctionBody() {
786 // Emit target-specific gunk before the function body.
787 EmitFunctionBodyStart();
789 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
791 // Print out code for the function.
792 bool HasAnyRealCode = false;
793 for (auto &MBB : *MF) {
794 // Print a label for the basic block.
795 EmitBasicBlockStart(MBB);
796 for (auto &MI : MBB) {
798 // Print the assembly for the instruction.
799 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
800 !MI.isDebugValue()) {
801 HasAnyRealCode = true;
805 if (ShouldPrintDebugScopes) {
806 for (const HandlerInfo &HI : Handlers) {
807 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
808 TimePassesIsEnabled);
809 HI.Handler->beginInstruction(&MI);
814 emitComments(MI, OutStreamer.GetCommentOS());
816 switch (MI.getOpcode()) {
817 case TargetOpcode::CFI_INSTRUCTION:
818 emitCFIInstruction(MI);
821 case TargetOpcode::FRAME_ALLOC:
825 case TargetOpcode::EH_LABEL:
826 case TargetOpcode::GC_LABEL:
827 OutStreamer.EmitLabel(MI.getOperand(0).getMCSymbol());
829 case TargetOpcode::INLINEASM:
832 case TargetOpcode::DBG_VALUE:
834 if (!emitDebugValueComment(&MI, *this))
835 EmitInstruction(&MI);
838 case TargetOpcode::IMPLICIT_DEF:
839 if (isVerbose()) emitImplicitDef(&MI);
841 case TargetOpcode::KILL:
842 if (isVerbose()) emitKill(&MI, *this);
845 EmitInstruction(&MI);
849 if (ShouldPrintDebugScopes) {
850 for (const HandlerInfo &HI : Handlers) {
851 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
852 TimePassesIsEnabled);
853 HI.Handler->endInstruction();
858 EmitBasicBlockEnd(MBB);
861 // If the function is empty and the object file uses .subsections_via_symbols,
862 // then we need to emit *something* to the function body to prevent the
863 // labels from collapsing together. Just emit a noop.
864 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
866 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
867 OutStreamer.AddComment("avoids zero-length function");
869 // Targets can opt-out of emitting the noop here by leaving the opcode
871 if (Noop.getOpcode())
872 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
875 const Function *F = MF->getFunction();
876 for (const auto &BB : *F) {
877 if (!BB.hasAddressTaken())
879 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
880 if (Sym->isDefined())
882 OutStreamer.AddComment("Address of block that was removed by CodeGen");
883 OutStreamer.EmitLabel(Sym);
886 // Emit target-specific gunk after the function body.
887 EmitFunctionBodyEnd();
889 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
890 MAI->hasDotTypeDotSizeDirective()) {
891 // Create a symbol for the end of function.
892 CurrentFnEnd = createTempSymbol("func_end", getFunctionNumber());
893 OutStreamer.EmitLabel(CurrentFnEnd);
896 // If the target wants a .size directive for the size of the function, emit
898 if (MAI->hasDotTypeDotSizeDirective()) {
899 // We can get the size as difference between the function label and the
901 const MCExpr *SizeExp =
902 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(CurrentFnEnd, OutContext),
903 MCSymbolRefExpr::Create(CurrentFnSymForSize,
906 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
909 // Emit post-function debug and/or EH information.
910 for (const HandlerInfo &HI : Handlers) {
911 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
912 HI.Handler->endFunction(MF);
916 // Print out jump tables referenced by the function.
919 OutStreamer.AddBlankLine();
922 /// \brief Compute the number of Global Variables that uses a Constant.
923 static unsigned getNumGlobalVariableUses(const Constant *C) {
927 if (isa<GlobalVariable>(C))
930 unsigned NumUses = 0;
931 for (auto *CU : C->users())
932 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
937 /// \brief Only consider global GOT equivalents if at least one user is a
938 /// cstexpr inside an initializer of another global variables. Also, don't
939 /// handle cstexpr inside instructions. During global variable emission,
940 /// candidates are skipped and are emitted later in case at least one cstexpr
941 /// isn't replaced by a PC relative GOT entry access.
942 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
943 unsigned &NumGOTEquivUsers) {
944 // Global GOT equivalents are unnamed private globals with a constant
945 // pointer initializer to another global symbol. They must point to a
946 // GlobalVariable or Function, i.e., as GlobalValue.
947 if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
948 !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
951 // To be a got equivalent, at least one of its users need to be a constant
952 // expression used by another global variable.
953 for (auto *U : GV->users())
954 NumGOTEquivUsers += getNumGlobalVariableUses(cast<Constant>(U));
956 return NumGOTEquivUsers > 0;
959 /// \brief Unnamed constant global variables solely contaning a pointer to
960 /// another globals variable is equivalent to a GOT table entry; it contains the
961 /// the address of another symbol. Optimize it and replace accesses to these
962 /// "GOT equivalents" by using the GOT entry for the final global instead.
963 /// Compute GOT equivalent candidates among all global variables to avoid
964 /// emitting them if possible later on, after it use is replaced by a GOT entry
966 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
967 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
970 for (const auto &G : M.globals()) {
971 unsigned NumGOTEquivUsers = 0;
972 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
975 const MCSymbol *GOTEquivSym = getSymbol(&G);
976 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
980 /// \brief Constant expressions using GOT equivalent globals may not be eligible
981 /// for PC relative GOT entry conversion, in such cases we need to emit such
982 /// globals we previously omitted in EmitGlobalVariable.
983 void AsmPrinter::emitGlobalGOTEquivs() {
984 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
987 while (!GlobalGOTEquivs.empty()) {
988 DenseMap<const MCSymbol *, GOTEquivUsePair>::iterator I =
989 GlobalGOTEquivs.begin();
990 const MCSymbol *S = I->first;
991 const GlobalVariable *GV = I->second.first;
992 GlobalGOTEquivs.erase(S);
993 EmitGlobalVariable(GV);
997 bool AsmPrinter::doFinalization(Module &M) {
998 // Gather all GOT equivalent globals in the module. We really need two
999 // passes over the globals: one to compute and another to avoid its emission
1000 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1001 // where the got equivalent shows up before its use.
1002 computeGlobalGOTEquivs(M);
1004 // Emit global variables.
1005 for (const auto &G : M.globals())
1006 EmitGlobalVariable(&G);
1008 // Emit remaining GOT equivalent globals.
1009 emitGlobalGOTEquivs();
1011 // Emit visibility info for declarations
1012 for (const Function &F : M) {
1013 if (!F.isDeclaration())
1015 GlobalValue::VisibilityTypes V = F.getVisibility();
1016 if (V == GlobalValue::DefaultVisibility)
1019 MCSymbol *Name = getSymbol(&F);
1020 EmitVisibility(Name, V, false);
1023 // Emit module flags.
1024 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1025 M.getModuleFlagsMetadata(ModuleFlags);
1026 if (!ModuleFlags.empty())
1027 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
1029 // Make sure we wrote out everything we need.
1030 OutStreamer.Flush();
1032 // Finalize debug and EH information.
1033 for (const HandlerInfo &HI : Handlers) {
1034 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1035 TimePassesIsEnabled);
1036 HI.Handler->endModule();
1042 // If the target wants to know about weak references, print them all.
1043 if (MAI->getWeakRefDirective()) {
1044 // FIXME: This is not lazy, it would be nice to only print weak references
1045 // to stuff that is actually used. Note that doing so would require targets
1046 // to notice uses in operands (due to constant exprs etc). This should
1047 // happen with the MC stuff eventually.
1049 // Print out module-level global variables here.
1050 for (const auto &G : M.globals()) {
1051 if (!G.hasExternalWeakLinkage())
1053 OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1056 for (const auto &F : M) {
1057 if (!F.hasExternalWeakLinkage())
1059 OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1063 OutStreamer.AddBlankLine();
1064 for (const auto &Alias : M.aliases()) {
1065 MCSymbol *Name = getSymbol(&Alias);
1067 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1068 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
1069 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1070 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
1072 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1074 EmitVisibility(Name, Alias.getVisibility());
1076 // Emit the directives as assignments aka .set:
1077 OutStreamer.EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1080 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1081 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1082 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1083 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1084 MP->finishAssembly(M, *MI, *this);
1086 // Emit llvm.ident metadata in an '.ident' directive.
1087 EmitModuleIdents(M);
1089 // Emit __morestack address if needed for indirect calls.
1090 if (MMI->usesMorestackAddr()) {
1091 const MCSection *ReadOnlySection =
1092 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1094 OutStreamer.SwitchSection(ReadOnlySection);
1096 MCSymbol *AddrSymbol =
1097 OutContext.GetOrCreateSymbol(StringRef("__morestack_addr"));
1098 OutStreamer.EmitLabel(AddrSymbol);
1100 unsigned PtrSize = TM.getDataLayout()->getPointerSize(0);
1101 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1105 // If we don't have any trampolines, then we don't require stack memory
1106 // to be executable. Some targets have a directive to declare this.
1107 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1108 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1109 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1110 OutStreamer.SwitchSection(S);
1112 // Allow the target to emit any magic that it wants at the end of the file,
1113 // after everything else has gone out.
1114 EmitEndOfAsmFile(M);
1116 delete Mang; Mang = nullptr;
1119 OutStreamer.Finish();
1120 OutStreamer.reset();
1125 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1127 // Get the function symbol.
1128 CurrentFnSym = getSymbol(MF.getFunction());
1129 CurrentFnSymForSize = CurrentFnSym;
1132 LI = &getAnalysis<MachineLoopInfo>();
1136 // SectionCPs - Keep track the alignment, constpool entries per Section.
1140 SmallVector<unsigned, 4> CPEs;
1141 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1145 /// EmitConstantPool - Print to the current output stream assembly
1146 /// representations of the constants in the constant pool MCP. This is
1147 /// used to print out constants which have been "spilled to memory" by
1148 /// the code generator.
1150 void AsmPrinter::EmitConstantPool() {
1151 const MachineConstantPool *MCP = MF->getConstantPool();
1152 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1153 if (CP.empty()) return;
1155 // Calculate sections for constant pool entries. We collect entries to go into
1156 // the same section together to reduce amount of section switch statements.
1157 SmallVector<SectionCPs, 4> CPSections;
1158 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1159 const MachineConstantPoolEntry &CPE = CP[i];
1160 unsigned Align = CPE.getAlignment();
1163 CPE.getSectionKind(TM.getDataLayout());
1165 const Constant *C = nullptr;
1166 if (!CPE.isMachineConstantPoolEntry())
1167 C = CPE.Val.ConstVal;
1169 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1171 // The number of sections are small, just do a linear search from the
1172 // last section to the first.
1174 unsigned SecIdx = CPSections.size();
1175 while (SecIdx != 0) {
1176 if (CPSections[--SecIdx].S == S) {
1182 SecIdx = CPSections.size();
1183 CPSections.push_back(SectionCPs(S, Align));
1186 if (Align > CPSections[SecIdx].Alignment)
1187 CPSections[SecIdx].Alignment = Align;
1188 CPSections[SecIdx].CPEs.push_back(i);
1191 // Now print stuff into the calculated sections.
1192 const MCSection *CurSection = nullptr;
1193 unsigned Offset = 0;
1194 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1195 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1196 unsigned CPI = CPSections[i].CPEs[j];
1197 MCSymbol *Sym = GetCPISymbol(CPI);
1198 if (!Sym->isUndefined())
1201 if (CurSection != CPSections[i].S) {
1202 OutStreamer.SwitchSection(CPSections[i].S);
1203 EmitAlignment(Log2_32(CPSections[i].Alignment));
1204 CurSection = CPSections[i].S;
1208 MachineConstantPoolEntry CPE = CP[CPI];
1210 // Emit inter-object padding for alignment.
1211 unsigned AlignMask = CPE.getAlignment() - 1;
1212 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1213 OutStreamer.EmitZeros(NewOffset - Offset);
1215 Type *Ty = CPE.getType();
1216 Offset = NewOffset +
1217 TM.getDataLayout()->getTypeAllocSize(Ty);
1219 OutStreamer.EmitLabel(Sym);
1220 if (CPE.isMachineConstantPoolEntry())
1221 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1223 EmitGlobalConstant(CPE.Val.ConstVal);
1228 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1229 /// by the current function to the current output stream.
1231 void AsmPrinter::EmitJumpTableInfo() {
1232 const DataLayout *DL = MF->getTarget().getDataLayout();
1233 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1235 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1236 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1237 if (JT.empty()) return;
1239 // Pick the directive to use to print the jump table entries, and switch to
1240 // the appropriate section.
1241 const Function *F = MF->getFunction();
1242 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1243 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1244 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1246 if (!JTInDiffSection) {
1247 OutStreamer.SwitchSection(TLOF.SectionForGlobal(F, *Mang, TM));
1249 // Otherwise, drop it in the readonly section.
1250 const MCSection *ReadOnlySection =
1251 TLOF.getSectionForJumpTable(*F, *Mang, TM);
1252 OutStreamer.SwitchSection(ReadOnlySection);
1255 EmitAlignment(Log2_32(
1256 MJTI->getEntryAlignment(*TM.getDataLayout())));
1258 // Jump tables in code sections are marked with a data_region directive
1259 // where that's supported.
1260 if (!JTInDiffSection)
1261 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1263 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1264 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1266 // If this jump table was deleted, ignore it.
1267 if (JTBBs.empty()) continue;
1269 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1270 /// emit a .set directive for each unique entry.
1271 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1272 MAI->doesSetDirectiveSuppressesReloc()) {
1273 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1274 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1275 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1276 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1277 const MachineBasicBlock *MBB = JTBBs[ii];
1278 if (!EmittedSets.insert(MBB).second)
1281 // .set LJTSet, LBB32-base
1283 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1284 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1285 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1289 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1290 // before each jump table. The first label is never referenced, but tells
1291 // the assembler and linker the extents of the jump table object. The
1292 // second label is actually referenced by the code.
1293 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1294 // FIXME: This doesn't have to have any specific name, just any randomly
1295 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1296 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1298 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1300 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1301 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1303 if (!JTInDiffSection)
1304 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1307 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1309 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1310 const MachineBasicBlock *MBB,
1311 unsigned UID) const {
1312 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1313 const MCExpr *Value = nullptr;
1314 switch (MJTI->getEntryKind()) {
1315 case MachineJumpTableInfo::EK_Inline:
1316 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1317 case MachineJumpTableInfo::EK_Custom32:
1318 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1319 MJTI, MBB, UID, OutContext);
1321 case MachineJumpTableInfo::EK_BlockAddress:
1322 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1324 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1326 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1327 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1328 // with a relocation as gp-relative, e.g.:
1330 MCSymbol *MBBSym = MBB->getSymbol();
1331 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1335 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1336 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1337 // with a relocation as gp-relative, e.g.:
1339 MCSymbol *MBBSym = MBB->getSymbol();
1340 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1344 case MachineJumpTableInfo::EK_LabelDifference32: {
1345 // Each entry is the address of the block minus the address of the jump
1346 // table. This is used for PIC jump tables where gprel32 is not supported.
1348 // .word LBB123 - LJTI1_2
1349 // If the .set directive avoids relocations, this is emitted as:
1350 // .set L4_5_set_123, LBB123 - LJTI1_2
1351 // .word L4_5_set_123
1352 if (MAI->doesSetDirectiveSuppressesReloc()) {
1353 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1357 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1358 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1359 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1360 Value = MCBinaryExpr::CreateSub(Value, Base, OutContext);
1365 assert(Value && "Unknown entry kind!");
1367 unsigned EntrySize =
1368 MJTI->getEntrySize(*TM.getDataLayout());
1369 OutStreamer.EmitValue(Value, EntrySize);
1373 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1374 /// special global used by LLVM. If so, emit it and return true, otherwise
1375 /// do nothing and return false.
1376 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1377 if (GV->getName() == "llvm.used") {
1378 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1379 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1383 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1384 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1385 GV->hasAvailableExternallyLinkage())
1388 if (!GV->hasAppendingLinkage()) return false;
1390 assert(GV->hasInitializer() && "Not a special LLVM global!");
1392 if (GV->getName() == "llvm.global_ctors") {
1393 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1395 if (TM.getRelocationModel() == Reloc::Static &&
1396 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1397 StringRef Sym(".constructors_used");
1398 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1404 if (GV->getName() == "llvm.global_dtors") {
1405 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1407 if (TM.getRelocationModel() == Reloc::Static &&
1408 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1409 StringRef Sym(".destructors_used");
1410 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1419 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1420 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1421 /// is true, as being used with this directive.
1422 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1423 // Should be an array of 'i8*'.
1424 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1425 const GlobalValue *GV =
1426 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1428 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1434 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1436 llvm::Constant *Func;
1437 llvm::GlobalValue *ComdatKey;
1441 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1443 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1444 // Should be an array of '{ int, void ()* }' structs. The first value is the
1446 if (!isa<ConstantArray>(List)) return;
1448 // Sanity check the structors list.
1449 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1450 if (!InitList) return; // Not an array!
1451 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1452 // FIXME: Only allow the 3-field form in LLVM 4.0.
1453 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1454 return; // Not an array of two or three elements!
1455 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1456 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1457 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1458 return; // Not (int, ptr, ptr).
1460 // Gather the structors in a form that's convenient for sorting by priority.
1461 SmallVector<Structor, 8> Structors;
1462 for (Value *O : InitList->operands()) {
1463 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1464 if (!CS) continue; // Malformed.
1465 if (CS->getOperand(1)->isNullValue())
1466 break; // Found a null terminator, skip the rest.
1467 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1468 if (!Priority) continue; // Malformed.
1469 Structors.push_back(Structor());
1470 Structor &S = Structors.back();
1471 S.Priority = Priority->getLimitedValue(65535);
1472 S.Func = CS->getOperand(1);
1473 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1474 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1477 // Emit the function pointers in the target-specific order
1478 const DataLayout *DL = TM.getDataLayout();
1479 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1480 std::stable_sort(Structors.begin(), Structors.end(),
1481 [](const Structor &L,
1482 const Structor &R) { return L.Priority < R.Priority; });
1483 for (Structor &S : Structors) {
1484 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1485 const MCSymbol *KeySym = nullptr;
1486 if (GlobalValue *GV = S.ComdatKey) {
1487 if (GV->hasAvailableExternallyLinkage())
1488 // If the associated variable is available_externally, some other TU
1489 // will provide its dynamic initializer.
1492 KeySym = getSymbol(GV);
1494 const MCSection *OutputSection =
1495 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1496 : Obj.getStaticDtorSection(S.Priority, KeySym));
1497 OutStreamer.SwitchSection(OutputSection);
1498 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1499 EmitAlignment(Align);
1500 EmitXXStructor(S.Func);
1504 void AsmPrinter::EmitModuleIdents(Module &M) {
1505 if (!MAI->hasIdentDirective())
1508 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1509 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1510 const MDNode *N = NMD->getOperand(i);
1511 assert(N->getNumOperands() == 1 &&
1512 "llvm.ident metadata entry can have only one operand");
1513 const MDString *S = cast<MDString>(N->getOperand(0));
1514 OutStreamer.EmitIdent(S->getString());
1519 //===--------------------------------------------------------------------===//
1520 // Emission and print routines
1523 /// EmitInt8 - Emit a byte directive and value.
1525 void AsmPrinter::EmitInt8(int Value) const {
1526 OutStreamer.EmitIntValue(Value, 1);
1529 /// EmitInt16 - Emit a short directive and value.
1531 void AsmPrinter::EmitInt16(int Value) const {
1532 OutStreamer.EmitIntValue(Value, 2);
1535 /// EmitInt32 - Emit a long directive and value.
1537 void AsmPrinter::EmitInt32(int Value) const {
1538 OutStreamer.EmitIntValue(Value, 4);
1541 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1542 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1543 /// .set if it avoids relocations.
1544 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1545 unsigned Size) const {
1546 // Get the Hi-Lo expression.
1547 const MCExpr *Diff =
1548 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1549 MCSymbolRefExpr::Create(Lo, OutContext),
1552 if (!MAI->doesSetDirectiveSuppressesReloc()) {
1553 OutStreamer.EmitValue(Diff, Size);
1557 // Otherwise, emit with .set (aka assignment).
1558 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1559 OutStreamer.EmitAssignment(SetLabel, Diff);
1560 OutStreamer.EmitSymbolValue(SetLabel, Size);
1563 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1564 /// where the size in bytes of the directive is specified by Size and Label
1565 /// specifies the label. This implicitly uses .set if it is available.
1566 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1568 bool IsSectionRelative) const {
1569 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1570 OutStreamer.EmitCOFFSecRel32(Label);
1574 // Emit Label+Offset (or just Label if Offset is zero)
1575 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1577 Expr = MCBinaryExpr::CreateAdd(
1578 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1580 OutStreamer.EmitValue(Expr, Size);
1583 //===----------------------------------------------------------------------===//
1585 // EmitAlignment - Emit an alignment directive to the specified power of
1586 // two boundary. For example, if you pass in 3 here, you will get an 8
1587 // byte alignment. If a global value is specified, and if that global has
1588 // an explicit alignment requested, it will override the alignment request
1589 // if required for correctness.
1591 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1593 NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(),
1596 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1599 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1600 "undefined behavior");
1601 if (getCurrentSection()->getKind().isText())
1602 OutStreamer.EmitCodeAlignment(1u << NumBits);
1604 OutStreamer.EmitValueToAlignment(1u << NumBits);
1607 //===----------------------------------------------------------------------===//
1608 // Constant emission.
1609 //===----------------------------------------------------------------------===//
1611 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1612 MCContext &Ctx = OutContext;
1614 if (CV->isNullValue() || isa<UndefValue>(CV))
1615 return MCConstantExpr::Create(0, Ctx);
1617 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1618 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1620 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1621 return MCSymbolRefExpr::Create(getSymbol(GV), Ctx);
1623 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1624 return MCSymbolRefExpr::Create(GetBlockAddressSymbol(BA), Ctx);
1626 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1628 llvm_unreachable("Unknown constant value to lower!");
1631 if (const MCExpr *RelocExpr
1632 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1635 switch (CE->getOpcode()) {
1637 // If the code isn't optimized, there may be outstanding folding
1638 // opportunities. Attempt to fold the expression using DataLayout as a
1639 // last resort before giving up.
1640 if (Constant *C = ConstantFoldConstantExpression(
1641 CE, TM.getDataLayout()))
1643 return lowerConstant(C);
1645 // Otherwise report the problem to the user.
1648 raw_string_ostream OS(S);
1649 OS << "Unsupported expression in static initializer: ";
1650 CE->printAsOperand(OS, /*PrintType=*/false,
1651 !MF ? nullptr : MF->getFunction()->getParent());
1652 report_fatal_error(OS.str());
1654 case Instruction::GetElementPtr: {
1655 const DataLayout &DL = *TM.getDataLayout();
1657 // Generate a symbolic expression for the byte address
1658 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1659 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1661 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1665 int64_t Offset = OffsetAI.getSExtValue();
1666 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1670 case Instruction::Trunc:
1671 // We emit the value and depend on the assembler to truncate the generated
1672 // expression properly. This is important for differences between
1673 // blockaddress labels. Since the two labels are in the same function, it
1674 // is reasonable to treat their delta as a 32-bit value.
1676 case Instruction::BitCast:
1677 return lowerConstant(CE->getOperand(0));
1679 case Instruction::IntToPtr: {
1680 const DataLayout &DL = *TM.getDataLayout();
1682 // Handle casts to pointers by changing them into casts to the appropriate
1683 // integer type. This promotes constant folding and simplifies this code.
1684 Constant *Op = CE->getOperand(0);
1685 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1687 return lowerConstant(Op);
1690 case Instruction::PtrToInt: {
1691 const DataLayout &DL = *TM.getDataLayout();
1693 // Support only foldable casts to/from pointers that can be eliminated by
1694 // changing the pointer to the appropriately sized integer type.
1695 Constant *Op = CE->getOperand(0);
1696 Type *Ty = CE->getType();
1698 const MCExpr *OpExpr = lowerConstant(Op);
1700 // We can emit the pointer value into this slot if the slot is an
1701 // integer slot equal to the size of the pointer.
1702 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1705 // Otherwise the pointer is smaller than the resultant integer, mask off
1706 // the high bits so we are sure to get a proper truncation if the input is
1708 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1709 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1710 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1713 // The MC library also has a right-shift operator, but it isn't consistently
1714 // signed or unsigned between different targets.
1715 case Instruction::Add:
1716 case Instruction::Sub:
1717 case Instruction::Mul:
1718 case Instruction::SDiv:
1719 case Instruction::SRem:
1720 case Instruction::Shl:
1721 case Instruction::And:
1722 case Instruction::Or:
1723 case Instruction::Xor: {
1724 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1725 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1726 switch (CE->getOpcode()) {
1727 default: llvm_unreachable("Unknown binary operator constant cast expr");
1728 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1729 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1730 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1731 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1732 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1733 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1734 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1735 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1736 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1742 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP,
1743 const Constant *BaseCV = nullptr,
1744 uint64_t Offset = 0);
1746 /// isRepeatedByteSequence - Determine whether the given value is
1747 /// composed of a repeated sequence of identical bytes and return the
1748 /// byte value. If it is not a repeated sequence, return -1.
1749 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1750 StringRef Data = V->getRawDataValues();
1751 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1753 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1754 if (Data[i] != C) return -1;
1755 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1759 /// isRepeatedByteSequence - Determine whether the given value is
1760 /// composed of a repeated sequence of identical bytes and return the
1761 /// byte value. If it is not a repeated sequence, return -1.
1762 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1764 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1765 if (CI->getBitWidth() > 64) return -1;
1768 TM.getDataLayout()->getTypeAllocSize(V->getType());
1769 uint64_t Value = CI->getZExtValue();
1771 // Make sure the constant is at least 8 bits long and has a power
1772 // of 2 bit width. This guarantees the constant bit width is
1773 // always a multiple of 8 bits, avoiding issues with padding out
1774 // to Size and other such corner cases.
1775 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1777 uint8_t Byte = static_cast<uint8_t>(Value);
1779 for (unsigned i = 1; i < Size; ++i) {
1781 if (static_cast<uint8_t>(Value) != Byte) return -1;
1785 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1786 // Make sure all array elements are sequences of the same repeated
1788 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1789 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1790 if (Byte == -1) return -1;
1792 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1793 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1794 if (ThisByte == -1) return -1;
1795 if (Byte != ThisByte) return -1;
1800 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1801 return isRepeatedByteSequence(CDS);
1806 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1809 // See if we can aggregate this into a .fill, if so, emit it as such.
1810 int Value = isRepeatedByteSequence(CDS, AP.TM);
1813 AP.TM.getDataLayout()->getTypeAllocSize(
1815 // Don't emit a 1-byte object as a .fill.
1817 return AP.OutStreamer.EmitFill(Bytes, Value);
1820 // If this can be emitted with .ascii/.asciz, emit it as such.
1821 if (CDS->isString())
1822 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1824 // Otherwise, emit the values in successive locations.
1825 unsigned ElementByteSize = CDS->getElementByteSize();
1826 if (isa<IntegerType>(CDS->getElementType())) {
1827 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1829 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1830 CDS->getElementAsInteger(i));
1831 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1834 } else if (ElementByteSize == 4) {
1835 // FP Constants are printed as integer constants to avoid losing
1837 assert(CDS->getElementType()->isFloatTy());
1838 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1844 F = CDS->getElementAsFloat(i);
1846 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1847 AP.OutStreamer.EmitIntValue(I, 4);
1850 assert(CDS->getElementType()->isDoubleTy());
1851 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1857 F = CDS->getElementAsDouble(i);
1859 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1860 AP.OutStreamer.EmitIntValue(I, 8);
1864 const DataLayout &DL = *AP.TM.getDataLayout();
1865 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1866 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1867 CDS->getNumElements();
1868 if (unsigned Padding = Size - EmittedSize)
1869 AP.OutStreamer.EmitZeros(Padding);
1873 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP,
1874 const Constant *BaseCV, uint64_t Offset) {
1875 // See if we can aggregate some values. Make sure it can be
1876 // represented as a series of bytes of the constant value.
1877 int Value = isRepeatedByteSequence(CA, AP.TM);
1878 const DataLayout &DL = *AP.TM.getDataLayout();
1881 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1882 AP.OutStreamer.EmitFill(Bytes, Value);
1885 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1886 emitGlobalConstantImpl(CA->getOperand(i), AP, BaseCV, Offset);
1887 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1892 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1893 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1894 emitGlobalConstantImpl(CV->getOperand(i), AP);
1896 const DataLayout &DL = *AP.TM.getDataLayout();
1897 unsigned Size = DL.getTypeAllocSize(CV->getType());
1898 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1899 CV->getType()->getNumElements();
1900 if (unsigned Padding = Size - EmittedSize)
1901 AP.OutStreamer.EmitZeros(Padding);
1904 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP,
1905 const Constant *BaseCV, uint64_t Offset) {
1906 // Print the fields in successive locations. Pad to align if needed!
1907 const DataLayout *DL = AP.TM.getDataLayout();
1908 unsigned Size = DL->getTypeAllocSize(CS->getType());
1909 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1910 uint64_t SizeSoFar = 0;
1911 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1912 const Constant *Field = CS->getOperand(i);
1914 // Print the actual field value.
1915 emitGlobalConstantImpl(Field, AP, BaseCV, Offset+SizeSoFar);
1917 // Check if padding is needed and insert one or more 0s.
1918 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1919 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1920 - Layout->getElementOffset(i)) - FieldSize;
1921 SizeSoFar += FieldSize + PadSize;
1923 // Insert padding - this may include padding to increase the size of the
1924 // current field up to the ABI size (if the struct is not packed) as well
1925 // as padding to ensure that the next field starts at the right offset.
1926 AP.OutStreamer.EmitZeros(PadSize);
1928 assert(SizeSoFar == Layout->getSizeInBytes() &&
1929 "Layout of constant struct may be incorrect!");
1932 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1933 APInt API = CFP->getValueAPF().bitcastToAPInt();
1935 // First print a comment with what we think the original floating-point value
1936 // should have been.
1937 if (AP.isVerbose()) {
1938 SmallString<8> StrVal;
1939 CFP->getValueAPF().toString(StrVal);
1942 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1944 AP.OutStreamer.GetCommentOS() << "Printing <null> Type";
1945 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1948 // Now iterate through the APInt chunks, emitting them in endian-correct
1949 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1951 unsigned NumBytes = API.getBitWidth() / 8;
1952 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1953 const uint64_t *p = API.getRawData();
1955 // PPC's long double has odd notions of endianness compared to how LLVM
1956 // handles it: p[0] goes first for *big* endian on PPC.
1957 if (AP.TM.getDataLayout()->isBigEndian() &&
1958 !CFP->getType()->isPPC_FP128Ty()) {
1959 int Chunk = API.getNumWords() - 1;
1962 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1964 for (; Chunk >= 0; --Chunk)
1965 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1968 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1969 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1972 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1975 // Emit the tail padding for the long double.
1976 const DataLayout &DL = *AP.TM.getDataLayout();
1977 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1978 DL.getTypeStoreSize(CFP->getType()));
1981 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1982 const DataLayout *DL = AP.TM.getDataLayout();
1983 unsigned BitWidth = CI->getBitWidth();
1985 // Copy the value as we may massage the layout for constants whose bit width
1986 // is not a multiple of 64-bits.
1987 APInt Realigned(CI->getValue());
1988 uint64_t ExtraBits = 0;
1989 unsigned ExtraBitsSize = BitWidth & 63;
1991 if (ExtraBitsSize) {
1992 // The bit width of the data is not a multiple of 64-bits.
1993 // The extra bits are expected to be at the end of the chunk of the memory.
1995 // * Nothing to be done, just record the extra bits to emit.
1997 // * Record the extra bits to emit.
1998 // * Realign the raw data to emit the chunks of 64-bits.
1999 if (DL->isBigEndian()) {
2000 // Basically the structure of the raw data is a chunk of 64-bits cells:
2001 // 0 1 BitWidth / 64
2002 // [chunk1][chunk2] ... [chunkN].
2003 // The most significant chunk is chunkN and it should be emitted first.
2004 // However, due to the alignment issue chunkN contains useless bits.
2005 // Realign the chunks so that they contain only useless information:
2006 // ExtraBits 0 1 (BitWidth / 64) - 1
2007 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2008 ExtraBits = Realigned.getRawData()[0] &
2009 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2010 Realigned = Realigned.lshr(ExtraBitsSize);
2012 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2015 // We don't expect assemblers to support integer data directives
2016 // for more than 64 bits, so we emit the data in at most 64-bit
2017 // quantities at a time.
2018 const uint64_t *RawData = Realigned.getRawData();
2019 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2020 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
2021 AP.OutStreamer.EmitIntValue(Val, 8);
2024 if (ExtraBitsSize) {
2025 // Emit the extra bits after the 64-bits chunks.
2027 // Emit a directive that fills the expected size.
2028 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(
2030 Size -= (BitWidth / 64) * 8;
2031 assert(Size && Size * 8 >= ExtraBitsSize &&
2032 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2033 == ExtraBits && "Directive too small for extra bits.");
2034 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
2038 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2039 /// equivalent global, by a target specific GOT pc relative access to the
2041 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2042 const Constant *BaseCst,
2044 // The global @foo below illustrates a global that uses a got equivalent.
2046 // @bar = global i32 42
2047 // @gotequiv = private unnamed_addr constant i32* @bar
2048 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2049 // i64 ptrtoint (i32* @foo to i64))
2052 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2053 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2056 // foo = cstexpr, where
2057 // cstexpr := <gotequiv> - "." + <cst>
2058 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2060 // After canonicalization by EvaluateAsRelocatable `ME` turns into:
2062 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2063 // gotpcrelcst := <offset from @foo base> + <cst>
2066 if (!(*ME)->EvaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2069 const MCSymbol *GOTEquivSym = &MV.getSymA()->getSymbol();
2070 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2073 const GlobalValue *BaseGV = dyn_cast<GlobalValue>(BaseCst);
2077 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2078 if (BaseSym != &MV.getSymB()->getSymbol())
2081 // Make sure to match:
2083 // gotpcrelcst := <offset from @foo base> + <cst>
2085 int64_t GOTPCRelCst = Offset + MV.getConstant();
2086 if (GOTPCRelCst < 0)
2089 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2096 // .long gotequiv - "." + <cst>
2098 // is replaced by the target specific equivalent to:
2103 // .long bar@GOTPCREL+<gotpcrelcst>
2105 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2106 const GlobalVariable *GV = Result.first;
2107 unsigned NumUses = Result.second;
2108 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2109 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2110 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(FinalSym,
2113 // Update GOT equivalent usage information
2116 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2118 AP.GlobalGOTEquivs.erase(GOTEquivSym);
2121 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP,
2122 const Constant *BaseCV, uint64_t Offset) {
2123 const DataLayout *DL = AP.TM.getDataLayout();
2124 uint64_t Size = DL->getTypeAllocSize(CV->getType());
2126 // Globals with sub-elements such as combinations of arrays and structs
2127 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2128 // constant symbol base and the current position with BaseCV and Offset.
2129 if (!BaseCV && CV->hasOneUse())
2130 BaseCV = dyn_cast<Constant>(CV->user_back());
2132 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2133 return AP.OutStreamer.EmitZeros(Size);
2135 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2142 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
2143 CI->getZExtValue());
2144 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
2147 emitGlobalConstantLargeInt(CI, AP);
2152 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2153 return emitGlobalConstantFP(CFP, AP);
2155 if (isa<ConstantPointerNull>(CV)) {
2156 AP.OutStreamer.EmitIntValue(0, Size);
2160 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2161 return emitGlobalConstantDataSequential(CDS, AP);
2163 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2164 return emitGlobalConstantArray(CVA, AP, BaseCV, Offset);
2166 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2167 return emitGlobalConstantStruct(CVS, AP, BaseCV, Offset);
2169 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2170 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2172 if (CE->getOpcode() == Instruction::BitCast)
2173 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2176 // If the constant expression's size is greater than 64-bits, then we have
2177 // to emit the value in chunks. Try to constant fold the value and emit it
2179 Constant *New = ConstantFoldConstantExpression(CE, DL);
2180 if (New && New != CE)
2181 return emitGlobalConstantImpl(New, AP);
2185 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2186 return emitGlobalConstantVector(V, AP);
2188 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2189 // thread the streamer with EmitValue.
2190 const MCExpr *ME = AP.lowerConstant(CV);
2192 // Since lowerConstant already folded and got rid of all IR pointer and
2193 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2195 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2196 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2198 AP.OutStreamer.EmitValue(ME, Size);
2201 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2202 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2204 TM.getDataLayout()->getTypeAllocSize(CV->getType());
2206 emitGlobalConstantImpl(CV, *this);
2207 else if (MAI->hasSubsectionsViaSymbols()) {
2208 // If the global has zero size, emit a single byte so that two labels don't
2209 // look like they are at the same location.
2210 OutStreamer.EmitIntValue(0, 1);
2214 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2215 // Target doesn't support this yet!
2216 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2219 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2221 OS << '+' << Offset;
2222 else if (Offset < 0)
2226 //===----------------------------------------------------------------------===//
2227 // Symbol Lowering Routines.
2228 //===----------------------------------------------------------------------===//
2230 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2231 /// temporary label with the specified stem and unique ID.
2232 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name, unsigned ID) const {
2233 const DataLayout *DL = TM.getDataLayout();
2234 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2238 /// GetTempSymbol - Return an assembler temporary label with the specified
2240 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name) const {
2241 const DataLayout *DL = TM.getDataLayout();
2242 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2246 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name, unsigned ID) const {
2247 return OutContext.createTempSymbol(Name + Twine(ID));
2250 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2251 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2254 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2255 return MMI->getAddrLabelSymbol(BB);
2258 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2259 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2260 const DataLayout *DL = TM.getDataLayout();
2261 return OutContext.GetOrCreateSymbol
2262 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2263 + "_" + Twine(CPID));
2266 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2267 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2268 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2271 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2272 /// FIXME: privatize to AsmPrinter.
2273 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2274 const DataLayout *DL = TM.getDataLayout();
2275 return OutContext.GetOrCreateSymbol
2276 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2277 Twine(UID) + "_set_" + Twine(MBBID));
2280 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2281 StringRef Suffix) const {
2282 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2286 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2288 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2289 SmallString<60> NameStr;
2290 Mang->getNameWithPrefix(NameStr, Sym);
2291 return OutContext.GetOrCreateSymbol(NameStr.str());
2296 /// PrintParentLoopComment - Print comments about parent loops of this one.
2297 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2298 unsigned FunctionNumber) {
2300 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2301 OS.indent(Loop->getLoopDepth()*2)
2302 << "Parent Loop BB" << FunctionNumber << "_"
2303 << Loop->getHeader()->getNumber()
2304 << " Depth=" << Loop->getLoopDepth() << '\n';
2308 /// PrintChildLoopComment - Print comments about child loops within
2309 /// the loop for this basic block, with nesting.
2310 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2311 unsigned FunctionNumber) {
2312 // Add child loop information
2313 for (const MachineLoop *CL : *Loop) {
2314 OS.indent(CL->getLoopDepth()*2)
2315 << "Child Loop BB" << FunctionNumber << "_"
2316 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2318 PrintChildLoopComment(OS, CL, FunctionNumber);
2322 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2323 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2324 const MachineLoopInfo *LI,
2325 const AsmPrinter &AP) {
2326 // Add loop depth information
2327 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2330 MachineBasicBlock *Header = Loop->getHeader();
2331 assert(Header && "No header for loop");
2333 // If this block is not a loop header, just print out what is the loop header
2335 if (Header != &MBB) {
2336 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2337 Twine(AP.getFunctionNumber())+"_" +
2338 Twine(Loop->getHeader()->getNumber())+
2339 " Depth="+Twine(Loop->getLoopDepth()));
2343 // Otherwise, it is a loop header. Print out information about child and
2345 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2347 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2350 OS.indent(Loop->getLoopDepth()*2-2);
2355 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2357 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2361 /// EmitBasicBlockStart - This method prints the label for the specified
2362 /// MachineBasicBlock, an alignment (if present) and a comment describing
2363 /// it if appropriate.
2364 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2365 // Emit an alignment directive for this block, if needed.
2366 if (unsigned Align = MBB.getAlignment())
2367 EmitAlignment(Align);
2369 // If the block has its address taken, emit any labels that were used to
2370 // reference the block. It is possible that there is more than one label
2371 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2372 // the references were generated.
2373 if (MBB.hasAddressTaken()) {
2374 const BasicBlock *BB = MBB.getBasicBlock();
2376 OutStreamer.AddComment("Block address taken");
2378 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2379 for (auto *Sym : Symbols)
2380 OutStreamer.EmitLabel(Sym);
2383 // Print some verbose block comments.
2385 if (const BasicBlock *BB = MBB.getBasicBlock())
2387 OutStreamer.AddComment("%" + BB->getName());
2388 emitBasicBlockLoopComments(MBB, LI, *this);
2391 // Print the main label for the block.
2392 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2394 // NOTE: Want this comment at start of line, don't emit with AddComment.
2395 OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2398 OutStreamer.EmitLabel(MBB.getSymbol());
2402 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2403 bool IsDefinition) const {
2404 MCSymbolAttr Attr = MCSA_Invalid;
2406 switch (Visibility) {
2408 case GlobalValue::HiddenVisibility:
2410 Attr = MAI->getHiddenVisibilityAttr();
2412 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2414 case GlobalValue::ProtectedVisibility:
2415 Attr = MAI->getProtectedVisibilityAttr();
2419 if (Attr != MCSA_Invalid)
2420 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2423 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2424 /// exactly one predecessor and the control transfer mechanism between
2425 /// the predecessor and this block is a fall-through.
2427 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2428 // If this is a landing pad, it isn't a fall through. If it has no preds,
2429 // then nothing falls through to it.
2430 if (MBB->isLandingPad() || MBB->pred_empty())
2433 // If there isn't exactly one predecessor, it can't be a fall through.
2434 if (MBB->pred_size() > 1)
2437 // The predecessor has to be immediately before this block.
2438 MachineBasicBlock *Pred = *MBB->pred_begin();
2439 if (!Pred->isLayoutSuccessor(MBB))
2442 // If the block is completely empty, then it definitely does fall through.
2446 // Check the terminators in the previous blocks
2447 for (const auto &MI : Pred->terminators()) {
2448 // If it is not a simple branch, we are in a table somewhere.
2449 if (!MI.isBranch() || MI.isIndirectBranch())
2452 // If we are the operands of one of the branches, this is not a fall
2453 // through. Note that targets with delay slots will usually bundle
2454 // terminators with the delay slot instruction.
2455 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2458 if (OP->isMBB() && OP->getMBB() == MBB)
2468 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2469 if (!S.usesMetadata())
2472 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2473 " stackmap formats, please see the documentation for a description of"
2474 " the default format. If you really need a custom serialized format,"
2475 " please file a bug");
2477 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2478 gcp_map_type::iterator GCPI = GCMap.find(&S);
2479 if (GCPI != GCMap.end())
2480 return GCPI->second.get();
2482 const char *Name = S.getName().c_str();
2484 for (GCMetadataPrinterRegistry::iterator
2485 I = GCMetadataPrinterRegistry::begin(),
2486 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2487 if (strcmp(Name, I->getName()) == 0) {
2488 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2490 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2491 return IterBool.first->second.get();
2494 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2497 /// Pin vtable to this file.
2498 AsmPrinterHandler::~AsmPrinterHandler() {}