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 &DL,
81 unsigned InBits = 0) {
83 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
84 NumBits = DL.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 if (CurrentFnBegin) {
560 if (MAI->useAssignmentForEHBegin()) {
561 MCSymbol *CurPos = OutContext.CreateTempSymbol();
562 OutStreamer.EmitLabel(CurPos);
563 OutStreamer.EmitAssignment(CurrentFnBegin,
564 MCSymbolRefExpr::Create(CurPos, OutContext));
566 OutStreamer.EmitLabel(CurrentFnBegin);
570 // Emit pre-function debug and/or EH information.
571 for (const HandlerInfo &HI : Handlers) {
572 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
573 HI.Handler->beginFunction(MF);
576 // Emit the prologue data.
577 if (F->hasPrologueData())
578 EmitGlobalConstant(F->getPrologueData());
581 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
582 /// function. This can be overridden by targets as required to do custom stuff.
583 void AsmPrinter::EmitFunctionEntryLabel() {
584 CurrentFnSym->redefineIfPossible();
586 // The function label could have already been emitted if two symbols end up
587 // conflicting due to asm renaming. Detect this and emit an error.
588 if (CurrentFnSym->isVariable())
589 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
590 "' is a protected alias");
591 if (CurrentFnSym->isDefined())
592 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
593 "' label emitted multiple times to assembly file");
595 return OutStreamer.EmitLabel(CurrentFnSym);
598 /// emitComments - Pretty-print comments for instructions.
599 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
600 const MachineFunction *MF = MI.getParent()->getParent();
601 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
603 // Check for spills and reloads
606 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
608 // We assume a single instruction only has a spill or reload, not
610 const MachineMemOperand *MMO;
611 if (TII->isLoadFromStackSlotPostFE(&MI, FI)) {
612 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
613 MMO = *MI.memoperands_begin();
614 CommentOS << MMO->getSize() << "-byte Reload\n";
616 } else if (TII->hasLoadFromStackSlot(&MI, MMO, FI)) {
617 if (FrameInfo->isSpillSlotObjectIndex(FI))
618 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
619 } else if (TII->isStoreToStackSlotPostFE(&MI, FI)) {
620 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
621 MMO = *MI.memoperands_begin();
622 CommentOS << MMO->getSize() << "-byte Spill\n";
624 } else if (TII->hasStoreToStackSlot(&MI, MMO, FI)) {
625 if (FrameInfo->isSpillSlotObjectIndex(FI))
626 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
629 // Check for spill-induced copies
630 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
631 CommentOS << " Reload Reuse\n";
634 /// emitImplicitDef - This method emits the specified machine instruction
635 /// that is an implicit def.
636 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
637 unsigned RegNo = MI->getOperand(0).getReg();
638 OutStreamer.AddComment(Twine("implicit-def: ") +
639 MMI->getContext().getRegisterInfo()->getName(RegNo));
640 OutStreamer.AddBlankLine();
643 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
644 std::string Str = "kill:";
645 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
646 const MachineOperand &Op = MI->getOperand(i);
647 assert(Op.isReg() && "KILL instruction must have only register operands");
649 Str += AP.MMI->getContext().getRegisterInfo()->getName(Op.getReg());
650 Str += (Op.isDef() ? "<def>" : "<kill>");
652 AP.OutStreamer.AddComment(Str);
653 AP.OutStreamer.AddBlankLine();
656 /// emitDebugValueComment - This method handles the target-independent form
657 /// of DBG_VALUE, returning true if it was able to do so. A false return
658 /// means the target will need to handle MI in EmitInstruction.
659 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
660 // This code handles only the 4-operand target-independent form.
661 if (MI->getNumOperands() != 4)
664 SmallString<128> Str;
665 raw_svector_ostream OS(Str);
666 OS << "DEBUG_VALUE: ";
668 DIVariable V = MI->getDebugVariable();
669 if (V.getContext().isSubprogram()) {
670 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
676 DIExpression Expr = MI->getDebugExpression();
677 if (Expr.isBitPiece())
678 OS << " [bit_piece offset=" << Expr.getBitPieceOffset()
679 << " size=" << Expr.getBitPieceSize() << "]";
682 // The second operand is only an offset if it's an immediate.
683 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
684 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
686 // Register or immediate value. Register 0 means undef.
687 if (MI->getOperand(0).isFPImm()) {
688 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
689 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
690 OS << (double)APF.convertToFloat();
691 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
692 OS << APF.convertToDouble();
694 // There is no good way to print long double. Convert a copy to
695 // double. Ah well, it's only a comment.
697 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
699 OS << "(long double) " << APF.convertToDouble();
701 } else if (MI->getOperand(0).isImm()) {
702 OS << MI->getOperand(0).getImm();
703 } else if (MI->getOperand(0).isCImm()) {
704 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
707 if (MI->getOperand(0).isReg()) {
708 Reg = MI->getOperand(0).getReg();
710 assert(MI->getOperand(0).isFI() && "Unknown operand type");
711 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
712 Offset += TFI->getFrameIndexReference(*AP.MF,
713 MI->getOperand(0).getIndex(), Reg);
717 // Suppress offset, it is not meaningful here.
719 // NOTE: Want this comment at start of line, don't emit with AddComment.
720 AP.OutStreamer.emitRawComment(OS.str());
725 OS << AP.MMI->getContext().getRegisterInfo()->getName(Reg);
729 OS << '+' << Offset << ']';
731 // NOTE: Want this comment at start of line, don't emit with AddComment.
732 AP.OutStreamer.emitRawComment(OS.str());
736 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
737 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
738 MF->getFunction()->needsUnwindTableEntry())
741 if (MMI->hasDebugInfo())
747 bool AsmPrinter::needsSEHMoves() {
748 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry();
751 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
752 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
753 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
754 ExceptionHandlingType != ExceptionHandling::ARM)
757 if (needsCFIMoves() == CFI_M_None)
760 const MachineModuleInfo &MMI = MF->getMMI();
761 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
762 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
763 const MCCFIInstruction &CFI = Instrs[CFIIndex];
764 emitCFIInstruction(CFI);
767 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
768 // The operands are the MCSymbol and the frame offset of the allocation.
769 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
770 int FrameOffset = MI.getOperand(1).getImm();
772 // Emit a symbol assignment.
773 OutStreamer.EmitAssignment(FrameAllocSym,
774 MCConstantExpr::Create(FrameOffset, OutContext));
777 /// EmitFunctionBody - This method emits the body and trailer for a
779 void AsmPrinter::EmitFunctionBody() {
780 // Emit target-specific gunk before the function body.
781 EmitFunctionBodyStart();
783 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
785 // Print out code for the function.
786 bool HasAnyRealCode = false;
787 for (auto &MBB : *MF) {
788 // Print a label for the basic block.
789 EmitBasicBlockStart(MBB);
790 for (auto &MI : MBB) {
792 // Print the assembly for the instruction.
793 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
794 !MI.isDebugValue()) {
795 HasAnyRealCode = true;
799 if (ShouldPrintDebugScopes) {
800 for (const HandlerInfo &HI : Handlers) {
801 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
802 TimePassesIsEnabled);
803 HI.Handler->beginInstruction(&MI);
808 emitComments(MI, OutStreamer.GetCommentOS());
810 switch (MI.getOpcode()) {
811 case TargetOpcode::CFI_INSTRUCTION:
812 emitCFIInstruction(MI);
815 case TargetOpcode::FRAME_ALLOC:
819 case TargetOpcode::EH_LABEL:
820 case TargetOpcode::GC_LABEL:
821 OutStreamer.EmitLabel(MI.getOperand(0).getMCSymbol());
823 case TargetOpcode::INLINEASM:
826 case TargetOpcode::DBG_VALUE:
828 if (!emitDebugValueComment(&MI, *this))
829 EmitInstruction(&MI);
832 case TargetOpcode::IMPLICIT_DEF:
833 if (isVerbose()) emitImplicitDef(&MI);
835 case TargetOpcode::KILL:
836 if (isVerbose()) emitKill(&MI, *this);
839 EmitInstruction(&MI);
843 if (ShouldPrintDebugScopes) {
844 for (const HandlerInfo &HI : Handlers) {
845 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
846 TimePassesIsEnabled);
847 HI.Handler->endInstruction();
852 EmitBasicBlockEnd(MBB);
855 // If the function is empty and the object file uses .subsections_via_symbols,
856 // then we need to emit *something* to the function body to prevent the
857 // labels from collapsing together. Just emit a noop.
858 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
860 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
861 OutStreamer.AddComment("avoids zero-length function");
863 // Targets can opt-out of emitting the noop here by leaving the opcode
865 if (Noop.getOpcode())
866 OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
869 const Function *F = MF->getFunction();
870 for (const auto &BB : *F) {
871 if (!BB.hasAddressTaken())
873 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
874 if (Sym->isDefined())
876 OutStreamer.AddComment("Address of block that was removed by CodeGen");
877 OutStreamer.EmitLabel(Sym);
880 // Emit target-specific gunk after the function body.
881 EmitFunctionBodyEnd();
883 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
884 MAI->hasDotTypeDotSizeDirective()) {
885 // Create a symbol for the end of function.
886 CurrentFnEnd = createTempSymbol("func_end", getFunctionNumber());
887 OutStreamer.EmitLabel(CurrentFnEnd);
890 // If the target wants a .size directive for the size of the function, emit
892 if (MAI->hasDotTypeDotSizeDirective()) {
893 // We can get the size as difference between the function label and the
895 const MCExpr *SizeExp =
896 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(CurrentFnEnd, OutContext),
897 MCSymbolRefExpr::Create(CurrentFnSymForSize,
900 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
903 for (const HandlerInfo &HI : Handlers) {
904 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
905 HI.Handler->markFunctionEnd();
908 // Print out jump tables referenced by the function.
911 // Emit post-function debug and/or EH information.
912 for (const HandlerInfo &HI : Handlers) {
913 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
914 HI.Handler->endFunction(MF);
918 OutStreamer.AddBlankLine();
921 /// \brief Compute the number of Global Variables that uses a Constant.
922 static unsigned getNumGlobalVariableUses(const Constant *C) {
926 if (isa<GlobalVariable>(C))
929 unsigned NumUses = 0;
930 for (auto *CU : C->users())
931 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
936 /// \brief Only consider global GOT equivalents if at least one user is a
937 /// cstexpr inside an initializer of another global variables. Also, don't
938 /// handle cstexpr inside instructions. During global variable emission,
939 /// candidates are skipped and are emitted later in case at least one cstexpr
940 /// isn't replaced by a PC relative GOT entry access.
941 static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
942 unsigned &NumGOTEquivUsers) {
943 // Global GOT equivalents are unnamed private globals with a constant
944 // pointer initializer to another global symbol. They must point to a
945 // GlobalVariable or Function, i.e., as GlobalValue.
946 if (!GV->hasUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() ||
947 !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0)))
950 // To be a got equivalent, at least one of its users need to be a constant
951 // expression used by another global variable.
952 for (auto *U : GV->users())
953 NumGOTEquivUsers += getNumGlobalVariableUses(cast<Constant>(U));
955 return NumGOTEquivUsers > 0;
958 /// \brief Unnamed constant global variables solely contaning a pointer to
959 /// another globals variable is equivalent to a GOT table entry; it contains the
960 /// the address of another symbol. Optimize it and replace accesses to these
961 /// "GOT equivalents" by using the GOT entry for the final global instead.
962 /// Compute GOT equivalent candidates among all global variables to avoid
963 /// emitting them if possible later on, after it use is replaced by a GOT entry
965 void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
966 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
969 for (const auto &G : M.globals()) {
970 unsigned NumGOTEquivUsers = 0;
971 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
974 const MCSymbol *GOTEquivSym = getSymbol(&G);
975 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
979 /// \brief Constant expressions using GOT equivalent globals may not be eligible
980 /// for PC relative GOT entry conversion, in such cases we need to emit such
981 /// globals we previously omitted in EmitGlobalVariable.
982 void AsmPrinter::emitGlobalGOTEquivs() {
983 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
986 while (!GlobalGOTEquivs.empty()) {
987 DenseMap<const MCSymbol *, GOTEquivUsePair>::iterator I =
988 GlobalGOTEquivs.begin();
989 const MCSymbol *S = I->first;
990 const GlobalVariable *GV = I->second.first;
991 GlobalGOTEquivs.erase(S);
992 EmitGlobalVariable(GV);
996 bool AsmPrinter::doFinalization(Module &M) {
997 // Gather all GOT equivalent globals in the module. We really need two
998 // passes over the globals: one to compute and another to avoid its emission
999 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1000 // where the got equivalent shows up before its use.
1001 computeGlobalGOTEquivs(M);
1003 // Emit global variables.
1004 for (const auto &G : M.globals())
1005 EmitGlobalVariable(&G);
1007 // Emit remaining GOT equivalent globals.
1008 emitGlobalGOTEquivs();
1010 // Emit visibility info for declarations
1011 for (const Function &F : M) {
1012 if (!F.isDeclaration())
1014 GlobalValue::VisibilityTypes V = F.getVisibility();
1015 if (V == GlobalValue::DefaultVisibility)
1018 MCSymbol *Name = getSymbol(&F);
1019 EmitVisibility(Name, V, false);
1022 // Emit module flags.
1023 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1024 M.getModuleFlagsMetadata(ModuleFlags);
1025 if (!ModuleFlags.empty())
1026 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
1028 // Make sure we wrote out everything we need.
1029 OutStreamer.Flush();
1031 // Finalize debug and EH information.
1032 for (const HandlerInfo &HI : Handlers) {
1033 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1034 TimePassesIsEnabled);
1035 HI.Handler->endModule();
1041 // If the target wants to know about weak references, print them all.
1042 if (MAI->getWeakRefDirective()) {
1043 // FIXME: This is not lazy, it would be nice to only print weak references
1044 // to stuff that is actually used. Note that doing so would require targets
1045 // to notice uses in operands (due to constant exprs etc). This should
1046 // happen with the MC stuff eventually.
1048 // Print out module-level global variables here.
1049 for (const auto &G : M.globals()) {
1050 if (!G.hasExternalWeakLinkage())
1052 OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1055 for (const auto &F : M) {
1056 if (!F.hasExternalWeakLinkage())
1058 OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1062 OutStreamer.AddBlankLine();
1063 for (const auto &Alias : M.aliases()) {
1064 MCSymbol *Name = getSymbol(&Alias);
1066 if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1067 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
1068 else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1069 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
1071 assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1073 EmitVisibility(Name, Alias.getVisibility());
1075 // Emit the directives as assignments aka .set:
1076 OutStreamer.EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1079 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1080 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1081 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1082 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1083 MP->finishAssembly(M, *MI, *this);
1085 // Emit llvm.ident metadata in an '.ident' directive.
1086 EmitModuleIdents(M);
1088 // Emit __morestack address if needed for indirect calls.
1089 if (MMI->usesMorestackAddr()) {
1090 const MCSection *ReadOnlySection =
1091 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
1093 OutStreamer.SwitchSection(ReadOnlySection);
1095 MCSymbol *AddrSymbol =
1096 OutContext.GetOrCreateSymbol(StringRef("__morestack_addr"));
1097 OutStreamer.EmitLabel(AddrSymbol);
1099 unsigned PtrSize = TM.getDataLayout()->getPointerSize(0);
1100 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1104 // If we don't have any trampolines, then we don't require stack memory
1105 // to be executable. Some targets have a directive to declare this.
1106 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1107 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1108 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1109 OutStreamer.SwitchSection(S);
1111 // Allow the target to emit any magic that it wants at the end of the file,
1112 // after everything else has gone out.
1113 EmitEndOfAsmFile(M);
1115 delete Mang; Mang = nullptr;
1118 OutStreamer.Finish();
1119 OutStreamer.reset();
1124 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1126 // Get the function symbol.
1127 CurrentFnSym = getSymbol(MF.getFunction());
1128 CurrentFnSymForSize = CurrentFnSym;
1129 CurrentFnBegin = nullptr;
1130 bool NeedsLocalForSize = MAI->needsLocalForSize();
1131 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
1132 NeedsLocalForSize) {
1133 CurrentFnBegin = createTempSymbol("func_begin", getFunctionNumber());
1134 if (NeedsLocalForSize)
1135 CurrentFnSymForSize = CurrentFnBegin;
1139 LI = &getAnalysis<MachineLoopInfo>();
1143 // SectionCPs - Keep track the alignment, constpool entries per Section.
1147 SmallVector<unsigned, 4> CPEs;
1148 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1152 /// EmitConstantPool - Print to the current output stream assembly
1153 /// representations of the constants in the constant pool MCP. This is
1154 /// used to print out constants which have been "spilled to memory" by
1155 /// the code generator.
1157 void AsmPrinter::EmitConstantPool() {
1158 const MachineConstantPool *MCP = MF->getConstantPool();
1159 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1160 if (CP.empty()) return;
1162 // Calculate sections for constant pool entries. We collect entries to go into
1163 // the same section together to reduce amount of section switch statements.
1164 SmallVector<SectionCPs, 4> CPSections;
1165 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1166 const MachineConstantPoolEntry &CPE = CP[i];
1167 unsigned Align = CPE.getAlignment();
1170 CPE.getSectionKind(TM.getDataLayout());
1172 const Constant *C = nullptr;
1173 if (!CPE.isMachineConstantPoolEntry())
1174 C = CPE.Val.ConstVal;
1176 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
1178 // The number of sections are small, just do a linear search from the
1179 // last section to the first.
1181 unsigned SecIdx = CPSections.size();
1182 while (SecIdx != 0) {
1183 if (CPSections[--SecIdx].S == S) {
1189 SecIdx = CPSections.size();
1190 CPSections.push_back(SectionCPs(S, Align));
1193 if (Align > CPSections[SecIdx].Alignment)
1194 CPSections[SecIdx].Alignment = Align;
1195 CPSections[SecIdx].CPEs.push_back(i);
1198 // Now print stuff into the calculated sections.
1199 const MCSection *CurSection = nullptr;
1200 unsigned Offset = 0;
1201 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1202 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1203 unsigned CPI = CPSections[i].CPEs[j];
1204 MCSymbol *Sym = GetCPISymbol(CPI);
1205 if (!Sym->isUndefined())
1208 if (CurSection != CPSections[i].S) {
1209 OutStreamer.SwitchSection(CPSections[i].S);
1210 EmitAlignment(Log2_32(CPSections[i].Alignment));
1211 CurSection = CPSections[i].S;
1215 MachineConstantPoolEntry CPE = CP[CPI];
1217 // Emit inter-object padding for alignment.
1218 unsigned AlignMask = CPE.getAlignment() - 1;
1219 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1220 OutStreamer.EmitZeros(NewOffset - Offset);
1222 Type *Ty = CPE.getType();
1223 Offset = NewOffset +
1224 TM.getDataLayout()->getTypeAllocSize(Ty);
1226 OutStreamer.EmitLabel(Sym);
1227 if (CPE.isMachineConstantPoolEntry())
1228 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1230 EmitGlobalConstant(CPE.Val.ConstVal);
1235 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1236 /// by the current function to the current output stream.
1238 void AsmPrinter::EmitJumpTableInfo() {
1239 const DataLayout *DL = MF->getTarget().getDataLayout();
1240 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1242 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1243 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1244 if (JT.empty()) return;
1246 // Pick the directive to use to print the jump table entries, and switch to
1247 // the appropriate section.
1248 const Function *F = MF->getFunction();
1249 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1250 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1251 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1253 if (JTInDiffSection) {
1254 // Drop it in the readonly section.
1255 const MCSection *ReadOnlySection =
1256 TLOF.getSectionForJumpTable(*F, *Mang, TM);
1257 OutStreamer.SwitchSection(ReadOnlySection);
1260 EmitAlignment(Log2_32(
1261 MJTI->getEntryAlignment(*TM.getDataLayout())));
1263 // Jump tables in code sections are marked with a data_region directive
1264 // where that's supported.
1265 if (!JTInDiffSection)
1266 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1268 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1269 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1271 // If this jump table was deleted, ignore it.
1272 if (JTBBs.empty()) continue;
1274 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1275 /// emit a .set directive for each unique entry.
1276 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1277 MAI->doesSetDirectiveSuppressesReloc()) {
1278 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1279 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1280 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1281 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1282 const MachineBasicBlock *MBB = JTBBs[ii];
1283 if (!EmittedSets.insert(MBB).second)
1286 // .set LJTSet, LBB32-base
1288 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1289 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1290 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1294 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1295 // before each jump table. The first label is never referenced, but tells
1296 // the assembler and linker the extents of the jump table object. The
1297 // second label is actually referenced by the code.
1298 if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1299 // FIXME: This doesn't have to have any specific name, just any randomly
1300 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1301 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1303 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1305 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1306 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1308 if (!JTInDiffSection)
1309 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1312 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1314 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1315 const MachineBasicBlock *MBB,
1316 unsigned UID) const {
1317 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1318 const MCExpr *Value = nullptr;
1319 switch (MJTI->getEntryKind()) {
1320 case MachineJumpTableInfo::EK_Inline:
1321 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1322 case MachineJumpTableInfo::EK_Custom32:
1323 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1324 MJTI, MBB, UID, OutContext);
1326 case MachineJumpTableInfo::EK_BlockAddress:
1327 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1329 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1331 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1332 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1333 // with a relocation as gp-relative, e.g.:
1335 MCSymbol *MBBSym = MBB->getSymbol();
1336 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1340 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1341 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1342 // with a relocation as gp-relative, e.g.:
1344 MCSymbol *MBBSym = MBB->getSymbol();
1345 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1349 case MachineJumpTableInfo::EK_LabelDifference32: {
1350 // Each entry is the address of the block minus the address of the jump
1351 // table. This is used for PIC jump tables where gprel32 is not supported.
1353 // .word LBB123 - LJTI1_2
1354 // If the .set directive avoids relocations, this is emitted as:
1355 // .set L4_5_set_123, LBB123 - LJTI1_2
1356 // .word L4_5_set_123
1357 if (MAI->doesSetDirectiveSuppressesReloc()) {
1358 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1362 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1363 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1364 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1365 Value = MCBinaryExpr::CreateSub(Value, Base, OutContext);
1370 assert(Value && "Unknown entry kind!");
1372 unsigned EntrySize =
1373 MJTI->getEntrySize(*TM.getDataLayout());
1374 OutStreamer.EmitValue(Value, EntrySize);
1378 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1379 /// special global used by LLVM. If so, emit it and return true, otherwise
1380 /// do nothing and return false.
1381 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1382 if (GV->getName() == "llvm.used") {
1383 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1384 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1388 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1389 if (StringRef(GV->getSection()) == "llvm.metadata" ||
1390 GV->hasAvailableExternallyLinkage())
1393 if (!GV->hasAppendingLinkage()) return false;
1395 assert(GV->hasInitializer() && "Not a special LLVM global!");
1397 if (GV->getName() == "llvm.global_ctors") {
1398 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1400 if (TM.getRelocationModel() == Reloc::Static &&
1401 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1402 StringRef Sym(".constructors_used");
1403 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1409 if (GV->getName() == "llvm.global_dtors") {
1410 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1412 if (TM.getRelocationModel() == Reloc::Static &&
1413 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1414 StringRef Sym(".destructors_used");
1415 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1424 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1425 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1426 /// is true, as being used with this directive.
1427 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1428 // Should be an array of 'i8*'.
1429 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1430 const GlobalValue *GV =
1431 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1433 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1439 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1441 llvm::Constant *Func;
1442 llvm::GlobalValue *ComdatKey;
1446 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1448 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1449 // Should be an array of '{ int, void ()* }' structs. The first value is the
1451 if (!isa<ConstantArray>(List)) return;
1453 // Sanity check the structors list.
1454 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1455 if (!InitList) return; // Not an array!
1456 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1457 // FIXME: Only allow the 3-field form in LLVM 4.0.
1458 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1459 return; // Not an array of two or three elements!
1460 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1461 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1462 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1463 return; // Not (int, ptr, ptr).
1465 // Gather the structors in a form that's convenient for sorting by priority.
1466 SmallVector<Structor, 8> Structors;
1467 for (Value *O : InitList->operands()) {
1468 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1469 if (!CS) continue; // Malformed.
1470 if (CS->getOperand(1)->isNullValue())
1471 break; // Found a null terminator, skip the rest.
1472 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1473 if (!Priority) continue; // Malformed.
1474 Structors.push_back(Structor());
1475 Structor &S = Structors.back();
1476 S.Priority = Priority->getLimitedValue(65535);
1477 S.Func = CS->getOperand(1);
1478 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1479 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1482 // Emit the function pointers in the target-specific order
1483 const DataLayout *DL = TM.getDataLayout();
1484 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1485 std::stable_sort(Structors.begin(), Structors.end(),
1486 [](const Structor &L,
1487 const Structor &R) { return L.Priority < R.Priority; });
1488 for (Structor &S : Structors) {
1489 const TargetLoweringObjectFile &Obj = getObjFileLowering();
1490 const MCSymbol *KeySym = nullptr;
1491 if (GlobalValue *GV = S.ComdatKey) {
1492 if (GV->hasAvailableExternallyLinkage())
1493 // If the associated variable is available_externally, some other TU
1494 // will provide its dynamic initializer.
1497 KeySym = getSymbol(GV);
1499 const MCSection *OutputSection =
1500 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1501 : Obj.getStaticDtorSection(S.Priority, KeySym));
1502 OutStreamer.SwitchSection(OutputSection);
1503 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1504 EmitAlignment(Align);
1505 EmitXXStructor(S.Func);
1509 void AsmPrinter::EmitModuleIdents(Module &M) {
1510 if (!MAI->hasIdentDirective())
1513 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1514 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1515 const MDNode *N = NMD->getOperand(i);
1516 assert(N->getNumOperands() == 1 &&
1517 "llvm.ident metadata entry can have only one operand");
1518 const MDString *S = cast<MDString>(N->getOperand(0));
1519 OutStreamer.EmitIdent(S->getString());
1524 //===--------------------------------------------------------------------===//
1525 // Emission and print routines
1528 /// EmitInt8 - Emit a byte directive and value.
1530 void AsmPrinter::EmitInt8(int Value) const {
1531 OutStreamer.EmitIntValue(Value, 1);
1534 /// EmitInt16 - Emit a short directive and value.
1536 void AsmPrinter::EmitInt16(int Value) const {
1537 OutStreamer.EmitIntValue(Value, 2);
1540 /// EmitInt32 - Emit a long directive and value.
1542 void AsmPrinter::EmitInt32(int Value) const {
1543 OutStreamer.EmitIntValue(Value, 4);
1546 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1547 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1548 /// .set if it avoids relocations.
1549 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1550 unsigned Size) const {
1551 // Get the Hi-Lo expression.
1552 const MCExpr *Diff =
1553 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1554 MCSymbolRefExpr::Create(Lo, OutContext),
1557 if (!MAI->doesSetDirectiveSuppressesReloc()) {
1558 OutStreamer.EmitValue(Diff, Size);
1562 // Otherwise, emit with .set (aka assignment).
1563 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1564 OutStreamer.EmitAssignment(SetLabel, Diff);
1565 OutStreamer.EmitSymbolValue(SetLabel, Size);
1568 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1569 /// where the size in bytes of the directive is specified by Size and Label
1570 /// specifies the label. This implicitly uses .set if it is available.
1571 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1573 bool IsSectionRelative) const {
1574 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1575 OutStreamer.EmitCOFFSecRel32(Label);
1579 // Emit Label+Offset (or just Label if Offset is zero)
1580 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1582 Expr = MCBinaryExpr::CreateAdd(
1583 Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1585 OutStreamer.EmitValue(Expr, Size);
1588 //===----------------------------------------------------------------------===//
1590 // EmitAlignment - Emit an alignment directive to the specified power of
1591 // two boundary. For example, if you pass in 3 here, you will get an 8
1592 // byte alignment. If a global value is specified, and if that global has
1593 // an explicit alignment requested, it will override the alignment request
1594 // if required for correctness.
1596 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1598 NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(),
1601 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1604 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1605 "undefined behavior");
1606 if (getCurrentSection()->getKind().isText())
1607 OutStreamer.EmitCodeAlignment(1u << NumBits);
1609 OutStreamer.EmitValueToAlignment(1u << NumBits);
1612 //===----------------------------------------------------------------------===//
1613 // Constant emission.
1614 //===----------------------------------------------------------------------===//
1616 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1617 MCContext &Ctx = OutContext;
1619 if (CV->isNullValue() || isa<UndefValue>(CV))
1620 return MCConstantExpr::Create(0, Ctx);
1622 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1623 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1625 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1626 return MCSymbolRefExpr::Create(getSymbol(GV), Ctx);
1628 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1629 return MCSymbolRefExpr::Create(GetBlockAddressSymbol(BA), Ctx);
1631 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1633 llvm_unreachable("Unknown constant value to lower!");
1636 if (const MCExpr *RelocExpr
1637 = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1640 switch (CE->getOpcode()) {
1642 // If the code isn't optimized, there may be outstanding folding
1643 // opportunities. Attempt to fold the expression using DataLayout as a
1644 // last resort before giving up.
1645 if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
1647 return lowerConstant(C);
1649 // Otherwise report the problem to the user.
1652 raw_string_ostream OS(S);
1653 OS << "Unsupported expression in static initializer: ";
1654 CE->printAsOperand(OS, /*PrintType=*/false,
1655 !MF ? nullptr : MF->getFunction()->getParent());
1656 report_fatal_error(OS.str());
1658 case Instruction::GetElementPtr: {
1659 const DataLayout &DL = *TM.getDataLayout();
1661 // Generate a symbolic expression for the byte address
1662 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1663 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1665 const MCExpr *Base = lowerConstant(CE->getOperand(0));
1669 int64_t Offset = OffsetAI.getSExtValue();
1670 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1674 case Instruction::Trunc:
1675 // We emit the value and depend on the assembler to truncate the generated
1676 // expression properly. This is important for differences between
1677 // blockaddress labels. Since the two labels are in the same function, it
1678 // is reasonable to treat their delta as a 32-bit value.
1680 case Instruction::BitCast:
1681 return lowerConstant(CE->getOperand(0));
1683 case Instruction::IntToPtr: {
1684 const DataLayout &DL = *TM.getDataLayout();
1686 // Handle casts to pointers by changing them into casts to the appropriate
1687 // integer type. This promotes constant folding and simplifies this code.
1688 Constant *Op = CE->getOperand(0);
1689 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1691 return lowerConstant(Op);
1694 case Instruction::PtrToInt: {
1695 const DataLayout &DL = *TM.getDataLayout();
1697 // Support only foldable casts to/from pointers that can be eliminated by
1698 // changing the pointer to the appropriately sized integer type.
1699 Constant *Op = CE->getOperand(0);
1700 Type *Ty = CE->getType();
1702 const MCExpr *OpExpr = lowerConstant(Op);
1704 // We can emit the pointer value into this slot if the slot is an
1705 // integer slot equal to the size of the pointer.
1706 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1709 // Otherwise the pointer is smaller than the resultant integer, mask off
1710 // the high bits so we are sure to get a proper truncation if the input is
1712 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1713 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1714 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1717 // The MC library also has a right-shift operator, but it isn't consistently
1718 // signed or unsigned between different targets.
1719 case Instruction::Add:
1720 case Instruction::Sub:
1721 case Instruction::Mul:
1722 case Instruction::SDiv:
1723 case Instruction::SRem:
1724 case Instruction::Shl:
1725 case Instruction::And:
1726 case Instruction::Or:
1727 case Instruction::Xor: {
1728 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1729 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1730 switch (CE->getOpcode()) {
1731 default: llvm_unreachable("Unknown binary operator constant cast expr");
1732 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1733 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1734 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1735 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1736 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1737 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1738 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1739 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1740 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1746 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP,
1747 const Constant *BaseCV = nullptr,
1748 uint64_t Offset = 0);
1750 /// isRepeatedByteSequence - Determine whether the given value is
1751 /// composed of a repeated sequence of identical bytes and return the
1752 /// byte value. If it is not a repeated sequence, return -1.
1753 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1754 StringRef Data = V->getRawDataValues();
1755 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1757 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1758 if (Data[i] != C) return -1;
1759 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1763 /// isRepeatedByteSequence - Determine whether the given value is
1764 /// composed of a repeated sequence of identical bytes and return the
1765 /// byte value. If it is not a repeated sequence, return -1.
1766 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1768 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1769 if (CI->getBitWidth() > 64) return -1;
1772 TM.getDataLayout()->getTypeAllocSize(V->getType());
1773 uint64_t Value = CI->getZExtValue();
1775 // Make sure the constant is at least 8 bits long and has a power
1776 // of 2 bit width. This guarantees the constant bit width is
1777 // always a multiple of 8 bits, avoiding issues with padding out
1778 // to Size and other such corner cases.
1779 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1781 uint8_t Byte = static_cast<uint8_t>(Value);
1783 for (unsigned i = 1; i < Size; ++i) {
1785 if (static_cast<uint8_t>(Value) != Byte) return -1;
1789 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1790 // Make sure all array elements are sequences of the same repeated
1792 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1793 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1794 if (Byte == -1) return -1;
1796 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1797 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1798 if (ThisByte == -1) return -1;
1799 if (Byte != ThisByte) return -1;
1804 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1805 return isRepeatedByteSequence(CDS);
1810 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1813 // See if we can aggregate this into a .fill, if so, emit it as such.
1814 int Value = isRepeatedByteSequence(CDS, AP.TM);
1817 AP.TM.getDataLayout()->getTypeAllocSize(
1819 // Don't emit a 1-byte object as a .fill.
1821 return AP.OutStreamer.EmitFill(Bytes, Value);
1824 // If this can be emitted with .ascii/.asciz, emit it as such.
1825 if (CDS->isString())
1826 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1828 // Otherwise, emit the values in successive locations.
1829 unsigned ElementByteSize = CDS->getElementByteSize();
1830 if (isa<IntegerType>(CDS->getElementType())) {
1831 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1833 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1834 CDS->getElementAsInteger(i));
1835 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1838 } else if (ElementByteSize == 4) {
1839 // FP Constants are printed as integer constants to avoid losing
1841 assert(CDS->getElementType()->isFloatTy());
1842 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1848 F = CDS->getElementAsFloat(i);
1850 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1851 AP.OutStreamer.EmitIntValue(I, 4);
1854 assert(CDS->getElementType()->isDoubleTy());
1855 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1861 F = CDS->getElementAsDouble(i);
1863 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1864 AP.OutStreamer.EmitIntValue(I, 8);
1868 const DataLayout &DL = *AP.TM.getDataLayout();
1869 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1870 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1871 CDS->getNumElements();
1872 if (unsigned Padding = Size - EmittedSize)
1873 AP.OutStreamer.EmitZeros(Padding);
1877 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP,
1878 const Constant *BaseCV, uint64_t Offset) {
1879 // See if we can aggregate some values. Make sure it can be
1880 // represented as a series of bytes of the constant value.
1881 int Value = isRepeatedByteSequence(CA, AP.TM);
1882 const DataLayout &DL = *AP.TM.getDataLayout();
1885 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1886 AP.OutStreamer.EmitFill(Bytes, Value);
1889 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1890 emitGlobalConstantImpl(CA->getOperand(i), AP, BaseCV, Offset);
1891 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1896 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1897 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1898 emitGlobalConstantImpl(CV->getOperand(i), AP);
1900 const DataLayout &DL = *AP.TM.getDataLayout();
1901 unsigned Size = DL.getTypeAllocSize(CV->getType());
1902 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1903 CV->getType()->getNumElements();
1904 if (unsigned Padding = Size - EmittedSize)
1905 AP.OutStreamer.EmitZeros(Padding);
1908 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP,
1909 const Constant *BaseCV, uint64_t Offset) {
1910 // Print the fields in successive locations. Pad to align if needed!
1911 const DataLayout *DL = AP.TM.getDataLayout();
1912 unsigned Size = DL->getTypeAllocSize(CS->getType());
1913 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1914 uint64_t SizeSoFar = 0;
1915 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1916 const Constant *Field = CS->getOperand(i);
1918 // Print the actual field value.
1919 emitGlobalConstantImpl(Field, AP, BaseCV, Offset+SizeSoFar);
1921 // Check if padding is needed and insert one or more 0s.
1922 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1923 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1924 - Layout->getElementOffset(i)) - FieldSize;
1925 SizeSoFar += FieldSize + PadSize;
1927 // Insert padding - this may include padding to increase the size of the
1928 // current field up to the ABI size (if the struct is not packed) as well
1929 // as padding to ensure that the next field starts at the right offset.
1930 AP.OutStreamer.EmitZeros(PadSize);
1932 assert(SizeSoFar == Layout->getSizeInBytes() &&
1933 "Layout of constant struct may be incorrect!");
1936 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1937 APInt API = CFP->getValueAPF().bitcastToAPInt();
1939 // First print a comment with what we think the original floating-point value
1940 // should have been.
1941 if (AP.isVerbose()) {
1942 SmallString<8> StrVal;
1943 CFP->getValueAPF().toString(StrVal);
1946 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1948 AP.OutStreamer.GetCommentOS() << "Printing <null> Type";
1949 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1952 // Now iterate through the APInt chunks, emitting them in endian-correct
1953 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1955 unsigned NumBytes = API.getBitWidth() / 8;
1956 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1957 const uint64_t *p = API.getRawData();
1959 // PPC's long double has odd notions of endianness compared to how LLVM
1960 // handles it: p[0] goes first for *big* endian on PPC.
1961 if (AP.TM.getDataLayout()->isBigEndian() &&
1962 !CFP->getType()->isPPC_FP128Ty()) {
1963 int Chunk = API.getNumWords() - 1;
1966 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1968 for (; Chunk >= 0; --Chunk)
1969 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1972 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1973 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1976 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1979 // Emit the tail padding for the long double.
1980 const DataLayout &DL = *AP.TM.getDataLayout();
1981 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1982 DL.getTypeStoreSize(CFP->getType()));
1985 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1986 const DataLayout *DL = AP.TM.getDataLayout();
1987 unsigned BitWidth = CI->getBitWidth();
1989 // Copy the value as we may massage the layout for constants whose bit width
1990 // is not a multiple of 64-bits.
1991 APInt Realigned(CI->getValue());
1992 uint64_t ExtraBits = 0;
1993 unsigned ExtraBitsSize = BitWidth & 63;
1995 if (ExtraBitsSize) {
1996 // The bit width of the data is not a multiple of 64-bits.
1997 // The extra bits are expected to be at the end of the chunk of the memory.
1999 // * Nothing to be done, just record the extra bits to emit.
2001 // * Record the extra bits to emit.
2002 // * Realign the raw data to emit the chunks of 64-bits.
2003 if (DL->isBigEndian()) {
2004 // Basically the structure of the raw data is a chunk of 64-bits cells:
2005 // 0 1 BitWidth / 64
2006 // [chunk1][chunk2] ... [chunkN].
2007 // The most significant chunk is chunkN and it should be emitted first.
2008 // However, due to the alignment issue chunkN contains useless bits.
2009 // Realign the chunks so that they contain only useless information:
2010 // ExtraBits 0 1 (BitWidth / 64) - 1
2011 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2012 ExtraBits = Realigned.getRawData()[0] &
2013 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2014 Realigned = Realigned.lshr(ExtraBitsSize);
2016 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2019 // We don't expect assemblers to support integer data directives
2020 // for more than 64 bits, so we emit the data in at most 64-bit
2021 // quantities at a time.
2022 const uint64_t *RawData = Realigned.getRawData();
2023 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2024 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
2025 AP.OutStreamer.EmitIntValue(Val, 8);
2028 if (ExtraBitsSize) {
2029 // Emit the extra bits after the 64-bits chunks.
2031 // Emit a directive that fills the expected size.
2032 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(
2034 Size -= (BitWidth / 64) * 8;
2035 assert(Size && Size * 8 >= ExtraBitsSize &&
2036 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2037 == ExtraBits && "Directive too small for extra bits.");
2038 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
2042 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2043 /// equivalent global, by a target specific GOT pc relative access to the
2045 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2046 const Constant *BaseCst,
2048 // The global @foo below illustrates a global that uses a got equivalent.
2050 // @bar = global i32 42
2051 // @gotequiv = private unnamed_addr constant i32* @bar
2052 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2053 // i64 ptrtoint (i32* @foo to i64))
2056 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2057 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2060 // foo = cstexpr, where
2061 // cstexpr := <gotequiv> - "." + <cst>
2062 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2064 // After canonicalization by EvaluateAsRelocatable `ME` turns into:
2066 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2067 // gotpcrelcst := <offset from @foo base> + <cst>
2070 if (!(*ME)->EvaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2073 const MCSymbol *GOTEquivSym = &MV.getSymA()->getSymbol();
2074 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2077 const GlobalValue *BaseGV = dyn_cast<GlobalValue>(BaseCst);
2081 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2082 if (BaseSym != &MV.getSymB()->getSymbol())
2085 // Make sure to match:
2087 // gotpcrelcst := <offset from @foo base> + <cst>
2089 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2090 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2091 // if the target knows how to encode it.
2093 int64_t GOTPCRelCst = Offset + MV.getConstant();
2094 if (GOTPCRelCst < 0)
2096 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2099 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2106 // .long gotequiv - "." + <cst>
2108 // is replaced by the target specific equivalent to:
2113 // .long bar@GOTPCREL+<gotpcrelcst>
2115 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2116 const GlobalVariable *GV = Result.first;
2117 unsigned NumUses = Result.second;
2118 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2119 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2120 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2121 FinalSym, MV, Offset, AP.MMI, AP.OutStreamer);
2123 // Update GOT equivalent usage information
2126 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2128 AP.GlobalGOTEquivs.erase(GOTEquivSym);
2131 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP,
2132 const Constant *BaseCV, uint64_t Offset) {
2133 const DataLayout *DL = AP.TM.getDataLayout();
2134 uint64_t Size = DL->getTypeAllocSize(CV->getType());
2136 // Globals with sub-elements such as combinations of arrays and structs
2137 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2138 // constant symbol base and the current position with BaseCV and Offset.
2139 if (!BaseCV && CV->hasOneUse())
2140 BaseCV = dyn_cast<Constant>(CV->user_back());
2142 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2143 return AP.OutStreamer.EmitZeros(Size);
2145 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2152 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
2153 CI->getZExtValue());
2154 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
2157 emitGlobalConstantLargeInt(CI, AP);
2162 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2163 return emitGlobalConstantFP(CFP, AP);
2165 if (isa<ConstantPointerNull>(CV)) {
2166 AP.OutStreamer.EmitIntValue(0, Size);
2170 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2171 return emitGlobalConstantDataSequential(CDS, AP);
2173 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2174 return emitGlobalConstantArray(CVA, AP, BaseCV, Offset);
2176 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2177 return emitGlobalConstantStruct(CVS, AP, BaseCV, Offset);
2179 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2180 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2182 if (CE->getOpcode() == Instruction::BitCast)
2183 return emitGlobalConstantImpl(CE->getOperand(0), AP);
2186 // If the constant expression's size is greater than 64-bits, then we have
2187 // to emit the value in chunks. Try to constant fold the value and emit it
2189 Constant *New = ConstantFoldConstantExpression(CE, *DL);
2190 if (New && New != CE)
2191 return emitGlobalConstantImpl(New, AP);
2195 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2196 return emitGlobalConstantVector(V, AP);
2198 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2199 // thread the streamer with EmitValue.
2200 const MCExpr *ME = AP.lowerConstant(CV);
2202 // Since lowerConstant already folded and got rid of all IR pointer and
2203 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2205 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2206 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2208 AP.OutStreamer.EmitValue(ME, Size);
2211 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2212 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2214 TM.getDataLayout()->getTypeAllocSize(CV->getType());
2216 emitGlobalConstantImpl(CV, *this);
2217 else if (MAI->hasSubsectionsViaSymbols()) {
2218 // If the global has zero size, emit a single byte so that two labels don't
2219 // look like they are at the same location.
2220 OutStreamer.EmitIntValue(0, 1);
2224 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2225 // Target doesn't support this yet!
2226 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2229 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2231 OS << '+' << Offset;
2232 else if (Offset < 0)
2236 //===----------------------------------------------------------------------===//
2237 // Symbol Lowering Routines.
2238 //===----------------------------------------------------------------------===//
2240 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2241 /// temporary label with the specified stem and unique ID.
2242 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name, unsigned ID) const {
2243 const DataLayout *DL = TM.getDataLayout();
2244 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2248 /// GetTempSymbol - Return an assembler temporary label with the specified
2250 MCSymbol *AsmPrinter::GetTempSymbol(const Twine &Name) const {
2251 const DataLayout *DL = TM.getDataLayout();
2252 return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2256 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name, unsigned ID) const {
2257 return OutContext.createTempSymbol(Name + Twine(ID));
2260 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2261 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2264 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2265 return MMI->getAddrLabelSymbol(BB);
2268 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2269 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2270 const DataLayout *DL = TM.getDataLayout();
2271 return OutContext.GetOrCreateSymbol
2272 (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2273 + "_" + Twine(CPID));
2276 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2277 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2278 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2281 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2282 /// FIXME: privatize to AsmPrinter.
2283 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2284 const DataLayout *DL = TM.getDataLayout();
2285 return OutContext.GetOrCreateSymbol
2286 (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2287 Twine(UID) + "_set_" + Twine(MBBID));
2290 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2291 StringRef Suffix) const {
2292 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2296 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2298 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2299 SmallString<60> NameStr;
2300 Mang->getNameWithPrefix(NameStr, Sym);
2301 return OutContext.GetOrCreateSymbol(NameStr.str());
2306 /// PrintParentLoopComment - Print comments about parent loops of this one.
2307 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2308 unsigned FunctionNumber) {
2310 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2311 OS.indent(Loop->getLoopDepth()*2)
2312 << "Parent Loop BB" << FunctionNumber << "_"
2313 << Loop->getHeader()->getNumber()
2314 << " Depth=" << Loop->getLoopDepth() << '\n';
2318 /// PrintChildLoopComment - Print comments about child loops within
2319 /// the loop for this basic block, with nesting.
2320 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2321 unsigned FunctionNumber) {
2322 // Add child loop information
2323 for (const MachineLoop *CL : *Loop) {
2324 OS.indent(CL->getLoopDepth()*2)
2325 << "Child Loop BB" << FunctionNumber << "_"
2326 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2328 PrintChildLoopComment(OS, CL, FunctionNumber);
2332 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2333 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2334 const MachineLoopInfo *LI,
2335 const AsmPrinter &AP) {
2336 // Add loop depth information
2337 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2340 MachineBasicBlock *Header = Loop->getHeader();
2341 assert(Header && "No header for loop");
2343 // If this block is not a loop header, just print out what is the loop header
2345 if (Header != &MBB) {
2346 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2347 Twine(AP.getFunctionNumber())+"_" +
2348 Twine(Loop->getHeader()->getNumber())+
2349 " Depth="+Twine(Loop->getLoopDepth()));
2353 // Otherwise, it is a loop header. Print out information about child and
2355 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2357 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2360 OS.indent(Loop->getLoopDepth()*2-2);
2365 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2367 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2371 /// EmitBasicBlockStart - This method prints the label for the specified
2372 /// MachineBasicBlock, an alignment (if present) and a comment describing
2373 /// it if appropriate.
2374 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2375 // Emit an alignment directive for this block, if needed.
2376 if (unsigned Align = MBB.getAlignment())
2377 EmitAlignment(Align);
2379 // If the block has its address taken, emit any labels that were used to
2380 // reference the block. It is possible that there is more than one label
2381 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2382 // the references were generated.
2383 if (MBB.hasAddressTaken()) {
2384 const BasicBlock *BB = MBB.getBasicBlock();
2386 OutStreamer.AddComment("Block address taken");
2388 std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
2389 for (auto *Sym : Symbols)
2390 OutStreamer.EmitLabel(Sym);
2393 // Print some verbose block comments.
2395 if (const BasicBlock *BB = MBB.getBasicBlock())
2397 OutStreamer.AddComment("%" + BB->getName());
2398 emitBasicBlockLoopComments(MBB, LI, *this);
2401 // Print the main label for the block.
2402 if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
2404 // NOTE: Want this comment at start of line, don't emit with AddComment.
2405 OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2408 OutStreamer.EmitLabel(MBB.getSymbol());
2412 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2413 bool IsDefinition) const {
2414 MCSymbolAttr Attr = MCSA_Invalid;
2416 switch (Visibility) {
2418 case GlobalValue::HiddenVisibility:
2420 Attr = MAI->getHiddenVisibilityAttr();
2422 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2424 case GlobalValue::ProtectedVisibility:
2425 Attr = MAI->getProtectedVisibilityAttr();
2429 if (Attr != MCSA_Invalid)
2430 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2433 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2434 /// exactly one predecessor and the control transfer mechanism between
2435 /// the predecessor and this block is a fall-through.
2437 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2438 // If this is a landing pad, it isn't a fall through. If it has no preds,
2439 // then nothing falls through to it.
2440 if (MBB->isLandingPad() || MBB->pred_empty())
2443 // If there isn't exactly one predecessor, it can't be a fall through.
2444 if (MBB->pred_size() > 1)
2447 // The predecessor has to be immediately before this block.
2448 MachineBasicBlock *Pred = *MBB->pred_begin();
2449 if (!Pred->isLayoutSuccessor(MBB))
2452 // If the block is completely empty, then it definitely does fall through.
2456 // Check the terminators in the previous blocks
2457 for (const auto &MI : Pred->terminators()) {
2458 // If it is not a simple branch, we are in a table somewhere.
2459 if (!MI.isBranch() || MI.isIndirectBranch())
2462 // If we are the operands of one of the branches, this is not a fall
2463 // through. Note that targets with delay slots will usually bundle
2464 // terminators with the delay slot instruction.
2465 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2468 if (OP->isMBB() && OP->getMBB() == MBB)
2478 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2479 if (!S.usesMetadata())
2482 assert(!S.useStatepoints() && "statepoints do not currently support custom"
2483 " stackmap formats, please see the documentation for a description of"
2484 " the default format. If you really need a custom serialized format,"
2485 " please file a bug");
2487 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2488 gcp_map_type::iterator GCPI = GCMap.find(&S);
2489 if (GCPI != GCMap.end())
2490 return GCPI->second.get();
2492 const char *Name = S.getName().c_str();
2494 for (GCMetadataPrinterRegistry::iterator
2495 I = GCMetadataPrinterRegistry::begin(),
2496 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2497 if (strcmp(Name, I->getName()) == 0) {
2498 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2500 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2501 return IterBool.first->second.get();
2504 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2507 /// Pin vtable to this file.
2508 AsmPrinterHandler::~AsmPrinterHandler() {}
2510 void AsmPrinterHandler::markFunctionEnd() {}