LLVM 23.0.0git
AsmPrinter.cpp
Go to the documentation of this file.
1//===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AsmPrinter class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "CodeViewDebug.h"
15#include "DwarfDebug.h"
16#include "DwarfException.h"
17#include "PseudoProbePrinter.h"
18#include "WasmException.h"
19#include "WinCFGuard.h"
20#include "WinException.h"
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/StringRef.h"
32#include "llvm/ADT/Twine.h"
66#include "llvm/Config/config.h"
67#include "llvm/IR/BasicBlock.h"
68#include "llvm/IR/Comdat.h"
69#include "llvm/IR/Constant.h"
70#include "llvm/IR/Constants.h"
71#include "llvm/IR/DataLayout.h"
75#include "llvm/IR/Function.h"
76#include "llvm/IR/GCStrategy.h"
77#include "llvm/IR/GlobalAlias.h"
78#include "llvm/IR/GlobalIFunc.h"
80#include "llvm/IR/GlobalValue.h"
82#include "llvm/IR/Instruction.h"
85#include "llvm/IR/Mangler.h"
86#include "llvm/IR/Metadata.h"
87#include "llvm/IR/Module.h"
88#include "llvm/IR/Operator.h"
89#include "llvm/IR/PseudoProbe.h"
90#include "llvm/IR/Type.h"
91#include "llvm/IR/Value.h"
92#include "llvm/IR/ValueHandle.h"
93#include "llvm/MC/MCAsmInfo.h"
94#include "llvm/MC/MCContext.h"
96#include "llvm/MC/MCExpr.h"
97#include "llvm/MC/MCInst.h"
98#include "llvm/MC/MCSchedule.h"
99#include "llvm/MC/MCSection.h"
101#include "llvm/MC/MCSectionELF.h"
104#include "llvm/MC/MCStreamer.h"
106#include "llvm/MC/MCSymbol.h"
107#include "llvm/MC/MCSymbolELF.h"
109#include "llvm/MC/MCValue.h"
110#include "llvm/MC/SectionKind.h"
111#include "llvm/Object/ELFTypes.h"
112#include "llvm/Pass.h"
114#include "llvm/Support/Casting.h"
119#include "llvm/Support/Format.h"
121#include "llvm/Support/Path.h"
122#include "llvm/Support/VCSRevision.h"
129#include <algorithm>
130#include <cassert>
131#include <cinttypes>
132#include <cstdint>
133#include <iterator>
134#include <memory>
135#include <optional>
136#include <string>
137#include <utility>
138#include <vector>
139
140using namespace llvm;
141
142#define DEBUG_TYPE "asm-printer"
143
144// This is a replication of fields of object::PGOAnalysisMap::Features. It
145// should match the order of the fields so that
146// `object::PGOAnalysisMap::Features::decode(PgoAnalysisMapFeatures.getBits())`
147// succeeds.
157 "pgo-analysis-map", cl::Hidden, cl::CommaSeparated,
159 clEnumValN(PGOMapFeaturesEnum::None, "none", "Disable all options"),
161 "Function Entry Count"),
163 "Basic Block Frequency"),
164 clEnumValN(PGOMapFeaturesEnum::BrProb, "br-prob", "Branch Probability"),
165 clEnumValN(PGOMapFeaturesEnum::All, "all", "Enable all options")),
166 cl::desc(
167 "Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is "
168 "extracted from PGO related analysis."));
169
171 "pgo-analysis-map-emit-bb-sections-cfg",
172 cl::desc("Enable the post-link cfg information from the basic block "
173 "sections profile in the PGO analysis map"),
174 cl::Hidden, cl::init(false));
175
177 "basic-block-address-map-skip-bb-entries",
178 cl::desc("Skip emitting basic block entries in the SHT_LLVM_BB_ADDR_MAP "
179 "section. It's used to save binary size when BB entries are "
180 "unnecessary for some PGOAnalysisMap features."),
181 cl::Hidden, cl::init(false));
182
184 "emit-jump-table-sizes-section",
185 cl::desc("Emit a section containing jump table addresses and sizes"),
186 cl::Hidden, cl::init(false));
187
188// This isn't turned on by default, since several of the scheduling models are
189// not completely accurate, and we don't want to be misleading.
191 "asm-print-latency",
192 cl::desc("Print instruction latencies as verbose asm comments"), cl::Hidden,
193 cl::init(false));
194
196 StackUsageFile("stack-usage-file",
197 cl::desc("Output filename for stack usage information"),
198 cl::value_desc("filename"), cl::Hidden);
199
201
202STATISTIC(EmittedInsts, "Number of machine instrs printed");
203
204char AsmPrinter::ID = 0;
205
206namespace {
207class AddrLabelMapCallbackPtr final : CallbackVH {
208 AddrLabelMap *Map = nullptr;
209
210public:
211 AddrLabelMapCallbackPtr() = default;
212 AddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
213
214 void setPtr(BasicBlock *BB) {
216 }
217
218 void setMap(AddrLabelMap *map) { Map = map; }
219
220 void deleted() override;
221 void allUsesReplacedWith(Value *V2) override;
222};
223} // namespace
224
226 MCContext &Context;
227 struct AddrLabelSymEntry {
228 /// The symbols for the label.
230
231 Function *Fn; // The containing function of the BasicBlock.
232 unsigned Index; // The index in BBCallbacks for the BasicBlock.
233 };
234
235 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
236
237 /// Callbacks for the BasicBlock's that we have entries for. We use this so
238 /// we get notified if a block is deleted or RAUWd.
239 std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
240
241 /// This is a per-function list of symbols whose corresponding BasicBlock got
242 /// deleted. These symbols need to be emitted at some point in the file, so
243 /// AsmPrinter emits them after the function body.
244 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>
245 DeletedAddrLabelsNeedingEmission;
246
247public:
248 AddrLabelMap(MCContext &context) : Context(context) {}
249
251 assert(DeletedAddrLabelsNeedingEmission.empty() &&
252 "Some labels for deleted blocks never got emitted");
253 }
254
256
258 std::vector<MCSymbol *> &Result);
259
262};
263
265 assert(BB->hasAddressTaken() &&
266 "Shouldn't get label for block without address taken");
267 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
268
269 // If we already had an entry for this block, just return it.
270 if (!Entry.Symbols.empty()) {
271 assert(BB->getParent() == Entry.Fn && "Parent changed");
272 return Entry.Symbols;
273 }
274
275 // Otherwise, this is a new entry, create a new symbol for it and add an
276 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
277 BBCallbacks.emplace_back(BB);
278 BBCallbacks.back().setMap(this);
279 Entry.Index = BBCallbacks.size() - 1;
280 Entry.Fn = BB->getParent();
281 MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
282 : Context.createTempSymbol();
283 Entry.Symbols.push_back(Sym);
284 return Entry.Symbols;
285}
286
287/// If we have any deleted symbols for F, return them.
289 Function *F, std::vector<MCSymbol *> &Result) {
290 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>::iterator I =
291 DeletedAddrLabelsNeedingEmission.find(F);
292
293 // If there are no entries for the function, just return.
294 if (I == DeletedAddrLabelsNeedingEmission.end())
295 return;
296
297 // Otherwise, take the list.
298 std::swap(Result, I->second);
299 DeletedAddrLabelsNeedingEmission.erase(I);
300}
301
302//===- Address of Block Management ----------------------------------------===//
303
306 // Lazily create AddrLabelSymbols.
307 if (!AddrLabelSymbols)
308 AddrLabelSymbols = std::make_unique<AddrLabelMap>(OutContext);
309 return AddrLabelSymbols->getAddrLabelSymbolToEmit(
310 const_cast<BasicBlock *>(BB));
311}
312
314 const Function *F, std::vector<MCSymbol *> &Result) {
315 // If no blocks have had their addresses taken, we're done.
316 if (!AddrLabelSymbols)
317 return;
318 return AddrLabelSymbols->takeDeletedSymbolsForFunction(
319 const_cast<Function *>(F), Result);
320}
321
323 // If the block got deleted, there is no need for the symbol. If the symbol
324 // was already emitted, we can just forget about it, otherwise we need to
325 // queue it up for later emission when the function is output.
326 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
327 AddrLabelSymbols.erase(BB);
328 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
329 BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
330
331#if !LLVM_MEMORY_SANITIZER_BUILD
332 // BasicBlock is destroyed already, so this access is UB detectable by msan.
333 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
334 "Block/parent mismatch");
335#endif
336
337 for (MCSymbol *Sym : Entry.Symbols) {
338 if (Sym->isDefined())
339 return;
340
341 // If the block is not yet defined, we need to emit it at the end of the
342 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
343 // for the containing Function. Since the block is being deleted, its
344 // parent may already be removed, we have to get the function from 'Entry'.
345 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
346 }
347}
348
350 // Get the entry for the RAUW'd block and remove it from our map.
351 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
352 AddrLabelSymbols.erase(Old);
353 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
354
355 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
356
357 // If New is not address taken, just move our symbol over to it.
358 if (NewEntry.Symbols.empty()) {
359 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
360 NewEntry = std::move(OldEntry); // Set New's entry.
361 return;
362 }
363
364 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
365
366 // Otherwise, we need to add the old symbols to the new block's set.
367 llvm::append_range(NewEntry.Symbols, OldEntry.Symbols);
368}
369
370void AddrLabelMapCallbackPtr::deleted() {
371 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
372}
373
374void AddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
375 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
376}
377
378/// getGVAlignment - Return the alignment to use for the specified global
379/// value. This rounds up to the preferred alignment if possible and legal.
381 Align InAlign) {
382 Align Alignment;
383 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
384 Alignment = DL.getPreferredAlign(GVar);
385
386 // If InAlign is specified, round it to it.
387 if (InAlign > Alignment)
388 Alignment = InAlign;
389
390 // If the GV has a specified alignment, take it into account.
391 MaybeAlign GVAlign;
392 if (auto *GVar = dyn_cast<GlobalVariable>(GV))
393 GVAlign = GVar->getAlign();
394 else if (auto *F = dyn_cast<Function>(GV))
395 GVAlign = F->getAlign();
396 if (!GVAlign)
397 return Alignment;
398
399 assert(GVAlign && "GVAlign must be set");
400
401 // If the GVAlign is larger than NumBits, or if we are required to obey
402 // NumBits because the GV has an assigned section, obey it.
403 if (*GVAlign > Alignment || GV->hasSection())
404 Alignment = *GVAlign;
405 return Alignment;
406}
407
408AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer,
409 char &ID)
410 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
411 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
412 SM(*this) {
413 VerboseAsm = OutStreamer->isVerboseAsm();
414 DwarfUsesRelocationsAcrossSections =
415 MAI->doesDwarfUseRelocationsAcrossSections();
416 GetMMI = [this]() {
418 return MMIWP ? &MMIWP->getMMI() : nullptr;
419 };
420 GetORE = [this](MachineFunction &MF) {
422 };
423 GetMDT = [this](MachineFunction &MF) {
424 auto *MDTWrapper =
426 return MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
427 };
428 GetMLI = [this](MachineFunction &MF) {
430 return MLIWrapper ? &MLIWrapper->getLI() : nullptr;
431 };
432 BeginGCAssembly = [this](Module &M) {
434 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
435 for (const auto &I : *MI)
436 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*I))
437 MP->beginAssembly(M, *MI, *this);
438 };
439 FinishGCAssembly = [this](Module &M) {
441 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
442 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E;)
443 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(**--I))
444 MP->finishAssembly(M, *MI, *this);
445 };
446 EmitStackMaps = [this](Module &M) {
448 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
449 bool NeedsDefault = false;
450 if (MI->begin() == MI->end())
451 // No GC strategy, use the default format.
452 NeedsDefault = true;
453 else
454 for (const auto &I : *MI) {
455 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*I))
456 if (MP->emitStackMaps(SM, *this))
457 continue;
458 // The strategy doesn't have printer or doesn't emit custom stack maps.
459 // Use the default format.
460 NeedsDefault = true;
461 }
462
463 if (NeedsDefault)
464 SM.serializeToStackMapSection();
465 };
466 AssertDebugEHFinalized = [&]() {
467 assert(!DD && Handlers.size() == NumUserHandlers &&
468 "Debug/EH info didn't get finalized");
469 };
470}
471
473
475 return TM.isPositionIndependent();
476}
477
478/// getFunctionNumber - Return a unique ID for the current function.
480 return MF->getFunctionNumber();
481}
482
484 return *TM.getObjFileLowering();
485}
486
488 assert(MMI && "MMI could not be nullptr!");
489 return MMI->getModule()->getDataLayout();
490}
491
492// Do not use the cached DataLayout because some client use it without a Module
493// (dsymutil, llvm-dwarfdump).
495 return TM.getPointerSize(0); // FIXME: Default address space
496}
497
499 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
500 return MF->getSubtarget<MCSubtargetInfo>();
501}
502
506
508 if (DD) {
509 assert(OutStreamer->hasRawTextSupport() &&
510 "Expected assembly output mode.");
511 // This is NVPTX specific and it's unclear why.
512 // PR51079: If we have code without debug information we need to give up.
513 DISubprogram *MFSP = MF.getFunction().getSubprogram();
514 if (!MFSP)
515 return;
516 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
517 }
518}
519
520/// getCurrentSection() - Return the current section we are emitting to.
522 return OutStreamer->getCurrentSectionOnly();
523}
524
525/// createDwarfDebug() - Create the DwarfDebug handler.
527
539
541 MMI = GetMMI();
542 HasSplitStack = false;
543 HasNoSplitStack = false;
544 DbgInfoAvailable = !M.debug_compile_units().empty();
545 const Triple &Target = TM.getTargetTriple();
546
547 AddrLabelSymbols = nullptr;
548
549 // Initialize TargetLoweringObjectFile.
550 TM.getObjFileLowering()->Initialize(OutContext, TM);
551
552 TM.getObjFileLowering()->getModuleMetadata(M);
553
554 // On AIX, we delay emitting any section information until
555 // after emitting the .file pseudo-op. This allows additional
556 // information (such as the embedded command line) to be associated
557 // with all sections in the object file rather than a single section.
558 if (!Target.isOSBinFormatXCOFF())
559 OutStreamer->initSections(false, *TM.getMCSubtargetInfo());
560
561 // Emit the version-min deployment target directive if needed.
562 //
563 // FIXME: If we end up with a collection of these sorts of Darwin-specific
564 // or ELF-specific things, it may make sense to have a platform helper class
565 // that will work with the target helper class. For now keep it here, as the
566 // alternative is duplicated code in each of the target asm printers that
567 // use the directive, where it would need the same conditionalization
568 // anyway.
569 if (Target.isOSBinFormatMachO() && Target.isOSDarwin()) {
570 Triple TVT(M.getDarwinTargetVariantTriple());
571 OutStreamer->emitVersionForTarget(
572 Target, M.getSDKVersion(),
573 M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
574 M.getDarwinTargetVariantSDKVersion());
575 }
576
577 // Allow the target to emit any magic that it wants at the start of the file.
579
580 // Very minimal debug info. It is ignored if we emit actual debug info. If we
581 // don't, this at least helps the user find where a global came from.
582 if (MAI->hasSingleParameterDotFile()) {
583 // .file "foo.c"
584 if (MAI->isAIX()) {
585 const char VerStr[] =
586#ifdef PACKAGE_VENDOR
587 PACKAGE_VENDOR " "
588#endif
589 PACKAGE_NAME " version " PACKAGE_VERSION
590#ifdef LLVM_REVISION
591 " (" LLVM_REVISION ")"
592#endif
593 ;
594 // TODO: Add timestamp and description.
595 OutStreamer->emitFileDirective(M.getSourceFileName(), VerStr, "", "");
596 } else {
597 OutStreamer->emitFileDirective(
598 llvm::sys::path::filename(M.getSourceFileName()));
599 }
600 }
601
602 // On AIX, emit bytes for llvm.commandline metadata after .file so that the
603 // C_INFO symbol is preserved if any csect is kept by the linker.
604 if (Target.isOSBinFormatXCOFF()) {
605 emitModuleCommandLines(M);
606 // Now we can generate section information.
607 OutStreamer->switchSection(
608 OutContext.getObjectFileInfo()->getTextSection());
609
610 // To work around an AIX assembler and/or linker bug, generate
611 // a rename for the default text-section symbol name. This call has
612 // no effect when generating object code directly.
613 MCSection *TextSection =
614 OutStreamer->getContext().getObjectFileInfo()->getTextSection();
615 MCSymbolXCOFF *XSym =
616 static_cast<MCSectionXCOFF *>(TextSection)->getQualNameSymbol();
617 if (XSym->hasRename())
618 OutStreamer->emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
619 }
620
622
623 // Emit module-level inline asm if it exists.
624 if (!M.getModuleInlineAsm().empty()) {
625 OutStreamer->AddComment("Start of file scope inline assembly");
626 OutStreamer->addBlankLine();
627 emitInlineAsm(
628 M.getModuleInlineAsm() + "\n", *TM.getMCSubtargetInfo(),
629 TM.Options.MCOptions, nullptr,
630 InlineAsm::AsmDialect(TM.getMCAsmInfo()->getAssemblerDialect()));
631 OutStreamer->AddComment("End of file scope inline assembly");
632 OutStreamer->addBlankLine();
633 }
634
635 if (MAI->doesSupportDebugInformation()) {
636 bool EmitCodeView = M.getCodeViewFlag();
637 // On Windows targets, emit minimal CodeView compiler info even when debug
638 // info is disabled.
639 if ((Target.isOSWindows() || (Target.isUEFI() && EmitCodeView)) &&
640 M.getNamedMetadata("llvm.dbg.cu"))
641 Handlers.push_back(std::make_unique<CodeViewDebug>(this));
642 if (!EmitCodeView || M.getDwarfVersion()) {
643 if (hasDebugInfo()) {
644 DD = createDwarfDebug();
645 Handlers.push_back(std::unique_ptr<DwarfDebug>(DD));
646 }
647 }
648 }
649
650 if (M.getNamedMetadata(PseudoProbeDescMetadataName))
651 PP = std::make_unique<PseudoProbeHandler>(this);
652
653 switch (MAI->getExceptionHandlingType()) {
655 // We may want to emit CFI for debug.
656 [[fallthrough]];
660 for (auto &F : M.getFunctionList()) {
662 ModuleCFISection = getFunctionCFISectionType(F);
663 // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
664 // the module needs .eh_frame. If we have found that case, we are done.
665 if (ModuleCFISection == CFISection::EH)
666 break;
667 }
668 assert(MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI ||
669 usesCFIWithoutEH() || ModuleCFISection != CFISection::EH);
670 break;
671 default:
672 break;
673 }
674
675 EHStreamer *ES = nullptr;
676 switch (MAI->getExceptionHandlingType()) {
678 if (!usesCFIWithoutEH())
679 break;
680 [[fallthrough]];
684 ES = new DwarfCFIException(this);
685 break;
687 ES = new ARMException(this);
688 break;
690 switch (MAI->getWinEHEncodingType()) {
691 default: llvm_unreachable("unsupported unwinding information encoding");
693 break;
696 ES = new WinException(this);
697 break;
698 }
699 break;
701 ES = new WasmException(this);
702 break;
704 ES = new AIXException(this);
705 break;
706 }
707 if (ES)
708 Handlers.push_back(std::unique_ptr<EHStreamer>(ES));
709
710 // All CFG modes required the tables emitted.
711 if (M.getControlFlowGuardMode() != ControlFlowGuardMode::Disabled)
712 EHHandlers.push_back(std::make_unique<WinCFGuard>(this));
713
714 for (auto &Handler : Handlers)
715 Handler->beginModule(&M);
716 for (auto &Handler : EHHandlers)
717 Handler->beginModule(&M);
718
719 return false;
720}
721
722static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
724 return false;
725
726 return GV->canBeOmittedFromSymbolTable();
727}
728
729void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
731 switch (Linkage) {
737 if (MAI->isMachO()) {
738 // .globl _foo
739 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
740
741 if (!canBeHidden(GV, *MAI))
742 // .weak_definition _foo
743 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
744 else
745 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
746 } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
747 // .globl _foo
748 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
749 //NOTE: linkonce is handled by the section the symbol was assigned to.
750 } else {
751 // .weak _foo
752 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
753 }
754 return;
756 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
757 return;
760 return;
764 llvm_unreachable("Should never emit this");
765 }
766 llvm_unreachable("Unknown linkage type!");
767}
768
770 const GlobalValue *GV) const {
771 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
772}
773
775 return TM.getSymbol(GV);
776}
777
779 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
780 // exact definion (intersection of GlobalValue::hasExactDefinition() and
781 // !isInterposable()). These linkages include: external, appending, internal,
782 // private. It may be profitable to use a local alias for external. The
783 // assembler would otherwise be conservative and assume a global default
784 // visibility symbol can be interposable, even if the code generator already
785 // assumed it.
786 if (TM.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) {
787 const Module &M = *GV.getParent();
788 if (TM.getRelocationModel() != Reloc::Static &&
789 M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
790 return getSymbolWithGlobalValueBase(&GV, "$local");
791 }
792 return TM.getSymbol(&GV);
793}
794
795/// EmitGlobalVariable - Emit the specified global variable to the .s file.
797 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
798 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
799 "No emulated TLS variables in the common section");
800
801 // Never emit TLS variable xyz in emulated TLS model.
802 // The initialization value is in __emutls_t.xyz instead of xyz.
803 if (IsEmuTLSVar)
804 return;
805
806 if (GV->hasInitializer()) {
807 // Check to see if this is a special global used by LLVM, if so, emit it.
808 if (emitSpecialLLVMGlobal(GV))
809 return;
810
811 // Skip the emission of global equivalents. The symbol can be emitted later
812 // on by emitGlobalGOTEquivs in case it turns out to be needed.
813 if (GlobalGOTEquivs.count(getSymbol(GV)))
814 return;
815
816 if (isVerbose()) {
817 // When printing the control variable __emutls_v.*,
818 // we don't need to print the original TLS variable name.
819 GV->printAsOperand(OutStreamer->getCommentOS(),
820 /*PrintType=*/false, GV->getParent());
821 OutStreamer->getCommentOS() << '\n';
822 }
823 }
824
825 MCSymbol *GVSym = getSymbol(GV);
826 MCSymbol *EmittedSym = GVSym;
827
828 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
829 // attributes.
830 // GV's or GVSym's attributes will be used for the EmittedSym.
831 emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
832
833 if (GV->isTagged()) {
834 Triple T = TM.getTargetTriple();
835
836 if (T.getArch() != Triple::aarch64)
837 OutContext.reportError(SMLoc(),
838 "tagged symbols (-fsanitize=memtag-globals) are "
839 "only supported on AArch64");
840 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_Memtag);
841 }
842
843 if (!GV->hasInitializer()) // External globals require no extra code.
844 return;
845
846 GVSym->redefineIfPossible();
847 if (GVSym->isDefined() || GVSym->isVariable())
848 OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
849 "' is already defined");
850
851 if (MAI->hasDotTypeDotSizeDirective())
852 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
853
855
856 const DataLayout &DL = GV->getDataLayout();
858
859 // If the alignment is specified, we *must* obey it. Overaligning a global
860 // with a specified alignment is a prompt way to break globals emitted to
861 // sections and expected to be contiguous (e.g. ObjC metadata).
862 const Align Alignment = getGVAlignment(GV, DL);
863
864 for (auto &Handler : Handlers)
865 Handler->setSymbolSize(GVSym, Size);
866
867 // Handle common symbols
868 if (GVKind.isCommon()) {
869 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
870 // .comm _foo, 42, 4
871 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
872 return;
873 }
874
875 // Determine to which section this global should be emitted.
876 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
877
878 // If we have a bss global going to a section that supports the
879 // zerofill directive, do so here.
880 if (GVKind.isBSS() && MAI->isMachO() && TheSection->isBssSection()) {
881 if (Size == 0)
882 Size = 1; // zerofill of 0 bytes is undefined.
883 emitLinkage(GV, GVSym);
884 // .zerofill __DATA, __bss, _foo, 400, 5
885 OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment);
886 return;
887 }
888
889 // If this is a BSS local symbol and we are emitting in the BSS
890 // section use .lcomm/.comm directive.
891 if (GVKind.isBSSLocal() &&
892 getObjFileLowering().getBSSSection() == TheSection) {
893 if (Size == 0)
894 Size = 1; // .comm Foo, 0 is undefined, avoid it.
895
896 // Use .lcomm only if it supports user-specified alignment.
897 // Otherwise, while it would still be correct to use .lcomm in some
898 // cases (e.g. when Align == 1), the external assembler might enfore
899 // some -unknown- default alignment behavior, which could cause
900 // spurious differences between external and integrated assembler.
901 // Prefer to simply fall back to .local / .comm in this case.
902 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
903 // .lcomm _foo, 42
904 OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment);
905 return;
906 }
907
908 // .local _foo
909 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
910 // .comm _foo, 42, 4
911 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
912 return;
913 }
914
915 // Handle thread local data for mach-o which requires us to output an
916 // additional structure of data and mangle the original symbol so that we
917 // can reference it later.
918 //
919 // TODO: This should become an "emit thread local global" method on TLOF.
920 // All of this macho specific stuff should be sunk down into TLOFMachO and
921 // stuff like "TLSExtraDataSection" should no longer be part of the parent
922 // TLOF class. This will also make it more obvious that stuff like
923 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
924 // specific code.
925 if (GVKind.isThreadLocal() && MAI->isMachO()) {
926 // Emit the .tbss symbol
927 MCSymbol *MangSym =
928 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
929
930 if (GVKind.isThreadBSS()) {
931 TheSection = getObjFileLowering().getTLSBSSSection();
932 OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment);
933 } else if (GVKind.isThreadData()) {
934 OutStreamer->switchSection(TheSection);
935
936 emitAlignment(Alignment, GV);
937 OutStreamer->emitLabel(MangSym);
938
940 GV->getInitializer());
941 }
942
943 OutStreamer->addBlankLine();
944
945 // Emit the variable struct for the runtime.
947
948 OutStreamer->switchSection(TLVSect);
949 // Emit the linkage here.
950 emitLinkage(GV, GVSym);
951 OutStreamer->emitLabel(GVSym);
952
953 // Three pointers in size:
954 // - __tlv_bootstrap - used to make sure support exists
955 // - spare pointer, used when mapped by the runtime
956 // - pointer to mangled symbol above with initializer
957 unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
958 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
959 PtrSize);
960 OutStreamer->emitIntValue(0, PtrSize);
961 OutStreamer->emitSymbolValue(MangSym, PtrSize);
962
963 OutStreamer->addBlankLine();
964 return;
965 }
966
967 MCSymbol *EmittedInitSym = GVSym;
968
969 OutStreamer->switchSection(TheSection);
970
971 emitLinkage(GV, EmittedInitSym);
972 emitAlignment(Alignment, GV);
973
974 OutStreamer->emitLabel(EmittedInitSym);
975 MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
976 if (LocalAlias != EmittedInitSym)
977 OutStreamer->emitLabel(LocalAlias);
978
980
981 if (MAI->hasDotTypeDotSizeDirective())
982 // .size foo, 42
983 OutStreamer->emitELFSize(EmittedInitSym,
985
986 OutStreamer->addBlankLine();
987}
988
989/// Emit the directive and value for debug thread local expression
990///
991/// \p Value - The value to emit.
992/// \p Size - The size of the integer (in bytes) to emit.
993void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
994 OutStreamer->emitValue(Value, Size);
995}
996
997void AsmPrinter::emitFunctionHeaderComment() {}
998
999void AsmPrinter::emitFunctionPrefix(ArrayRef<const Constant *> Prefix) {
1000 const Function &F = MF->getFunction();
1001 if (!MAI->hasSubsectionsViaSymbols()) {
1002 for (auto &C : Prefix)
1003 emitGlobalConstant(F.getDataLayout(), C);
1004 return;
1005 }
1006 // Preserving prefix-like data on platforms which use subsections-via-symbols
1007 // is a bit tricky. Here we introduce a symbol for the prefix-like data
1008 // and use the .alt_entry attribute to mark the function's real entry point
1009 // as an alternative entry point to the symbol that precedes the function..
1010 OutStreamer->emitLabel(OutContext.createLinkerPrivateTempSymbol());
1011
1012 for (auto &C : Prefix) {
1013 emitGlobalConstant(F.getDataLayout(), C);
1014 }
1015
1016 // Emit an .alt_entry directive for the actual function symbol.
1017 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
1018}
1019
1020/// EmitFunctionHeader - This method emits the header for the current
1021/// function.
1022void AsmPrinter::emitFunctionHeader() {
1023 const Function &F = MF->getFunction();
1024
1025 if (isVerbose())
1026 OutStreamer->getCommentOS()
1027 << "-- Begin function "
1028 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
1029
1030 // Print out constants referenced by the function
1032
1033 // Print the 'header' of function.
1034 // If basic block sections are desired, explicitly request a unique section
1035 // for this function's entry block.
1036 if (MF->front().isBeginSection())
1037 MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
1038 else
1039 MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
1040 OutStreamer->switchSection(MF->getSection());
1041
1042 if (MAI->isAIX())
1044 else
1045 emitVisibility(CurrentFnSym, F.getVisibility());
1046
1048 if (MAI->hasFunctionAlignment()) {
1049 // Make sure that the preferred alignment directive (.prefalign) is
1050 // supported before using it. The preferred alignment directive will not
1051 // have the intended effect unless function sections are enabled, so check
1052 // for that as well.
1053 if (MAI->useIntegratedAssembler() && MAI->hasPreferredAlignment() &&
1054 TM.getFunctionSections()) {
1055 Align Alignment = MF->getAlignment();
1056 Align PrefAlignment = MF->getPreferredAlignment();
1057 emitAlignment(Alignment, &F);
1058 if (Alignment != PrefAlignment)
1059 OutStreamer->emitPrefAlign(PrefAlignment);
1060 } else {
1061 emitAlignment(MF->getPreferredAlignment(), &F);
1062 }
1063 }
1064
1065 if (MAI->hasDotTypeDotSizeDirective())
1066 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
1067
1068 if (F.hasFnAttribute(Attribute::Cold))
1069 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
1070
1071 // Emit the prefix data.
1072 if (F.hasPrefixData())
1073 emitFunctionPrefix({F.getPrefixData()});
1074
1075 // Emit KCFI type information before patchable-function-prefix nops.
1077
1078 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
1079 // place prefix data before NOPs.
1080 unsigned PatchableFunctionPrefix = 0;
1081 unsigned PatchableFunctionEntry = 0;
1082 (void)F.getFnAttribute("patchable-function-prefix")
1083 .getValueAsString()
1084 .getAsInteger(10, PatchableFunctionPrefix);
1085 (void)F.getFnAttribute("patchable-function-entry")
1086 .getValueAsString()
1087 .getAsInteger(10, PatchableFunctionEntry);
1088 if (PatchableFunctionPrefix) {
1090 OutContext.createLinkerPrivateTempSymbol();
1092 emitNops(PatchableFunctionPrefix);
1093 } else if (PatchableFunctionEntry) {
1094 // May be reassigned when emitting the body, to reference the label after
1095 // the initial BTI (AArch64) or endbr32/endbr64 (x86).
1097 }
1098
1099 // Emit the function prologue data for the indirect call sanitizer.
1100 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_func_sanitize)) {
1101 assert(MD->getNumOperands() == 2);
1102
1103 auto *PrologueSig = mdconst::extract<Constant>(MD->getOperand(0));
1104 auto *TypeHash = mdconst::extract<Constant>(MD->getOperand(1));
1105 emitFunctionPrefix({PrologueSig, TypeHash});
1106 }
1107
1108 if (isVerbose()) {
1109 F.printAsOperand(OutStreamer->getCommentOS(),
1110 /*PrintType=*/false, F.getParent());
1111 emitFunctionHeaderComment();
1112 OutStreamer->getCommentOS() << '\n';
1113 }
1114
1115 // Emit the function descriptor. This is a virtual function to allow targets
1116 // to emit their specific function descriptor. Right now it is only used by
1117 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
1118 // descriptors and should be converted to use this hook as well.
1119 if (MAI->isAIX())
1121
1122 // Emit the CurrentFnSym. This is a virtual function to allow targets to do
1123 // their wild and crazy things as required.
1125
1126 // If the function had address-taken blocks that got deleted, then we have
1127 // references to the dangling symbols. Emit them at the start of the function
1128 // so that we don't get references to undefined symbols.
1129 std::vector<MCSymbol*> DeadBlockSyms;
1130 takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
1131 for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
1132 OutStreamer->AddComment("Address taken block that was later removed");
1133 OutStreamer->emitLabel(DeadBlockSym);
1134 }
1135
1136 if (CurrentFnBegin) {
1137 if (MAI->useAssignmentForEHBegin()) {
1138 MCSymbol *CurPos = OutContext.createTempSymbol();
1139 OutStreamer->emitLabel(CurPos);
1140 OutStreamer->emitAssignment(CurrentFnBegin,
1142 } else {
1143 OutStreamer->emitLabel(CurrentFnBegin);
1144 }
1145 }
1146
1147 // Emit pre-function debug and/or EH information.
1148 for (auto &Handler : Handlers) {
1149 Handler->beginFunction(MF);
1150 Handler->beginBasicBlockSection(MF->front());
1151 }
1152 for (auto &Handler : EHHandlers) {
1153 Handler->beginFunction(MF);
1154 Handler->beginBasicBlockSection(MF->front());
1155 }
1156
1157 // Emit the prologue data.
1158 if (F.hasPrologueData())
1159 emitGlobalConstant(F.getDataLayout(), F.getPrologueData());
1160}
1161
1162/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
1163/// function. This can be overridden by targets as required to do custom stuff.
1165 CurrentFnSym->redefineIfPossible();
1166 OutStreamer->emitLabel(CurrentFnSym);
1167
1168 if (TM.getTargetTriple().isOSBinFormatELF()) {
1169 MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction());
1170 if (Sym != CurrentFnSym) {
1171 CurrentFnBeginLocal = Sym;
1172 OutStreamer->emitLabel(Sym);
1173 OutStreamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeFunction);
1174 }
1175 }
1176}
1177
1178/// emitComments - Pretty-print comments for instructions.
1179static void emitComments(const MachineInstr &MI, const MCSubtargetInfo *STI,
1180 raw_ostream &CommentOS) {
1181 const MachineFunction *MF = MI.getMF();
1183
1184 // Check for spills and reloads
1185
1186 // We assume a single instruction only has a spill or reload, not
1187 // both.
1188 std::optional<LocationSize> Size;
1189 if ((Size = MI.getRestoreSize(TII))) {
1190 CommentOS << Size->getValue() << "-byte Reload\n";
1191 } else if ((Size = MI.getFoldedRestoreSize(TII))) {
1192 if (!Size->hasValue())
1193 CommentOS << "Unknown-size Folded Reload\n";
1194 else if (Size->getValue())
1195 CommentOS << Size->getValue() << "-byte Folded Reload\n";
1196 } else if ((Size = MI.getSpillSize(TII))) {
1197 CommentOS << Size->getValue() << "-byte Spill\n";
1198 } else if ((Size = MI.getFoldedSpillSize(TII))) {
1199 if (!Size->hasValue())
1200 CommentOS << "Unknown-size Folded Spill\n";
1201 else if (Size->getValue())
1202 CommentOS << Size->getValue() << "-byte Folded Spill\n";
1203 }
1204
1205 // Check for spill-induced copies
1206 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
1207 CommentOS << " Reload Reuse\n";
1208
1209 if (PrintLatency) {
1211 const MCSchedModel &SCModel = STI->getSchedModel();
1214 *STI, *TII, MI);
1215 // Report only interesting latencies.
1216 if (1 < Latency)
1217 CommentOS << " Latency: " << Latency << "\n";
1218 }
1219}
1220
1221/// emitImplicitDef - This method emits the specified machine instruction
1222/// that is an implicit def.
1224 Register RegNo = MI->getOperand(0).getReg();
1225
1226 SmallString<128> Str;
1227 raw_svector_ostream OS(Str);
1228 OS << "implicit-def: "
1229 << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
1230
1231 OutStreamer->AddComment(OS.str());
1232 OutStreamer->addBlankLine();
1233}
1234
1235static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
1236 std::string Str;
1237 raw_string_ostream OS(Str);
1238 OS << "kill:";
1239 for (const MachineOperand &Op : MI->operands()) {
1240 assert(Op.isReg() && "KILL instruction must have only register operands");
1241 OS << ' ' << (Op.isDef() ? "def " : "killed ")
1242 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
1243 }
1244 AP.OutStreamer->AddComment(Str);
1245 AP.OutStreamer->addBlankLine();
1246}
1247
1248static void emitFakeUse(const MachineInstr *MI, AsmPrinter &AP) {
1249 std::string Str;
1250 raw_string_ostream OS(Str);
1251 OS << "fake_use:";
1252 for (const MachineOperand &Op : MI->operands()) {
1253 // In some circumstances we can end up with fake uses of constants; skip
1254 // these.
1255 if (!Op.isReg())
1256 continue;
1257 OS << ' ' << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
1258 }
1259 AP.OutStreamer->AddComment(OS.str());
1260 AP.OutStreamer->addBlankLine();
1261}
1262
1263/// emitDebugValueComment - This method handles the target-independent form
1264/// of DBG_VALUE, returning true if it was able to do so. A false return
1265/// means the target will need to handle MI in EmitInstruction.
1267 // This code handles only the 4-operand target-independent form.
1268 if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
1269 return false;
1270
1271 SmallString<128> Str;
1272 raw_svector_ostream OS(Str);
1273 OS << "DEBUG_VALUE: ";
1274
1275 const DILocalVariable *V = MI->getDebugVariable();
1276 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
1277 StringRef Name = SP->getName();
1278 if (!Name.empty())
1279 OS << Name << ":";
1280 }
1281 OS << V->getName();
1282 OS << " <- ";
1283
1284 const DIExpression *Expr = MI->getDebugExpression();
1285 // First convert this to a non-variadic expression if possible, to simplify
1286 // the output.
1287 if (auto NonVariadicExpr = DIExpression::convertToNonVariadicExpression(Expr))
1288 Expr = *NonVariadicExpr;
1289 // Then, output the possibly-simplified expression.
1290 if (Expr->getNumElements()) {
1291 OS << '[';
1292 ListSeparator LS;
1293 for (auto &Op : Expr->expr_ops()) {
1294 OS << LS << dwarf::OperationEncodingString(Op.getOp());
1295 for (unsigned I = 0; I < Op.getNumArgs(); ++I)
1296 OS << ' ' << Op.getArg(I);
1297 }
1298 OS << "] ";
1299 }
1300
1301 // Register or immediate value. Register 0 means undef.
1302 for (const MachineOperand &Op : MI->debug_operands()) {
1303 if (&Op != MI->debug_operands().begin())
1304 OS << ", ";
1305 switch (Op.getType()) {
1307 APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
1308 Type *ImmTy = Op.getFPImm()->getType();
1309 if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
1310 ImmTy->isDoubleTy()) {
1311 OS << APF.convertToDouble();
1312 } else {
1313 // There is no good way to print long double. Convert a copy to
1314 // double. Ah well, it's only a comment.
1315 bool ignored;
1317 &ignored);
1318 OS << "(long double) " << APF.convertToDouble();
1319 }
1320 break;
1321 }
1323 OS << Op.getImm();
1324 break;
1325 }
1327 Op.getCImm()->getValue().print(OS, false /*isSigned*/);
1328 break;
1329 }
1331 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
1332 break;
1333 }
1336 Register Reg;
1337 std::optional<StackOffset> Offset;
1338 if (Op.isReg()) {
1339 Reg = Op.getReg();
1340 } else {
1341 const TargetFrameLowering *TFI =
1343 Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
1344 }
1345 if (!Reg) {
1346 // Suppress offset, it is not meaningful here.
1347 OS << "undef";
1348 break;
1349 }
1350 // The second operand is only an offset if it's an immediate.
1351 if (MI->isIndirectDebugValue())
1352 Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
1353 if (Offset)
1354 OS << '[';
1355 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
1356 if (Offset)
1357 OS << '+' << Offset->getFixed() << ']';
1358 break;
1359 }
1360 default:
1361 llvm_unreachable("Unknown operand type");
1362 }
1363 }
1364
1365 // NOTE: Want this comment at start of line, don't emit with AddComment.
1366 AP.OutStreamer->emitRawComment(Str);
1367 return true;
1368}
1369
1370/// This method handles the target-independent form of DBG_LABEL, returning
1371/// true if it was able to do so. A false return means the target will need
1372/// to handle MI in EmitInstruction.
1374 if (MI->getNumOperands() != 1)
1375 return false;
1376
1377 SmallString<128> Str;
1378 raw_svector_ostream OS(Str);
1379 OS << "DEBUG_LABEL: ";
1380
1381 const DILabel *V = MI->getDebugLabel();
1382 if (auto *SP = dyn_cast<DISubprogram>(
1383 V->getScope()->getNonLexicalBlockFileScope())) {
1384 StringRef Name = SP->getName();
1385 if (!Name.empty())
1386 OS << Name << ":";
1387 }
1388 OS << V->getName();
1389
1390 // NOTE: Want this comment at start of line, don't emit with AddComment.
1391 AP.OutStreamer->emitRawComment(OS.str());
1392 return true;
1393}
1394
1397 // Ignore functions that won't get emitted.
1398 if (F.isDeclarationForLinker())
1399 return CFISection::None;
1400
1401 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
1402 F.needsUnwindTableEntry())
1403 return CFISection::EH;
1404
1405 if (MAI->usesCFIWithoutEH() && F.hasUWTable())
1406 return CFISection::EH;
1407
1408 if (hasDebugInfo() || TM.Options.ForceDwarfFrameSection)
1409 return CFISection::Debug;
1410
1411 return CFISection::None;
1412}
1413
1418
1420 return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
1421}
1422
1424 return MAI->usesCFIWithoutEH() && ModuleCFISection != CFISection::None;
1425}
1426
1428 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
1429 if (!usesCFIWithoutEH() &&
1430 ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
1431 ExceptionHandlingType != ExceptionHandling::ARM)
1432 return;
1433
1435 return;
1436
1437 // If there is no "real" instruction following this CFI instruction, skip
1438 // emitting it; it would be beyond the end of the function's FDE range.
1439 auto *MBB = MI.getParent();
1440 auto I = std::next(MI.getIterator());
1441 while (I != MBB->end() && I->isTransient())
1442 ++I;
1443 if (I == MBB->instr_end() &&
1444 MBB->getReverseIterator() == MBB->getParent()->rbegin())
1445 return;
1446
1447 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1448 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1449 const MCCFIInstruction &CFI = Instrs[CFIIndex];
1450 emitCFIInstruction(CFI);
1451}
1452
1454 // The operands are the MCSymbol and the frame offset of the allocation.
1455 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1456 int FrameOffset = MI.getOperand(1).getImm();
1457
1458 // Emit a symbol assignment.
1459 OutStreamer->emitAssignment(FrameAllocSym,
1460 MCConstantExpr::create(FrameOffset, OutContext));
1461}
1462
1463/// Returns the BB metadata to be emitted in the SHT_LLVM_BB_ADDR_MAP section
1464/// for a given basic block. This can be used to capture more precise profile
1465/// information.
1467 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
1469 MBB.isReturnBlock(), !MBB.empty() && TII->isTailCall(MBB.back()),
1470 MBB.isEHPad(), const_cast<MachineBasicBlock &>(MBB).canFallThrough(),
1471 !MBB.empty() && MBB.rbegin()->isIndirectBranch()}
1472 .encode();
1473}
1474
1476getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges,
1477 bool HasCalls, const CFGProfile *FuncCFGProfile) {
1478 // Ensure that the user has not passed in additional options while also
1479 // specifying all or none.
1482 popcount(PgoAnalysisMapFeatures.getBits()) != 1) {
1484 "-pgo-analysis-map can accept only all or none with no additional "
1485 "values.");
1486 }
1487
1488 bool NoFeatures = PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::None);
1490 bool FuncEntryCountEnabled =
1491 AllFeatures || (!NoFeatures && PgoAnalysisMapFeatures.isSet(
1493 bool BBFreqEnabled =
1494 AllFeatures ||
1495 (!NoFeatures && PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::BBFreq));
1496 bool BrProbEnabled =
1497 AllFeatures ||
1498 (!NoFeatures && PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::BrProb));
1499 bool PostLinkCfgEnabled = FuncCFGProfile && PgoAnalysisMapEmitBBSectionsCfg;
1500
1501 if ((BBFreqEnabled || BrProbEnabled) && BBAddrMapSkipEmitBBEntries) {
1503 "BB entries info is required for BBFreq and BrProb features");
1504 }
1505 return {FuncEntryCountEnabled, BBFreqEnabled, BrProbEnabled,
1506 MF.hasBBSections() && NumMBBSectionRanges > 1,
1507 // Use static_cast to avoid breakage of tests on windows.
1508 static_cast<bool>(BBAddrMapSkipEmitBBEntries), HasCalls,
1509 static_cast<bool>(EmitBBHash), PostLinkCfgEnabled};
1510}
1511
1513 MCSection *BBAddrMapSection =
1514 getObjFileLowering().getBBAddrMapSection(*MF.getSection());
1515 assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
1516 bool HasCalls = !CurrentFnCallsiteEndSymbols.empty();
1517
1518 const BasicBlockSectionsProfileReader *BBSPR = nullptr;
1519 if (auto *BBSPRPass =
1521 BBSPR = &BBSPRPass->getBBSPR();
1522 const CFGProfile *FuncCFGProfile = nullptr;
1523 if (BBSPR)
1524 FuncCFGProfile = BBSPR->getFunctionCFGProfile(MF.getFunction().getName());
1525
1526 const MCSymbol *FunctionSymbol = getFunctionBegin();
1527
1528 OutStreamer->pushSection();
1529 OutStreamer->switchSection(BBAddrMapSection);
1530 OutStreamer->AddComment("version");
1531 uint8_t BBAddrMapVersion = OutStreamer->getContext().getBBAddrMapVersion();
1532 OutStreamer->emitInt8(BBAddrMapVersion);
1533 OutStreamer->AddComment("feature");
1534 auto Features = getBBAddrMapFeature(MF, MBBSectionRanges.size(), HasCalls,
1535 FuncCFGProfile);
1536 OutStreamer->emitInt16(Features.encode());
1537 // Emit BB Information for each basic block in the function.
1538 if (Features.MultiBBRange) {
1539 OutStreamer->AddComment("number of basic block ranges");
1540 OutStreamer->emitULEB128IntValue(MBBSectionRanges.size());
1541 }
1542 // Number of blocks in each MBB section.
1543 MapVector<MBBSectionID, unsigned> MBBSectionNumBlocks;
1544 const MCSymbol *PrevMBBEndSymbol = nullptr;
1545 if (!Features.MultiBBRange) {
1546 OutStreamer->AddComment("function address");
1547 OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
1548 OutStreamer->AddComment("number of basic blocks");
1549 OutStreamer->emitULEB128IntValue(MF.size());
1550 PrevMBBEndSymbol = FunctionSymbol;
1551 } else {
1552 unsigned BBCount = 0;
1553 for (const MachineBasicBlock &MBB : MF) {
1554 BBCount++;
1555 if (MBB.isEndSection()) {
1556 // Store each section's basic block count when it ends.
1557 MBBSectionNumBlocks[MBB.getSectionID()] = BBCount;
1558 // Reset the count for the next section.
1559 BBCount = 0;
1560 }
1561 }
1562 }
1563 // Emit the BB entry for each basic block in the function.
1564 for (const MachineBasicBlock &MBB : MF) {
1565 const MCSymbol *MBBSymbol =
1566 MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1567 bool IsBeginSection =
1568 Features.MultiBBRange && (MBB.isBeginSection() || MBB.isEntryBlock());
1569 if (IsBeginSection) {
1570 OutStreamer->AddComment("base address");
1571 OutStreamer->emitSymbolValue(MBBSymbol, getPointerSize());
1572 OutStreamer->AddComment("number of basic blocks");
1573 OutStreamer->emitULEB128IntValue(MBBSectionNumBlocks[MBB.getSectionID()]);
1574 PrevMBBEndSymbol = MBBSymbol;
1575 }
1576
1577 auto MBHI =
1578 Features.BBHash ? &getAnalysis<MachineBlockHashInfo>() : nullptr;
1579
1580 if (!Features.OmitBBEntries) {
1581 OutStreamer->AddComment("BB id");
1582 // Emit the BB ID for this basic block.
1583 // We only emit BaseID since CloneID is unset for
1584 // -basic-block-adress-map.
1585 // TODO: Emit the full BBID when labels and sections can be mixed
1586 // together.
1587 OutStreamer->emitULEB128IntValue(MBB.getBBID()->BaseID);
1588 // Emit the basic block offset relative to the end of the previous block.
1589 // This is zero unless the block is padded due to alignment.
1590 emitLabelDifferenceAsULEB128(MBBSymbol, PrevMBBEndSymbol);
1591 const MCSymbol *CurrentLabel = MBBSymbol;
1592 if (HasCalls) {
1593 auto CallsiteEndSymbols = CurrentFnCallsiteEndSymbols.lookup(&MBB);
1594 OutStreamer->AddComment("number of callsites");
1595 OutStreamer->emitULEB128IntValue(CallsiteEndSymbols.size());
1596 for (const MCSymbol *CallsiteEndSymbol : CallsiteEndSymbols) {
1597 // Emit the callsite offset.
1598 emitLabelDifferenceAsULEB128(CallsiteEndSymbol, CurrentLabel);
1599 CurrentLabel = CallsiteEndSymbol;
1600 }
1601 }
1602 // Emit the offset to the end of the block, which can be used to compute
1603 // the total block size.
1604 emitLabelDifferenceAsULEB128(MBB.getEndSymbol(), CurrentLabel);
1605 // Emit the Metadata.
1606 OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
1607 // Emit the Hash.
1608 if (MBHI) {
1609 OutStreamer->emitInt64(MBHI->getMBBHash(MBB));
1610 }
1611 }
1612 PrevMBBEndSymbol = MBB.getEndSymbol();
1613 }
1614
1615 if (Features.hasPGOAnalysis()) {
1616 assert(BBAddrMapVersion >= 2 &&
1617 "PGOAnalysisMap only supports version 2 or later");
1618
1619 if (Features.FuncEntryCount) {
1620 OutStreamer->AddComment("function entry count");
1621 auto MaybeEntryCount = MF.getFunction().getEntryCount();
1622 OutStreamer->emitULEB128IntValue(
1623 MaybeEntryCount ? MaybeEntryCount->getCount() : 0);
1624 }
1625 const MachineBlockFrequencyInfo *MBFI =
1626 Features.BBFreq
1628 : nullptr;
1629 const MachineBranchProbabilityInfo *MBPI =
1630 Features.BrProb
1632 : nullptr;
1633
1634 if (Features.BBFreq || Features.BrProb) {
1635 for (const MachineBasicBlock &MBB : MF) {
1636 if (Features.BBFreq) {
1637 OutStreamer->AddComment("basic block frequency");
1638 OutStreamer->emitULEB128IntValue(
1639 MBFI->getBlockFreq(&MBB).getFrequency());
1640 if (Features.PostLinkCfg) {
1641 OutStreamer->AddComment("basic block frequency (propeller)");
1642 OutStreamer->emitULEB128IntValue(
1643 FuncCFGProfile->getBlockCount(*MBB.getBBID()));
1644 }
1645 }
1646 if (Features.BrProb) {
1647 unsigned SuccCount = MBB.succ_size();
1648 OutStreamer->AddComment("basic block successor count");
1649 OutStreamer->emitULEB128IntValue(SuccCount);
1650 for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
1651 OutStreamer->AddComment("successor BB ID");
1652 OutStreamer->emitULEB128IntValue(SuccMBB->getBBID()->BaseID);
1653 OutStreamer->AddComment("successor branch probability");
1654 OutStreamer->emitULEB128IntValue(
1655 MBPI->getEdgeProbability(&MBB, SuccMBB).getNumerator());
1656 if (Features.PostLinkCfg) {
1657 OutStreamer->AddComment("successor branch frequency (propeller)");
1658 OutStreamer->emitULEB128IntValue(FuncCFGProfile->getEdgeCount(
1659 *MBB.getBBID(), *SuccMBB->getBBID()));
1660 }
1661 }
1662 }
1663 }
1664 }
1665 }
1666
1667 OutStreamer->popSection();
1668}
1669
1671 const MCSymbol *Symbol) {
1672 MCSection *Section =
1673 getObjFileLowering().getKCFITrapSection(*MF.getSection());
1674 if (!Section)
1675 return;
1676
1677 OutStreamer->pushSection();
1678 OutStreamer->switchSection(Section);
1679
1680 MCSymbol *Loc = OutContext.createLinkerPrivateTempSymbol();
1681 OutStreamer->emitLabel(Loc);
1682 OutStreamer->emitAbsoluteSymbolDiff(Symbol, Loc, 4);
1683
1684 OutStreamer->popSection();
1685}
1686
1688 const Function &F = MF.getFunction();
1689 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_kcfi_type))
1690 emitGlobalConstant(F.getDataLayout(),
1691 mdconst::extract<ConstantInt>(MD->getOperand(0)));
1692}
1693
1695 if (PP) {
1696 auto GUID = MI.getOperand(0).getImm();
1697 auto Index = MI.getOperand(1).getImm();
1698 auto Type = MI.getOperand(2).getImm();
1699 auto Attr = MI.getOperand(3).getImm();
1700 DILocation *DebugLoc = MI.getDebugLoc();
1701 PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
1702 }
1703}
1704
1706 if (!MF.getTarget().Options.EmitStackSizeSection)
1707 return;
1708
1709 MCSection *StackSizeSection =
1711 if (!StackSizeSection)
1712 return;
1713
1714 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1715 // Don't emit functions with dynamic stack allocations.
1716 if (FrameInfo.hasVarSizedObjects())
1717 return;
1718
1719 OutStreamer->pushSection();
1720 OutStreamer->switchSection(StackSizeSection);
1721
1722 const MCSymbol *FunctionSymbol = getFunctionBegin();
1723 uint64_t StackSize =
1724 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1725 OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
1726 OutStreamer->emitULEB128IntValue(StackSize);
1727
1728 OutStreamer->popSection();
1729}
1730
1732 const std::string OutputFilename =
1734 : MF.getTarget().Options.StackUsageFile;
1735
1736 // OutputFilename empty implies -fstack-usage is not passed.
1737 if (OutputFilename.empty())
1738 return;
1739
1740 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1741 uint64_t StackSize =
1742 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1743
1744 if (StackUsageStream == nullptr) {
1745 std::error_code EC;
1746 StackUsageStream =
1747 std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
1748 if (EC) {
1749 errs() << "Could not open file: " << EC.message();
1750 return;
1751 }
1752 }
1753
1754 if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1755 *StackUsageStream << DSP->getFilename() << ':' << DSP->getLine();
1756 else
1757 *StackUsageStream << MF.getFunction().getParent()->getName();
1758
1759 *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1760 if (FrameInfo.hasVarSizedObjects())
1761 *StackUsageStream << "dynamic\n";
1762 else
1763 *StackUsageStream << "static\n";
1764}
1765
1766/// Extracts a generalized numeric type identifier of a Function's type from
1767/// type metadata. Returns null if metadata cannot be found.
1770 F.getMetadata(LLVMContext::MD_type, Types);
1771 for (const auto &Type : Types) {
1772 if (Type->hasGeneralizedMDString()) {
1773 MDString *MDGeneralizedTypeId = cast<MDString>(Type->getOperand(1));
1774 uint64_t TypeIdVal = llvm::MD5Hash(MDGeneralizedTypeId->getString());
1775 IntegerType *Int64Ty = Type::getInt64Ty(F.getContext());
1776 return ConstantInt::get(Int64Ty, TypeIdVal);
1777 }
1778 }
1779 return nullptr;
1780}
1781
1782/// Emits .llvm.callgraph section.
1784 FunctionCallGraphInfo &FuncCGInfo) {
1785 if (!MF.getTarget().Options.EmitCallGraphSection)
1786 return;
1787
1788 // Switch to the call graph section for the function
1789 MCSection *FuncCGSection =
1791 assert(FuncCGSection && "null callgraph section");
1792 OutStreamer->pushSection();
1793 OutStreamer->switchSection(FuncCGSection);
1794
1795 const Function &F = MF.getFunction();
1796 // If this function has external linkage or has its address taken and
1797 // it is not a callback, then anything could call it.
1798 bool IsIndirectTarget =
1799 !F.hasLocalLinkage() || F.hasAddressTaken(nullptr,
1800 /*IgnoreCallbackUses=*/true,
1801 /*IgnoreAssumeLikeCalls=*/true,
1802 /*IgnoreLLVMUsed=*/false);
1803
1804 const auto &DirectCallees = FuncCGInfo.DirectCallees;
1805 const auto &IndirectCalleeTypeIDs = FuncCGInfo.IndirectCalleeTypeIDs;
1806
1807 using namespace callgraph;
1808 Flags CGFlags = Flags::None;
1809 if (IsIndirectTarget)
1810 CGFlags |= Flags::IsIndirectTarget;
1811 if (DirectCallees.size() > 0)
1812 CGFlags |= Flags::HasDirectCallees;
1813 if (IndirectCalleeTypeIDs.size() > 0)
1814 CGFlags |= Flags::HasIndirectCallees;
1815
1816 // Emit function's call graph information.
1817 // 1) CallGraphSectionFormatVersion
1818 // 2) Flags
1819 // a. LSB bit 0 is set to 1 if the function is a potential indirect
1820 // target.
1821 // b. LSB bit 1 is set to 1 if there are direct callees.
1822 // c. LSB bit 2 is set to 1 if there are indirect callees.
1823 // d. Rest of the 5 bits in Flags are reserved for any future use.
1824 // 3) Function entry PC.
1825 // 4) FunctionTypeID if the function is indirect target and its type id
1826 // is known, otherwise it is set to 0.
1827 // 5) Number of unique direct callees, if at least one exists.
1828 // 6) For each unique direct callee, the callee's PC.
1829 // 7) Number of unique indirect target type IDs, if at least one exists.
1830 // 8) Each unique indirect target type id.
1831 OutStreamer->emitInt8(CallGraphSectionFormatVersion::V_0);
1832 OutStreamer->emitInt8(static_cast<uint8_t>(CGFlags));
1833 OutStreamer->emitSymbolValue(getSymbol(&F), TM.getProgramPointerSize());
1834 const auto *TypeId = extractNumericCGTypeId(F);
1835 if (IsIndirectTarget && TypeId)
1836 OutStreamer->emitInt64(TypeId->getZExtValue());
1837 else
1838 OutStreamer->emitInt64(0);
1839
1840 if (DirectCallees.size() > 0) {
1841 OutStreamer->emitULEB128IntValue(DirectCallees.size());
1842 for (const auto &CalleeSymbol : DirectCallees)
1843 OutStreamer->emitSymbolValue(CalleeSymbol, TM.getProgramPointerSize());
1844 FuncCGInfo.DirectCallees.clear();
1845 }
1846 if (IndirectCalleeTypeIDs.size() > 0) {
1847 OutStreamer->emitULEB128IntValue(IndirectCalleeTypeIDs.size());
1848 for (const auto &CalleeTypeId : IndirectCalleeTypeIDs)
1849 OutStreamer->emitInt64(CalleeTypeId);
1850 FuncCGInfo.IndirectCalleeTypeIDs.clear();
1851 }
1852 // End of emitting call graph section contents.
1853 OutStreamer->popSection();
1854}
1855
1857 const MDNode &MD) {
1858 MCSymbol *S = MF.getContext().createTempSymbol("pcsection");
1859 OutStreamer->emitLabel(S);
1860 PCSectionsSymbols[&MD].emplace_back(S);
1861}
1862
1864 const Function &F = MF.getFunction();
1865 if (PCSectionsSymbols.empty() && !F.hasMetadata(LLVMContext::MD_pcsections))
1866 return;
1867
1868 const CodeModel::Model CM = MF.getTarget().getCodeModel();
1869 const unsigned RelativeRelocSize =
1871 : 4;
1872
1873 // Switch to PCSection, short-circuiting the common case where the current
1874 // section is still valid (assume most MD_pcsections contain just 1 section).
1875 auto SwitchSection = [&, Prev = StringRef()](const StringRef &Sec) mutable {
1876 if (Sec == Prev)
1877 return;
1878 MCSection *S = getObjFileLowering().getPCSection(Sec, MF.getSection());
1879 assert(S && "PC section is not initialized");
1880 OutStreamer->switchSection(S);
1881 Prev = Sec;
1882 };
1883 // Emit symbols into sections and data as specified in the pcsections MDNode.
1884 auto EmitForMD = [&](const MDNode &MD, ArrayRef<const MCSymbol *> Syms,
1885 bool Deltas) {
1886 // Expect the first operand to be a section name. After that, a tuple of
1887 // constants may appear, which will simply be emitted into the current
1888 // section (the user of MD_pcsections decides the format of encoded data).
1889 assert(isa<MDString>(MD.getOperand(0)) && "first operand not a string");
1890 bool ConstULEB128 = false;
1891 for (const MDOperand &MDO : MD.operands()) {
1892 if (auto *S = dyn_cast<MDString>(MDO)) {
1893 // Found string, start of new section!
1894 // Find options for this section "<section>!<opts>" - supported options:
1895 // C = Compress constant integers of size 2-8 bytes as ULEB128.
1896 const StringRef SecWithOpt = S->getString();
1897 const size_t OptStart = SecWithOpt.find('!'); // likely npos
1898 const StringRef Sec = SecWithOpt.substr(0, OptStart);
1899 const StringRef Opts = SecWithOpt.substr(OptStart); // likely empty
1900 ConstULEB128 = Opts.contains('C');
1901#ifndef NDEBUG
1902 for (char O : Opts)
1903 assert((O == '!' || O == 'C') && "Invalid !pcsections options");
1904#endif
1905 SwitchSection(Sec);
1906 const MCSymbol *Prev = Syms.front();
1907 for (const MCSymbol *Sym : Syms) {
1908 if (Sym == Prev || !Deltas) {
1909 // Use the entry itself as the base of the relative offset.
1910 MCSymbol *Base = MF.getContext().createTempSymbol("pcsection_base");
1911 OutStreamer->emitLabel(Base);
1912 // Emit relative relocation `addr - base`, which avoids a dynamic
1913 // relocation in the final binary. User will get the address with
1914 // `base + addr`.
1915 emitLabelDifference(Sym, Base, RelativeRelocSize);
1916 } else {
1917 // Emit delta between symbol and previous symbol.
1918 if (ConstULEB128)
1920 else
1921 emitLabelDifference(Sym, Prev, 4);
1922 }
1923 Prev = Sym;
1924 }
1925 } else {
1926 // Emit auxiliary data after PC.
1927 assert(isa<MDNode>(MDO) && "expecting either string or tuple");
1928 const auto *AuxMDs = cast<MDNode>(MDO);
1929 for (const MDOperand &AuxMDO : AuxMDs->operands()) {
1930 assert(isa<ConstantAsMetadata>(AuxMDO) && "expecting a constant");
1931 const Constant *C = cast<ConstantAsMetadata>(AuxMDO)->getValue();
1932 const DataLayout &DL = F.getDataLayout();
1933 const uint64_t Size = DL.getTypeStoreSize(C->getType());
1934
1935 if (auto *CI = dyn_cast<ConstantInt>(C);
1936 CI && ConstULEB128 && Size > 1 && Size <= 8) {
1937 emitULEB128(CI->getZExtValue());
1938 } else {
1940 }
1941 }
1942 }
1943 }
1944 };
1945
1946 OutStreamer->pushSection();
1947 // Emit PCs for function start and function size.
1948 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_pcsections))
1949 EmitForMD(*MD, {getFunctionBegin(), getFunctionEnd()}, true);
1950 // Emit PCs for instructions collected.
1951 for (const auto &MS : PCSectionsSymbols)
1952 EmitForMD(*MS.first, MS.second, false);
1953 OutStreamer->popSection();
1954 PCSectionsSymbols.clear();
1955}
1956
1957/// Returns true if function begin and end labels should be emitted.
1958static bool needFuncLabels(const MachineFunction &MF, const AsmPrinter &Asm) {
1959 if (Asm.hasDebugInfo() || !MF.getLandingPads().empty() ||
1960 MF.hasEHFunclets() ||
1961 MF.getFunction().hasMetadata(LLVMContext::MD_pcsections))
1962 return true;
1963
1964 // We might emit an EH table that uses function begin and end labels even if
1965 // we don't have any landingpads.
1966 if (!MF.getFunction().hasPersonalityFn())
1967 return false;
1968 return !isNoOpWithoutInvoke(
1970}
1971
1972// Return the mnemonic of a MachineInstr if available, or the MachineInstr
1973// opcode name otherwise.
1975 const TargetInstrInfo *TII =
1976 MI.getParent()->getParent()->getSubtarget().getInstrInfo();
1977 MCInst MCI;
1978 MCI.setOpcode(MI.getOpcode());
1979 if (StringRef Name = Streamer.getMnemonic(MCI); !Name.empty())
1980 return Name;
1981 StringRef Name = TII->getName(MI.getOpcode());
1982 assert(!Name.empty() && "Missing mnemonic and name for opcode");
1983 return Name;
1984}
1985
1987 FunctionCallGraphInfo &FuncCGInfo,
1988 const MachineFunction::CallSiteInfoMap &CallSitesInfoMap,
1989 const MachineInstr &MI) {
1990 assert(MI.isCall() && "This method is meant for call instructions only.");
1991 const MachineOperand &CalleeOperand = MI.getOperand(0);
1992 if (CalleeOperand.isGlobal() || CalleeOperand.isSymbol()) {
1993 // Handle direct calls.
1994 MCSymbol *CalleeSymbol = nullptr;
1995 switch (CalleeOperand.getType()) {
1997 CalleeSymbol = getSymbol(CalleeOperand.getGlobal());
1998 break;
2000 CalleeSymbol = GetExternalSymbolSymbol(CalleeOperand.getSymbolName());
2001 break;
2002 default:
2004 "Expected to only handle direct call instructions here.");
2005 }
2006 FuncCGInfo.DirectCallees.insert(CalleeSymbol);
2007 return; // Early exit after handling the direct call instruction.
2008 }
2009 const auto &CallSiteInfo = CallSitesInfoMap.find(&MI);
2010 if (CallSiteInfo == CallSitesInfoMap.end())
2011 return;
2012 // Handle indirect callsite info.
2013 // Only indirect calls have type identifiers set.
2014 for (ConstantInt *CalleeTypeId : CallSiteInfo->second.CalleeTypeIds) {
2015 uint64_t CalleeTypeIdVal = CalleeTypeId->getZExtValue();
2016 FuncCGInfo.IndirectCalleeTypeIDs.insert(CalleeTypeIdVal);
2017 }
2018}
2019
2020/// Helper to emit a symbol for the prefetch target associated with the given
2021/// BBID and callsite index.
2023 unsigned CallsiteIndex) {
2024 SmallString<128> FunctionName;
2025 getNameWithPrefix(FunctionName, &MF->getFunction());
2026 MCSymbol *PrefetchTargetSymbol = OutContext.getOrCreateSymbol(
2027 "__llvm_prefetch_target_" + FunctionName + "_" + Twine(BaseID) + "_" +
2029 // If the function is weak-linkage it may be replaced by a strong
2030 // version, in which case the prefetch targets should also be replaced.
2031 OutStreamer->emitSymbolAttribute(
2032 PrefetchTargetSymbol,
2033 MF->getFunction().isWeakForLinker() ? MCSA_Weak : MCSA_Global);
2034 OutStreamer->emitLabel(PrefetchTargetSymbol);
2035}
2036
2037/// Emit dangling prefetch targets that were not mapped to any basic block.
2039 const DenseMap<UniqueBBID, SmallVector<unsigned>> &MFPrefetchTargets =
2040 MF->getPrefetchTargets();
2041 if (MFPrefetchTargets.empty())
2042 return;
2043 DenseSet<UniqueBBID> MFBBIDs;
2044 for (const MachineBasicBlock &MBB : *MF)
2045 if (std::optional<UniqueBBID> BBID = MBB.getBBID())
2046 MFBBIDs.insert(*BBID);
2047
2048 for (const auto &[BBID, CallsiteIndexes] : MFPrefetchTargets) {
2049 if (MFBBIDs.contains(BBID))
2050 continue;
2051 for (unsigned CallsiteIndex : CallsiteIndexes)
2053 }
2054}
2055
2056/// EmitFunctionBody - This method emits the body and trailer for a
2057/// function.
2059 emitFunctionHeader();
2060
2061 // Emit target-specific gunk before the function body.
2063
2064 if (isVerbose()) {
2065 // Get MachineDominatorTree or compute it on the fly if it's unavailable
2066 MDT = GetMDT(*MF);
2067 if (!MDT) {
2068 OwnedMDT = std::make_unique<MachineDominatorTree>();
2069 OwnedMDT->recalculate(*MF);
2070 MDT = OwnedMDT.get();
2071 }
2072
2073 // Get MachineLoopInfo or compute it on the fly if it's unavailable
2074 MLI = GetMLI(*MF);
2075 if (!MLI) {
2076 OwnedMLI = std::make_unique<MachineLoopInfo>();
2077 OwnedMLI->analyze(*MDT);
2078 MLI = OwnedMLI.get();
2079 }
2080 }
2081
2082 // Print out code for the function.
2083 bool HasAnyRealCode = false;
2084 int NumInstsInFunction = 0;
2085 bool IsEHa = MMI->getModule()->getModuleFlag("eh-asynch");
2086
2087 const MCSubtargetInfo *STI = nullptr;
2088 if (this->MF)
2089 STI = &getSubtargetInfo();
2090 else
2091 STI = TM.getMCSubtargetInfo();
2092
2093 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
2094 // Create a slot for the entry basic block section so that the section
2095 // order is preserved when iterating over MBBSectionRanges.
2096 if (!MF->empty())
2097 MBBSectionRanges[MF->front().getSectionID()] =
2099
2100 FunctionCallGraphInfo FuncCGInfo;
2101 const auto &CallSitesInfoMap = MF->getCallSitesInfo();
2102
2103 // Dangling targets are not mapped to any blocks and must be emitted at the
2104 // beginning of the function.
2106
2107 const auto &MFPrefetchTargets = MF->getPrefetchTargets();
2108 for (auto &MBB : *MF) {
2109 // Print a label for the basic block.
2111 DenseMap<StringRef, unsigned> MnemonicCounts;
2112
2113 const SmallVector<unsigned> *PrefetchTargets = nullptr;
2114 if (auto BBID = MBB.getBBID()) {
2115 auto R = MFPrefetchTargets.find(*BBID);
2116 if (R != MFPrefetchTargets.end())
2117 PrefetchTargets = &R->second;
2118 }
2119 auto PrefetchTargetIt =
2120 PrefetchTargets ? PrefetchTargets->begin() : nullptr;
2121 auto PrefetchTargetEnd = PrefetchTargets ? PrefetchTargets->end() : nullptr;
2122 unsigned LastCallsiteIndex = 0;
2123
2124 for (auto &MI : MBB) {
2125 if (PrefetchTargetIt != PrefetchTargetEnd &&
2126 *PrefetchTargetIt == LastCallsiteIndex) {
2127 emitPrefetchTargetSymbol(MBB.getBBID()->BaseID, *PrefetchTargetIt);
2128 ++PrefetchTargetIt;
2129 }
2130
2131 // Print the assembly for the instruction.
2132 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
2133 !MI.isDebugInstr()) {
2134 HasAnyRealCode = true;
2135 }
2136
2137 // If there is a pre-instruction symbol, emit a label for it here.
2138 if (MCSymbol *S = MI.getPreInstrSymbol())
2139 OutStreamer->emitLabel(S);
2140
2141 if (MDNode *MD = MI.getPCSections())
2142 emitPCSectionsLabel(*MF, *MD);
2143
2144 for (auto &Handler : Handlers)
2145 Handler->beginInstruction(&MI);
2146
2147 if (isVerbose())
2148 emitComments(MI, STI, OutStreamer->getCommentOS());
2149
2150 switch (MI.getOpcode()) {
2151 case TargetOpcode::CFI_INSTRUCTION:
2153 break;
2154 case TargetOpcode::LOCAL_ESCAPE:
2156 break;
2157 case TargetOpcode::ANNOTATION_LABEL:
2158 case TargetOpcode::GC_LABEL:
2159 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
2160 break;
2161 case TargetOpcode::EH_LABEL:
2162 OutStreamer->AddComment("EH_LABEL");
2163 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
2164 // For AsynchEH, insert a Nop if followed by a trap inst
2165 // Or the exception won't be caught.
2166 // (see MCConstantExpr::create(1,..) in WinException.cpp)
2167 // Ignore SDiv/UDiv because a DIV with Const-0 divisor
2168 // must have being turned into an UndefValue.
2169 // Div with variable opnds won't be the first instruction in
2170 // an EH region as it must be led by at least a Load
2171 {
2172 auto MI2 = std::next(MI.getIterator());
2173 if (IsEHa && MI2 != MBB.end() &&
2174 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
2175 emitNops(1);
2176 }
2177 break;
2178 case TargetOpcode::INLINEASM:
2179 case TargetOpcode::INLINEASM_BR:
2180 emitInlineAsm(&MI);
2181 break;
2182 case TargetOpcode::DBG_VALUE:
2183 case TargetOpcode::DBG_VALUE_LIST:
2184 if (isVerbose()) {
2185 if (!emitDebugValueComment(&MI, *this))
2187 }
2188 break;
2189 case TargetOpcode::DBG_INSTR_REF:
2190 // This instruction reference will have been resolved to a machine
2191 // location, and a nearby DBG_VALUE created. We can safely ignore
2192 // the instruction reference.
2193 break;
2194 case TargetOpcode::DBG_PHI:
2195 // This instruction is only used to label a program point, it's purely
2196 // meta information.
2197 break;
2198 case TargetOpcode::DBG_LABEL:
2199 if (isVerbose()) {
2200 if (!emitDebugLabelComment(&MI, *this))
2202 }
2203 break;
2204 case TargetOpcode::IMPLICIT_DEF:
2205 if (isVerbose()) emitImplicitDef(&MI);
2206 break;
2207 case TargetOpcode::KILL:
2208 if (isVerbose()) emitKill(&MI, *this);
2209 break;
2210 case TargetOpcode::FAKE_USE:
2211 if (isVerbose())
2212 emitFakeUse(&MI, *this);
2213 break;
2214 case TargetOpcode::PSEUDO_PROBE:
2216 break;
2217 case TargetOpcode::ARITH_FENCE:
2218 if (isVerbose())
2219 OutStreamer->emitRawComment("ARITH_FENCE");
2220 break;
2221 case TargetOpcode::MEMBARRIER:
2222 OutStreamer->emitRawComment("MEMBARRIER");
2223 break;
2224 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
2225 // This instruction is only used to note jump table debug info, it's
2226 // purely meta information.
2227 break;
2228 case TargetOpcode::INIT_UNDEF:
2229 // This is only used to influence register allocation behavior, no
2230 // actual initialization is needed.
2231 break;
2232 case TargetOpcode::RELOC_NONE: {
2233 // Generate a temporary label for the current PC.
2234 MCSymbol *Sym = OutContext.createTempSymbol("reloc_none");
2235 OutStreamer->emitLabel(Sym);
2236 const MCExpr *Dot = MCSymbolRefExpr::create(Sym, OutContext);
2238 OutContext.getOrCreateSymbol(MI.getOperand(0).getSymbolName()),
2239 OutContext);
2240 OutStreamer->emitRelocDirective(*Dot, "BFD_RELOC_NONE", Value, SMLoc());
2241 break;
2242 }
2243 default:
2245
2246 auto CountInstruction = [&](const MachineInstr &MI) {
2247 // Skip Meta instructions inside bundles.
2248 if (MI.isMetaInstruction())
2249 return;
2250 ++NumInstsInFunction;
2251 if (CanDoExtraAnalysis) {
2253 ++MnemonicCounts[Name];
2254 }
2255 };
2256 if (!MI.isBundle()) {
2257 CountInstruction(MI);
2258 break;
2259 }
2260 // Separately count all the instructions in a bundle.
2261 for (auto It = std::next(MI.getIterator());
2262 It != MBB.end() && It->isInsideBundle(); ++It) {
2263 CountInstruction(*It);
2264 }
2265 break;
2266 }
2267
2268 if (MI.isCall()) {
2269 if (MF->getTarget().Options.BBAddrMap)
2271 LastCallsiteIndex++;
2272 }
2273
2274 if (TM.Options.EmitCallGraphSection && MI.isCall())
2275 handleCallsiteForCallgraph(FuncCGInfo, CallSitesInfoMap, MI);
2276
2277 // If there is a post-instruction symbol, emit a label for it here.
2278 if (MCSymbol *S = MI.getPostInstrSymbol())
2279 OutStreamer->emitLabel(S);
2280
2281 for (auto &Handler : Handlers)
2282 Handler->endInstruction();
2283 }
2284 // Emit the remaining prefetch targets for this block. This includes
2285 // nonexisting callsite indexes.
2286 while (PrefetchTargetIt != PrefetchTargetEnd) {
2287 emitPrefetchTargetSymbol(MBB.getBBID()->BaseID, *PrefetchTargetIt);
2288 ++PrefetchTargetIt;
2289 }
2290
2291 // We must emit temporary symbol for the end of this basic block, if either
2292 // we have BBLabels enabled or if this basic blocks marks the end of a
2293 // section.
2294 if (MF->getTarget().Options.BBAddrMap ||
2295 (MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection()))
2296 OutStreamer->emitLabel(MBB.getEndSymbol());
2297
2298 if (MBB.isEndSection()) {
2299 // The size directive for the section containing the entry block is
2300 // handled separately by the function section.
2301 if (!MBB.sameSection(&MF->front())) {
2302 if (MAI->hasDotTypeDotSizeDirective()) {
2303 // Emit the size directive for the basic block section.
2304 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2305 MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext),
2306 MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
2307 OutContext);
2308 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
2309 }
2310 assert(!MBBSectionRanges.contains(MBB.getSectionID()) &&
2311 "Overwrite section range");
2312 MBBSectionRanges[MBB.getSectionID()] =
2313 MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
2314 }
2315 }
2317
2318 if (CanDoExtraAnalysis) {
2319 // Skip empty blocks.
2320 if (MBB.empty())
2321 continue;
2322
2324 MBB.begin()->getDebugLoc(), &MBB);
2325
2326 // Generate instruction mix remark. First, sort counts in descending order
2327 // by count and name.
2329 for (auto &KV : MnemonicCounts)
2330 MnemonicVec.emplace_back(KV.first, KV.second);
2331
2332 sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
2333 const std::pair<StringRef, unsigned> &B) {
2334 if (A.second > B.second)
2335 return true;
2336 if (A.second == B.second)
2337 return StringRef(A.first) < StringRef(B.first);
2338 return false;
2339 });
2340 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
2341 for (auto &KV : MnemonicVec) {
2342 auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
2343 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
2344 }
2345 ORE->emit(R);
2346 }
2347 }
2348
2349 EmittedInsts += NumInstsInFunction;
2350 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
2351 MF->getFunction().getSubprogram(),
2352 &MF->front());
2353 R << ore::NV("NumInstructions", NumInstsInFunction)
2354 << " instructions in function";
2355 ORE->emit(R);
2356
2357 // If the function is empty and the object file uses .subsections_via_symbols,
2358 // then we need to emit *something* to the function body to prevent the
2359 // labels from collapsing together. Just emit a noop.
2360 // Similarly, don't emit empty functions on Windows either. It can lead to
2361 // duplicate entries (two functions with the same RVA) in the Guard CF Table
2362 // after linking, causing the kernel not to load the binary:
2363 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
2364 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
2365 const Triple &TT = TM.getTargetTriple();
2366 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
2367 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
2368 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
2369
2370 // Targets can opt-out of emitting the noop here by leaving the opcode
2371 // unspecified.
2372 if (Noop.getOpcode()) {
2373 OutStreamer->AddComment("avoids zero-length function");
2374 emitNops(1);
2375 }
2376 }
2377
2378 // Switch to the original section in case basic block sections was used.
2379 OutStreamer->switchSection(MF->getSection());
2380
2381 const Function &F = MF->getFunction();
2382 for (const auto &BB : F) {
2383 if (!BB.hasAddressTaken())
2384 continue;
2385 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
2386 if (Sym->isDefined())
2387 continue;
2388 OutStreamer->AddComment("Address of block that was removed by CodeGen");
2389 OutStreamer->emitLabel(Sym);
2390 }
2391
2392 // Emit target-specific gunk after the function body.
2394
2395 // Even though wasm supports .type and .size in general, function symbols
2396 // are automatically sized.
2397 bool EmitFunctionSize = MAI->hasDotTypeDotSizeDirective() && !TT.isWasm();
2398
2399 // SPIR-V supports label instructions only inside a block, not after the
2400 // function body.
2401 if (TT.getObjectFormat() != Triple::SPIRV &&
2402 (EmitFunctionSize || needFuncLabels(*MF, *this))) {
2403 // Create a symbol for the end of function.
2404 CurrentFnEnd = createTempSymbol("func_end");
2405 OutStreamer->emitLabel(CurrentFnEnd);
2406 }
2407
2408 // If the target wants a .size directive for the size of the function, emit
2409 // it.
2410 if (EmitFunctionSize) {
2411 // We can get the size as difference between the function label and the
2412 // temp label.
2413 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2414 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
2416 OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
2418 OutStreamer->emitELFSize(CurrentFnBeginLocal, SizeExp);
2419 }
2420
2421 // Call endBasicBlockSection on the last block now, if it wasn't already
2422 // called.
2423 if (!MF->back().isEndSection()) {
2424 for (auto &Handler : Handlers)
2425 Handler->endBasicBlockSection(MF->back());
2426 for (auto &Handler : EHHandlers)
2427 Handler->endBasicBlockSection(MF->back());
2428 }
2429 for (auto &Handler : Handlers)
2430 Handler->markFunctionEnd();
2431 for (auto &Handler : EHHandlers)
2432 Handler->markFunctionEnd();
2433 // Update the end label of the entry block's section.
2434 MBBSectionRanges[MF->front().getSectionID()].EndLabel = CurrentFnEnd;
2435
2436 // Print out jump tables referenced by the function.
2438
2439 // Emit post-function debug and/or EH information.
2440 for (auto &Handler : Handlers)
2441 Handler->endFunction(MF);
2442 for (auto &Handler : EHHandlers)
2443 Handler->endFunction(MF);
2444
2445 // Emit section containing BB address offsets and their metadata, when
2446 // BB labels are requested for this function. Skip empty functions.
2447 if (HasAnyRealCode) {
2448 if (MF->getTarget().Options.BBAddrMap)
2450 else if (PgoAnalysisMapFeatures.getBits() != 0)
2451 MF->getContext().reportWarning(
2452 SMLoc(), "pgo-analysis-map is enabled for function " + MF->getName() +
2453 " but it does not have labels");
2454 }
2455
2456 // Emit sections containing instruction and function PCs.
2458
2459 // Emit section containing stack size metadata.
2461
2462 // Emit section containing call graph metadata.
2463 emitCallGraphSection(*MF, FuncCGInfo);
2464
2465 // Emit .su file containing function stack size information.
2467
2469
2470 if (isVerbose())
2471 OutStreamer->getCommentOS() << "-- End function\n";
2472
2473 OutStreamer->addBlankLine();
2474}
2475
2476/// Compute the number of Global Variables that uses a Constant.
2477static unsigned getNumGlobalVariableUses(const Constant *C,
2478 bool &HasNonGlobalUsers) {
2479 if (!C) {
2480 HasNonGlobalUsers = true;
2481 return 0;
2482 }
2483
2485 return 1;
2486
2487 unsigned NumUses = 0;
2488 for (const auto *CU : C->users())
2489 NumUses +=
2490 getNumGlobalVariableUses(dyn_cast<Constant>(CU), HasNonGlobalUsers);
2491
2492 return NumUses;
2493}
2494
2495/// Only consider global GOT equivalents if at least one user is a
2496/// cstexpr inside an initializer of another global variables. Also, don't
2497/// handle cstexpr inside instructions. During global variable emission,
2498/// candidates are skipped and are emitted later in case at least one cstexpr
2499/// isn't replaced by a PC relative GOT entry access.
2501 unsigned &NumGOTEquivUsers,
2502 bool &HasNonGlobalUsers) {
2503 // Global GOT equivalents are unnamed private globals with a constant
2504 // pointer initializer to another global symbol. They must point to a
2505 // GlobalVariable or Function, i.e., as GlobalValue.
2506 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
2507 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
2509 return false;
2510
2511 // To be a got equivalent, at least one of its users need to be a constant
2512 // expression used by another global variable.
2513 for (const auto *U : GV->users())
2514 NumGOTEquivUsers +=
2515 getNumGlobalVariableUses(dyn_cast<Constant>(U), HasNonGlobalUsers);
2516
2517 return NumGOTEquivUsers > 0;
2518}
2519
2520/// Unnamed constant global variables solely contaning a pointer to
2521/// another globals variable is equivalent to a GOT table entry; it contains the
2522/// the address of another symbol. Optimize it and replace accesses to these
2523/// "GOT equivalents" by using the GOT entry for the final global instead.
2524/// Compute GOT equivalent candidates among all global variables to avoid
2525/// emitting them if possible later on, after it use is replaced by a GOT entry
2526/// access.
2528 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2529 return;
2530
2531 for (const auto &G : M.globals()) {
2532 unsigned NumGOTEquivUsers = 0;
2533 bool HasNonGlobalUsers = false;
2534 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers, HasNonGlobalUsers))
2535 continue;
2536 // If non-global variables use it, we still need to emit it.
2537 // Add 1 here, then emit it in `emitGlobalGOTEquivs`.
2538 if (HasNonGlobalUsers)
2539 NumGOTEquivUsers += 1;
2540 const MCSymbol *GOTEquivSym = getSymbol(&G);
2541 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
2542 }
2543}
2544
2545/// Constant expressions using GOT equivalent globals may not be eligible
2546/// for PC relative GOT entry conversion, in such cases we need to emit such
2547/// globals we previously omitted in EmitGlobalVariable.
2549 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2550 return;
2551
2553 for (auto &I : GlobalGOTEquivs) {
2554 const GlobalVariable *GV = I.second.first;
2555 unsigned Cnt = I.second.second;
2556 if (Cnt)
2557 FailedCandidates.push_back(GV);
2558 }
2559 GlobalGOTEquivs.clear();
2560
2561 for (const auto *GV : FailedCandidates)
2563}
2564
2566 MCSymbol *Name = getSymbol(&GA);
2567 const GlobalObject *BaseObject = GA.getAliaseeObject();
2568
2569 bool IsFunction = GA.getValueType()->isFunctionTy();
2570 // Treat bitcasts of functions as functions also. This is important at least
2571 // on WebAssembly where object and function addresses can't alias each other.
2572 if (!IsFunction)
2573 IsFunction = isa_and_nonnull<Function>(BaseObject);
2574
2575 // AIX's assembly directive `.set` is not usable for aliasing purpose,
2576 // so AIX has to use the extra-label-at-definition strategy. At this
2577 // point, all the extra label is emitted, we just have to emit linkage for
2578 // those labels.
2579 if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
2580 // Linkage for alias of global variable has been emitted.
2581 if (isa_and_nonnull<GlobalVariable>(BaseObject))
2582 return;
2583
2584 emitLinkage(&GA, Name);
2585 // If it's a function, also emit linkage for aliases of function entry
2586 // point.
2587 if (IsFunction)
2588 emitLinkage(&GA,
2589 getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
2590 return;
2591 }
2592
2593 if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
2594 OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
2595 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
2596 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
2597 else
2598 assert(GA.hasLocalLinkage() && "Invalid alias linkage");
2599
2600 // Set the symbol type to function if the alias has a function type.
2601 // This affects codegen when the aliasee is not a function.
2602 if (IsFunction) {
2603 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
2604 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
2605 OutStreamer->beginCOFFSymbolDef(Name);
2606 OutStreamer->emitCOFFSymbolStorageClass(
2611 OutStreamer->endCOFFSymbolDef();
2612 }
2613 }
2614
2615 emitVisibility(Name, GA.getVisibility());
2616
2617 const MCExpr *Expr = lowerConstant(GA.getAliasee());
2618
2619 if (MAI->isMachO() && isa<MCBinaryExpr>(Expr))
2620 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
2621
2622 // Emit the directives as assignments aka .set:
2623 OutStreamer->emitAssignment(Name, Expr);
2624 MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
2625 if (LocalAlias != Name)
2626 OutStreamer->emitAssignment(LocalAlias, Expr);
2627
2628 // If the aliasee does not correspond to a symbol in the output, i.e. the
2629 // alias is not of an object or the aliased object is private, then set the
2630 // size of the alias symbol from the type of the alias. We don't do this in
2631 // other situations as the alias and aliasee having differing types but same
2632 // size may be intentional.
2633 if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
2634 (!BaseObject || BaseObject->hasPrivateLinkage())) {
2635 const DataLayout &DL = M.getDataLayout();
2636 uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
2637 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
2638 }
2639}
2640
2641void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
2642 auto EmitLinkage = [&](MCSymbol *Sym) {
2644 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
2645 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
2646 OutStreamer->emitSymbolAttribute(Sym, MCSA_WeakReference);
2647 else
2648 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
2649 };
2650
2652 MCSymbol *Name = getSymbol(&GI);
2653 EmitLinkage(Name);
2654 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
2655 emitVisibility(Name, GI.getVisibility());
2656
2657 // Emit the directives as assignments aka .set:
2658 const MCExpr *Expr = lowerConstant(GI.getResolver());
2659 OutStreamer->emitAssignment(Name, Expr);
2660 MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
2661 if (LocalAlias != Name)
2662 OutStreamer->emitAssignment(LocalAlias, Expr);
2663
2664 return;
2665 }
2666
2667 if (!TM.getTargetTriple().isOSBinFormatMachO() || !getIFuncMCSubtargetInfo())
2668 reportFatalUsageError("IFuncs are not supported on this platform");
2669
2670 // On Darwin platforms, emit a manually-constructed .symbol_resolver that
2671 // implements the symbol resolution duties of the IFunc.
2672 //
2673 // Normally, this would be handled by linker magic, but unfortunately there
2674 // are a few limitations in ld64 and ld-prime's implementation of
2675 // .symbol_resolver that mean we can't always use them:
2676 //
2677 // * resolvers cannot be the target of an alias
2678 // * resolvers cannot have private linkage
2679 // * resolvers cannot have linkonce linkage
2680 // * resolvers cannot appear in executables
2681 // * resolvers cannot appear in bundles
2682 //
2683 // This works around that by emitting a close approximation of what the
2684 // linker would have done.
2685
2686 MCSymbol *LazyPointer =
2687 GetExternalSymbolSymbol(GI.getName() + ".lazy_pointer");
2688 MCSymbol *StubHelper = GetExternalSymbolSymbol(GI.getName() + ".stub_helper");
2689
2690 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
2691
2692 const DataLayout &DL = M.getDataLayout();
2693 emitAlignment(Align(DL.getPointerSize()));
2694 OutStreamer->emitLabel(LazyPointer);
2695 emitVisibility(LazyPointer, GI.getVisibility());
2696 OutStreamer->emitValue(MCSymbolRefExpr::create(StubHelper, OutContext), 8);
2697
2698 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getTextSection());
2699
2700 const TargetSubtargetInfo *STI =
2701 TM.getSubtargetImpl(*GI.getResolverFunction());
2702 const TargetLowering *TLI = STI->getTargetLowering();
2703 Align TextAlign(TLI->getMinFunctionAlignment());
2704
2705 MCSymbol *Stub = getSymbol(&GI);
2706 EmitLinkage(Stub);
2707 OutStreamer->emitCodeAlignment(TextAlign, getIFuncMCSubtargetInfo());
2708 OutStreamer->emitLabel(Stub);
2709 emitVisibility(Stub, GI.getVisibility());
2710 emitMachOIFuncStubBody(M, GI, LazyPointer);
2711
2712 OutStreamer->emitCodeAlignment(TextAlign, getIFuncMCSubtargetInfo());
2713 OutStreamer->emitLabel(StubHelper);
2714 emitVisibility(StubHelper, GI.getVisibility());
2715 emitMachOIFuncStubHelperBody(M, GI, LazyPointer);
2716}
2717
2719 if (!RS.wantsSection())
2720 return;
2721 if (!RS.getFilename())
2722 return;
2723
2724 MCSection *RemarksSection =
2725 OutContext.getObjectFileInfo()->getRemarksSection();
2726 if (!RemarksSection && RS.needsSection()) {
2727 OutContext.reportWarning(SMLoc(), "Current object file format does not "
2728 "support remarks sections.");
2729 }
2730 if (!RemarksSection)
2731 return;
2732
2733 SmallString<128> Filename = *RS.getFilename();
2735 assert(!Filename.empty() && "The filename can't be empty.");
2736
2737 std::string Buf;
2738 raw_string_ostream OS(Buf);
2739
2740 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
2741 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2742 RemarkSerializer.metaSerializer(OS, Filename);
2743 MetaSerializer->emit();
2744
2745 // Switch to the remarks section.
2746 OutStreamer->switchSection(RemarksSection);
2747 OutStreamer->emitBinaryData(Buf);
2748}
2749
2751 const Constant *Initializer = G.getInitializer();
2752 return G.getParent()->getDataLayout().getTypeAllocSize(
2753 Initializer->getType());
2754}
2755
2757 // We used to do this in clang, but there are optimization passes that turn
2758 // non-constant globals into constants. So now, clang only tells us whether
2759 // it would *like* a global to be tagged, but we still make the decision here.
2760 //
2761 // For now, don't instrument constant data, as it'll be in .rodata anyway. It
2762 // may be worth instrumenting these in future to stop them from being used as
2763 // gadgets.
2764 if (G.getName().starts_with("llvm.") || G.isThreadLocal() || G.isConstant())
2765 return false;
2766
2767 // Globals can be placed implicitly or explicitly in sections. There's two
2768 // different types of globals that meet this criteria that cause problems:
2769 // 1. Function pointers that are going into various init arrays (either
2770 // explicitly through `__attribute__((section(<foo>)))` or implicitly
2771 // through `__attribute__((constructor)))`, such as ".(pre)init(_array)",
2772 // ".fini(_array)", ".ctors", and ".dtors". These function pointers end up
2773 // overaligned and overpadded, making iterating over them problematic, and
2774 // each function pointer is individually tagged (so the iteration over
2775 // them causes SIGSEGV/MTE[AS]ERR).
2776 // 2. Global variables put into an explicit section, where the section's name
2777 // is a valid C-style identifier. The linker emits a `__start_<name>` and
2778 // `__stop_<name>` symbol for the section, so that you can iterate over
2779 // globals within this section. Unfortunately, again, these globals would
2780 // be tagged and so iteration causes SIGSEGV/MTE[AS]ERR.
2781 //
2782 // To mitigate both these cases, and because specifying a section is rare
2783 // outside of these two cases, disable MTE protection for globals in any
2784 // section.
2785 if (G.hasSection())
2786 return false;
2787
2788 return globalSize(G) > 0;
2789}
2790
2792 uint64_t SizeInBytes = globalSize(*G);
2793
2794 uint64_t NewSize = alignTo(SizeInBytes, 16);
2795 if (SizeInBytes != NewSize) {
2796 // Pad the initializer out to the next multiple of 16 bytes.
2797 llvm::SmallVector<uint8_t> Init(NewSize - SizeInBytes, 0);
2798 Constant *Padding = ConstantDataArray::get(M.getContext(), Init);
2799 Constant *Initializer = G->getInitializer();
2800 Initializer = ConstantStruct::getAnon({Initializer, Padding});
2801 auto *NewGV = new GlobalVariable(
2802 M, Initializer->getType(), G->isConstant(), G->getLinkage(),
2803 Initializer, "", G, G->getThreadLocalMode(), G->getAddressSpace());
2804 NewGV->copyAttributesFrom(G);
2805 NewGV->setComdat(G->getComdat());
2806 NewGV->copyMetadata(G, 0);
2807
2808 NewGV->takeName(G);
2809 G->replaceAllUsesWith(NewGV);
2810 G->eraseFromParent();
2811 G = NewGV;
2812 }
2813
2814 if (G->getAlign().valueOrOne() < 16)
2815 G->setAlignment(Align(16));
2816
2817 // Ensure that tagged globals don't get merged by ICF - as they should have
2818 // different tags at runtime.
2819 G->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2820}
2821
2823 auto Meta = G.getSanitizerMetadata();
2824 Meta.Memtag = false;
2825 G.setSanitizerMetadata(Meta);
2826}
2827
2829 // Set the MachineFunction to nullptr so that we can catch attempted
2830 // accesses to MF specific features at the module level and so that
2831 // we can conditionalize accesses based on whether or not it is nullptr.
2832 MF = nullptr;
2833 const Triple &Target = TM.getTargetTriple();
2834
2835 std::vector<GlobalVariable *> GlobalsToTag;
2836 for (GlobalVariable &G : M.globals()) {
2837 if (G.isDeclaration() || !G.isTagged())
2838 continue;
2839 if (!shouldTagGlobal(G)) {
2840 assert(G.hasSanitizerMetadata()); // because isTagged.
2842 assert(!G.isTagged());
2843 continue;
2844 }
2845 GlobalsToTag.push_back(&G);
2846 }
2847 for (GlobalVariable *G : GlobalsToTag)
2849
2850 // Gather all GOT equivalent globals in the module. We really need two
2851 // passes over the globals: one to compute and another to avoid its emission
2852 // in EmitGlobalVariable, otherwise we would not be able to handle cases
2853 // where the got equivalent shows up before its use.
2855
2856 // Emit global variables.
2857 for (const auto &G : M.globals())
2859
2860 // Emit remaining GOT equivalent globals.
2862
2864
2865 // Emit linkage(XCOFF) and visibility info for declarations
2866 for (const Function &F : M) {
2867 if (!F.isDeclarationForLinker())
2868 continue;
2869
2870 MCSymbol *Name = getSymbol(&F);
2871 // Function getSymbol gives us the function descriptor symbol for XCOFF.
2872
2873 if (!Target.isOSBinFormatXCOFF()) {
2874 GlobalValue::VisibilityTypes V = F.getVisibility();
2876 continue;
2877
2878 emitVisibility(Name, V, false);
2879 continue;
2880 }
2881
2882 if (F.isIntrinsic())
2883 continue;
2884
2885 // Handle the XCOFF case.
2886 // Variable `Name` is the function descriptor symbol (see above). Get the
2887 // function entry point symbol.
2888 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
2889 // Emit linkage for the function entry point.
2890 emitLinkage(&F, FnEntryPointSym);
2891
2892 // If a function's address is taken, which means it may be called via a
2893 // function pointer, we need the function descriptor for it.
2894 if (F.hasAddressTaken())
2895 emitLinkage(&F, Name);
2896 }
2897
2898 // Emit the remarks section contents.
2899 // FIXME: Figure out when is the safest time to emit this section. It should
2900 // not come after debug info.
2901 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
2902 emitRemarksSection(*RS);
2903
2905
2906 if (Target.isOSBinFormatELF()) {
2907 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
2908
2909 // Output stubs for external and common global variables.
2911 if (!Stubs.empty()) {
2912 OutStreamer->switchSection(TLOF.getDataSection());
2913 const DataLayout &DL = M.getDataLayout();
2914
2915 emitAlignment(Align(DL.getPointerSize()));
2916 for (const auto &Stub : Stubs) {
2917 OutStreamer->emitLabel(Stub.first);
2918 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2919 DL.getPointerSize());
2920 }
2921 }
2922 }
2923
2924 if (Target.isOSBinFormatCOFF()) {
2925 MachineModuleInfoCOFF &MMICOFF =
2926 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
2927
2928 // Output stubs for external and common global variables.
2930 if (!Stubs.empty()) {
2931 const DataLayout &DL = M.getDataLayout();
2932
2933 for (const auto &Stub : Stubs) {
2935 SectionName += Stub.first->getName();
2936 OutStreamer->switchSection(OutContext.getCOFFSection(
2940 Stub.first->getName(), COFF::IMAGE_COMDAT_SELECT_ANY));
2941 emitAlignment(Align(DL.getPointerSize()));
2942 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
2943 OutStreamer->emitLabel(Stub.first);
2944 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2945 DL.getPointerSize());
2946 }
2947 }
2948 }
2949
2950 // This needs to happen before emitting debug information since that can end
2951 // arbitrary sections.
2952 if (auto *TS = OutStreamer->getTargetStreamer())
2953 TS->emitConstantPools();
2954
2955 // Emit Stack maps before any debug info. Mach-O requires that no data or
2956 // text sections come after debug info has been emitted. This matters for
2957 // stack maps as they are arbitrary data, and may even have a custom format
2958 // through user plugins.
2959 EmitStackMaps(M);
2960
2961 // Print aliases in topological order, that is, for each alias a = b,
2962 // b must be printed before a.
2963 // This is because on some targets (e.g. PowerPC) linker expects aliases in
2964 // such an order to generate correct TOC information.
2967 for (const auto &Alias : M.aliases()) {
2968 if (Alias.hasAvailableExternallyLinkage())
2969 continue;
2970 for (const GlobalAlias *Cur = &Alias; Cur;
2971 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
2972 if (!AliasVisited.insert(Cur).second)
2973 break;
2974 AliasStack.push_back(Cur);
2975 }
2976 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
2977 emitGlobalAlias(M, *AncestorAlias);
2978 AliasStack.clear();
2979 }
2980
2981 // IFuncs must come before deubginfo in case the backend decides to emit them
2982 // as actual functions, since on Mach-O targets, we cannot create regular
2983 // sections after DWARF.
2984 for (const auto &IFunc : M.ifuncs())
2985 emitGlobalIFunc(M, IFunc);
2986 if (TM.getTargetTriple().isOSBinFormatXCOFF() && hasDebugInfo()) {
2987 // Emit section end. This is used to tell the debug line section where the
2988 // end is for a text section if we don't use .loc to represent the debug
2989 // line.
2990 auto *Sec = OutContext.getObjectFileInfo()->getTextSection();
2991 OutStreamer->switchSectionNoPrint(Sec);
2992 MCSymbol *Sym = Sec->getEndSymbol(OutContext);
2993 OutStreamer->emitLabel(Sym);
2994 }
2995
2996 // Finalize debug and EH information.
2997 for (auto &Handler : Handlers)
2998 Handler->endModule();
2999 for (auto &Handler : EHHandlers)
3000 Handler->endModule();
3001
3002 // This deletes all the ephemeral handlers that AsmPrinter added, while
3003 // keeping all the user-added handlers alive until the AsmPrinter is
3004 // destroyed.
3005 EHHandlers.clear();
3006 Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
3007 DD = nullptr;
3008
3009 // If the target wants to know about weak references, print them all.
3010 if (MAI->getWeakRefDirective()) {
3011 // FIXME: This is not lazy, it would be nice to only print weak references
3012 // to stuff that is actually used. Note that doing so would require targets
3013 // to notice uses in operands (due to constant exprs etc). This should
3014 // happen with the MC stuff eventually.
3015
3016 // Print out module-level global objects here.
3017 for (const auto &GO : M.global_objects()) {
3018 if (!GO.hasExternalWeakLinkage())
3019 continue;
3020 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
3021 }
3023 auto SymbolName = "swift_async_extendedFramePointerFlags";
3024 auto Global = M.getGlobalVariable(SymbolName);
3025 if (!Global) {
3026 auto PtrTy = PointerType::getUnqual(M.getContext());
3027 Global = new GlobalVariable(M, PtrTy, false,
3029 SymbolName);
3030 OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
3031 }
3032 }
3033 }
3034
3036
3037 // Emit llvm.ident metadata in an '.ident' directive.
3038 emitModuleIdents(M);
3039
3040 // Emit bytes for llvm.commandline metadata.
3041 // The command line metadata is emitted earlier on XCOFF.
3042 if (!Target.isOSBinFormatXCOFF())
3043 emitModuleCommandLines(M);
3044
3045 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
3046 // split-stack is used.
3047 if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
3048 OutStreamer->switchSection(OutContext.getELFSection(".note.GNU-split-stack",
3049 ELF::SHT_PROGBITS, 0));
3050 if (HasNoSplitStack)
3051 OutStreamer->switchSection(OutContext.getELFSection(
3052 ".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
3053 }
3054
3055 // If we don't have any trampolines, then we don't require stack memory
3056 // to be executable. Some targets have a directive to declare this.
3057 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
3058 bool HasTrampolineUses =
3059 InitTrampolineIntrinsic && !InitTrampolineIntrinsic->use_empty();
3060 MCSection *S = MAI->getStackSection(OutContext, /*Exec=*/HasTrampolineUses);
3061 if (S)
3062 OutStreamer->switchSection(S);
3063
3064 if (TM.Options.EmitAddrsig) {
3065 // Emit address-significance attributes for all globals.
3066 OutStreamer->emitAddrsig();
3067 for (const GlobalValue &GV : M.global_values()) {
3068 if (!GV.use_empty() && !GV.isThreadLocal() &&
3069 !GV.hasDLLImportStorageClass() &&
3070 !GV.getName().starts_with("llvm.") &&
3071 !GV.hasAtLeastLocalUnnamedAddr())
3072 OutStreamer->emitAddrsigSym(getSymbol(&GV));
3073 }
3074 }
3075
3076 // Emit symbol partition specifications (ELF only).
3077 if (Target.isOSBinFormatELF()) {
3078 unsigned UniqueID = 0;
3079 for (const GlobalValue &GV : M.global_values()) {
3080 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
3081 GV.getVisibility() != GlobalValue::DefaultVisibility)
3082 continue;
3083
3084 OutStreamer->switchSection(
3085 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
3086 "", false, ++UniqueID, nullptr));
3087 OutStreamer->emitBytes(GV.getPartition());
3088 OutStreamer->emitZeros(1);
3089 OutStreamer->emitValue(
3091 MAI->getCodePointerSize());
3092 }
3093 }
3094
3095 // Allow the target to emit any magic that it wants at the end of the file,
3096 // after everything else has gone out.
3098
3099 MMI = nullptr;
3100 AddrLabelSymbols = nullptr;
3101
3102 OutStreamer->finish();
3103 OutStreamer->reset();
3104 OwnedMLI.reset();
3105 OwnedMDT.reset();
3106
3107 return false;
3108}
3109
3111 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionID());
3112 if (Res.second)
3113 Res.first->second = createTempSymbol("exception");
3114 return Res.first->second;
3115}
3116
3118 MCContext &Ctx = MF->getContext();
3119 MCSymbol *Sym = Ctx.createTempSymbol("BB" + Twine(MF->getFunctionNumber()) +
3120 "_" + Twine(MBB.getNumber()) + "_CS");
3121 CurrentFnCallsiteEndSymbols[&MBB].push_back(Sym);
3122 return Sym;
3123}
3124
3126 this->MF = &MF;
3127 const Function &F = MF.getFunction();
3128
3129 // Record that there are split-stack functions, so we will emit a special
3130 // section to tell the linker.
3131 if (MF.shouldSplitStack()) {
3132 HasSplitStack = true;
3133
3134 if (!MF.getFrameInfo().needsSplitStackProlog())
3135 HasNoSplitStack = true;
3136 } else
3137 HasNoSplitStack = true;
3138
3139 // Get the function symbol.
3140 if (!MAI->isAIX()) {
3141 CurrentFnSym = getSymbol(&MF.getFunction());
3142 } else {
3143 assert(TM.getTargetTriple().isOSAIX() &&
3144 "Only AIX uses the function descriptor hooks.");
3145 // AIX is unique here in that the name of the symbol emitted for the
3146 // function body does not have the same name as the source function's
3147 // C-linkage name.
3148 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
3149 " initalized first.");
3150
3151 // Get the function entry point symbol.
3153 }
3154
3156 CurrentFnBegin = nullptr;
3157 CurrentFnBeginLocal = nullptr;
3158 CurrentSectionBeginSym = nullptr;
3160 MBBSectionRanges.clear();
3161 MBBSectionExceptionSyms.clear();
3162 bool NeedsLocalForSize = MAI->needsLocalForSize();
3163 if (F.hasFnAttribute("patchable-function-entry") ||
3164 F.hasFnAttribute("function-instrument") ||
3165 F.hasFnAttribute("xray-instruction-threshold") ||
3166 needFuncLabels(MF, *this) || NeedsLocalForSize ||
3167 MF.getTarget().Options.EmitStackSizeSection ||
3168 MF.getTarget().Options.EmitCallGraphSection ||
3169 MF.getTarget().Options.BBAddrMap) {
3170 CurrentFnBegin = createTempSymbol("func_begin");
3171 if (NeedsLocalForSize)
3173 }
3174
3175 ORE = GetORE(MF);
3176}
3177
3178namespace {
3179
3180// Keep track the alignment, constpool entries per Section.
3181 struct SectionCPs {
3182 MCSection *S;
3183 Align Alignment;
3185
3186 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
3187 };
3188
3189} // end anonymous namespace
3190
3192 if (TM.Options.EnableStaticDataPartitioning && C && SDPI && PSI)
3193 return SDPI->getConstantSectionPrefix(C, PSI);
3194
3195 return "";
3196}
3197
3198/// EmitConstantPool - Print to the current output stream assembly
3199/// representations of the constants in the constant pool MCP. This is
3200/// used to print out constants which have been "spilled to memory" by
3201/// the code generator.
3203 const MachineConstantPool *MCP = MF->getConstantPool();
3204 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
3205 if (CP.empty()) return;
3206
3207 // Calculate sections for constant pool entries. We collect entries to go into
3208 // the same section together to reduce amount of section switch statements.
3209 SmallVector<SectionCPs, 4> CPSections;
3210 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
3211 const MachineConstantPoolEntry &CPE = CP[i];
3212 Align Alignment = CPE.getAlign();
3213
3215
3216 const Constant *C = nullptr;
3217 if (!CPE.isMachineConstantPoolEntry())
3218 C = CPE.Val.ConstVal;
3219
3221 getDataLayout(), Kind, C, Alignment, &MF->getFunction(),
3223
3224 // The number of sections are small, just do a linear search from the
3225 // last section to the first.
3226 bool Found = false;
3227 unsigned SecIdx = CPSections.size();
3228 while (SecIdx != 0) {
3229 if (CPSections[--SecIdx].S == S) {
3230 Found = true;
3231 break;
3232 }
3233 }
3234 if (!Found) {
3235 SecIdx = CPSections.size();
3236 CPSections.push_back(SectionCPs(S, Alignment));
3237 }
3238
3239 if (Alignment > CPSections[SecIdx].Alignment)
3240 CPSections[SecIdx].Alignment = Alignment;
3241 CPSections[SecIdx].CPEs.push_back(i);
3242 }
3243
3244 // Now print stuff into the calculated sections.
3245 const MCSection *CurSection = nullptr;
3246 unsigned Offset = 0;
3247 for (const SectionCPs &CPSection : CPSections) {
3248 for (unsigned CPI : CPSection.CPEs) {
3249 MCSymbol *Sym = GetCPISymbol(CPI);
3250 if (!Sym->isUndefined())
3251 continue;
3252
3253 if (CurSection != CPSection.S) {
3254 OutStreamer->switchSection(CPSection.S);
3255 emitAlignment(Align(CPSection.Alignment));
3256 CurSection = CPSection.S;
3257 Offset = 0;
3258 }
3259
3260 MachineConstantPoolEntry CPE = CP[CPI];
3261
3262 // Emit inter-object padding for alignment.
3263 unsigned NewOffset = alignTo(Offset, CPE.getAlign());
3264 OutStreamer->emitZeros(NewOffset - Offset);
3265
3266 Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
3267
3268 OutStreamer->emitLabel(Sym);
3271 else
3273 }
3274 }
3275}
3276
3277// Print assembly representations of the jump tables used by the current
3278// function.
3280 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
3281 if (!MJTI) return;
3282
3283 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
3284 if (JT.empty()) return;
3285
3286 if (!TM.Options.EnableStaticDataPartitioning) {
3287 emitJumpTableImpl(*MJTI, llvm::to_vector(llvm::seq<unsigned>(JT.size())));
3288 return;
3289 }
3290
3291 SmallVector<unsigned> HotJumpTableIndices, ColdJumpTableIndices;
3292 // When static data partitioning is enabled, collect jump table entries that
3293 // go into the same section together to reduce the amount of section switch
3294 // statements.
3295 for (unsigned JTI = 0, JTSize = JT.size(); JTI < JTSize; ++JTI) {
3296 if (JT[JTI].Hotness == MachineFunctionDataHotness::Cold) {
3297 ColdJumpTableIndices.push_back(JTI);
3298 } else {
3299 HotJumpTableIndices.push_back(JTI);
3300 }
3301 }
3302
3303 emitJumpTableImpl(*MJTI, HotJumpTableIndices);
3304 emitJumpTableImpl(*MJTI, ColdJumpTableIndices);
3305}
3306
3307void AsmPrinter::emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
3308 ArrayRef<unsigned> JumpTableIndices) {
3310 JumpTableIndices.empty())
3311 return;
3312
3314 const Function &F = MF->getFunction();
3315 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3316 MCSection *JumpTableSection = nullptr;
3317
3318 const bool UseLabelDifference =
3321 // Pick the directive to use to print the jump table entries, and switch to
3322 // the appropriate section.
3323 const bool JTInDiffSection =
3324 !TLOF.shouldPutJumpTableInFunctionSection(UseLabelDifference, F);
3325 if (JTInDiffSection) {
3327 JumpTableSection =
3328 TLOF.getSectionForJumpTable(F, TM, &JT[JumpTableIndices.front()]);
3329 } else {
3330 JumpTableSection = TLOF.getSectionForJumpTable(F, TM);
3331 }
3332 OutStreamer->switchSection(JumpTableSection);
3333 }
3334
3335 const DataLayout &DL = MF->getDataLayout();
3337
3338 // Jump tables in code sections are marked with a data_region directive
3339 // where that's supported.
3340 if (!JTInDiffSection)
3341 OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
3342
3343 for (const unsigned JumpTableIndex : JumpTableIndices) {
3344 ArrayRef<MachineBasicBlock *> JTBBs = JT[JumpTableIndex].MBBs;
3345
3346 // If this jump table was deleted, ignore it.
3347 if (JTBBs.empty())
3348 continue;
3349
3350 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
3351 /// emit a .set directive for each unique entry.
3353 MAI->doesSetDirectiveSuppressReloc()) {
3354 SmallPtrSet<const MachineBasicBlock *, 16> EmittedSets;
3355 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3356 const MCExpr *Base =
3357 TLI->getPICJumpTableRelocBaseExpr(MF, JumpTableIndex, OutContext);
3358 for (const MachineBasicBlock *MBB : JTBBs) {
3359 if (!EmittedSets.insert(MBB).second)
3360 continue;
3361
3362 // .set LJTSet, LBB32-base
3363 const MCExpr *LHS =
3365 OutStreamer->emitAssignment(
3366 GetJTSetSymbol(JumpTableIndex, MBB->getNumber()),
3368 }
3369 }
3370
3371 // On some targets (e.g. Darwin) we want to emit two consecutive labels
3372 // before each jump table. The first label is never referenced, but tells
3373 // the assembler and linker the extents of the jump table object. The
3374 // second label is actually referenced by the code.
3375 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
3376 // FIXME: This doesn't have to have any specific name, just any randomly
3377 // named and numbered local label started with 'l' would work. Simplify
3378 // GetJTISymbol.
3379 OutStreamer->emitLabel(GetJTISymbol(JumpTableIndex, true));
3380
3381 MCSymbol *JTISymbol = GetJTISymbol(JumpTableIndex);
3382 OutStreamer->emitLabel(JTISymbol);
3383
3384 // Defer MCAssembler based constant folding due to a performance issue. The
3385 // label differences will be evaluated at write time.
3386 for (const MachineBasicBlock *MBB : JTBBs)
3387 emitJumpTableEntry(MJTI, MBB, JumpTableIndex);
3388 }
3389
3391 emitJumpTableSizesSection(MJTI, MF->getFunction());
3392
3393 if (!JTInDiffSection)
3394 OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
3395}
3396
3397void AsmPrinter::emitJumpTableSizesSection(const MachineJumpTableInfo &MJTI,
3398 const Function &F) const {
3399 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3400
3401 if (JT.empty())
3402 return;
3403
3404 StringRef GroupName = F.hasComdat() ? F.getComdat()->getName() : "";
3405 MCSection *JumpTableSizesSection = nullptr;
3406 StringRef sectionName = ".llvm_jump_table_sizes";
3407
3408 bool isElf = TM.getTargetTriple().isOSBinFormatELF();
3409 bool isCoff = TM.getTargetTriple().isOSBinFormatCOFF();
3410
3411 if (!isCoff && !isElf)
3412 return;
3413
3414 if (isElf) {
3415 auto *LinkedToSym = static_cast<MCSymbolELF *>(CurrentFnSym);
3416 int Flags = F.hasComdat() ? static_cast<int>(ELF::SHF_GROUP) : 0;
3417
3418 JumpTableSizesSection = OutContext.getELFSection(
3419 sectionName, ELF::SHT_LLVM_JT_SIZES, Flags, 0, GroupName, F.hasComdat(),
3420 MCSection::NonUniqueID, LinkedToSym);
3421 } else if (isCoff) {
3422 if (F.hasComdat()) {
3423 JumpTableSizesSection = OutContext.getCOFFSection(
3424 sectionName,
3427 F.getComdat()->getName(), COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
3428 } else {
3429 JumpTableSizesSection = OutContext.getCOFFSection(
3433 }
3434 }
3435
3436 OutStreamer->switchSection(JumpTableSizesSection);
3437
3438 for (unsigned JTI = 0, E = JT.size(); JTI != E; ++JTI) {
3439 const std::vector<MachineBasicBlock *> &JTBBs = JT[JTI].MBBs;
3440 OutStreamer->emitSymbolValue(GetJTISymbol(JTI), TM.getProgramPointerSize());
3441 OutStreamer->emitIntValue(JTBBs.size(), TM.getProgramPointerSize());
3442 }
3443}
3444
3445/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
3446/// current stream.
3448 const MachineBasicBlock *MBB,
3449 unsigned UID) const {
3450 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
3451 const MCExpr *Value = nullptr;
3452 switch (MJTI.getEntryKind()) {
3454 llvm_unreachable("Cannot emit EK_Inline jump table entry");
3457 llvm_unreachable("MIPS specific");
3459 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
3460 &MJTI, MBB, UID, OutContext);
3461 break;
3463 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
3464 // .word LBB123
3466 break;
3467
3470 // Each entry is the address of the block minus the address of the jump
3471 // table. This is used for PIC jump tables where gprel32 is not supported.
3472 // e.g.:
3473 // .word LBB123 - LJTI1_2
3474 // If the .set directive avoids relocations, this is emitted as:
3475 // .set L4_5_set_123, LBB123 - LJTI1_2
3476 // .word L4_5_set_123
3478 MAI->doesSetDirectiveSuppressReloc()) {
3479 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
3480 OutContext);
3481 break;
3482 }
3484 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3487 break;
3488 }
3489 }
3490
3491 assert(Value && "Unknown entry kind!");
3492
3493 unsigned EntrySize = MJTI.getEntrySize(getDataLayout());
3494 OutStreamer->emitValue(Value, EntrySize);
3495}
3496
3497/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
3498/// special global used by LLVM. If so, emit it and return true, otherwise
3499/// do nothing and return false.
3501 if (GV->getName() == "llvm.used") {
3502 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
3503 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
3504 return true;
3505 }
3506
3507 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
3508 if (GV->getSection() == "llvm.metadata" ||
3510 return true;
3511
3512 if (GV->getName() == "llvm.arm64ec.symbolmap") {
3513 // For ARM64EC, print the table that maps between symbols and the
3514 // corresponding thunks to translate between x64 and AArch64 code.
3515 // This table is generated by AArch64Arm64ECCallLowering.
3516 OutStreamer->switchSection(
3517 OutContext.getCOFFSection(".hybmp$x", COFF::IMAGE_SCN_LNK_INFO));
3518 auto *Arr = cast<ConstantArray>(GV->getInitializer());
3519 for (auto &U : Arr->operands()) {
3520 auto *C = cast<Constant>(U);
3521 auto *Src = cast<GlobalValue>(C->getOperand(0)->stripPointerCasts());
3522 auto *Dst = cast<GlobalValue>(C->getOperand(1)->stripPointerCasts());
3523 int Kind = cast<ConstantInt>(C->getOperand(2))->getZExtValue();
3524
3525 if (Src->hasDLLImportStorageClass()) {
3526 // For now, we assume dllimport functions aren't directly called.
3527 // (We might change this later to match MSVC.)
3528 OutStreamer->emitCOFFSymbolIndex(
3529 OutContext.getOrCreateSymbol("__imp_" + Src->getName()));
3530 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3531 OutStreamer->emitInt32(Kind);
3532 } else {
3533 // FIXME: For non-dllimport functions, MSVC emits the same entry
3534 // twice, for reasons I don't understand. I have to assume the linker
3535 // ignores the redundant entry; there aren't any reasonable semantics
3536 // to attach to it.
3537 OutStreamer->emitCOFFSymbolIndex(getSymbol(Src));
3538 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3539 OutStreamer->emitInt32(Kind);
3540 }
3541 }
3542 return true;
3543 }
3544
3545 if (!GV->hasAppendingLinkage()) return false;
3546
3547 assert(GV->hasInitializer() && "Not a special LLVM global!");
3548
3549 if (GV->getName() == "llvm.global_ctors") {
3551 /* isCtor */ true);
3552
3553 return true;
3554 }
3555
3556 if (GV->getName() == "llvm.global_dtors") {
3558 /* isCtor */ false);
3559
3560 return true;
3561 }
3562
3563 GV->getContext().emitError(
3564 "unknown special variable with appending linkage: " +
3565 GV->getNameOrAsOperand());
3566 return true;
3567}
3568
3569/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
3570/// global in the specified llvm.used list.
3571void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
3572 // Should be an array of 'i8*'.
3573 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
3574 const GlobalValue *GV =
3576 if (GV)
3577 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
3578 }
3579}
3580
3582 const Constant *List,
3583 SmallVector<Structor, 8> &Structors) {
3584 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
3585 // the init priority.
3587 return;
3588
3589 // Gather the structors in a form that's convenient for sorting by priority.
3590 for (Value *O : cast<ConstantArray>(List)->operands()) {
3591 auto *CS = cast<ConstantStruct>(O);
3592 if (CS->getOperand(1)->isNullValue())
3593 break; // Found a null terminator, skip the rest.
3594 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
3595 if (!Priority)
3596 continue; // Malformed.
3597 Structors.push_back(Structor());
3598 Structor &S = Structors.back();
3599 S.Priority = Priority->getLimitedValue(65535);
3600 S.Func = CS->getOperand(1);
3601 if (!CS->getOperand(2)->isNullValue()) {
3602 if (TM.getTargetTriple().isOSAIX()) {
3603 CS->getContext().emitError(
3604 "associated data of XXStructor list is not yet supported on AIX");
3605 }
3606
3607 S.ComdatKey =
3608 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
3609 }
3610 }
3611
3612 // Emit the function pointers in the target-specific order
3613 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
3614 return L.Priority < R.Priority;
3615 });
3616}
3617
3618/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
3619/// priority.
3621 bool IsCtor) {
3622 SmallVector<Structor, 8> Structors;
3623 preprocessXXStructorList(DL, List, Structors);
3624 if (Structors.empty())
3625 return;
3626
3627 // Emit the structors in reverse order if we are using the .ctor/.dtor
3628 // initialization scheme.
3629 if (!TM.Options.UseInitArray)
3630 std::reverse(Structors.begin(), Structors.end());
3631
3632 const Align Align = DL.getPointerPrefAlignment(DL.getProgramAddressSpace());
3633 for (Structor &S : Structors) {
3635 const MCSymbol *KeySym = nullptr;
3636 if (GlobalValue *GV = S.ComdatKey) {
3637 if (GV->isDeclarationForLinker())
3638 // If the associated variable is not defined in this module
3639 // (it might be available_externally, or have been an
3640 // available_externally definition that was dropped by the
3641 // EliminateAvailableExternally pass), some other TU
3642 // will provide its dynamic initializer.
3643 continue;
3644
3645 KeySym = getSymbol(GV);
3646 }
3647
3648 MCSection *OutputSection =
3649 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
3650 : Obj.getStaticDtorSection(S.Priority, KeySym));
3651 OutStreamer->switchSection(OutputSection);
3652 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
3654 emitXXStructor(DL, S.Func);
3655 }
3656}
3657
3658void AsmPrinter::emitModuleIdents(Module &M) {
3659 if (!MAI->hasIdentDirective())
3660 return;
3661
3662 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
3663 for (const MDNode *N : NMD->operands()) {
3664 assert(N->getNumOperands() == 1 &&
3665 "llvm.ident metadata entry can have only one operand");
3666 const MDString *S = cast<MDString>(N->getOperand(0));
3667 OutStreamer->emitIdent(S->getString());
3668 }
3669 }
3670}
3671
3672void AsmPrinter::emitModuleCommandLines(Module &M) {
3673 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
3674 if (!CommandLine)
3675 return;
3676
3677 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3678 if (!NMD || !NMD->getNumOperands())
3679 return;
3680
3681 OutStreamer->pushSection();
3682 OutStreamer->switchSection(CommandLine);
3683 OutStreamer->emitZeros(1);
3684 for (const MDNode *N : NMD->operands()) {
3685 assert(N->getNumOperands() == 1 &&
3686 "llvm.commandline metadata entry can have only one operand");
3687 const MDString *S = cast<MDString>(N->getOperand(0));
3688 OutStreamer->emitBytes(S->getString());
3689 OutStreamer->emitZeros(1);
3690 }
3691 OutStreamer->popSection();
3692}
3693
3694//===--------------------------------------------------------------------===//
3695// Emission and print routines
3696//
3697
3698/// Emit a byte directive and value.
3699///
3700void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
3701
3702/// Emit a short directive and value.
3703void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
3704
3705/// Emit a long directive and value.
3706void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
3707
3708/// EmitSLEB128 - emit the specified signed leb128 value.
3709void AsmPrinter::emitSLEB128(int64_t Value, const char *Desc) const {
3710 if (isVerbose() && Desc)
3711 OutStreamer->AddComment(Desc);
3712
3713 OutStreamer->emitSLEB128IntValue(Value);
3714}
3715
3717 unsigned PadTo) const {
3718 if (isVerbose() && Desc)
3719 OutStreamer->AddComment(Desc);
3720
3721 OutStreamer->emitULEB128IntValue(Value, PadTo);
3722}
3723
3724/// Emit a long long directive and value.
3726 OutStreamer->emitInt64(Value);
3727}
3728
3729/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
3730/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
3731/// .set if it avoids relocations.
3733 unsigned Size) const {
3734 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
3735}
3736
3737/// Emit something like ".uleb128 Hi-Lo".
3739 const MCSymbol *Lo) const {
3740 OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
3741}
3742
3743/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
3744/// where the size in bytes of the directive is specified by Size and Label
3745/// specifies the label. This implicitly uses .set if it is available.
3747 unsigned Size,
3748 bool IsSectionRelative) const {
3749 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
3750 OutStreamer->emitCOFFSecRel32(Label, Offset);
3751 if (Size > 4)
3752 OutStreamer->emitZeros(Size - 4);
3753 return;
3754 }
3755
3756 // Emit Label+Offset (or just Label if Offset is zero)
3757 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
3758 if (Offset)
3761
3762 OutStreamer->emitValue(Expr, Size);
3763}
3764
3765//===----------------------------------------------------------------------===//
3766
3767// EmitAlignment - Emit an alignment directive to the specified power of
3768// two boundary. If a global value is specified, and if that global has
3769// an explicit alignment requested, it will override the alignment request
3770// if required for correctness.
3772 unsigned MaxBytesToEmit) const {
3773 if (GV)
3774 Alignment = getGVAlignment(GV, GV->getDataLayout(), Alignment);
3775
3776 if (Alignment == Align(1))
3777 return; // 1-byte aligned: no need to emit alignment.
3778
3779 if (getCurrentSection()->isText()) {
3780 const MCSubtargetInfo *STI = nullptr;
3781 if (this->MF)
3782 STI = &getSubtargetInfo();
3783 else
3784 STI = TM.getMCSubtargetInfo();
3785 OutStreamer->emitCodeAlignment(Alignment, STI, MaxBytesToEmit);
3786 } else
3787 OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
3788}
3789
3790//===----------------------------------------------------------------------===//
3791// Constant emission.
3792//===----------------------------------------------------------------------===//
3793
3795 const Constant *BaseCV,
3796 uint64_t Offset) {
3797 MCContext &Ctx = OutContext;
3798
3799 if (CV->isNullValue() || isa<UndefValue>(CV))
3800 return MCConstantExpr::create(0, Ctx);
3801
3802 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
3803 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
3804
3805 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV))
3806 return MCConstantExpr::create(CB->getZExtValue(), Ctx);
3807
3808 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV))
3809 return lowerConstantPtrAuth(*CPA);
3810
3811 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
3812 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
3813
3814 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
3815 return lowerBlockAddressConstant(*BA);
3816
3817 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
3819 getSymbol(Equiv->getGlobalValue()), nullptr, 0, std::nullopt, TM);
3820
3821 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
3822 return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
3823
3824 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
3825 if (!CE) {
3826 llvm_unreachable("Unknown constant value to lower!");
3827 }
3828
3829 // The constant expression opcodes are limited to those that are necessary
3830 // to represent relocations on supported targets. Expressions involving only
3831 // constant addresses are constant folded instead.
3832 switch (CE->getOpcode()) {
3833 default:
3834 break; // Error
3835 case Instruction::AddrSpaceCast: {
3836 const Constant *Op = CE->getOperand(0);
3837 unsigned DstAS = CE->getType()->getPointerAddressSpace();
3838 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
3839 if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
3840 return lowerConstant(Op);
3841
3842 break; // Error
3843 }
3844 case Instruction::GetElementPtr: {
3845 // Generate a symbolic expression for the byte address
3846 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
3847 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
3848
3849 const MCExpr *Base = lowerConstant(CE->getOperand(0));
3850 if (!OffsetAI)
3851 return Base;
3852
3853 int64_t Offset = OffsetAI.getSExtValue();
3855 Ctx);
3856 }
3857
3858 case Instruction::Trunc:
3859 // We emit the value and depend on the assembler to truncate the generated
3860 // expression properly. This is important for differences between
3861 // blockaddress labels. Since the two labels are in the same function, it
3862 // is reasonable to treat their delta as a 32-bit value.
3863 [[fallthrough]];
3864 case Instruction::BitCast:
3865 return lowerConstant(CE->getOperand(0), BaseCV, Offset);
3866
3867 case Instruction::IntToPtr: {
3868 const DataLayout &DL = getDataLayout();
3869
3870 // Handle casts to pointers by changing them into casts to the appropriate
3871 // integer type. This promotes constant folding and simplifies this code.
3872 Constant *Op = CE->getOperand(0);
3873 Op = ConstantFoldIntegerCast(Op, DL.getIntPtrType(CV->getType()),
3874 /*IsSigned*/ false, DL);
3875 if (Op)
3876 return lowerConstant(Op);
3877
3878 break; // Error
3879 }
3880
3881 case Instruction::PtrToAddr:
3882 case Instruction::PtrToInt: {
3883 const DataLayout &DL = getDataLayout();
3884
3885 // Support only foldable casts to/from pointers that can be eliminated by
3886 // changing the pointer to the appropriately sized integer type.
3887 Constant *Op = CE->getOperand(0);
3888 Type *Ty = CE->getType();
3889
3890 const MCExpr *OpExpr = lowerConstant(Op);
3891
3892 // We can emit the pointer value into this slot if the slot is an
3893 // integer slot equal to the size of the pointer.
3894 //
3895 // If the pointer is larger than the resultant integer, then
3896 // as with Trunc just depend on the assembler to truncate it.
3897 if (DL.getTypeAllocSize(Ty).getFixedValue() <=
3898 DL.getTypeAllocSize(Op->getType()).getFixedValue())
3899 return OpExpr;
3900
3901 break; // Error
3902 }
3903
3904 case Instruction::Sub: {
3905 GlobalValue *LHSGV, *RHSGV;
3906 APInt LHSOffset, RHSOffset;
3907 DSOLocalEquivalent *DSOEquiv;
3908 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
3909 getDataLayout(), &DSOEquiv) &&
3910 IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
3911 getDataLayout())) {
3912 auto *LHSSym = getSymbol(LHSGV);
3913 auto *RHSSym = getSymbol(RHSGV);
3914 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
3915 std::optional<int64_t> PCRelativeOffset;
3916 if (getObjFileLowering().hasPLTPCRelative() && RHSGV == BaseCV)
3917 PCRelativeOffset = Offset;
3918
3919 // Try the generic symbol difference first.
3921 LHSGV, RHSGV, Addend, PCRelativeOffset, TM);
3922
3923 // (ELF-specific) If the generic symbol difference does not apply, and
3924 // LHS is a dso_local_equivalent of a function, reference the PLT entry
3925 // instead. Note: A default visibility symbol is by default preemptible
3926 // during linking, and should not be referenced with PC-relative
3927 // relocations. Therefore, use a PLT relocation even if the function is
3928 // dso_local.
3929 if (DSOEquiv && TM.getTargetTriple().isOSBinFormatELF())
3931 LHSSym, RHSSym, Addend, PCRelativeOffset, TM);
3932
3933 // Otherwise, return LHS-RHS+Addend.
3934 if (!Res) {
3935 Res =
3937 MCSymbolRefExpr::create(RHSSym, Ctx), Ctx);
3938 if (Addend != 0)
3940 Res, MCConstantExpr::create(Addend, Ctx), Ctx);
3941 }
3942 return Res;
3943 }
3944
3945 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
3946 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
3947 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
3948 break;
3949 }
3950
3951 case Instruction::Add: {
3952 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
3953 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
3954 return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
3955 }
3956 }
3957
3958 // If the code isn't optimized, there may be outstanding folding
3959 // opportunities. Attempt to fold the expression using DataLayout as a
3960 // last resort before giving up.
3962 if (C != CE)
3963 return lowerConstant(C);
3964
3965 // Otherwise report the problem to the user.
3966 std::string S;
3967 raw_string_ostream OS(S);
3968 OS << "unsupported expression in static initializer: ";
3969 CE->printAsOperand(OS, /*PrintType=*/false,
3970 !MF ? nullptr : MF->getFunction().getParent());
3971 CE->getContext().emitError(S);
3972 return MCConstantExpr::create(0, Ctx);
3973}
3974
3975static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
3976 AsmPrinter &AP,
3977 const Constant *BaseCV = nullptr,
3978 uint64_t Offset = 0,
3979 AsmPrinter::AliasMapTy *AliasList = nullptr);
3980
3981static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
3982static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
3983
3984/// isRepeatedByteSequence - Determine whether the given value is
3985/// composed of a repeated sequence of identical bytes and return the
3986/// byte value. If it is not a repeated sequence, return -1.
3988 StringRef Data = V->getRawDataValues();
3989 assert(!Data.empty() && "Empty aggregates should be CAZ node");
3990 char C = Data[0];
3991 for (unsigned i = 1, e = Data.size(); i != e; ++i)
3992 if (Data[i] != C) return -1;
3993 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
3994}
3995
3996/// isRepeatedByteSequence - Determine whether the given value is
3997/// composed of a repeated sequence of identical bytes and return the
3998/// byte value. If it is not a repeated sequence, return -1.
3999static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
4000 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
4001 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
4002 assert(Size % 8 == 0);
4003
4004 // Extend the element to take zero padding into account.
4005 APInt Value = CI->getValue().zext(Size);
4006 if (!Value.isSplat(8))
4007 return -1;
4008
4009 return Value.zextOrTrunc(8).getZExtValue();
4010 }
4011 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
4012 // Make sure all array elements are sequences of the same repeated
4013 // byte.
4014 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
4015 Constant *Op0 = CA->getOperand(0);
4016 int Byte = isRepeatedByteSequence(Op0, DL);
4017 if (Byte == -1)
4018 return -1;
4019
4020 // All array elements must be equal.
4021 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
4022 if (CA->getOperand(i) != Op0)
4023 return -1;
4024 return Byte;
4025 }
4026
4028 return isRepeatedByteSequence(CDS);
4029
4030 return -1;
4031}
4032
4034 AsmPrinter::AliasMapTy *AliasList) {
4035 if (AliasList) {
4036 auto AliasIt = AliasList->find(Offset);
4037 if (AliasIt != AliasList->end()) {
4038 for (const GlobalAlias *GA : AliasIt->second)
4039 AP.OutStreamer->emitLabel(AP.getSymbol(GA));
4040 AliasList->erase(Offset);
4041 }
4042 }
4043}
4044
4046 const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
4047 AsmPrinter::AliasMapTy *AliasList) {
4048 // See if we can aggregate this into a .fill, if so, emit it as such.
4049 int Value = isRepeatedByteSequence(CDS, DL);
4050 if (Value != -1) {
4051 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
4052 // Don't emit a 1-byte object as a .fill.
4053 if (Bytes > 1)
4054 return AP.OutStreamer->emitFill(Bytes, Value);
4055 }
4056
4057 // If this can be emitted with .ascii/.asciz, emit it as such.
4058 if (CDS->isString())
4059 return AP.OutStreamer->emitBytes(CDS->getAsString());
4060
4061 // Otherwise, emit the values in successive locations.
4062 uint64_t ElementByteSize = CDS->getElementByteSize();
4063 if (isa<IntegerType>(CDS->getElementType()) ||
4064 isa<ByteType>(CDS->getElementType())) {
4065 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4066 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4067 if (AP.isVerbose())
4068 AP.OutStreamer->getCommentOS()
4069 << format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
4070 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
4071 ElementByteSize);
4072 }
4073 } else {
4074 Type *ET = CDS->getElementType();
4075 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4076 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4078 }
4079 }
4080
4081 unsigned Size = DL.getTypeAllocSize(CDS->getType());
4082 unsigned EmittedSize =
4083 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
4084 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
4085 if (unsigned Padding = Size - EmittedSize)
4086 AP.OutStreamer->emitZeros(Padding);
4087}
4088
4090 const ConstantArray *CA, AsmPrinter &AP,
4091 const Constant *BaseCV, uint64_t Offset,
4092 AsmPrinter::AliasMapTy *AliasList) {
4093 // See if we can aggregate some values. Make sure it can be
4094 // represented as a series of bytes of the constant value.
4095 int Value = isRepeatedByteSequence(CA, DL);
4096
4097 if (Value != -1) {
4098 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
4099 AP.OutStreamer->emitFill(Bytes, Value);
4100 } else {
4101 for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
4102 emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
4103 AliasList);
4104 Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
4105 }
4106 }
4107}
4108
4109static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
4110
4111static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV,
4112 AsmPrinter &AP,
4113 AsmPrinter::AliasMapTy *AliasList) {
4114 auto *VTy = cast<FixedVectorType>(CV->getType());
4115 Type *ElementType = VTy->getElementType();
4116 uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
4117 uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
4118 uint64_t EmittedSize;
4119 if (ElementSizeInBits != ElementAllocSizeInBits) {
4120 // If the allocation size of an element is different from the size in bits,
4121 // printing each element separately will insert incorrect padding.
4122 //
4123 // The general algorithm here is complicated; instead of writing it out
4124 // here, just use the existing code in ConstantFolding.
4125 Type *IntT =
4126 IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
4128 ConstantExpr::getBitCast(const_cast<Constant *>(CV), IntT), DL));
4129 if (!CI) {
4131 "Cannot lower vector global with unusual element type");
4132 }
4133 emitGlobalAliasInline(AP, 0, AliasList);
4135 EmittedSize = DL.getTypeStoreSize(CV->getType());
4136 } else {
4137 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
4138 emitGlobalAliasInline(AP, DL.getTypeAllocSize(CV->getType()) * I, AliasList);
4140 }
4141 EmittedSize = DL.getTypeAllocSize(ElementType) * VTy->getNumElements();
4142 }
4143
4144 unsigned Size = DL.getTypeAllocSize(CV->getType());
4145 if (unsigned Padding = Size - EmittedSize)
4146 AP.OutStreamer->emitZeros(Padding);
4147}
4148
4150 const ConstantStruct *CS, AsmPrinter &AP,
4151 const Constant *BaseCV, uint64_t Offset,
4152 AsmPrinter::AliasMapTy *AliasList) {
4153 // Print the fields in successive locations. Pad to align if needed!
4154 uint64_t Size = DL.getTypeAllocSize(CS->getType());
4155 const StructLayout *Layout = DL.getStructLayout(CS->getType());
4156 uint64_t SizeSoFar = 0;
4157 for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
4158 const Constant *Field = CS->getOperand(I);
4159
4160 // Print the actual field value.
4161 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
4162 AliasList);
4163
4164 // Check if padding is needed and insert one or more 0s.
4165 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
4166 uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
4167 Layout->getElementOffset(I)) -
4168 FieldSize;
4169 SizeSoFar += FieldSize + PadSize;
4170
4171 // Insert padding - this may include padding to increase the size of the
4172 // current field up to the ABI size (if the struct is not packed) as well
4173 // as padding to ensure that the next field starts at the right offset.
4174 AP.OutStreamer->emitZeros(PadSize);
4175 }
4176 assert(SizeSoFar == Layout->getSizeInBytes() &&
4177 "Layout of constant struct may be incorrect!");
4178}
4179
4180static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
4181 assert(ET && "Unknown float type");
4182 APInt API = APF.bitcastToAPInt();
4183
4184 // First print a comment with what we think the original floating-point value
4185 // should have been.
4186 if (AP.isVerbose()) {
4187 SmallString<8> StrVal;
4188 APF.toString(StrVal);
4189 ET->print(AP.OutStreamer->getCommentOS());
4190 AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
4191 }
4192
4193 // Now iterate through the APInt chunks, emitting them in endian-correct
4194 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
4195 // floats).
4196 unsigned NumBytes = API.getBitWidth() / 8;
4197 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
4198 const uint64_t *p = API.getRawData();
4199
4200 // PPC's long double has odd notions of endianness compared to how LLVM
4201 // handles it: p[0] goes first for *big* endian on PPC.
4202 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
4203 int Chunk = API.getNumWords() - 1;
4204
4205 if (TrailingBytes)
4206 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
4207
4208 for (; Chunk >= 0; --Chunk)
4209 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4210 } else {
4211 unsigned Chunk;
4212 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
4213 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4214
4215 if (TrailingBytes)
4216 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
4217 }
4218
4219 // Emit the tail padding for the long double.
4220 const DataLayout &DL = AP.getDataLayout();
4221 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
4222}
4223
4224static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
4225 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
4226}
4227
4229 uint64_t TypeStoreSize,
4230 AsmPrinter &AP) {
4231 const DataLayout &DL = AP.getDataLayout();
4232 unsigned BitWidth = Val.getBitWidth();
4233
4234 // Copy the value as we may massage the layout for constants whose bit width
4235 // is not a multiple of 64-bits.
4236 APInt Realigned(Val);
4237 uint64_t ExtraBits = 0;
4238 unsigned ExtraBitsSize = BitWidth & 63;
4239
4240 if (ExtraBitsSize) {
4241 // The bit width of the data is not a multiple of 64-bits.
4242 // The extra bits are expected to be at the end of the chunk of the memory.
4243 // Little endian:
4244 // * Nothing to be done, just record the extra bits to emit.
4245 // Big endian:
4246 // * Record the extra bits to emit.
4247 // * Realign the raw data to emit the chunks of 64-bits.
4248 if (DL.isBigEndian()) {
4249 // Basically the structure of the raw data is a chunk of 64-bits cells:
4250 // 0 1 BitWidth / 64
4251 // [chunk1][chunk2] ... [chunkN].
4252 // The most significant chunk is chunkN and it should be emitted first.
4253 // However, due to the alignment issue chunkN contains useless bits.
4254 // Realign the chunks so that they contain only useful information:
4255 // ExtraBits 0 1 (BitWidth / 64) - 1
4256 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
4257 ExtraBitsSize = alignTo(ExtraBitsSize, 8);
4258 ExtraBits =
4259 Realigned.getRawData()[0] & (((uint64_t)-1) >> (64 - ExtraBitsSize));
4260 if (BitWidth >= 64)
4261 Realigned.lshrInPlace(ExtraBitsSize);
4262 } else
4263 ExtraBits = Realigned.getRawData()[BitWidth / 64];
4264 }
4265
4266 // We don't expect assemblers to support data directives
4267 // for more than 64 bits, so we emit the data in at most 64-bit
4268 // quantities at a time.
4269 const uint64_t *RawData = Realigned.getRawData();
4270 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
4271 uint64_t ChunkVal = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
4272 AP.OutStreamer->emitIntValue(ChunkVal, 8);
4273 }
4274
4275 if (ExtraBitsSize) {
4276 // Emit the extra bits after the 64-bits chunks.
4277
4278 // Emit a directive that fills the expected size.
4279 uint64_t Size = TypeStoreSize - (BitWidth / 64) * 8;
4280 assert(Size && Size * 8 >= ExtraBitsSize &&
4281 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) ==
4282 ExtraBits &&
4283 "Directive too small for extra bits.");
4284 AP.OutStreamer->emitIntValue(ExtraBits, Size);
4285 }
4286}
4287
4289 AsmPrinter &AP) {
4291 CB->getValue(), AP.getDataLayout().getTypeStoreSize(CB->getType()), AP);
4292}
4293
4298
4299/// Transform a not absolute MCExpr containing a reference to a GOT
4300/// equivalent global, by a target specific GOT pc relative access to the
4301/// final symbol.
4303 const Constant *BaseCst,
4304 uint64_t Offset) {
4305 // The global @foo below illustrates a global that uses a got equivalent.
4306 //
4307 // @bar = global i32 42
4308 // @gotequiv = private unnamed_addr constant i32* @bar
4309 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
4310 // i64 ptrtoint (i32* @foo to i64))
4311 // to i32)
4312 //
4313 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
4314 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
4315 // form:
4316 //
4317 // foo = cstexpr, where
4318 // cstexpr := <gotequiv> - "." + <cst>
4319 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
4320 //
4321 // After canonicalization by evaluateAsRelocatable `ME` turns into:
4322 //
4323 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
4324 // gotpcrelcst := <offset from @foo base> + <cst>
4325 MCValue MV;
4326 if (!(*ME)->evaluateAsRelocatable(MV, nullptr) || MV.isAbsolute())
4327 return;
4328 const MCSymbol *GOTEquivSym = MV.getAddSym();
4329 if (!GOTEquivSym)
4330 return;
4331
4332 // Check that GOT equivalent symbol is cached.
4333 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
4334 return;
4335
4336 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
4337 if (!BaseGV)
4338 return;
4339
4340 // Check for a valid base symbol
4341 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
4342 const MCSymbol *SymB = MV.getSubSym();
4343
4344 if (!SymB || BaseSym != SymB)
4345 return;
4346
4347 // Make sure to match:
4348 //
4349 // gotpcrelcst := <offset from @foo base> + <cst>
4350 //
4351 int64_t GOTPCRelCst = Offset + MV.getConstant();
4352 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
4353 return;
4354
4355 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
4356 //
4357 // bar:
4358 // .long 42
4359 // gotequiv:
4360 // .quad bar
4361 // foo:
4362 // .long gotequiv - "." + <cst>
4363 //
4364 // is replaced by the target specific equivalent to:
4365 //
4366 // bar:
4367 // .long 42
4368 // foo:
4369 // .long bar@GOTPCREL+<gotpcrelcst>
4370 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
4371 const GlobalVariable *GV = Result.first;
4372 int NumUses = (int)Result.second;
4373 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
4374 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
4376 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
4377
4378 // Update GOT equivalent usage information
4379 --NumUses;
4380 if (NumUses >= 0)
4381 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
4382}
4383
4384static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
4385 AsmPrinter &AP, const Constant *BaseCV,
4387 AsmPrinter::AliasMapTy *AliasList) {
4388 assert((!AliasList || AP.TM.getTargetTriple().isOSBinFormatXCOFF()) &&
4389 "AliasList only expected for XCOFF");
4390 emitGlobalAliasInline(AP, Offset, AliasList);
4391 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4392
4393 // Globals with sub-elements such as combinations of arrays and structs
4394 // are handled recursively by emitGlobalConstantImpl. Keep track of the
4395 // constant symbol base and the current position with BaseCV and Offset.
4396 if (!BaseCV && CV->hasOneUse())
4397 BaseCV = dyn_cast<Constant>(CV->user_back());
4398
4400 StructType *structType;
4401 if (AliasList && (structType = llvm::dyn_cast<StructType>(CV->getType()))) {
4402 unsigned numElements = {structType->getNumElements()};
4403 if (numElements != 0) {
4404 // Handle cases of aliases to direct struct elements
4405 const StructLayout *Layout = DL.getStructLayout(structType);
4406 uint64_t SizeSoFar = 0;
4407 for (unsigned int i = 0; i < numElements - 1; ++i) {
4408 uint64_t GapToNext = Layout->getElementOffset(i + 1) - SizeSoFar;
4409 AP.OutStreamer->emitZeros(GapToNext);
4410 SizeSoFar += GapToNext;
4411 emitGlobalAliasInline(AP, Offset + SizeSoFar, AliasList);
4412 }
4413 AP.OutStreamer->emitZeros(Size - SizeSoFar);
4414 return;
4415 }
4416 }
4417 return AP.OutStreamer->emitZeros(Size);
4418 }
4419
4420 if (isa<UndefValue>(CV))
4421 return AP.OutStreamer->emitZeros(Size);
4422
4423 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
4424 if (isa<VectorType>(CV->getType()))
4425 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4426
4427 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4428 if (StoreSize <= 8) {
4429 if (AP.isVerbose())
4430 AP.OutStreamer->getCommentOS()
4431 << format("0x%" PRIx64 "\n", CI->getZExtValue());
4432 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
4433 } else {
4435 }
4436
4437 // Emit tail padding if needed
4438 if (Size != StoreSize)
4439 AP.OutStreamer->emitZeros(Size - StoreSize);
4440
4441 return;
4442 }
4443
4444 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV)) {
4445 if (isa<VectorType>(CV->getType()))
4446 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4447
4448 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4449 if (StoreSize <= 8) {
4450 if (AP.isVerbose())
4451 AP.OutStreamer->getCommentOS()
4452 << format("0x%" PRIx64 "\n", CB->getZExtValue());
4453 AP.OutStreamer->emitIntValue(CB->getZExtValue(), StoreSize);
4454 } else {
4456 }
4457
4458 // Emit tail padding if needed
4459 if (Size != StoreSize)
4460 AP.OutStreamer->emitZeros(Size - StoreSize);
4461
4462 return;
4463 }
4464
4465 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
4466 if (isa<VectorType>(CV->getType()))
4467 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4468 else
4469 return emitGlobalConstantFP(CFP, AP);
4470 }
4471
4472 if (isa<ConstantPointerNull>(CV)) {
4473 AP.OutStreamer->emitIntValue(0, Size);
4474 return;
4475 }
4476
4478 return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
4479
4480 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
4481 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
4482
4483 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
4484 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
4485
4486 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
4487 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
4488 // vectors).
4489 if (CE->getOpcode() == Instruction::BitCast)
4490 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
4491
4492 if (Size > 8) {
4493 // If the constant expression's size is greater than 64-bits, then we have
4494 // to emit the value in chunks. Try to constant fold the value and emit it
4495 // that way.
4496 Constant *New = ConstantFoldConstant(CE, DL);
4497 if (New != CE)
4498 return emitGlobalConstantImpl(DL, New, AP);
4499 }
4500 }
4501
4502 if (isa<ConstantVector>(CV))
4503 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4504
4505 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
4506 // thread the streamer with EmitValue.
4507 const MCExpr *ME = AP.lowerConstant(CV, BaseCV, Offset);
4508
4509 // Since lowerConstant already folded and got rid of all IR pointer and
4510 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
4511 // directly.
4513 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
4514
4515 AP.OutStreamer->emitValue(ME, Size);
4516}
4517
4518/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
4520 AliasMapTy *AliasList) {
4521 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4522 if (Size)
4523 emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
4524 else if (MAI->hasSubsectionsViaSymbols()) {
4525 // If the global has zero size, emit a single byte so that two labels don't
4526 // look like they are at the same location.
4527 OutStreamer->emitIntValue(0, 1);
4528 }
4529 if (!AliasList)
4530 return;
4531 // TODO: These remaining aliases are not emitted in the correct location. Need
4532 // to handle the case where the alias offset doesn't refer to any sub-element.
4533 for (auto &AliasPair : *AliasList) {
4534 for (const GlobalAlias *GA : AliasPair.second)
4535 OutStreamer->emitLabel(getSymbol(GA));
4536 }
4537}
4538
4540 // Target doesn't support this yet!
4541 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
4542}
4543
4545 if (Offset > 0)
4546 OS << '+' << Offset;
4547 else if (Offset < 0)
4548 OS << Offset;
4549}
4550
4551void AsmPrinter::emitNops(unsigned N) {
4552 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
4553 for (; N; --N)
4555}
4556
4557//===----------------------------------------------------------------------===//
4558// Symbol Lowering Routines.
4559//===----------------------------------------------------------------------===//
4560
4562 return OutContext.createTempSymbol(Name, true);
4563}
4564
4566 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
4567 BA->getBasicBlock());
4568}
4569
4571 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
4572}
4573
4577
4578/// GetCPISymbol - Return the symbol for the specified constant pool entry.
4579MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
4580 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment() ||
4581 getSubtargetInfo().getTargetTriple().isUEFI()) {
4582 const MachineConstantPoolEntry &CPE =
4583 MF->getConstantPool()->getConstants()[CPID];
4584 if (!CPE.isMachineConstantPoolEntry()) {
4585 const DataLayout &DL = MF->getDataLayout();
4586 SectionKind Kind = CPE.getSectionKind(&DL);
4587 const Constant *C = CPE.Val.ConstVal;
4588 Align Alignment = CPE.Alignment;
4590 DL, Kind, C, Alignment, &MF->getFunction());
4591 if (S && TM.getTargetTriple().isOSBinFormatCOFF()) {
4592 if (MCSymbol *Sym =
4593 static_cast<const MCSectionCOFF *>(S)->getCOMDATSymbol()) {
4594 if (Sym->isUndefined())
4595 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
4596 return Sym;
4597 }
4598 }
4599 }
4600 }
4601
4602 const DataLayout &DL = getDataLayout();
4603 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4604 "CPI" + Twine(getFunctionNumber()) + "_" +
4605 Twine(CPID));
4606}
4607
4608/// GetJTISymbol - Return the symbol for the specified jump table entry.
4609MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
4610 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
4611}
4612
4613/// GetJTSetSymbol - Return the symbol for the specified jump table .set
4614/// FIXME: privatize to AsmPrinter.
4615MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
4616 const DataLayout &DL = getDataLayout();
4617 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4618 Twine(getFunctionNumber()) + "_" +
4619 Twine(UID) + "_set_" + Twine(MBBID));
4620}
4621
4626
4627/// Return the MCSymbol for the specified ExternalSymbol.
4629 SmallString<60> NameStr;
4631 return OutContext.getOrCreateSymbol(NameStr);
4632}
4633
4634/// PrintParentLoopComment - Print comments about parent loops of this one.
4636 unsigned FunctionNumber) {
4637 if (!Loop) return;
4638 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
4639 OS.indent(Loop->getLoopDepth()*2)
4640 << "Parent Loop BB" << FunctionNumber << "_"
4641 << Loop->getHeader()->getNumber()
4642 << " Depth=" << Loop->getLoopDepth() << '\n';
4643}
4644
4645/// PrintChildLoopComment - Print comments about child loops within
4646/// the loop for this basic block, with nesting.
4648 unsigned FunctionNumber) {
4649 // Add child loop information
4650 for (const MachineLoop *CL : *Loop) {
4651 OS.indent(CL->getLoopDepth()*2)
4652 << "Child Loop BB" << FunctionNumber << "_"
4653 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
4654 << '\n';
4655 PrintChildLoopComment(OS, CL, FunctionNumber);
4656 }
4657}
4658
4659/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
4661 const MachineLoopInfo *LI,
4662 const AsmPrinter &AP) {
4663 // Add loop depth information
4664 const MachineLoop *Loop = LI->getLoopFor(&MBB);
4665 if (!Loop) return;
4666
4667 MachineBasicBlock *Header = Loop->getHeader();
4668 assert(Header && "No header for loop");
4669
4670 // If this block is not a loop header, just print out what is the loop header
4671 // and return.
4672 if (Header != &MBB) {
4673 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
4674 Twine(AP.getFunctionNumber())+"_" +
4676 " Depth="+Twine(Loop->getLoopDepth()));
4677 return;
4678 }
4679
4680 // Otherwise, it is a loop header. Print out information about child and
4681 // parent loops.
4682 raw_ostream &OS = AP.OutStreamer->getCommentOS();
4683
4685
4686 OS << "=>";
4687 OS.indent(Loop->getLoopDepth()*2-2);
4688
4689 OS << "This ";
4690 if (Loop->isInnermost())
4691 OS << "Inner ";
4692 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
4693
4695}
4696
4697/// emitBasicBlockStart - This method prints the label for the specified
4698/// MachineBasicBlock, an alignment (if present) and a comment describing
4699/// it if appropriate.
4701 // End the previous funclet and start a new one.
4702 if (MBB.isEHFuncletEntry()) {
4703 for (auto &Handler : Handlers) {
4704 Handler->endFunclet();
4705 Handler->beginFunclet(MBB);
4706 }
4707 for (auto &Handler : EHHandlers) {
4708 Handler->endFunclet();
4709 Handler->beginFunclet(MBB);
4710 }
4711 }
4712
4713 // Switch to a new section if this basic block must begin a section. The
4714 // entry block is always placed in the function section and is handled
4715 // separately.
4716 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4717 OutStreamer->switchSection(
4718 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
4719 MBB, TM));
4720 CurrentSectionBeginSym = MBB.getSymbol();
4721 }
4722
4723 for (auto &Handler : Handlers)
4724 Handler->beginCodeAlignment(MBB);
4725
4726 // Emit an alignment directive for this block, if needed.
4727 const Align Alignment = MBB.getAlignment();
4728 if (Alignment != Align(1))
4729 emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
4730
4731 // If the block has its address taken, emit any labels that were used to
4732 // reference the block. It is possible that there is more than one label
4733 // here, because multiple LLVM BB's may have been RAUW'd to this block after
4734 // the references were generated.
4735 if (MBB.isIRBlockAddressTaken()) {
4736 if (isVerbose())
4737 OutStreamer->AddComment("Block address taken");
4738
4739 BasicBlock *BB = MBB.getAddressTakenIRBlock();
4740 assert(BB && BB->hasAddressTaken() && "Missing BB");
4741 for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
4742 OutStreamer->emitLabel(Sym);
4743 } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
4744 OutStreamer->AddComment("Block address taken");
4745 } else if (isVerbose() && MBB.isInlineAsmBrIndirectTarget()) {
4746 OutStreamer->AddComment("Inline asm indirect target");
4747 }
4748
4749 // Print some verbose block comments.
4750 if (isVerbose()) {
4751 if (const BasicBlock *BB = MBB.getBasicBlock()) {
4752 if (BB->hasName()) {
4753 BB->printAsOperand(OutStreamer->getCommentOS(),
4754 /*PrintType=*/false, BB->getModule());
4755 OutStreamer->getCommentOS() << '\n';
4756 }
4757 }
4758
4759 assert(MLI != nullptr && "MachineLoopInfo should has been computed");
4761 }
4762
4763 // Print the main label for the block.
4764 if (shouldEmitLabelForBasicBlock(MBB)) {
4765 if (isVerbose() && MBB.hasLabelMustBeEmitted())
4766 OutStreamer->AddComment("Label of block must be emitted");
4767 OutStreamer->emitLabel(MBB.getSymbol());
4768 } else {
4769 if (isVerbose()) {
4770 // NOTE: Want this comment at start of line, don't emit with AddComment.
4771 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
4772 false);
4773 }
4774 }
4775
4776 if (MBB.isEHContTarget() &&
4777 MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) {
4778 OutStreamer->emitLabel(MBB.getEHContSymbol());
4779 }
4780
4781 // With BB sections, each basic block must handle CFI information on its own
4782 // if it begins a section (Entry block call is handled separately, next to
4783 // beginFunction).
4784 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4785 for (auto &Handler : Handlers)
4786 Handler->beginBasicBlockSection(MBB);
4787 for (auto &Handler : EHHandlers)
4788 Handler->beginBasicBlockSection(MBB);
4789 }
4790}
4791
4793 // Check if CFI information needs to be updated for this MBB with basic block
4794 // sections.
4795 if (MBB.isEndSection()) {
4796 for (auto &Handler : Handlers)
4797 Handler->endBasicBlockSection(MBB);
4798 for (auto &Handler : EHHandlers)
4799 Handler->endBasicBlockSection(MBB);
4800 }
4801}
4802
4803void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
4804 bool IsDefinition) const {
4806
4807 switch (Visibility) {
4808 default: break;
4810 if (IsDefinition)
4811 Attr = MAI->getHiddenVisibilityAttr();
4812 else
4813 Attr = MAI->getHiddenDeclarationVisibilityAttr();
4814 break;
4816 Attr = MAI->getProtectedVisibilityAttr();
4817 break;
4818 }
4819
4820 if (Attr != MCSA_Invalid)
4821 OutStreamer->emitSymbolAttribute(Sym, Attr);
4822}
4823
4824bool AsmPrinter::shouldEmitLabelForBasicBlock(
4825 const MachineBasicBlock &MBB) const {
4826 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
4827 // in the labels mode (option `=labels`) and every section beginning in the
4828 // sections mode (`=all` and `=list=`).
4829 if ((MF->getTarget().Options.BBAddrMap || MBB.isBeginSection()) &&
4830 !MBB.isEntryBlock())
4831 return true;
4832 // A label is needed for any block with at least one predecessor (when that
4833 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
4834 // entry, or if a label is forced).
4835 return !MBB.pred_empty() &&
4836 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
4837 MBB.hasLabelMustBeEmitted());
4838}
4839
4840/// isBlockOnlyReachableByFallthough - Return true if the basic block has
4841/// exactly one predecessor and the control transfer mechanism between
4842/// the predecessor and this block is a fall-through.
4845 // If this is a landing pad, it isn't a fall through. If it has no preds,
4846 // then nothing falls through to it.
4847 if (MBB->isEHPad() || MBB->pred_empty())
4848 return false;
4849
4850 // If there isn't exactly one predecessor, it can't be a fall through.
4851 if (MBB->pred_size() > 1)
4852 return false;
4853
4854 // The predecessor has to be immediately before this block.
4855 MachineBasicBlock *Pred = *MBB->pred_begin();
4856 if (!Pred->isLayoutSuccessor(MBB))
4857 return false;
4858
4859 // If the block is completely empty, then it definitely does fall through.
4860 if (Pred->empty())
4861 return true;
4862
4863 // Check the terminators in the previous blocks
4864 for (const auto &MI : Pred->terminators()) {
4865 // If it is not a simple branch, we are in a table somewhere.
4866 if (!MI.isBranch() || MI.isIndirectBranch())
4867 return false;
4868
4869 // If we are the operands of one of the branches, this is not a fall
4870 // through. Note that targets with delay slots will usually bundle
4871 // terminators with the delay slot instruction.
4872 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
4873 if (OP->isJTI())
4874 return false;
4875 if (OP->isMBB() && OP->getMBB() == MBB)
4876 return false;
4877 }
4878 }
4879
4880 return true;
4881}
4882
4883GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
4884 if (!S.usesMetadata())
4885 return nullptr;
4886
4887 auto [GCPI, Inserted] = GCMetadataPrinters.try_emplace(&S);
4888 if (!Inserted)
4889 return GCPI->second.get();
4890
4891 auto Name = S.getName();
4892
4893 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
4895 if (Name == GCMetaPrinter.getName()) {
4896 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
4897 GMP->S = &S;
4898 GCPI->second = std::move(GMP);
4899 return GCPI->second.get();
4900 }
4901
4902 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
4903}
4904
4906 std::unique_ptr<AsmPrinterHandler> Handler) {
4907 Handlers.insert(Handlers.begin(), std::move(Handler));
4909}
4910
4911/// Pin vtables to this file.
4913
4915
4916// In the binary's "xray_instr_map" section, an array of these function entries
4917// describes each instrumentation point. When XRay patches your code, the index
4918// into this table will be given to your handler as a patch point identifier.
4920 auto Kind8 = static_cast<uint8_t>(Kind);
4921 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
4922 Out->emitBinaryData(
4923 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
4924 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
4925 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
4926 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
4927 Out->emitZeros(Padding);
4928}
4929
4931 if (Sleds.empty())
4932 return;
4933
4934 auto PrevSection = OutStreamer->getCurrentSectionOnly();
4935 const Function &F = MF->getFunction();
4936 MCSection *InstMap = nullptr;
4937 MCSection *FnSledIndex = nullptr;
4938 const Triple &TT = TM.getTargetTriple();
4939 // Use PC-relative addresses on all targets.
4940 if (TT.isOSBinFormatELF()) {
4941 auto LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
4942 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
4943 StringRef GroupName;
4944 if (F.hasComdat()) {
4945 Flags |= ELF::SHF_GROUP;
4946 GroupName = F.getComdat()->getName();
4947 }
4948 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
4949 Flags, 0, GroupName, F.hasComdat(),
4950 MCSection::NonUniqueID, LinkedToSym);
4951
4952 if (TM.Options.XRayFunctionIndex)
4953 FnSledIndex = OutContext.getELFSection(
4954 "xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
4955 MCSection::NonUniqueID, LinkedToSym);
4956 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
4957 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map",
4960 if (TM.Options.XRayFunctionIndex)
4961 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx",
4964 } else {
4965 llvm_unreachable("Unsupported target");
4966 }
4967
4968 auto WordSizeBytes = MAI->getCodePointerSize();
4969
4970 // Now we switch to the instrumentation map section. Because this is done
4971 // per-function, we are able to create an index entry that will represent the
4972 // range of sleds associated with a function.
4973 auto &Ctx = OutContext;
4974 MCSymbol *SledsStart =
4975 OutContext.createLinkerPrivateSymbol("xray_sleds_start");
4976 OutStreamer->switchSection(InstMap);
4977 OutStreamer->emitLabel(SledsStart);
4978 for (const auto &Sled : Sleds) {
4979 MCSymbol *Dot = Ctx.createTempSymbol();
4980 OutStreamer->emitLabel(Dot);
4981 OutStreamer->emitValueImpl(
4983 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
4984 WordSizeBytes);
4985 OutStreamer->emitValueImpl(
4989 MCConstantExpr::create(WordSizeBytes, Ctx),
4990 Ctx),
4991 Ctx),
4992 WordSizeBytes);
4993 Sled.emit(WordSizeBytes, OutStreamer.get());
4994 }
4995 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
4996 OutStreamer->emitLabel(SledsEnd);
4997
4998 // We then emit a single entry in the index per function. We use the symbols
4999 // that bound the instrumentation map as the range for a specific function.
5000 // Each entry contains 2 words and needs to be word-aligned.
5001 if (FnSledIndex) {
5002 OutStreamer->switchSection(FnSledIndex);
5003 OutStreamer->emitValueToAlignment(Align(WordSizeBytes));
5004 // For Mach-O, use an "l" symbol as the atom of this subsection. The label
5005 // difference uses a SUBTRACTOR external relocation which references the
5006 // symbol.
5007 MCSymbol *Dot = Ctx.createLinkerPrivateSymbol("xray_fn_idx");
5008 OutStreamer->emitLabel(Dot);
5009 OutStreamer->emitValueImpl(
5011 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5012 WordSizeBytes);
5013 OutStreamer->emitValueImpl(MCConstantExpr::create(Sleds.size(), Ctx),
5014 WordSizeBytes);
5015 OutStreamer->switchSection(PrevSection);
5016 }
5017 Sleds.clear();
5018}
5019
5021 SledKind Kind, uint8_t Version) {
5022 const Function &F = MI.getMF()->getFunction();
5023 auto Attr = F.getFnAttribute("function-instrument");
5024 bool LogArgs = F.hasFnAttribute("xray-log-args");
5025 bool AlwaysInstrument =
5026 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
5027 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
5029 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
5030 AlwaysInstrument, &F, Version});
5031}
5032
5034 const Function &F = MF->getFunction();
5035 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
5036 (void)F.getFnAttribute("patchable-function-prefix")
5037 .getValueAsString()
5038 .getAsInteger(10, PatchableFunctionPrefix);
5039 (void)F.getFnAttribute("patchable-function-entry")
5040 .getValueAsString()
5041 .getAsInteger(10, PatchableFunctionEntry);
5042 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
5043 return;
5044 const unsigned PointerSize = getPointerSize();
5045 if (TM.getTargetTriple().isOSBinFormatELF()) {
5046 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
5047 const MCSymbolELF *LinkedToSym = nullptr;
5048 StringRef GroupName, SectionName;
5049
5050 if (F.hasFnAttribute("patchable-function-entry-section"))
5051 SectionName = F.getFnAttribute("patchable-function-entry-section")
5052 .getValueAsString();
5053 if (SectionName.empty())
5054 SectionName = "__patchable_function_entries";
5055
5056 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
5057 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
5058 if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
5059 Flags |= ELF::SHF_LINK_ORDER;
5060 if (F.hasComdat()) {
5061 Flags |= ELF::SHF_GROUP;
5062 GroupName = F.getComdat()->getName();
5063 }
5064 LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5065 }
5066 OutStreamer->switchSection(OutContext.getELFSection(
5067 SectionName, ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5068 MCSection::NonUniqueID, LinkedToSym));
5069 emitAlignment(Align(PointerSize));
5070 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
5071 }
5072}
5073
5075 return OutStreamer->getContext().getDwarfVersion();
5076}
5077
5079 OutStreamer->getContext().setDwarfVersion(Version);
5080}
5081
5083 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
5084}
5085
5088 OutStreamer->getContext().getDwarfFormat());
5089}
5090
5092 return {getDwarfVersion(), uint8_t(MAI->getCodePointerSize()),
5093 OutStreamer->getContext().getDwarfFormat(),
5095}
5096
5099 OutStreamer->getContext().getDwarfFormat());
5100}
5101
5102std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
5105 const MCSymbol *BranchLabel) const {
5106 const auto TLI = MF->getSubtarget().getTargetLowering();
5107 const auto BaseExpr =
5108 TLI->getPICJumpTableRelocBaseExpr(MF, JTI, MMI->getContext());
5109 const auto Base = &cast<MCSymbolRefExpr>(BaseExpr)->getSymbol();
5110
5111 // By default, for the architectures that support CodeView,
5112 // EK_LabelDifference32 is implemented as an Int32 from the base address.
5113 return std::make_tuple(Base, 0, BranchLabel,
5115}
5116
5118 const Triple &TT = TM.getTargetTriple();
5119 assert(TT.isOSBinFormatCOFF());
5120
5121 bool IsTargetArm64EC = TT.isWindowsArm64EC();
5123 SmallVector<MCSymbol *> FuncOverrideDefaultSymbols;
5124 bool SwitchedToDirectiveSection = false;
5125 for (const Function &F : M.functions()) {
5126 if (F.hasFnAttribute("loader-replaceable")) {
5127 if (!SwitchedToDirectiveSection) {
5128 OutStreamer->switchSection(
5129 OutContext.getObjectFileInfo()->getDrectveSection());
5130 SwitchedToDirectiveSection = true;
5131 }
5132
5133 StringRef Name = F.getName();
5134
5135 // For hybrid-patchable targets, strip the prefix so that we can mark
5136 // the real function as replaceable.
5137 if (IsTargetArm64EC && Name.ends_with(HybridPatchableTargetSuffix)) {
5138 Name = Name.drop_back(HybridPatchableTargetSuffix.size());
5139 }
5140
5141 MCSymbol *FuncOverrideSymbol =
5142 MMI->getContext().getOrCreateSymbol(Name + "_$fo$");
5143 OutStreamer->beginCOFFSymbolDef(FuncOverrideSymbol);
5144 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5145 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5146 OutStreamer->endCOFFSymbolDef();
5147
5148 MCSymbol *FuncOverrideDefaultSymbol =
5149 MMI->getContext().getOrCreateSymbol(Name + "_$fo_default$");
5150 OutStreamer->beginCOFFSymbolDef(FuncOverrideDefaultSymbol);
5151 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5152 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5153 OutStreamer->endCOFFSymbolDef();
5154 FuncOverrideDefaultSymbols.push_back(FuncOverrideDefaultSymbol);
5155
5156 OutStreamer->emitBytes((Twine(" /ALTERNATENAME:") +
5157 FuncOverrideSymbol->getName() + "=" +
5158 FuncOverrideDefaultSymbol->getName())
5159 .toStringRef(Buf));
5160 Buf.clear();
5161 }
5162 }
5163
5164 if (SwitchedToDirectiveSection)
5165 OutStreamer->popSection();
5166
5167 if (FuncOverrideDefaultSymbols.empty())
5168 return;
5169
5170 // MSVC emits the symbols for the default variables pointing at the start of
5171 // the .data section, but doesn't actually allocate any space for them. LLVM
5172 // can't do this, so have all of the variables pointing at a single byte
5173 // instead.
5174 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
5175 for (MCSymbol *Symbol : FuncOverrideDefaultSymbols) {
5176 OutStreamer->emitLabel(Symbol);
5177 }
5178 OutStreamer->emitZeros(1);
5179 OutStreamer->popSection();
5180}
5181
5183 const Triple &TT = TM.getTargetTriple();
5184 assert(TT.isOSBinFormatCOFF());
5185
5186 // Emit an absolute @feat.00 symbol.
5187 MCSymbol *S = MMI->getContext().getOrCreateSymbol(StringRef("@feat.00"));
5188 OutStreamer->beginCOFFSymbolDef(S);
5189 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
5190 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5191 OutStreamer->endCOFFSymbolDef();
5192 int64_t Feat00Value = 0;
5193
5194 if (TT.getArch() == Triple::x86) {
5195 // According to the PE-COFF spec, the LSB of this value marks the object
5196 // for "registered SEH". This means that all SEH handler entry points
5197 // must be registered in .sxdata. Use of any unregistered handlers will
5198 // cause the process to terminate immediately. LLVM does not know how to
5199 // register any SEH handlers, so its object files should be safe.
5200 Feat00Value |= COFF::Feat00Flags::SafeSEH;
5201 }
5202
5203 if (M.getControlFlowGuardMode() == ControlFlowGuardMode::Enabled) {
5204 // Object is CFG-aware. Only set if we actually inserted the checks.
5205 Feat00Value |= COFF::Feat00Flags::GuardCF;
5206 }
5207
5208 if (M.getModuleFlag("ehcontguard")) {
5209 // Object also has EHCont.
5210 Feat00Value |= COFF::Feat00Flags::GuardEHCont;
5211 }
5212
5213 if (M.getModuleFlag("ms-kernel")) {
5214 // Object is compiled with /kernel.
5215 Feat00Value |= COFF::Feat00Flags::Kernel;
5216 }
5217
5218 OutStreamer->emitSymbolAttribute(S, MCSA_Global);
5219 OutStreamer->emitAssignment(
5220 S, MCConstantExpr::create(Feat00Value, MMI->getContext()));
5221}
5222
5223namespace llvm {
5224namespace {
5226 MachineFunction &MF) {
5228 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
5231 MF.getFunction())
5232 .getManager();
5233 return MFAM;
5234}
5235} // anonymous namespace
5236
5239 MachineModuleInfo &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
5240 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5241 AsmPrinter.MMI = &MMI;
5242 AsmPrinter.GetORE = [&MAM, &M](MachineFunction &MF) {
5243 return &getMFAM(M, MAM, MF)
5245 };
5246 AsmPrinter.GetMDT = [&MAM, &M](MachineFunction &MF) {
5247 return &getMFAM(M, MAM, MF).getResult<MachineDominatorTreeAnalysis>(MF);
5248 };
5249 AsmPrinter.GetMLI = [&MAM, &M](MachineFunction &MF) {
5250 return &getMFAM(M, MAM, MF).getResult<MachineLoopAnalysis>(MF);
5251 };
5252 // TODO(boomanaiden154): Get GC working with the new pass manager.
5253 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5255 AsmPrinter.EmitStackMaps = [](Module &M) {};
5257}
5258
5260 MachineFunction &MF,
5262 const ModuleAnalysisManagerMachineFunctionProxy::Result &MAMProxy =
5264 MachineModuleInfo &MMI =
5265 MAMProxy
5266 .getCachedResult<MachineModuleAnalysis>(*MF.getFunction().getParent())
5267 ->getMMI();
5268 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5269 AsmPrinter.MMI = &MMI;
5270 AsmPrinter.GetORE = [&MFAM](MachineFunction &MF) {
5272 };
5273 AsmPrinter.GetMDT = [&MFAM](MachineFunction &MF) {
5274 return &MFAM.getResult<MachineDominatorTreeAnalysis>(MF);
5275 };
5276 AsmPrinter.GetMLI = [&MFAM](MachineFunction &MF) {
5277 return &MFAM.getResult<MachineLoopAnalysis>(MF);
5278 };
5279 // TODO(boomanaiden154): Get GC working with the new pass manager.
5280 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5282 AsmPrinter.EmitStackMaps = [](Module &M) {};
5284}
5285
5286} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< bool > PgoAnalysisMapEmitBBSectionsCfg("pgo-analysis-map-emit-bb-sections-cfg", cl::desc("Enable the post-link cfg information from the basic block " "sections profile in the PGO analysis map"), cl::Hidden, cl::init(false))
static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP)
emitDebugValueComment - This method handles the target-independent form of DBG_VALUE,...
static cl::opt< std::string > StackUsageFile("stack-usage-file", cl::desc("Output filename for stack usage information"), cl::value_desc("filename"), cl::Hidden)
static uint32_t getBBAddrMapMetadata(const MachineBasicBlock &MBB)
Returns the BB metadata to be emitted in the SHT_LLVM_BB_ADDR_MAP section for a given basic block.
cl::opt< bool > EmitBBHash
static cl::opt< bool > BBAddrMapSkipEmitBBEntries("basic-block-address-map-skip-bb-entries", cl::desc("Skip emitting basic block entries in the SHT_LLVM_BB_ADDR_MAP " "section. It's used to save binary size when BB entries are " "unnecessary for some PGOAnalysisMap features."), cl::Hidden, cl::init(false))
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
static void emitFakeUse(const MachineInstr *MI, AsmPrinter &AP)
static bool isGOTEquivalentCandidate(const GlobalVariable *GV, unsigned &NumGOTEquivUsers, bool &HasNonGlobalUsers)
Only consider global GOT equivalents if at least one user is a cstexpr inside an initializer of anoth...
static void emitGlobalConstantLargeByte(const ConstantByte *CB, AsmPrinter &AP)
static void tagGlobalDefinition(Module &M, GlobalVariable *G)
static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, const MachineLoopInfo *LI, const AsmPrinter &AP)
emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
static void emitGlobalConstantLargeAPInt(const APInt &Val, uint64_t TypeStoreSize, AsmPrinter &AP)
static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, const Constant *BaseCst, uint64_t Offset)
Transform a not absolute MCExpr containing a reference to a GOT equivalent global,...
static llvm::object::BBAddrMap::Features getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges, bool HasCalls, const CFGProfile *FuncCFGProfile)
static int isRepeatedByteSequence(const ConstantDataSequential *V)
isRepeatedByteSequence - Determine whether the given value is composed of a repeated sequence of iden...
static void emitGlobalAliasInline(AsmPrinter &AP, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
static bool needFuncLabels(const MachineFunction &MF, const AsmPrinter &Asm)
Returns true if function begin and end labels should be emitted.
static unsigned getNumGlobalVariableUses(const Constant *C, bool &HasNonGlobalUsers)
Compute the number of Global Variables that uses a Constant.
static cl::bits< PGOMapFeaturesEnum > PgoAnalysisMapFeatures("pgo-analysis-map", cl::Hidden, cl::CommaSeparated, cl::values(clEnumValN(PGOMapFeaturesEnum::None, "none", "Disable all options"), clEnumValN(PGOMapFeaturesEnum::FuncEntryCount, "func-entry-count", "Function Entry Count"), clEnumValN(PGOMapFeaturesEnum::BBFreq, "bb-freq", "Basic Block Frequency"), clEnumValN(PGOMapFeaturesEnum::BrProb, "br-prob", "Branch Probability"), clEnumValN(PGOMapFeaturesEnum::All, "all", "Enable all options")), cl::desc("Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is " "extracted from PGO related analysis."))
static void removeMemtagFromGlobal(GlobalVariable &G)
static uint64_t globalSize(const llvm::GlobalVariable &G)
static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintChildLoopComment - Print comments about child loops within the loop for this basic block,...
static StringRef getMIMnemonic(const MachineInstr &MI, MCStreamer &Streamer)
PGOMapFeaturesEnum
static void emitComments(const MachineInstr &MI, const MCSubtargetInfo *STI, raw_ostream &CommentOS)
emitComments - Pretty-print comments for instructions.
static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintParentLoopComment - Print comments about parent loops of this one.
static void emitGlobalConstantStruct(const DataLayout &DL, const ConstantStruct *CS, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
static void emitGlobalConstantDataSequential(const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP, AsmPrinter::AliasMapTy *AliasList)
static void emitKill(const MachineInstr *MI, AsmPrinter &AP)
static bool shouldTagGlobal(const llvm::GlobalVariable &G)
static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, AsmPrinter &AP, const Constant *BaseCV=nullptr, uint64_t Offset=0, AsmPrinter::AliasMapTy *AliasList=nullptr)
static ConstantInt * extractNumericCGTypeId(const Function &F)
Extracts a generalized numeric type identifier of a Function's type from type metadata.
static cl::opt< bool > PrintLatency("asm-print-latency", cl::desc("Print instruction latencies as verbose asm comments"), cl::Hidden, cl::init(false))
static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP)
This method handles the target-independent form of DBG_LABEL, returning true if it was able to do so.
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI)
static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV, AsmPrinter &AP, AsmPrinter::AliasMapTy *AliasList)
static cl::opt< bool > EmitJumpTableSizesSection("emit-jump-table-sizes-section", cl::desc("Emit a section containing jump table addresses and sizes"), cl::Hidden, cl::init(false))
static void emitGlobalConstantArray(const DataLayout &DL, const ConstantArray *CA, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP)
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
#define DEBUG_TYPE
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
const FeatureInfo AllFeatures[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
#define T
static constexpr StringLiteral Filename
OptimizedStructLayoutField Field
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file contains some templates that are useful if you are working with the STL at all.
#define OP(OPC)
Definition Instruction.h:46
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
This file describes how to lower LLVM code to machine code.
Defines the virtual file system interface vfs::FileSystem.
Value * LHS
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5976
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6035
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition APFloat.h:1545
APInt bitcastToAPInt() const
Definition APFloat.h:1408
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1503
unsigned getNumWords() const
Get the number of words.
Definition APInt.h:1510
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:576
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1577
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:865
AddrLabelMap(MCContext &context)
void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New)
void takeDeletedSymbolsForFunction(Function *F, std::vector< MCSymbol * > &Result)
If we have any deleted symbols for F, return them.
void UpdateForDeletedBlock(BasicBlock *BB)
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(BasicBlock *BB)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
front - Get the first element.
Definition ArrayRef.h:145
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
virtual ~AsmPrinterHandler()
Pin vtables to this file.
virtual void markFunctionEnd()
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition AsmPrinter.h:642
void emitDanglingPrefetchTargets()
Emit prefetch targets that were not mapped to any basic block.
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
MCSymbol * getSymbol(const GlobalValue *GV) const
void emitULEB128(uint64_t Value, const char *Desc=nullptr, unsigned PadTo=0) const
Emit the specified unsigned leb128 value.
SmallVector< XRayFunctionEntry, 4 > Sleds
Definition AsmPrinter.h:431
MapVector< MBBSectionID, MBBSectionRange > MBBSectionRanges
Definition AsmPrinter.h:158
bool isDwarf64() const
void emitNops(unsigned N)
Emit N NOP instructions.
MCSymbol * CurrentFnBegin
Definition AsmPrinter.h:233
MachineLoopInfo * MLI
This is a pointer to the current MachineLoopInfo.
Definition AsmPrinter.h:118
virtual void emitDebugValue(const MCExpr *Value, unsigned Size) const
Emit the directive and value for debug thread local expression.
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
virtual void emitConstantPool()
Print to the current output stream assembly representations of the constants in the constant pool MCP...
virtual void emitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
std::function< MachineOptimizationRemarkEmitter *(MachineFunction &)> GetORE
Definition AsmPrinter.h:177
virtual const MCExpr * lowerConstantPtrAuth(const ConstantPtrAuth &CPA)
Definition AsmPrinter.h:663
unsigned int getUnitLengthFieldByteSize() const
Returns 4 for DWARF32 and 12 for DWARF64.
void emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label+Offset" where the size in bytes of the directive is specified by Siz...
~AsmPrinter() override
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:94
void emitXRayTable()
Emit a table with all XRay instrumentation points.
virtual void emitGlobalAlias(const Module &M, const GlobalAlias &GA)
DenseMap< const MachineBasicBlock *, SmallVector< MCSymbol *, 1 > > CurrentFnCallsiteEndSymbols
Vector of symbols marking the end of the callsites in the current function, keyed by their containing...
Definition AsmPrinter.h:144
virtual void emitBasicBlockEnd(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the end of a basic block.
virtual void emitJumpTableEntry(const MachineJumpTableInfo &MJTI, const MachineBasicBlock *MBB, unsigned uid) const
EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the current stream.
MCSymbol * CurrentFnDescSym
The symbol for the current function descriptor on AIX.
Definition AsmPrinter.h:132
MCSymbol * CurrentFnBeginLocal
For dso_local functions, the current $local alias for the function.
Definition AsmPrinter.h:236
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition AsmPrinter.h:163
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
void emitGlobalGOTEquivs()
Constant expressions using GOT equivalent globals may not be eligible for PC relative GOT entry conve...
MCSymbol * getFunctionBegin() const
Definition AsmPrinter.h:321
void emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) const
Emit something like ".long Hi-Lo" where the size in bytes of the directive is specified by Size and H...
void emitKCFITrapEntry(const MachineFunction &MF, const MCSymbol *Symbol)
virtual void emitMachOIFuncStubHelperBody(Module &M, const GlobalIFunc &GI, MCSymbol *LazyPointer)
Definition AsmPrinter.h:694
MCSymbol * getMBBExceptionSym(const MachineBasicBlock &MBB)
std::function< void(Module &)> EmitStackMaps
Definition AsmPrinter.h:182
MCSymbol * getAddrLabelSymbol(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
Definition AsmPrinter.h:331
virtual DwarfDebug * createDwarfDebug()
Create the DwarfDebug handler.
const MCAsmInfo * MAI
Target Asm Printer information.
Definition AsmPrinter.h:97
SmallVector< std::unique_ptr< AsmPrinterHandler >, 2 > Handlers
Definition AsmPrinter.h:246
bool emitSpecialLLVMGlobal(const GlobalVariable *GV)
Check to see if the specified global is a special global used by LLVM.
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:109
virtual void emitJumpTableInfo()
Print assembly representations of the jump tables used by the current function to the current output ...
void computeGlobalGOTEquivs(Module &M)
Unnamed constant global variables solely contaning a pointer to another globals variable act like a g...
static Align getGVAlignment(const GlobalObject *GV, const DataLayout &DL, Align InAlign=Align(1))
Return the alignment for the specified GV.
MCSymbol * createCallsiteEndSymbol(const MachineBasicBlock &MBB)
Creates a new symbol to be used for the end of a callsite at the specified basic block.
virtual const MCExpr * lowerConstant(const Constant *CV, const Constant *BaseCV=nullptr, uint64_t Offset=0)
Lower the specified LLVM Constant to an MCExpr.
void emitCallGraphSection(const MachineFunction &MF, FunctionCallGraphInfo &FuncCGInfo)
Emits .llvm.callgraph section.
void emitInt8(int Value) const
Emit a byte directive and value.
CFISection getFunctionCFISectionType(const Function &F) const
Get the CFISection type for a function.
virtual void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
void emitFunctionBody()
This method emits the body and trailer for a function.
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
void emitBBAddrMapSection(const MachineFunction &MF)
void emitPCSections(const MachineFunction &MF)
Emits the PC sections collected from instructions.
MachineDominatorTree * MDT
This is a pointer to the current MachineDominatorTree.
Definition AsmPrinter.h:115
virtual void emitStartOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the start of their fi...
Definition AsmPrinter.h:618
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
std::function< void(Module &)> FinishGCAssembly
Definition AsmPrinter.h:181
virtual void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV)
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition AsmPrinter.h:520
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition AsmPrinter.h:626
std::function< MachineDominatorTree *(MachineFunction &)> GetMDT
Definition AsmPrinter.h:178
std::pair< const GlobalVariable *, unsigned > GOTEquivUsePair
Map global GOT equivalent MCSymbols to GlobalVariables and keep track of its number of uses by other ...
Definition AsmPrinter.h:162
void emitPatchableFunctionEntries()
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
virtual void emitEndOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the end of their file...
Definition AsmPrinter.h:622
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
MCSymbol * GetJTSetSymbol(unsigned UID, unsigned MBBID) const
Return the symbol for the specified jump table .set FIXME: privatize to AsmPrinter.
virtual void emitMachOIFuncStubBody(Module &M, const GlobalIFunc &GI, MCSymbol *LazyPointer)
Definition AsmPrinter.h:688
virtual void emitImplicitDef(const MachineInstr *MI) const
Targets can override this to customize the output of IMPLICIT_DEF instructions in verbose mode.
virtual void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const
This emits linkage information about GVSym based on GV, if this is supported by the target.
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
unsigned getFunctionNumber() const
Return a unique ID for the current function.
MachineOptimizationRemarkEmitter * ORE
Optimization remark emitter.
Definition AsmPrinter.h:121
DenseMap< uint64_t, SmallVector< const GlobalAlias *, 1 > > AliasMapTy
Print a general LLVM constant to the .s file.
Definition AsmPrinter.h:588
virtual bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer, char &ID=AsmPrinter::ID)
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
void emitGlobalConstant(const DataLayout &DL, const Constant *CV, AliasMapTy *AliasList=nullptr)
EmitGlobalConstant - Print a general LLVM constant to the .s file.
void emitFrameAlloc(const MachineInstr &MI)
void emitStackSizeSection(const MachineFunction &MF)
MCSymbol * getSymbolPreferLocal(const GlobalValue &GV) const
Similar to getSymbol() but preferred for references.
std::function< void(Module &)> BeginGCAssembly
Definition AsmPrinter.h:180
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition AsmPrinter.h:128
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition AsmPrinter.h:112
void emitSLEB128(int64_t Value, const char *Desc=nullptr) const
Emit the specified signed leb128 value.
void emitAlignment(Align Alignment, const GlobalObject *GV=nullptr, unsigned MaxBytesToEmit=0) const
Emit an alignment directive to the specified power of two boundary.
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:101
const StaticDataProfileInfo * SDPI
Provides the profile information for constants.
Definition AsmPrinter.h:147
void emitCFIInstruction(const MachineInstr &MI)
MCSymbol * createTempSymbol(const Twine &Name) const
bool doFinalization(Module &M) override
Shut down the asmprinter.
virtual const MCSubtargetInfo * getIFuncMCSubtargetInfo() const
getSubtargetInfo() cannot be used where this is needed because we don't have a MachineFunction when w...
Definition AsmPrinter.h:684
void emitStackUsage(const MachineFunction &MF)
virtual void emitKCFITypeId(const MachineFunction &MF)
bool isPositionIndependent() const
virtual void emitXXStructorList(const DataLayout &DL, const Constant *List, bool IsCtor)
This method emits llvm.global_ctors or llvm.global_dtors list.
void emitPCSectionsLabel(const MachineFunction &MF, const MDNode &MD)
Emits a label as reference for PC sections.
MCSymbol * CurrentPatchableFunctionEntrySym
The symbol for the entry in __patchable_function_entires.
Definition AsmPrinter.h:124
virtual void emitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
void takeDeletedSymbolsForFunction(const Function *F, std::vector< MCSymbol * > &Result)
If the specified function has had any references to address-taken blocks generated,...
void emitVisibility(MCSymbol *Sym, unsigned Visibility, bool IsDefinition=true) const
This emits visibility information about symbol, if this is supported by the target.
void emitInt32(int Value) const
Emit a long directive and value.
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:106
const ProfileSummaryInfo * PSI
The profile summary information.
Definition AsmPrinter.h:150
std::function< void()> AssertDebugEHFinalized
Definition AsmPrinter.h:183
void emitPrefetchTargetSymbol(unsigned BaseID, unsigned CallsiteIndex)
Helper to emit a symbol for the prefetch target associated with the given BBID and callsite index.
virtual void emitFunctionDescriptor()
Definition AsmPrinter.h:651
const MCSection * getCurrentSection() const
Return the current section we are emitting to.
unsigned int getDwarfOffsetByteSize() const
Returns 4 for DWARF32 and 8 for DWARF64.
size_t NumUserHandlers
Definition AsmPrinter.h:247
MCSymbol * CurrentFnSymForSize
The symbol used to represent the start of the current function for the purpose of calculating its siz...
Definition AsmPrinter.h:137
std::function< MachineLoopInfo *(MachineFunction &)> GetMLI
Definition AsmPrinter.h:179
std::function< MachineModuleInfo *()> GetMMI
Definition AsmPrinter.h:176
bool isVerbose() const
Return true if assembly output should contain comments.
Definition AsmPrinter.h:312
MCSymbol * getFunctionEnd() const
Definition AsmPrinter.h:322
virtual void emitXXStructor(const DataLayout &DL, const Constant *CV)
Targets can override this to change how global constants that are part of a C++ static/global constru...
Definition AsmPrinter.h:659
void preprocessXXStructorList(const DataLayout &DL, const Constant *List, SmallVector< Structor, 8 > &Structors)
This method gathers an array of Structors and then sorts them out by Priority.
void emitInt16(int Value) const
Emit a short directive and value.
void setDwarfVersion(uint16_t Version)
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
StringRef getConstantSectionSuffix(const Constant *C) const
Returns a section suffix (hot or unlikely) for the constant if profiles are available.
SmallVector< std::unique_ptr< AsmPrinterHandler >, 1 > EHHandlers
A handle to the EH info emitter (if present).
Definition AsmPrinter.h:241
void emitPseudoProbe(const MachineInstr &MI)
unsigned getPointerSize() const
Return the pointer size from the TargetMachine.
void emitRemarksSection(remarks::RemarkStreamer &RS)
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
virtual void emitFunctionBodyEnd()
Targets can override this to emit stuff after the last basic block in the function.
Definition AsmPrinter.h:630
const DataLayout & getDataLayout() const
Return information about data layout.
void emitCOFFFeatureSymbol(Module &M)
Emits the @feat.00 symbol indicating the features enabled in this module.
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
void emitInitialRawDwarfLocDirective(const MachineFunction &MF)
Emits inital debug location directive.
MCSymbol * GetExternalSymbolSymbol(const Twine &Sym) const
Return the MCSymbol for the specified ExternalSymbol.
void handleCallsiteForCallgraph(FunctionCallGraphInfo &FuncCGInfo, const MachineFunction::CallSiteInfoMap &CallSitesInfoMap, const MachineInstr &MI)
If MI is an indirect call, add expected type IDs to indirect type ids list.
void emitInt64(uint64_t Value) const
Emit a long long directive and value.
uint16_t getDwarfVersion() const
dwarf::FormParams getDwarfFormParams() const
Returns information about the byte size of DW_FORM values.
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
void emitCOFFReplaceableFunctionData(Module &M)
Emits symbols and data to allow functions marked with the loader-replaceable attribute to be replacea...
bool usesCFIWithoutEH() const
Since emitting CFI unwind information is entangled with supporting the exceptions,...
bool doesDwarfUseRelocationsAcrossSections() const
Definition AsmPrinter.h:381
@ None
Do not emit either .eh_frame or .debug_frame.
Definition AsmPrinter.h:167
@ Debug
Emit .debug_frame.
Definition AsmPrinter.h:169
void addAsmPrinterHandler(std::unique_ptr< AsmPrinterHandler > Handler)
virtual std::tuple< const MCSymbol *, uint64_t, const MCSymbol *, codeview::JumpTableEntrySize > getCodeViewJumpTableInfo(int JTI, const MachineInstr *BranchInstr, const MCSymbol *BranchLabel) const
Gets information required to create a CodeView debug symbol for a jump table.
void emitLabelDifferenceAsULEB128(const MCSymbol *Hi, const MCSymbol *Lo) const
Emit something like ".uleb128 Hi-Lo".
virtual const MCExpr * lowerBlockAddressConstant(const BlockAddress &BA)
Lower the specified BlockAddress to an MCExpr.
const CFGProfile * getFunctionCFGProfile(StringRef FuncName) const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
unsigned getNumber() const
Definition BasicBlock.h:95
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:675
The address of a basic block.
Definition Constants.h:1065
BasicBlock * getBasicBlock() const
Definition Constants.h:1100
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
uint32_t getNumerator() const
Value handle with callbacks on RAUW and destruction.
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
ConstantArray - Constant Array Declarations.
Definition Constants.h:576
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition Constants.h:595
Class for constant bytes.
Definition Constants.h:281
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:345
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:859
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:736
LLVM_ABI APFloat getElementAsAPFloat(uint64_t i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
LLVM_ABI uint64_t getElementAsInteger(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:812
LLVM_ABI uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
LLVM_ABI bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers or bytes.
LLVM_ABI uint64_t getNumElements() const
Return the number of elements in the array or vector.
LLVM_ABI Type * getElementType() const
Return the element type of the array/vector.
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1291
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A signed pointer, in the ptrauth sense.
Definition Constants.h:1198
StructType * getType() const
Specialization - reduce amount of casting.
Definition Constants.h:647
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:629
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:74
DWARF expression.
iterator_range< expr_op_iterator > expr_ops() const
unsigned getNumElements() const
static LLVM_ABI std::optional< const DIExpression * > convertToNonVariadicExpression(const DIExpression *Expr)
If Expr is a valid single-location expression, i.e.
Subprogram description. Uses SubclassData1.
Wrapper for a function that represents a value that functionally represents the original function.
Definition Constants.h:1118
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isBigEndian() const
Definition DataLayout.h:216
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:572
A debug info location.
Definition DebugLoc.h:123
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool empty() const
Definition DenseMap.h:109
iterator end()
Definition DenseMap.h:81
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Collects and handles dwarf debug information.
Definition DwarfDebug.h:352
Emits exception handling directives.
Definition EHStreamer.h:30
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:905
Constant * getPersonalityFn() const
Get the personality function associated with this function.
const Function & getFunction() const
Definition Function.h:166
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
GCMetadataPrinter - Emits GC metadata as assembly code.
An analysis pass which caches information about the entire Module.
Definition GCMetadata.h:237
SmallVector< std::unique_ptr< GCStrategy >, 1 >::const_iterator iterator
Definition GCMetadata.h:266
GCStrategy describes a garbage collector algorithm's code generation requirements,...
Definition GCStrategy.h:64
bool usesMetadata() const
If set, appropriate metadata tables must be emitted by the back-end (assembler, JIT,...
Definition GCStrategy.h:120
const std::string & getName() const
Return the name of the GC strategy.
Definition GCStrategy.h:90
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:651
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:680
const Constant * getResolver() const
Definition GlobalIFunc.h:73
StringRef getSection() const
Get the custom section of this global if it has one.
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition Value.h:603
bool hasSection() const
Check if this global has a custom object file section.
bool hasLinkOnceLinkage() const
bool hasExternalLinkage() const
bool isDSOLocal() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
VisibilityTypes getVisibility() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:329
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool hasPrivateLinkage() const
bool isTagged() const
bool isDeclarationForLinker() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:133
LLVM_ABI bool canBenefitFromLocalAlias() const
Definition Globals.cpp:115
bool hasComdat() const
bool hasWeakLinkage() const
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition Globals.cpp:467
bool hasAvailableExternallyLinkage() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:561
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Itinerary data supplied by a subtarget to be used by a target.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:354
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
This is an alternative analysis pass to MachineBlockFrequencyInfo.
A helper class to return the specified delimiter string after the first invocation of operator String...
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:64
bool hasWeakDefCanBeHiddenDirective() const
Definition MCAsmInfo.h:616
bool hasSubsectionsViaSymbols() const
Definition MCAsmInfo.h:459
const char * getWeakRefDirective() const
Definition MCAsmInfo.h:614
bool hasIdentDirective() const
Definition MCAsmInfo.h:611
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:343
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:428
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
unsigned getOpcode() const
Definition MCInst.h:202
void setOpcode(unsigned Op)
Definition MCInst.h:201
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
MCSection * getTLSBSSSection() const
MCSection * getStackSizesSection(const MCSection &TextSec) const
MCSection * getBBAddrMapSection(const MCSection &TextSec) const
MCSection * getTLSExtraDataSection() const
MCSection * getKCFITrapSection(const MCSection &TextSec) const
MCSection * getPCSection(StringRef Name, const MCSection *TextSec) const
MCSection * getCallGraphSection(const MCSection &TextSec) const
MCSection * getDataSection() const
This represents a section on Windows.
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:516
bool isBssSection() const
Check whether this section is "virtual", that is has no actual object file contents.
Definition MCSection.h:646
static constexpr unsigned NonUniqueID
Definition MCSection.h:521
Streaming machine code generation interface.
Definition MCStreamer.h:221
virtual void emitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
virtual StringRef getMnemonic(const MCInst &MI) const
Returns the mnemonic for MI, if the streamer has access to a instruction printer and returns an empty...
Definition MCStreamer.h:477
void emitZeros(uint64_t NumBytes)
Emit NumBytes worth of zeros.
Generic base class for all target subtargets.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:214
StringRef getSymbolTableName() const
bool hasRename() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition MCSymbol.h:233
bool isUndefined() const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition MCSymbol.h:243
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition MCSymbol.h:267
void redefineIfPossible()
Prepare this symbol to be redefined.
Definition MCSymbol.h:212
const MCSymbol * getAddSym() const
Definition MCValue.h:49
int64_t getConstant() const
Definition MCValue.h:44
const MCSymbol * getSubSym() const
Definition MCValue.h:51
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition MCValue.h:54
Metadata node.
Definition Metadata.h:1080
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1444
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1442
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
A single uniqued string.
Definition Metadata.h:722
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
This class is a data container for one entry in a MachineConstantPool.
union llvm::MachineConstantPoolEntry::@004270020304201266316354007027341142157160323045 Val
The constant itself.
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
MachineConstantPoolValue * MachineCPVal
Align Alignment
The required alignment for this entry.
unsigned getSizeInBytes(const DataLayout &DL) const
SectionKind getSectionKind(const DataLayout *DL) const
Abstract base class for all machine specific constantpool value subclasses.
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
const std::vector< MachineConstantPoolEntry > & getConstants() const
Analysis pass which computes a MachineDominatorTree.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
DenseMap< const MachineInstr *, CallSiteInfo > CallSiteInfoMap
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
LLVM_ABI unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
@ EK_GPRel32BlockAddress
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
@ EK_LabelDifference64
EK_LabelDifference64 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
LLVM_ABI unsigned getEntryAlignment(const DataLayout &TD) const
getEntryAlignment - Return the alignment of each entry in the jump table.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
Analysis pass that exposes the MachineLoopInfo for a machine function.
An analysis that produces MachineModuleInfo for a module.
MachineModuleInfoCOFF - This is a MachineModuleInfoImpl implementation for COFF targets.
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
std::vector< std::pair< MCSymbol *, StubValueTy > > SymbolListTy
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_CImmediate
Immediate >64bit operand.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_TargetIndex
Target-dependent index+offset operand.
@ MO_FPImmediate
Floating-point immediate operand.
Diagnostic information for optimization analysis remarks.
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition Mangler.cpp:121
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1760
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1856
Wrapper for a value that won't be replaced with a CFI jump table pointer in LowerTypeTestsModule.
Definition Constants.h:1157
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
SimpleRegistryEntry< GCMetadataPrinter, CtorParamTypes... > entry
Definition Registry.h:60
static iterator_range< iterator > entries()
Definition Registry.h:130
Represents a location in source code.
Definition SMLoc.h:22
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition SectionKind.h:22
bool isCommon() const
bool isBSS() const
static SectionKind getReadOnlyWithRel()
bool isBSSLocal() const
bool isThreadBSS() const
bool isThreadLocal() const
bool isThreadData() const
static SectionKind getReadOnly()
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:46
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:736
TypeSize getSizeInBytes() const
Definition DataLayout.h:745
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:767
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Information about stack frame layout on the target.
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetInstrInfo - Interface to description of machine instruction set.
Align getMinFunctionAlignment() const
Return the minimum function alignment.
virtual const MCExpr * lowerDSOLocalEquivalent(const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset, const TargetMachine &TM) const
virtual MCSection * getSectionForCommandLines() const
If supported, return the section to use for the llvm.commandline metadata.
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
virtual const MCExpr * getIndirectSymViaGOTPCRel(const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Get the target specific PC relative GOT entry relocation.
virtual void emitModuleMetadata(MCStreamer &Streamer, Module &M) const
Emit the module-level metadata that the platform cares about.
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment, const Function *F) const
Given a constant with the SectionKind, return a section that it should be placed in.
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset, const TargetMachine &TM) const
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
bool supportGOTPCRelWithOffset() const
Target GOT "PC"-relative relocation supports encoding an additional binary expression with an offset?
bool supportIndirectSymViaGOTPCRel() const
Target supports replacing a data "PC"-relative access to a symbol through another symbol,...
virtual MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const
If supported, return the function entry point symbol.
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
Primary interface to the complete machine description for the target machine.
const Triple & getTargetTriple() const
TargetOptions Options
unsigned EnableStaticDataPartitioning
Enables the StaticDataSplitter pass.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
Target - Wrapper for Target specific information.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool isOSBinFormatXCOFF() const
Tests whether the OS uses the XCOFF binary format.
Definition Triple.h:826
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:803
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:314
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:328
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:275
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
Value * operator=(Value *RHS)
Definition ValueHandle.h:70
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:464
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:440
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
iterator_range< user_iterator > users()
Definition Value.h:427
User * user_back()
Definition Value.h:413
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
bool use_empty() const
Definition Value.h:347
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
Definition Dwarf.cpp:138
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ IMAGE_SCN_MEM_READ
Definition COFF.h:336
@ IMAGE_SCN_MEM_DISCARDABLE
Definition COFF.h:331
@ IMAGE_SCN_LNK_INFO
Definition COFF.h:307
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition COFF.h:304
@ IMAGE_SCN_LNK_COMDAT
Definition COFF.h:309
@ IMAGE_SYM_CLASS_EXTERNAL
External symbol.
Definition COFF.h:224
@ IMAGE_SYM_CLASS_STATIC
Static.
Definition COFF.h:225
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition COFF.h:459
@ IMAGE_COMDAT_SELECT_ANY
Definition COFF.h:456
@ SafeSEH
Definition COFF.h:847
@ GuardEHCont
Definition COFF.h:855
@ GuardCF
Definition COFF.h:853
@ Kernel
Definition COFF.h:857
@ IMAGE_SYM_DTYPE_NULL
No complex type; simple scalar variable.
Definition COFF.h:274
@ IMAGE_SYM_DTYPE_FUNCTION
A function that returns a base type.
Definition COFF.h:276
@ SCT_COMPLEX_TYPE_SHIFT
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition COFF.h:280
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ SHF_ALLOC
Definition ELF.h:1247
@ SHF_LINK_ORDER
Definition ELF.h:1262
@ SHF_GROUP
Definition ELF.h:1269
@ SHF_WRITE
Definition ELF.h:1244
@ SHT_LLVM_JT_SIZES
Definition ELF.h:1187
@ SHT_PROGBITS
Definition ELF.h:1146
@ SHT_LLVM_SYMPART
Definition ELF.h:1179
@ S_ATTR_LIVE_SUPPORT
S_ATTR_LIVE_SUPPORT - Blocks are live if they reference live blocks.
Definition MachO.h:202
@ Itanium
Windows CE ARM, PowerPC, SH3, SH4.
Definition MCAsmInfo.h:49
@ X86
Windows x64, Windows Itanium (IA-64)
Definition MCAsmInfo.h:50
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
uint8_t getUnitLengthFieldByteSize(DwarfFormat Format)
Get the byte size of the unit length field depending on the DWARF format.
Definition Dwarf.h:1139
@ DWARF64
Definition Dwarf.h:93
uint8_t getDwarfOffsetByteSize(DwarfFormat Format)
The size of a reference determined by the DWARF 32/64-bit format.
Definition Dwarf.h:1097
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
DiagnosticInfoOptimizationBase::Argument NV
uint64_t MD5Hash(const FunctionId &Obj)
Definition FunctionId.h:167
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:755
LLVM_ABI std::error_code make_absolute(SmallVectorImpl< char > &path)
Make path an absolute path.
Definition Path.cpp:963
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:578
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
void stable_sort(R &&Range)
Definition STLExtras.h:2116
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ExceptionHandling
Definition CodeGen.h:53
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:56
@ ZOS
z/OS MVS Exception Handling.
Definition CodeGen.h:61
@ None
No exception support.
Definition CodeGen.h:54
@ AIX
AIX Exception Handling.
Definition CodeGen.h:60
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:55
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:58
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:59
LLVM_ABI bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL, DSOLocalEquivalent **DSOEquiv=nullptr)
If this constant is a constant offset from a global, return the global and the constant.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Op::Description Desc
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:154
@ MCDR_DataRegionEnd
.end_data_region
@ MCDR_DataRegionJT32
.data_region jt32
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:302
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM, AsmPrinter &AsmPrinter)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
InnerAnalysisManagerProxy< MachineFunctionAnalysisManager, Function > MachineFunctionAnalysisManagerFunctionProxy
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
constexpr std::string_view HybridPatchableTargetSuffix
Definition Mangler.h:37
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM, MachineFunction &MF, AsmPrinter &AsmPrinter)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ TypeHash
Token ID based on allocated type hash.
Definition AllocToken.h:32
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
@ MCSA_Local
.local (ELF)
@ MCSA_WeakDefAutoPrivate
.weak_def_can_be_hidden (MachO)
@ MCSA_Memtag
.memtag (ELF)
@ MCSA_WeakReference
.weak_reference (MachO)
@ MCSA_AltEntry
.alt_entry (MachO)
@ MCSA_ELF_TypeIndFunction
.type _foo, STT_GNU_IFUNC
@ MCSA_Weak
.weak
@ MCSA_WeakDefinition
.weak_definition (MachO)
@ MCSA_Global
.type _foo, @gnu_unique_object
@ MCSA_Cold
.cold (MachO)
@ MCSA_ELF_TypeObject
.type _foo, STT_OBJECT # aka @object
@ MCSA_ELF_TypeFunction
.type _foo, STT_FUNC # aka @function
@ MCSA_Invalid
Not a valid directive.
@ MCSA_NoDeadStrip
.no_dead_strip (MachO)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
constexpr const char * PseudoProbeDescMetadataName
Definition PseudoProbe.h:26
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Map a basic block section ID to the begin and end symbols of that section which determine the section...
Definition AsmPrinter.h:154
llvm.global_ctors and llvm.global_dtors are arrays of Structor structs.
Definition AsmPrinter.h:552
LLVM_ABI void emit(int, MCStreamer *) const
uint64_t getEdgeCount(const UniqueBBID &SrcBBID, const UniqueBBID &SinkBBID) const
uint64_t getBlockCount(const UniqueBBID &BBID) const
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:258
static LLVM_ABI int computeInstrLatency(const MCSubtargetInfo &STI, const MCSchedClassDesc &SCDesc)
Returns the latency value for the scheduling class.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition Dwarf.h:1110
This is the base class for a remark serializer.
virtual std::unique_ptr< MetaSerializer > metaSerializer(raw_ostream &OS, StringRef ExternalFilename)=0
Return the corresponding metadata serializer.