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(*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#ifndef NDEBUG
2151 MCFragment *OldFragment = OutStreamer->getCurrentFragment();
2152 size_t OldFragSize = OldFragment->getFixedSize();
2153#endif
2154
2155 switch (MI.getOpcode()) {
2156 case TargetOpcode::CFI_INSTRUCTION:
2158 break;
2159 case TargetOpcode::LOCAL_ESCAPE:
2161 break;
2162 case TargetOpcode::ANNOTATION_LABEL:
2163 case TargetOpcode::GC_LABEL:
2164 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
2165 break;
2166 case TargetOpcode::EH_LABEL:
2167 OutStreamer->AddComment("EH_LABEL");
2168 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
2169 // For AsynchEH, insert a Nop if followed by a trap inst
2170 // Or the exception won't be caught.
2171 // (see MCConstantExpr::create(1,..) in WinException.cpp)
2172 // Ignore SDiv/UDiv because a DIV with Const-0 divisor
2173 // must have being turned into an UndefValue.
2174 // Div with variable opnds won't be the first instruction in
2175 // an EH region as it must be led by at least a Load
2176 {
2177 auto MI2 = std::next(MI.getIterator());
2178 if (IsEHa && MI2 != MBB.end() &&
2179 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
2180 emitNops(1);
2181 }
2182 break;
2183 case TargetOpcode::INLINEASM:
2184 case TargetOpcode::INLINEASM_BR:
2185 emitInlineAsm(&MI);
2186 break;
2187 case TargetOpcode::DBG_VALUE:
2188 case TargetOpcode::DBG_VALUE_LIST:
2189 if (isVerbose()) {
2190 if (!emitDebugValueComment(&MI, *this))
2192 }
2193 break;
2194 case TargetOpcode::DBG_INSTR_REF:
2195 // This instruction reference will have been resolved to a machine
2196 // location, and a nearby DBG_VALUE created. We can safely ignore
2197 // the instruction reference.
2198 break;
2199 case TargetOpcode::DBG_PHI:
2200 // This instruction is only used to label a program point, it's purely
2201 // meta information.
2202 break;
2203 case TargetOpcode::DBG_LABEL:
2204 if (isVerbose()) {
2205 if (!emitDebugLabelComment(&MI, *this))
2207 }
2208 break;
2209 case TargetOpcode::IMPLICIT_DEF:
2210 if (isVerbose()) emitImplicitDef(&MI);
2211 break;
2212 case TargetOpcode::KILL:
2213 if (isVerbose()) emitKill(&MI, *this);
2214 break;
2215 case TargetOpcode::FAKE_USE:
2216 if (isVerbose())
2217 emitFakeUse(&MI, *this);
2218 break;
2219 case TargetOpcode::PSEUDO_PROBE:
2221 break;
2222 case TargetOpcode::ARITH_FENCE:
2223 if (isVerbose())
2224 OutStreamer->emitRawComment("ARITH_FENCE");
2225 break;
2226 case TargetOpcode::MEMBARRIER:
2227 OutStreamer->emitRawComment("MEMBARRIER");
2228 break;
2229 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
2230 // This instruction is only used to note jump table debug info, it's
2231 // purely meta information.
2232 break;
2233 case TargetOpcode::INIT_UNDEF:
2234 // This is only used to influence register allocation behavior, no
2235 // actual initialization is needed.
2236 break;
2237 case TargetOpcode::RELOC_NONE: {
2238 // Generate a temporary label for the current PC.
2239 MCSymbol *Sym = OutContext.createTempSymbol("reloc_none");
2240 OutStreamer->emitLabel(Sym);
2241 const MCExpr *Dot = MCSymbolRefExpr::create(Sym, OutContext);
2243 OutContext.getOrCreateSymbol(MI.getOperand(0).getSymbolName()),
2244 OutContext);
2245 OutStreamer->emitRelocDirective(*Dot, "BFD_RELOC_NONE", Value, SMLoc());
2246 break;
2247 }
2248 default:
2250
2251 auto CountInstruction = [&](const MachineInstr &MI) {
2252 // Skip Meta instructions inside bundles.
2253 if (MI.isMetaInstruction())
2254 return;
2255 ++NumInstsInFunction;
2256 if (CanDoExtraAnalysis) {
2258 ++MnemonicCounts[Name];
2259 }
2260 };
2261 if (!MI.isBundle()) {
2262 CountInstruction(MI);
2263 break;
2264 }
2265 // Separately count all the instructions in a bundle.
2266 for (auto It = std::next(MI.getIterator());
2267 It != MBB.end() && It->isInsideBundle(); ++It) {
2268 CountInstruction(*It);
2269 }
2270 break;
2271 }
2272
2273#ifndef NDEBUG
2274 // Verify that the instruction size reported by InstrInfo matches the
2275 // actually emitted size. Many backends performing branch relaxation
2276 // on the MIR level rely on this for correctness.
2277 // TODO: We currently can't distinguish whether a parse error occurred
2278 // when handling INLINEASM.
2279 if (OutStreamer->isObj() && !OutContext.hadError() &&
2280 (MI.getOpcode() != TargetOpcode::INLINEASM &&
2281 MI.getOpcode() != TargetOpcode::INLINEASM_BR)) {
2282 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2284 TII->getInstSizeVerifyMode(MI);
2286 unsigned ExpectedSize = TII->getInstSizeInBytes(MI);
2287 if (MI.isBundled()) {
2288 // Bundled instructions are emitted together.
2289 auto It = MI.getIterator(), End = MBB.instr_end();
2290 for (++It; It != End && It->isInsideBundle(); ++It)
2291 ExpectedSize += TII->getInstSizeInBytes(*It);
2292 }
2293
2294 MCFragment *NewFragment = OutStreamer->getCurrentFragment();
2295 unsigned ActualSize;
2296 if (OldFragment == NewFragment) {
2297 ActualSize = NewFragment->getFixedSize() - OldFragSize;
2298 } else {
2299 ActualSize = OldFragment->getFixedSize() - OldFragSize;
2300 const MCFragment *F = OldFragment->getNext();
2301 for (; F != NewFragment; F = F->getNext())
2302 ActualSize += F->getFixedSize();
2303 ActualSize += NewFragment->getFixedSize();
2304 }
2305 bool AllowOverEstimate =
2307 bool Valid = AllowOverEstimate ? ActualSize <= ExpectedSize
2308 : ActualSize == ExpectedSize;
2309 if (!Valid) {
2310 dbgs() << "In function: " << MF->getName() << "\n";
2311 dbgs() << "Size mismatch for: " << MI;
2312 if (MI.isBundled()) {
2313 dbgs() << "{\n";
2314 auto It = MI.getIterator(), End = MBB.instr_end();
2315 for (++It; It != End && It->isInsideBundle(); ++It)
2316 dbgs().indent(2) << *It;
2317 dbgs() << "}\n";
2318 }
2319 dbgs() << "Expected " << (AllowOverEstimate ? "maximum" : "exact")
2320 << " size: " << ExpectedSize << "\n";
2321 dbgs() << "Actual size: " << ActualSize << "\n";
2322 abort();
2323 }
2324 }
2325 }
2326#endif
2327
2328 if (MI.isCall()) {
2329 if (MF->getTarget().Options.BBAddrMap)
2331 LastCallsiteIndex++;
2332 }
2333
2334 if (TM.Options.EmitCallGraphSection && MI.isCall())
2335 handleCallsiteForCallgraph(FuncCGInfo, CallSitesInfoMap, MI);
2336
2337 // If there is a post-instruction symbol, emit a label for it here.
2338 if (MCSymbol *S = MI.getPostInstrSymbol())
2339 OutStreamer->emitLabel(S);
2340
2341 for (auto &Handler : Handlers)
2342 Handler->endInstruction();
2343 }
2344 // Emit the remaining prefetch targets for this block. This includes
2345 // nonexisting callsite indexes.
2346 while (PrefetchTargetIt != PrefetchTargetEnd) {
2347 emitPrefetchTargetSymbol(MBB.getBBID()->BaseID, *PrefetchTargetIt);
2348 ++PrefetchTargetIt;
2349 }
2350
2351 // We must emit temporary symbol for the end of this basic block, if either
2352 // we have BBLabels enabled or if this basic blocks marks the end of a
2353 // section.
2354 if (MF->getTarget().Options.BBAddrMap ||
2355 (MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection()))
2356 OutStreamer->emitLabel(MBB.getEndSymbol());
2357
2358 if (MBB.isEndSection()) {
2359 // The size directive for the section containing the entry block is
2360 // handled separately by the function section.
2361 if (!MBB.sameSection(&MF->front())) {
2362 if (MAI->hasDotTypeDotSizeDirective()) {
2363 // Emit the size directive for the basic block section.
2364 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2365 MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext),
2366 MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
2367 OutContext);
2368 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
2369 }
2370 assert(!MBBSectionRanges.contains(MBB.getSectionID()) &&
2371 "Overwrite section range");
2372 MBBSectionRanges[MBB.getSectionID()] =
2373 MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
2374 }
2375 }
2377
2378 if (CanDoExtraAnalysis) {
2379 // Skip empty blocks.
2380 if (MBB.empty())
2381 continue;
2382
2384 MBB.begin()->getDebugLoc(), &MBB);
2385
2386 // Generate instruction mix remark. First, sort counts in descending order
2387 // by count and name.
2389 for (auto &KV : MnemonicCounts)
2390 MnemonicVec.emplace_back(KV.first, KV.second);
2391
2392 sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
2393 const std::pair<StringRef, unsigned> &B) {
2394 if (A.second > B.second)
2395 return true;
2396 if (A.second == B.second)
2397 return StringRef(A.first) < StringRef(B.first);
2398 return false;
2399 });
2400 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
2401 for (auto &KV : MnemonicVec) {
2402 auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
2403 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
2404 }
2405 ORE->emit(R);
2406 }
2407 }
2408
2409 EmittedInsts += NumInstsInFunction;
2410 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
2411 MF->getFunction().getSubprogram(),
2412 &MF->front());
2413 R << ore::NV("NumInstructions", NumInstsInFunction)
2414 << " instructions in function";
2415 ORE->emit(R);
2416
2417 // If the function is empty and the object file uses .subsections_via_symbols,
2418 // then we need to emit *something* to the function body to prevent the
2419 // labels from collapsing together. Just emit a noop.
2420 // Similarly, don't emit empty functions on Windows either. It can lead to
2421 // duplicate entries (two functions with the same RVA) in the Guard CF Table
2422 // after linking, causing the kernel not to load the binary:
2423 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
2424 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
2425 const Triple &TT = TM.getTargetTriple();
2426 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
2427 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
2428 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
2429
2430 // Targets can opt-out of emitting the noop here by leaving the opcode
2431 // unspecified.
2432 if (Noop.getOpcode()) {
2433 OutStreamer->AddComment("avoids zero-length function");
2434 emitNops(1);
2435 }
2436 }
2437
2438 // Switch to the original section in case basic block sections was used.
2439 OutStreamer->switchSection(MF->getSection());
2440
2441 const Function &F = MF->getFunction();
2442 for (const auto &BB : F) {
2443 if (!BB.hasAddressTaken())
2444 continue;
2445 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
2446 if (Sym->isDefined())
2447 continue;
2448 OutStreamer->AddComment("Address of block that was removed by CodeGen");
2449 OutStreamer->emitLabel(Sym);
2450 }
2451
2452 // Emit target-specific gunk after the function body.
2454
2455 // Even though wasm supports .type and .size in general, function symbols
2456 // are automatically sized.
2457 bool EmitFunctionSize = MAI->hasDotTypeDotSizeDirective() && !TT.isWasm();
2458
2459 // SPIR-V supports label instructions only inside a block, not after the
2460 // function body.
2461 if (TT.getObjectFormat() != Triple::SPIRV &&
2462 (EmitFunctionSize || needFuncLabels(*MF, *this))) {
2463 // Create a symbol for the end of function.
2464 CurrentFnEnd = createTempSymbol("func_end");
2465 OutStreamer->emitLabel(CurrentFnEnd);
2466 }
2467
2468 // If the target wants a .size directive for the size of the function, emit
2469 // it.
2470 if (EmitFunctionSize) {
2471 // We can get the size as difference between the function label and the
2472 // temp label.
2473 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2474 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
2476 OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
2478 OutStreamer->emitELFSize(CurrentFnBeginLocal, SizeExp);
2479 }
2480
2481 // Call endBasicBlockSection on the last block now, if it wasn't already
2482 // called.
2483 if (!MF->back().isEndSection()) {
2484 for (auto &Handler : Handlers)
2485 Handler->endBasicBlockSection(MF->back());
2486 for (auto &Handler : EHHandlers)
2487 Handler->endBasicBlockSection(MF->back());
2488 }
2489 for (auto &Handler : Handlers)
2490 Handler->markFunctionEnd();
2491 for (auto &Handler : EHHandlers)
2492 Handler->markFunctionEnd();
2493 // Update the end label of the entry block's section.
2494 MBBSectionRanges[MF->front().getSectionID()].EndLabel = CurrentFnEnd;
2495
2496 // Print out jump tables referenced by the function.
2498
2499 // Emit post-function debug and/or EH information.
2500 for (auto &Handler : Handlers)
2501 Handler->endFunction(MF);
2502 for (auto &Handler : EHHandlers)
2503 Handler->endFunction(MF);
2504
2505 // Emit section containing BB address offsets and their metadata, when
2506 // BB labels are requested for this function. Skip empty functions.
2507 if (HasAnyRealCode) {
2508 if (MF->getTarget().Options.BBAddrMap)
2510 else if (PgoAnalysisMapFeatures.getBits() != 0)
2511 MF->getContext().reportWarning(
2512 SMLoc(), "pgo-analysis-map is enabled for function " + MF->getName() +
2513 " but it does not have labels");
2514 }
2515
2516 // Emit sections containing instruction and function PCs.
2518
2519 // Emit section containing stack size metadata.
2521
2522 // Emit section containing call graph metadata.
2523 emitCallGraphSection(*MF, FuncCGInfo);
2524
2525 // Emit .su file containing function stack size information.
2527
2529
2530 if (isVerbose())
2531 OutStreamer->getCommentOS() << "-- End function\n";
2532
2533 OutStreamer->addBlankLine();
2534}
2535
2536/// Compute the number of Global Variables that uses a Constant.
2537static unsigned getNumGlobalVariableUses(const Constant *C,
2538 bool &HasNonGlobalUsers) {
2539 if (!C) {
2540 HasNonGlobalUsers = true;
2541 return 0;
2542 }
2543
2545 return 1;
2546
2547 unsigned NumUses = 0;
2548 for (const auto *CU : C->users())
2549 NumUses +=
2550 getNumGlobalVariableUses(dyn_cast<Constant>(CU), HasNonGlobalUsers);
2551
2552 return NumUses;
2553}
2554
2555/// Only consider global GOT equivalents if at least one user is a
2556/// cstexpr inside an initializer of another global variables. Also, don't
2557/// handle cstexpr inside instructions. During global variable emission,
2558/// candidates are skipped and are emitted later in case at least one cstexpr
2559/// isn't replaced by a PC relative GOT entry access.
2561 unsigned &NumGOTEquivUsers,
2562 bool &HasNonGlobalUsers) {
2563 // Global GOT equivalents are unnamed private globals with a constant
2564 // pointer initializer to another global symbol. They must point to a
2565 // GlobalVariable or Function, i.e., as GlobalValue.
2566 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
2567 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
2569 return false;
2570
2571 // To be a got equivalent, at least one of its users need to be a constant
2572 // expression used by another global variable.
2573 for (const auto *U : GV->users())
2574 NumGOTEquivUsers +=
2575 getNumGlobalVariableUses(dyn_cast<Constant>(U), HasNonGlobalUsers);
2576
2577 return NumGOTEquivUsers > 0;
2578}
2579
2580/// Unnamed constant global variables solely contaning a pointer to
2581/// another globals variable is equivalent to a GOT table entry; it contains the
2582/// the address of another symbol. Optimize it and replace accesses to these
2583/// "GOT equivalents" by using the GOT entry for the final global instead.
2584/// Compute GOT equivalent candidates among all global variables to avoid
2585/// emitting them if possible later on, after it use is replaced by a GOT entry
2586/// access.
2588 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2589 return;
2590
2591 for (const auto &G : M.globals()) {
2592 unsigned NumGOTEquivUsers = 0;
2593 bool HasNonGlobalUsers = false;
2594 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers, HasNonGlobalUsers))
2595 continue;
2596 // If non-global variables use it, we still need to emit it.
2597 // Add 1 here, then emit it in `emitGlobalGOTEquivs`.
2598 if (HasNonGlobalUsers)
2599 NumGOTEquivUsers += 1;
2600 const MCSymbol *GOTEquivSym = getSymbol(&G);
2601 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
2602 }
2603}
2604
2605/// Constant expressions using GOT equivalent globals may not be eligible
2606/// for PC relative GOT entry conversion, in such cases we need to emit such
2607/// globals we previously omitted in EmitGlobalVariable.
2609 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2610 return;
2611
2613 for (auto &I : GlobalGOTEquivs) {
2614 const GlobalVariable *GV = I.second.first;
2615 unsigned Cnt = I.second.second;
2616 if (Cnt)
2617 FailedCandidates.push_back(GV);
2618 }
2619 GlobalGOTEquivs.clear();
2620
2621 for (const auto *GV : FailedCandidates)
2623}
2624
2626 MCSymbol *Name = getSymbol(&GA);
2627 const GlobalObject *BaseObject = GA.getAliaseeObject();
2628
2629 bool IsFunction = GA.getValueType()->isFunctionTy();
2630 // Treat bitcasts of functions as functions also. This is important at least
2631 // on WebAssembly where object and function addresses can't alias each other.
2632 if (!IsFunction)
2633 IsFunction = isa_and_nonnull<Function>(BaseObject);
2634
2635 // AIX's assembly directive `.set` is not usable for aliasing purpose,
2636 // so AIX has to use the extra-label-at-definition strategy. At this
2637 // point, all the extra label is emitted, we just have to emit linkage for
2638 // those labels.
2639 if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
2640 // Linkage for alias of global variable has been emitted.
2641 if (isa_and_nonnull<GlobalVariable>(BaseObject))
2642 return;
2643
2644 emitLinkage(&GA, Name);
2645 // If it's a function, also emit linkage for aliases of function entry
2646 // point.
2647 if (IsFunction)
2648 emitLinkage(&GA,
2649 getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
2650 return;
2651 }
2652
2653 if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
2654 OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
2655 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
2656 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
2657 else
2658 assert(GA.hasLocalLinkage() && "Invalid alias linkage");
2659
2660 // Set the symbol type to function if the alias has a function type.
2661 // This affects codegen when the aliasee is not a function.
2662 if (IsFunction) {
2663 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
2664 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
2665 OutStreamer->beginCOFFSymbolDef(Name);
2666 OutStreamer->emitCOFFSymbolStorageClass(
2671 OutStreamer->endCOFFSymbolDef();
2672 }
2673 }
2674
2675 emitVisibility(Name, GA.getVisibility());
2676
2677 const MCExpr *Expr = lowerConstant(GA.getAliasee());
2678
2679 if (MAI->isMachO() && isa<MCBinaryExpr>(Expr))
2680 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
2681
2682 // Emit the directives as assignments aka .set:
2683 OutStreamer->emitAssignment(Name, Expr);
2684 MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
2685 if (LocalAlias != Name)
2686 OutStreamer->emitAssignment(LocalAlias, Expr);
2687
2688 // If the aliasee does not correspond to a symbol in the output, i.e. the
2689 // alias is not of an object or the aliased object is private, then set the
2690 // size of the alias symbol from the type of the alias. We don't do this in
2691 // other situations as the alias and aliasee having differing types but same
2692 // size may be intentional.
2693 if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
2694 (!BaseObject || BaseObject->hasPrivateLinkage())) {
2695 const DataLayout &DL = M.getDataLayout();
2696 uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
2697 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
2698 }
2699}
2700
2701void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
2702 auto EmitLinkage = [&](MCSymbol *Sym) {
2704 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
2705 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
2706 OutStreamer->emitSymbolAttribute(Sym, MCSA_WeakReference);
2707 else
2708 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
2709 };
2710
2712 MCSymbol *Name = getSymbol(&GI);
2713 EmitLinkage(Name);
2714 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
2715 emitVisibility(Name, GI.getVisibility());
2716
2717 // Emit the directives as assignments aka .set:
2718 const MCExpr *Expr = lowerConstant(GI.getResolver());
2719 OutStreamer->emitAssignment(Name, Expr);
2720 MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
2721 if (LocalAlias != Name)
2722 OutStreamer->emitAssignment(LocalAlias, Expr);
2723
2724 return;
2725 }
2726
2727 if (!TM.getTargetTriple().isOSBinFormatMachO() || !getIFuncMCSubtargetInfo())
2728 reportFatalUsageError("IFuncs are not supported on this platform");
2729
2730 // On Darwin platforms, emit a manually-constructed .symbol_resolver that
2731 // implements the symbol resolution duties of the IFunc.
2732 //
2733 // Normally, this would be handled by linker magic, but unfortunately there
2734 // are a few limitations in ld64 and ld-prime's implementation of
2735 // .symbol_resolver that mean we can't always use them:
2736 //
2737 // * resolvers cannot be the target of an alias
2738 // * resolvers cannot have private linkage
2739 // * resolvers cannot have linkonce linkage
2740 // * resolvers cannot appear in executables
2741 // * resolvers cannot appear in bundles
2742 //
2743 // This works around that by emitting a close approximation of what the
2744 // linker would have done.
2745
2746 MCSymbol *LazyPointer =
2747 GetExternalSymbolSymbol(GI.getName() + ".lazy_pointer");
2748 MCSymbol *StubHelper = GetExternalSymbolSymbol(GI.getName() + ".stub_helper");
2749
2750 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
2751
2752 const DataLayout &DL = M.getDataLayout();
2753 emitAlignment(Align(DL.getPointerSize()));
2754 OutStreamer->emitLabel(LazyPointer);
2755 emitVisibility(LazyPointer, GI.getVisibility());
2756 OutStreamer->emitValue(MCSymbolRefExpr::create(StubHelper, OutContext), 8);
2757
2758 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getTextSection());
2759
2760 const TargetSubtargetInfo *STI =
2761 TM.getSubtargetImpl(*GI.getResolverFunction());
2762 const TargetLowering *TLI = STI->getTargetLowering();
2763 Align TextAlign(TLI->getMinFunctionAlignment());
2764
2765 MCSymbol *Stub = getSymbol(&GI);
2766 EmitLinkage(Stub);
2767 OutStreamer->emitCodeAlignment(TextAlign, getIFuncMCSubtargetInfo());
2768 OutStreamer->emitLabel(Stub);
2769 emitVisibility(Stub, GI.getVisibility());
2770 emitMachOIFuncStubBody(M, GI, LazyPointer);
2771
2772 OutStreamer->emitCodeAlignment(TextAlign, getIFuncMCSubtargetInfo());
2773 OutStreamer->emitLabel(StubHelper);
2774 emitVisibility(StubHelper, GI.getVisibility());
2775 emitMachOIFuncStubHelperBody(M, GI, LazyPointer);
2776}
2777
2779 if (!RS.wantsSection())
2780 return;
2781 if (!RS.getFilename())
2782 return;
2783
2784 MCSection *RemarksSection =
2785 OutContext.getObjectFileInfo()->getRemarksSection();
2786 if (!RemarksSection && RS.needsSection()) {
2787 OutContext.reportWarning(SMLoc(), "Current object file format does not "
2788 "support remarks sections.");
2789 }
2790 if (!RemarksSection)
2791 return;
2792
2793 SmallString<128> Filename = *RS.getFilename();
2795 assert(!Filename.empty() && "The filename can't be empty.");
2796
2797 std::string Buf;
2798 raw_string_ostream OS(Buf);
2799
2800 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
2801 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2802 RemarkSerializer.metaSerializer(OS, Filename);
2803 MetaSerializer->emit();
2804
2805 // Switch to the remarks section.
2806 OutStreamer->switchSection(RemarksSection);
2807 OutStreamer->emitBinaryData(Buf);
2808}
2809
2811 const Constant *Initializer = G.getInitializer();
2812 return G.getParent()->getDataLayout().getTypeAllocSize(
2813 Initializer->getType());
2814}
2815
2817 // We used to do this in clang, but there are optimization passes that turn
2818 // non-constant globals into constants. So now, clang only tells us whether
2819 // it would *like* a global to be tagged, but we still make the decision here.
2820 //
2821 // For now, don't instrument constant data, as it'll be in .rodata anyway. It
2822 // may be worth instrumenting these in future to stop them from being used as
2823 // gadgets.
2824 if (G.getName().starts_with("llvm.") || G.isThreadLocal() || G.isConstant())
2825 return false;
2826
2827 // Globals can be placed implicitly or explicitly in sections. There's two
2828 // different types of globals that meet this criteria that cause problems:
2829 // 1. Function pointers that are going into various init arrays (either
2830 // explicitly through `__attribute__((section(<foo>)))` or implicitly
2831 // through `__attribute__((constructor)))`, such as ".(pre)init(_array)",
2832 // ".fini(_array)", ".ctors", and ".dtors". These function pointers end up
2833 // overaligned and overpadded, making iterating over them problematic, and
2834 // each function pointer is individually tagged (so the iteration over
2835 // them causes SIGSEGV/MTE[AS]ERR).
2836 // 2. Global variables put into an explicit section, where the section's name
2837 // is a valid C-style identifier. The linker emits a `__start_<name>` and
2838 // `__stop_<name>` symbol for the section, so that you can iterate over
2839 // globals within this section. Unfortunately, again, these globals would
2840 // be tagged and so iteration causes SIGSEGV/MTE[AS]ERR.
2841 //
2842 // To mitigate both these cases, and because specifying a section is rare
2843 // outside of these two cases, disable MTE protection for globals in any
2844 // section.
2845 if (G.hasSection())
2846 return false;
2847
2848 return globalSize(G) > 0;
2849}
2850
2852 uint64_t SizeInBytes = globalSize(*G);
2853
2854 uint64_t NewSize = alignTo(SizeInBytes, 16);
2855 if (SizeInBytes != NewSize) {
2856 // Pad the initializer out to the next multiple of 16 bytes.
2857 llvm::SmallVector<uint8_t> Init(NewSize - SizeInBytes, 0);
2858 Constant *Padding = ConstantDataArray::get(M.getContext(), Init);
2859 Constant *Initializer = G->getInitializer();
2860 Initializer = ConstantStruct::getAnon({Initializer, Padding});
2861 auto *NewGV = new GlobalVariable(
2862 M, Initializer->getType(), G->isConstant(), G->getLinkage(),
2863 Initializer, "", G, G->getThreadLocalMode(), G->getAddressSpace());
2864 NewGV->copyAttributesFrom(G);
2865 NewGV->setComdat(G->getComdat());
2866 NewGV->copyMetadata(G, 0);
2867
2868 NewGV->takeName(G);
2869 G->replaceAllUsesWith(NewGV);
2870 G->eraseFromParent();
2871 G = NewGV;
2872 }
2873
2874 if (G->getAlign().valueOrOne() < 16)
2875 G->setAlignment(Align(16));
2876
2877 // Ensure that tagged globals don't get merged by ICF - as they should have
2878 // different tags at runtime.
2879 G->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2880}
2881
2883 auto Meta = G.getSanitizerMetadata();
2884 Meta.Memtag = false;
2885 G.setSanitizerMetadata(Meta);
2886}
2887
2889 // Set the MachineFunction to nullptr so that we can catch attempted
2890 // accesses to MF specific features at the module level and so that
2891 // we can conditionalize accesses based on whether or not it is nullptr.
2892 MF = nullptr;
2893 const Triple &Target = TM.getTargetTriple();
2894
2895 std::vector<GlobalVariable *> GlobalsToTag;
2896 for (GlobalVariable &G : M.globals()) {
2897 if (G.isDeclaration() || !G.isTagged())
2898 continue;
2899 if (!shouldTagGlobal(G)) {
2900 assert(G.hasSanitizerMetadata()); // because isTagged.
2902 assert(!G.isTagged());
2903 continue;
2904 }
2905 GlobalsToTag.push_back(&G);
2906 }
2907 for (GlobalVariable *G : GlobalsToTag)
2909
2910 // Gather all GOT equivalent globals in the module. We really need two
2911 // passes over the globals: one to compute and another to avoid its emission
2912 // in EmitGlobalVariable, otherwise we would not be able to handle cases
2913 // where the got equivalent shows up before its use.
2915
2916 // Emit global variables.
2917 for (const auto &G : M.globals())
2919
2920 // Emit remaining GOT equivalent globals.
2922
2924
2925 // Emit linkage(XCOFF) and visibility info for declarations
2926 for (const Function &F : M) {
2927 if (!F.isDeclarationForLinker())
2928 continue;
2929
2930 MCSymbol *Name = getSymbol(&F);
2931 // Function getSymbol gives us the function descriptor symbol for XCOFF.
2932
2933 if (!Target.isOSBinFormatXCOFF()) {
2934 GlobalValue::VisibilityTypes V = F.getVisibility();
2936 continue;
2937
2938 emitVisibility(Name, V, false);
2939 continue;
2940 }
2941
2942 if (F.isIntrinsic())
2943 continue;
2944
2945 // Handle the XCOFF case.
2946 // Variable `Name` is the function descriptor symbol (see above). Get the
2947 // function entry point symbol.
2948 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
2949 // Emit linkage for the function entry point.
2950 emitLinkage(&F, FnEntryPointSym);
2951
2952 // If a function's address is taken, which means it may be called via a
2953 // function pointer, we need the function descriptor for it.
2954 if (F.hasAddressTaken())
2955 emitLinkage(&F, Name);
2956 }
2957
2958 // Emit the remarks section contents.
2959 // FIXME: Figure out when is the safest time to emit this section. It should
2960 // not come after debug info.
2961 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
2962 emitRemarksSection(*RS);
2963
2965
2966 if (Target.isOSBinFormatELF()) {
2967 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
2968
2969 // Output stubs for external and common global variables.
2971 if (!Stubs.empty()) {
2972 OutStreamer->switchSection(TLOF.getDataSection());
2973 const DataLayout &DL = M.getDataLayout();
2974
2975 emitAlignment(Align(DL.getPointerSize()));
2976 for (const auto &Stub : Stubs) {
2977 OutStreamer->emitLabel(Stub.first);
2978 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2979 DL.getPointerSize());
2980 }
2981 }
2982 }
2983
2984 if (Target.isOSBinFormatCOFF()) {
2985 MachineModuleInfoCOFF &MMICOFF =
2986 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
2987
2988 // Output stubs for external and common global variables.
2990 if (!Stubs.empty()) {
2991 const DataLayout &DL = M.getDataLayout();
2992
2993 for (const auto &Stub : Stubs) {
2995 SectionName += Stub.first->getName();
2996 OutStreamer->switchSection(OutContext.getCOFFSection(
3000 Stub.first->getName(), COFF::IMAGE_COMDAT_SELECT_ANY));
3001 emitAlignment(Align(DL.getPointerSize()));
3002 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
3003 OutStreamer->emitLabel(Stub.first);
3004 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
3005 DL.getPointerSize());
3006 }
3007 }
3008 }
3009
3010 // This needs to happen before emitting debug information since that can end
3011 // arbitrary sections.
3012 if (auto *TS = OutStreamer->getTargetStreamer())
3013 TS->emitConstantPools();
3014
3015 // Emit Stack maps before any debug info. Mach-O requires that no data or
3016 // text sections come after debug info has been emitted. This matters for
3017 // stack maps as they are arbitrary data, and may even have a custom format
3018 // through user plugins.
3019 EmitStackMaps(M);
3020
3021 // Print aliases in topological order, that is, for each alias a = b,
3022 // b must be printed before a.
3023 // This is because on some targets (e.g. PowerPC) linker expects aliases in
3024 // such an order to generate correct TOC information.
3027 for (const auto &Alias : M.aliases()) {
3028 if (Alias.hasAvailableExternallyLinkage())
3029 continue;
3030 for (const GlobalAlias *Cur = &Alias; Cur;
3031 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
3032 if (!AliasVisited.insert(Cur).second)
3033 break;
3034 AliasStack.push_back(Cur);
3035 }
3036 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
3037 emitGlobalAlias(M, *AncestorAlias);
3038 AliasStack.clear();
3039 }
3040
3041 // IFuncs must come before deubginfo in case the backend decides to emit them
3042 // as actual functions, since on Mach-O targets, we cannot create regular
3043 // sections after DWARF.
3044 for (const auto &IFunc : M.ifuncs())
3045 emitGlobalIFunc(M, IFunc);
3046 if (TM.getTargetTriple().isOSBinFormatXCOFF() && hasDebugInfo()) {
3047 // Emit section end. This is used to tell the debug line section where the
3048 // end is for a text section if we don't use .loc to represent the debug
3049 // line.
3050 auto *Sec = OutContext.getObjectFileInfo()->getTextSection();
3051 OutStreamer->switchSectionNoPrint(Sec);
3052 MCSymbol *Sym = Sec->getEndSymbol(OutContext);
3053 OutStreamer->emitLabel(Sym);
3054 }
3055
3056 // Finalize debug and EH information.
3057 for (auto &Handler : Handlers)
3058 Handler->endModule();
3059 for (auto &Handler : EHHandlers)
3060 Handler->endModule();
3061
3062 // This deletes all the ephemeral handlers that AsmPrinter added, while
3063 // keeping all the user-added handlers alive until the AsmPrinter is
3064 // destroyed.
3065 EHHandlers.clear();
3066 Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
3067 DD = nullptr;
3068
3069 // If the target wants to know about weak references, print them all.
3070 if (MAI->getWeakRefDirective()) {
3071 // FIXME: This is not lazy, it would be nice to only print weak references
3072 // to stuff that is actually used. Note that doing so would require targets
3073 // to notice uses in operands (due to constant exprs etc). This should
3074 // happen with the MC stuff eventually.
3075
3076 // Print out module-level global objects here.
3077 for (const auto &GO : M.global_objects()) {
3078 if (!GO.hasExternalWeakLinkage())
3079 continue;
3080 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
3081 }
3083 auto SymbolName = "swift_async_extendedFramePointerFlags";
3084 auto Global = M.getGlobalVariable(SymbolName);
3085 if (!Global) {
3086 auto PtrTy = PointerType::getUnqual(M.getContext());
3087 Global = new GlobalVariable(M, PtrTy, false,
3089 SymbolName);
3090 OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
3091 }
3092 }
3093 }
3094
3096
3097 // Emit llvm.ident metadata in an '.ident' directive.
3098 emitModuleIdents(M);
3099
3100 // Emit bytes for llvm.commandline metadata.
3101 // The command line metadata is emitted earlier on XCOFF.
3102 if (!Target.isOSBinFormatXCOFF())
3103 emitModuleCommandLines(M);
3104
3105 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
3106 // split-stack is used.
3107 if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
3108 OutStreamer->switchSection(OutContext.getELFSection(".note.GNU-split-stack",
3109 ELF::SHT_PROGBITS, 0));
3110 if (HasNoSplitStack)
3111 OutStreamer->switchSection(OutContext.getELFSection(
3112 ".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
3113 }
3114
3115 // If we don't have any trampolines, then we don't require stack memory
3116 // to be executable. Some targets have a directive to declare this.
3117 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
3118 bool HasTrampolineUses =
3119 InitTrampolineIntrinsic && !InitTrampolineIntrinsic->use_empty();
3120 MCSection *S = MAI->getStackSection(OutContext, /*Exec=*/HasTrampolineUses);
3121 if (S)
3122 OutStreamer->switchSection(S);
3123
3124 if (TM.Options.EmitAddrsig) {
3125 // Emit address-significance attributes for all globals.
3126 OutStreamer->emitAddrsig();
3127 for (const GlobalValue &GV : M.global_values()) {
3128 if (!GV.use_empty() && !GV.isThreadLocal() &&
3129 !GV.hasDLLImportStorageClass() &&
3130 !GV.getName().starts_with("llvm.") &&
3131 !GV.hasAtLeastLocalUnnamedAddr())
3132 OutStreamer->emitAddrsigSym(getSymbol(&GV));
3133 }
3134 }
3135
3136 // Emit symbol partition specifications (ELF only).
3137 if (Target.isOSBinFormatELF()) {
3138 unsigned UniqueID = 0;
3139 for (const GlobalValue &GV : M.global_values()) {
3140 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
3141 GV.getVisibility() != GlobalValue::DefaultVisibility)
3142 continue;
3143
3144 OutStreamer->switchSection(
3145 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
3146 "", false, ++UniqueID, nullptr));
3147 OutStreamer->emitBytes(GV.getPartition());
3148 OutStreamer->emitZeros(1);
3149 OutStreamer->emitValue(
3151 MAI->getCodePointerSize());
3152 }
3153 }
3154
3155 // Allow the target to emit any magic that it wants at the end of the file,
3156 // after everything else has gone out.
3158
3159 MMI = nullptr;
3160 AddrLabelSymbols = nullptr;
3161
3162 OutStreamer->finish();
3163 OutStreamer->reset();
3164 OwnedMLI.reset();
3165 OwnedMDT.reset();
3166
3167 return false;
3168}
3169
3171 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionID());
3172 if (Res.second)
3173 Res.first->second = createTempSymbol("exception");
3174 return Res.first->second;
3175}
3176
3178 MCContext &Ctx = MF->getContext();
3179 MCSymbol *Sym = Ctx.createTempSymbol("BB" + Twine(MF->getFunctionNumber()) +
3180 "_" + Twine(MBB.getNumber()) + "_CS");
3181 CurrentFnCallsiteEndSymbols[&MBB].push_back(Sym);
3182 return Sym;
3183}
3184
3186 this->MF = &MF;
3187 const Function &F = MF.getFunction();
3188
3189 // Record that there are split-stack functions, so we will emit a special
3190 // section to tell the linker.
3191 if (MF.shouldSplitStack()) {
3192 HasSplitStack = true;
3193
3194 if (!MF.getFrameInfo().needsSplitStackProlog())
3195 HasNoSplitStack = true;
3196 } else
3197 HasNoSplitStack = true;
3198
3199 // Get the function symbol.
3200 if (!MAI->isAIX()) {
3201 CurrentFnSym = getSymbol(&MF.getFunction());
3202 } else {
3203 assert(TM.getTargetTriple().isOSAIX() &&
3204 "Only AIX uses the function descriptor hooks.");
3205 // AIX is unique here in that the name of the symbol emitted for the
3206 // function body does not have the same name as the source function's
3207 // C-linkage name.
3208 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
3209 " initalized first.");
3210
3211 // Get the function entry point symbol.
3213 }
3214
3216 CurrentFnBegin = nullptr;
3217 CurrentFnBeginLocal = nullptr;
3218 CurrentSectionBeginSym = nullptr;
3220 MBBSectionRanges.clear();
3221 MBBSectionExceptionSyms.clear();
3222 bool NeedsLocalForSize = MAI->needsLocalForSize();
3223 if (F.hasFnAttribute("patchable-function-entry") ||
3224 F.hasFnAttribute("function-instrument") ||
3225 F.hasFnAttribute("xray-instruction-threshold") ||
3226 needFuncLabels(MF, *this) || NeedsLocalForSize ||
3227 MF.getTarget().Options.EmitStackSizeSection ||
3228 MF.getTarget().Options.EmitCallGraphSection ||
3229 MF.getTarget().Options.BBAddrMap) {
3230 CurrentFnBegin = createTempSymbol("func_begin");
3231 if (NeedsLocalForSize)
3233 }
3234
3235 ORE = GetORE(MF);
3236}
3237
3238namespace {
3239
3240// Keep track the alignment, constpool entries per Section.
3241 struct SectionCPs {
3242 MCSection *S;
3243 Align Alignment;
3245
3246 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
3247 };
3248
3249} // end anonymous namespace
3250
3252 if (TM.Options.EnableStaticDataPartitioning && C && SDPI && PSI)
3253 return SDPI->getConstantSectionPrefix(C, PSI);
3254
3255 return "";
3256}
3257
3258/// EmitConstantPool - Print to the current output stream assembly
3259/// representations of the constants in the constant pool MCP. This is
3260/// used to print out constants which have been "spilled to memory" by
3261/// the code generator.
3263 const MachineConstantPool *MCP = MF->getConstantPool();
3264 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
3265 if (CP.empty()) return;
3266
3267 // Calculate sections for constant pool entries. We collect entries to go into
3268 // the same section together to reduce amount of section switch statements.
3269 SmallVector<SectionCPs, 4> CPSections;
3270 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
3271 const MachineConstantPoolEntry &CPE = CP[i];
3272 Align Alignment = CPE.getAlign();
3273
3275
3276 const Constant *C = nullptr;
3277 if (!CPE.isMachineConstantPoolEntry())
3278 C = CPE.Val.ConstVal;
3279
3281 getDataLayout(), Kind, C, Alignment, &MF->getFunction(),
3283
3284 // The number of sections are small, just do a linear search from the
3285 // last section to the first.
3286 bool Found = false;
3287 unsigned SecIdx = CPSections.size();
3288 while (SecIdx != 0) {
3289 if (CPSections[--SecIdx].S == S) {
3290 Found = true;
3291 break;
3292 }
3293 }
3294 if (!Found) {
3295 SecIdx = CPSections.size();
3296 CPSections.push_back(SectionCPs(S, Alignment));
3297 }
3298
3299 if (Alignment > CPSections[SecIdx].Alignment)
3300 CPSections[SecIdx].Alignment = Alignment;
3301 CPSections[SecIdx].CPEs.push_back(i);
3302 }
3303
3304 // Now print stuff into the calculated sections.
3305 const MCSection *CurSection = nullptr;
3306 unsigned Offset = 0;
3307 for (const SectionCPs &CPSection : CPSections) {
3308 for (unsigned CPI : CPSection.CPEs) {
3309 MCSymbol *Sym = GetCPISymbol(CPI);
3310 if (!Sym->isUndefined())
3311 continue;
3312
3313 if (CurSection != CPSection.S) {
3314 OutStreamer->switchSection(CPSection.S);
3315 emitAlignment(Align(CPSection.Alignment));
3316 CurSection = CPSection.S;
3317 Offset = 0;
3318 }
3319
3320 MachineConstantPoolEntry CPE = CP[CPI];
3321
3322 // Emit inter-object padding for alignment.
3323 unsigned NewOffset = alignTo(Offset, CPE.getAlign());
3324 OutStreamer->emitZeros(NewOffset - Offset);
3325
3326 Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
3327
3328 OutStreamer->emitLabel(Sym);
3331 else
3333 }
3334 }
3335}
3336
3337// Print assembly representations of the jump tables used by the current
3338// function.
3340 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
3341 if (!MJTI) return;
3342
3343 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
3344 if (JT.empty()) return;
3345
3346 if (!TM.Options.EnableStaticDataPartitioning) {
3347 emitJumpTableImpl(*MJTI, llvm::to_vector(llvm::seq<unsigned>(JT.size())));
3348 return;
3349 }
3350
3351 SmallVector<unsigned> HotJumpTableIndices, ColdJumpTableIndices;
3352 // When static data partitioning is enabled, collect jump table entries that
3353 // go into the same section together to reduce the amount of section switch
3354 // statements.
3355 for (unsigned JTI = 0, JTSize = JT.size(); JTI < JTSize; ++JTI) {
3356 if (JT[JTI].Hotness == MachineFunctionDataHotness::Cold) {
3357 ColdJumpTableIndices.push_back(JTI);
3358 } else {
3359 HotJumpTableIndices.push_back(JTI);
3360 }
3361 }
3362
3363 emitJumpTableImpl(*MJTI, HotJumpTableIndices);
3364 emitJumpTableImpl(*MJTI, ColdJumpTableIndices);
3365}
3366
3367void AsmPrinter::emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
3368 ArrayRef<unsigned> JumpTableIndices) {
3370 JumpTableIndices.empty())
3371 return;
3372
3374 const Function &F = MF->getFunction();
3375 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3376 MCSection *JumpTableSection = nullptr;
3377
3378 const bool UseLabelDifference =
3381 // Pick the directive to use to print the jump table entries, and switch to
3382 // the appropriate section.
3383 const bool JTInDiffSection =
3384 !TLOF.shouldPutJumpTableInFunctionSection(UseLabelDifference, F);
3385 if (JTInDiffSection) {
3387 JumpTableSection =
3388 TLOF.getSectionForJumpTable(F, TM, &JT[JumpTableIndices.front()]);
3389 } else {
3390 JumpTableSection = TLOF.getSectionForJumpTable(F, TM);
3391 }
3392 OutStreamer->switchSection(JumpTableSection);
3393 }
3394
3395 const DataLayout &DL = MF->getDataLayout();
3397
3398 // Jump tables in code sections are marked with a data_region directive
3399 // where that's supported.
3400 if (!JTInDiffSection)
3401 OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
3402
3403 for (const unsigned JumpTableIndex : JumpTableIndices) {
3404 ArrayRef<MachineBasicBlock *> JTBBs = JT[JumpTableIndex].MBBs;
3405
3406 // If this jump table was deleted, ignore it.
3407 if (JTBBs.empty())
3408 continue;
3409
3410 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
3411 /// emit a .set directive for each unique entry.
3413 MAI->doesSetDirectiveSuppressReloc()) {
3414 SmallPtrSet<const MachineBasicBlock *, 16> EmittedSets;
3415 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3416 const MCExpr *Base =
3417 TLI->getPICJumpTableRelocBaseExpr(MF, JumpTableIndex, OutContext);
3418 for (const MachineBasicBlock *MBB : JTBBs) {
3419 if (!EmittedSets.insert(MBB).second)
3420 continue;
3421
3422 // .set LJTSet, LBB32-base
3423 const MCExpr *LHS =
3425 OutStreamer->emitAssignment(
3426 GetJTSetSymbol(JumpTableIndex, MBB->getNumber()),
3428 }
3429 }
3430
3431 // On some targets (e.g. Darwin) we want to emit two consecutive labels
3432 // before each jump table. The first label is never referenced, but tells
3433 // the assembler and linker the extents of the jump table object. The
3434 // second label is actually referenced by the code.
3435 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
3436 // FIXME: This doesn't have to have any specific name, just any randomly
3437 // named and numbered local label started with 'l' would work. Simplify
3438 // GetJTISymbol.
3439 OutStreamer->emitLabel(GetJTISymbol(JumpTableIndex, true));
3440
3441 MCSymbol *JTISymbol = GetJTISymbol(JumpTableIndex);
3442 OutStreamer->emitLabel(JTISymbol);
3443
3444 // Defer MCAssembler based constant folding due to a performance issue. The
3445 // label differences will be evaluated at write time.
3446 for (const MachineBasicBlock *MBB : JTBBs)
3447 emitJumpTableEntry(MJTI, MBB, JumpTableIndex);
3448 }
3449
3451 emitJumpTableSizesSection(MJTI, MF->getFunction());
3452
3453 if (!JTInDiffSection)
3454 OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
3455}
3456
3457void AsmPrinter::emitJumpTableSizesSection(const MachineJumpTableInfo &MJTI,
3458 const Function &F) const {
3459 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3460
3461 if (JT.empty())
3462 return;
3463
3464 StringRef GroupName = F.hasComdat() ? F.getComdat()->getName() : "";
3465 MCSection *JumpTableSizesSection = nullptr;
3466 StringRef sectionName = ".llvm_jump_table_sizes";
3467
3468 bool isElf = TM.getTargetTriple().isOSBinFormatELF();
3469 bool isCoff = TM.getTargetTriple().isOSBinFormatCOFF();
3470
3471 if (!isCoff && !isElf)
3472 return;
3473
3474 if (isElf) {
3475 auto *LinkedToSym = static_cast<MCSymbolELF *>(CurrentFnSym);
3476 int Flags = F.hasComdat() ? static_cast<int>(ELF::SHF_GROUP) : 0;
3477
3478 JumpTableSizesSection = OutContext.getELFSection(
3479 sectionName, ELF::SHT_LLVM_JT_SIZES, Flags, 0, GroupName, F.hasComdat(),
3480 MCSection::NonUniqueID, LinkedToSym);
3481 } else if (isCoff) {
3482 if (F.hasComdat()) {
3483 JumpTableSizesSection = OutContext.getCOFFSection(
3484 sectionName,
3487 F.getComdat()->getName(), COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
3488 } else {
3489 JumpTableSizesSection = OutContext.getCOFFSection(
3493 }
3494 }
3495
3496 OutStreamer->switchSection(JumpTableSizesSection);
3497
3498 for (unsigned JTI = 0, E = JT.size(); JTI != E; ++JTI) {
3499 const std::vector<MachineBasicBlock *> &JTBBs = JT[JTI].MBBs;
3500 OutStreamer->emitSymbolValue(GetJTISymbol(JTI), TM.getProgramPointerSize());
3501 OutStreamer->emitIntValue(JTBBs.size(), TM.getProgramPointerSize());
3502 }
3503}
3504
3505/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
3506/// current stream.
3508 const MachineBasicBlock *MBB,
3509 unsigned UID) const {
3510 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
3511 const MCExpr *Value = nullptr;
3512 switch (MJTI.getEntryKind()) {
3514 llvm_unreachable("Cannot emit EK_Inline jump table entry");
3517 llvm_unreachable("MIPS specific");
3519 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
3520 &MJTI, MBB, UID, OutContext);
3521 break;
3523 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
3524 // .word LBB123
3526 break;
3527
3530 // Each entry is the address of the block minus the address of the jump
3531 // table. This is used for PIC jump tables where gprel32 is not supported.
3532 // e.g.:
3533 // .word LBB123 - LJTI1_2
3534 // If the .set directive avoids relocations, this is emitted as:
3535 // .set L4_5_set_123, LBB123 - LJTI1_2
3536 // .word L4_5_set_123
3538 MAI->doesSetDirectiveSuppressReloc()) {
3539 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
3540 OutContext);
3541 break;
3542 }
3544 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3547 break;
3548 }
3549 }
3550
3551 assert(Value && "Unknown entry kind!");
3552
3553 unsigned EntrySize = MJTI.getEntrySize(getDataLayout());
3554 OutStreamer->emitValue(Value, EntrySize);
3555}
3556
3557/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
3558/// special global used by LLVM. If so, emit it and return true, otherwise
3559/// do nothing and return false.
3561 if (GV->getName() == "llvm.used") {
3562 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
3563 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
3564 return true;
3565 }
3566
3567 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
3568 if (GV->getSection() == "llvm.metadata" ||
3570 return true;
3571
3572 if (GV->getName() == "llvm.arm64ec.symbolmap") {
3573 // For ARM64EC, print the table that maps between symbols and the
3574 // corresponding thunks to translate between x64 and AArch64 code.
3575 // This table is generated by AArch64Arm64ECCallLowering.
3576 OutStreamer->switchSection(
3577 OutContext.getCOFFSection(".hybmp$x", COFF::IMAGE_SCN_LNK_INFO));
3578 auto *Arr = cast<ConstantArray>(GV->getInitializer());
3579 for (auto &U : Arr->operands()) {
3580 auto *C = cast<Constant>(U);
3581 auto *Src = cast<GlobalValue>(C->getOperand(0)->stripPointerCasts());
3582 auto *Dst = cast<GlobalValue>(C->getOperand(1)->stripPointerCasts());
3583 int Kind = cast<ConstantInt>(C->getOperand(2))->getZExtValue();
3584
3585 if (Src->hasDLLImportStorageClass()) {
3586 // For now, we assume dllimport functions aren't directly called.
3587 // (We might change this later to match MSVC.)
3588 OutStreamer->emitCOFFSymbolIndex(
3589 OutContext.getOrCreateSymbol("__imp_" + Src->getName()));
3590 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3591 OutStreamer->emitInt32(Kind);
3592 } else {
3593 // FIXME: For non-dllimport functions, MSVC emits the same entry
3594 // twice, for reasons I don't understand. I have to assume the linker
3595 // ignores the redundant entry; there aren't any reasonable semantics
3596 // to attach to it.
3597 OutStreamer->emitCOFFSymbolIndex(getSymbol(Src));
3598 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3599 OutStreamer->emitInt32(Kind);
3600 }
3601 }
3602 return true;
3603 }
3604
3605 if (!GV->hasAppendingLinkage()) return false;
3606
3607 assert(GV->hasInitializer() && "Not a special LLVM global!");
3608
3609 if (GV->getName() == "llvm.global_ctors") {
3611 /* isCtor */ true);
3612
3613 return true;
3614 }
3615
3616 if (GV->getName() == "llvm.global_dtors") {
3618 /* isCtor */ false);
3619
3620 return true;
3621 }
3622
3623 GV->getContext().emitError(
3624 "unknown special variable with appending linkage: " +
3625 GV->getNameOrAsOperand());
3626 return true;
3627}
3628
3629/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
3630/// global in the specified llvm.used list.
3631void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
3632 // Should be an array of 'i8*'.
3633 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
3634 const GlobalValue *GV =
3636 if (GV)
3637 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
3638 }
3639}
3640
3642 const Constant *List,
3643 SmallVector<Structor, 8> &Structors) {
3644 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
3645 // the init priority.
3647 return;
3648
3649 // Gather the structors in a form that's convenient for sorting by priority.
3650 for (Value *O : cast<ConstantArray>(List)->operands()) {
3651 auto *CS = cast<ConstantStruct>(O);
3652 if (CS->getOperand(1)->isNullValue())
3653 break; // Found a null terminator, skip the rest.
3654 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
3655 if (!Priority)
3656 continue; // Malformed.
3657 Structors.push_back(Structor());
3658 Structor &S = Structors.back();
3659 S.Priority = Priority->getLimitedValue(65535);
3660 S.Func = CS->getOperand(1);
3661 if (!CS->getOperand(2)->isNullValue()) {
3662 if (TM.getTargetTriple().isOSAIX()) {
3663 CS->getContext().emitError(
3664 "associated data of XXStructor list is not yet supported on AIX");
3665 }
3666
3667 S.ComdatKey =
3668 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
3669 }
3670 }
3671
3672 // Emit the function pointers in the target-specific order
3673 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
3674 return L.Priority < R.Priority;
3675 });
3676}
3677
3678/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
3679/// priority.
3681 bool IsCtor) {
3682 SmallVector<Structor, 8> Structors;
3683 preprocessXXStructorList(DL, List, Structors);
3684 if (Structors.empty())
3685 return;
3686
3687 // Emit the structors in reverse order if we are using the .ctor/.dtor
3688 // initialization scheme.
3689 if (!TM.Options.UseInitArray)
3690 std::reverse(Structors.begin(), Structors.end());
3691
3692 const Align Align = DL.getPointerPrefAlignment(DL.getProgramAddressSpace());
3693 for (Structor &S : Structors) {
3695 const MCSymbol *KeySym = nullptr;
3696 if (GlobalValue *GV = S.ComdatKey) {
3697 if (GV->isDeclarationForLinker())
3698 // If the associated variable is not defined in this module
3699 // (it might be available_externally, or have been an
3700 // available_externally definition that was dropped by the
3701 // EliminateAvailableExternally pass), some other TU
3702 // will provide its dynamic initializer.
3703 continue;
3704
3705 KeySym = getSymbol(GV);
3706 }
3707
3708 MCSection *OutputSection =
3709 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
3710 : Obj.getStaticDtorSection(S.Priority, KeySym));
3711 OutStreamer->switchSection(OutputSection);
3712 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
3714 emitXXStructor(DL, S.Func);
3715 }
3716}
3717
3718void AsmPrinter::emitModuleIdents(Module &M) {
3719 if (!MAI->hasIdentDirective())
3720 return;
3721
3722 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
3723 for (const MDNode *N : NMD->operands()) {
3724 assert(N->getNumOperands() == 1 &&
3725 "llvm.ident metadata entry can have only one operand");
3726 const MDString *S = cast<MDString>(N->getOperand(0));
3727 OutStreamer->emitIdent(S->getString());
3728 }
3729 }
3730}
3731
3732void AsmPrinter::emitModuleCommandLines(Module &M) {
3733 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
3734 if (!CommandLine)
3735 return;
3736
3737 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3738 if (!NMD || !NMD->getNumOperands())
3739 return;
3740
3741 OutStreamer->pushSection();
3742 OutStreamer->switchSection(CommandLine);
3743 OutStreamer->emitZeros(1);
3744 for (const MDNode *N : NMD->operands()) {
3745 assert(N->getNumOperands() == 1 &&
3746 "llvm.commandline metadata entry can have only one operand");
3747 const MDString *S = cast<MDString>(N->getOperand(0));
3748 OutStreamer->emitBytes(S->getString());
3749 OutStreamer->emitZeros(1);
3750 }
3751 OutStreamer->popSection();
3752}
3753
3754//===--------------------------------------------------------------------===//
3755// Emission and print routines
3756//
3757
3758/// Emit a byte directive and value.
3759///
3760void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
3761
3762/// Emit a short directive and value.
3763void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
3764
3765/// Emit a long directive and value.
3766void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
3767
3768/// EmitSLEB128 - emit the specified signed leb128 value.
3769void AsmPrinter::emitSLEB128(int64_t Value, const char *Desc) const {
3770 if (isVerbose() && Desc)
3771 OutStreamer->AddComment(Desc);
3772
3773 OutStreamer->emitSLEB128IntValue(Value);
3774}
3775
3777 unsigned PadTo) const {
3778 if (isVerbose() && Desc)
3779 OutStreamer->AddComment(Desc);
3780
3781 OutStreamer->emitULEB128IntValue(Value, PadTo);
3782}
3783
3784/// Emit a long long directive and value.
3786 OutStreamer->emitInt64(Value);
3787}
3788
3789/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
3790/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
3791/// .set if it avoids relocations.
3793 unsigned Size) const {
3794 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
3795}
3796
3797/// Emit something like ".uleb128 Hi-Lo".
3799 const MCSymbol *Lo) const {
3800 OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
3801}
3802
3803/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
3804/// where the size in bytes of the directive is specified by Size and Label
3805/// specifies the label. This implicitly uses .set if it is available.
3807 unsigned Size,
3808 bool IsSectionRelative) const {
3809 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
3810 OutStreamer->emitCOFFSecRel32(Label, Offset);
3811 if (Size > 4)
3812 OutStreamer->emitZeros(Size - 4);
3813 return;
3814 }
3815
3816 // Emit Label+Offset (or just Label if Offset is zero)
3817 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
3818 if (Offset)
3821
3822 OutStreamer->emitValue(Expr, Size);
3823}
3824
3825//===----------------------------------------------------------------------===//
3826
3827// EmitAlignment - Emit an alignment directive to the specified power of
3828// two boundary. If a global value is specified, and if that global has
3829// an explicit alignment requested, it will override the alignment request
3830// if required for correctness.
3832 unsigned MaxBytesToEmit) const {
3833 if (GV)
3834 Alignment = getGVAlignment(GV, GV->getDataLayout(), Alignment);
3835
3836 if (Alignment == Align(1))
3837 return; // 1-byte aligned: no need to emit alignment.
3838
3839 if (getCurrentSection()->isText()) {
3840 const MCSubtargetInfo *STI = nullptr;
3841 if (this->MF)
3842 STI = &getSubtargetInfo();
3843 else
3844 STI = TM.getMCSubtargetInfo();
3845 OutStreamer->emitCodeAlignment(Alignment, STI, MaxBytesToEmit);
3846 } else
3847 OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
3848}
3849
3850//===----------------------------------------------------------------------===//
3851// Constant emission.
3852//===----------------------------------------------------------------------===//
3853
3855 const Constant *BaseCV,
3856 uint64_t Offset) {
3857 MCContext &Ctx = OutContext;
3858
3859 if (CV->isNullValue() || isa<UndefValue>(CV))
3860 return MCConstantExpr::create(0, Ctx);
3861
3862 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
3863 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
3864
3865 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV))
3866 return MCConstantExpr::create(CB->getZExtValue(), Ctx);
3867
3868 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV))
3869 return lowerConstantPtrAuth(*CPA);
3870
3871 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
3872 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
3873
3874 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
3875 return lowerBlockAddressConstant(*BA);
3876
3877 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
3879 getSymbol(Equiv->getGlobalValue()), nullptr, 0, std::nullopt, TM);
3880
3881 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
3882 return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
3883
3884 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
3885 if (!CE) {
3886 llvm_unreachable("Unknown constant value to lower!");
3887 }
3888
3889 // The constant expression opcodes are limited to those that are necessary
3890 // to represent relocations on supported targets. Expressions involving only
3891 // constant addresses are constant folded instead.
3892 switch (CE->getOpcode()) {
3893 default:
3894 break; // Error
3895 case Instruction::AddrSpaceCast: {
3896 const Constant *Op = CE->getOperand(0);
3897 unsigned DstAS = CE->getType()->getPointerAddressSpace();
3898 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
3899 if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
3900 return lowerConstant(Op);
3901
3902 break; // Error
3903 }
3904 case Instruction::GetElementPtr: {
3905 // Generate a symbolic expression for the byte address
3906 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
3907 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
3908
3909 const MCExpr *Base = lowerConstant(CE->getOperand(0));
3910 if (!OffsetAI)
3911 return Base;
3912
3913 int64_t Offset = OffsetAI.getSExtValue();
3915 Ctx);
3916 }
3917
3918 case Instruction::Trunc:
3919 // We emit the value and depend on the assembler to truncate the generated
3920 // expression properly. This is important for differences between
3921 // blockaddress labels. Since the two labels are in the same function, it
3922 // is reasonable to treat their delta as a 32-bit value.
3923 [[fallthrough]];
3924 case Instruction::BitCast:
3925 return lowerConstant(CE->getOperand(0), BaseCV, Offset);
3926
3927 case Instruction::IntToPtr: {
3928 const DataLayout &DL = getDataLayout();
3929
3930 // Handle casts to pointers by changing them into casts to the appropriate
3931 // integer type. This promotes constant folding and simplifies this code.
3932 Constant *Op = CE->getOperand(0);
3933 Op = ConstantFoldIntegerCast(Op, DL.getIntPtrType(CV->getType()),
3934 /*IsSigned*/ false, DL);
3935 if (Op)
3936 return lowerConstant(Op);
3937
3938 break; // Error
3939 }
3940
3941 case Instruction::PtrToAddr:
3942 case Instruction::PtrToInt: {
3943 const DataLayout &DL = getDataLayout();
3944
3945 // Support only foldable casts to/from pointers that can be eliminated by
3946 // changing the pointer to the appropriately sized integer type.
3947 Constant *Op = CE->getOperand(0);
3948 Type *Ty = CE->getType();
3949
3950 const MCExpr *OpExpr = lowerConstant(Op);
3951
3952 // We can emit the pointer value into this slot if the slot is an
3953 // integer slot equal to the size of the pointer.
3954 //
3955 // If the pointer is larger than the resultant integer, then
3956 // as with Trunc just depend on the assembler to truncate it.
3957 if (DL.getTypeAllocSize(Ty).getFixedValue() <=
3958 DL.getTypeAllocSize(Op->getType()).getFixedValue())
3959 return OpExpr;
3960
3961 break; // Error
3962 }
3963
3964 case Instruction::Sub: {
3965 GlobalValue *LHSGV, *RHSGV;
3966 APInt LHSOffset, RHSOffset;
3967 DSOLocalEquivalent *DSOEquiv;
3968 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
3969 getDataLayout(), &DSOEquiv) &&
3970 IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
3971 getDataLayout())) {
3972 auto *LHSSym = getSymbol(LHSGV);
3973 auto *RHSSym = getSymbol(RHSGV);
3974 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
3975 std::optional<int64_t> PCRelativeOffset;
3976 if (getObjFileLowering().hasPLTPCRelative() && RHSGV == BaseCV)
3977 PCRelativeOffset = Offset;
3978
3979 // Try the generic symbol difference first.
3981 LHSGV, RHSGV, Addend, PCRelativeOffset, TM);
3982
3983 // (ELF-specific) If the generic symbol difference does not apply, and
3984 // LHS is a dso_local_equivalent of a function, reference the PLT entry
3985 // instead. Note: A default visibility symbol is by default preemptible
3986 // during linking, and should not be referenced with PC-relative
3987 // relocations. Therefore, use a PLT relocation even if the function is
3988 // dso_local.
3989 if (DSOEquiv && TM.getTargetTriple().isOSBinFormatELF())
3991 LHSSym, RHSSym, Addend, PCRelativeOffset, TM);
3992
3993 // Otherwise, return LHS-RHS+Addend.
3994 if (!Res) {
3995 Res =
3997 MCSymbolRefExpr::create(RHSSym, Ctx), Ctx);
3998 if (Addend != 0)
4000 Res, MCConstantExpr::create(Addend, Ctx), Ctx);
4001 }
4002 return Res;
4003 }
4004
4005 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
4006 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
4007 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
4008 break;
4009 }
4010
4011 case Instruction::Add: {
4012 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
4013 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
4014 return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
4015 }
4016 }
4017
4018 // If the code isn't optimized, there may be outstanding folding
4019 // opportunities. Attempt to fold the expression using DataLayout as a
4020 // last resort before giving up.
4022 if (C != CE)
4023 return lowerConstant(C);
4024
4025 // Otherwise report the problem to the user.
4026 std::string S;
4027 raw_string_ostream OS(S);
4028 OS << "unsupported expression in static initializer: ";
4029 CE->printAsOperand(OS, /*PrintType=*/false,
4030 !MF ? nullptr : MF->getFunction().getParent());
4031 CE->getContext().emitError(S);
4032 return MCConstantExpr::create(0, Ctx);
4033}
4034
4035static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
4036 AsmPrinter &AP,
4037 const Constant *BaseCV = nullptr,
4038 uint64_t Offset = 0,
4039 AsmPrinter::AliasMapTy *AliasList = nullptr);
4040
4041static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
4042static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
4043
4044/// isRepeatedByteSequence - Determine whether the given value is
4045/// composed of a repeated sequence of identical bytes and return the
4046/// byte value. If it is not a repeated sequence, return -1.
4048 StringRef Data = V->getRawDataValues();
4049 assert(!Data.empty() && "Empty aggregates should be CAZ node");
4050 char C = Data[0];
4051 for (unsigned i = 1, e = Data.size(); i != e; ++i)
4052 if (Data[i] != C) return -1;
4053 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
4054}
4055
4056/// isRepeatedByteSequence - Determine whether the given value is
4057/// composed of a repeated sequence of identical bytes and return the
4058/// byte value. If it is not a repeated sequence, return -1.
4059static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
4060 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
4061 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
4062 assert(Size % 8 == 0);
4063
4064 // Extend the element to take zero padding into account.
4065 APInt Value = CI->getValue().zext(Size);
4066 if (!Value.isSplat(8))
4067 return -1;
4068
4069 return Value.zextOrTrunc(8).getZExtValue();
4070 }
4071 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
4072 // Make sure all array elements are sequences of the same repeated
4073 // byte.
4074 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
4075 Constant *Op0 = CA->getOperand(0);
4076 int Byte = isRepeatedByteSequence(Op0, DL);
4077 if (Byte == -1)
4078 return -1;
4079
4080 // All array elements must be equal.
4081 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
4082 if (CA->getOperand(i) != Op0)
4083 return -1;
4084 return Byte;
4085 }
4086
4088 return isRepeatedByteSequence(CDS);
4089
4090 return -1;
4091}
4092
4094 AsmPrinter::AliasMapTy *AliasList) {
4095 if (AliasList) {
4096 auto AliasIt = AliasList->find(Offset);
4097 if (AliasIt != AliasList->end()) {
4098 for (const GlobalAlias *GA : AliasIt->second)
4099 AP.OutStreamer->emitLabel(AP.getSymbol(GA));
4100 AliasList->erase(Offset);
4101 }
4102 }
4103}
4104
4106 const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
4107 AsmPrinter::AliasMapTy *AliasList) {
4108 // See if we can aggregate this into a .fill, if so, emit it as such.
4109 int Value = isRepeatedByteSequence(CDS, DL);
4110 if (Value != -1) {
4111 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
4112 // Don't emit a 1-byte object as a .fill.
4113 if (Bytes > 1)
4114 return AP.OutStreamer->emitFill(Bytes, Value);
4115 }
4116
4117 // If this can be emitted with .ascii/.asciz, emit it as such.
4118 if (CDS->isString())
4119 return AP.OutStreamer->emitBytes(CDS->getAsString());
4120
4121 // Otherwise, emit the values in successive locations.
4122 uint64_t ElementByteSize = CDS->getElementByteSize();
4123 if (isa<IntegerType>(CDS->getElementType()) ||
4124 isa<ByteType>(CDS->getElementType())) {
4125 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4126 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4127 if (AP.isVerbose())
4128 AP.OutStreamer->getCommentOS()
4129 << format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
4130 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
4131 ElementByteSize);
4132 }
4133 } else {
4134 Type *ET = CDS->getElementType();
4135 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4136 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4138 }
4139 }
4140
4141 unsigned Size = DL.getTypeAllocSize(CDS->getType());
4142 unsigned EmittedSize =
4143 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
4144 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
4145 if (unsigned Padding = Size - EmittedSize)
4146 AP.OutStreamer->emitZeros(Padding);
4147}
4148
4150 const ConstantArray *CA, AsmPrinter &AP,
4151 const Constant *BaseCV, uint64_t Offset,
4152 AsmPrinter::AliasMapTy *AliasList) {
4153 // See if we can aggregate some values. Make sure it can be
4154 // represented as a series of bytes of the constant value.
4155 int Value = isRepeatedByteSequence(CA, DL);
4156
4157 if (Value != -1) {
4158 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
4159 AP.OutStreamer->emitFill(Bytes, Value);
4160 } else {
4161 for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
4162 emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
4163 AliasList);
4164 Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
4165 }
4166 }
4167}
4168
4169static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
4170
4171static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV,
4172 AsmPrinter &AP,
4173 AsmPrinter::AliasMapTy *AliasList) {
4174 auto *VTy = cast<FixedVectorType>(CV->getType());
4175 Type *ElementType = VTy->getElementType();
4176 uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
4177 uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
4178 uint64_t EmittedSize;
4179 if (ElementSizeInBits != ElementAllocSizeInBits) {
4180 // If the allocation size of an element is different from the size in bits,
4181 // printing each element separately will insert incorrect padding.
4182 //
4183 // The general algorithm here is complicated; instead of writing it out
4184 // here, just use the existing code in ConstantFolding.
4185 Type *IntT =
4186 IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
4188 ConstantExpr::getBitCast(const_cast<Constant *>(CV), IntT), DL));
4189 if (!CI) {
4191 "Cannot lower vector global with unusual element type");
4192 }
4193 emitGlobalAliasInline(AP, 0, AliasList);
4195 EmittedSize = DL.getTypeStoreSize(CV->getType());
4196 } else {
4197 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
4198 emitGlobalAliasInline(AP, DL.getTypeAllocSize(CV->getType()) * I, AliasList);
4200 }
4201 EmittedSize = DL.getTypeAllocSize(ElementType) * VTy->getNumElements();
4202 }
4203
4204 unsigned Size = DL.getTypeAllocSize(CV->getType());
4205 if (unsigned Padding = Size - EmittedSize)
4206 AP.OutStreamer->emitZeros(Padding);
4207}
4208
4210 const ConstantStruct *CS, AsmPrinter &AP,
4211 const Constant *BaseCV, uint64_t Offset,
4212 AsmPrinter::AliasMapTy *AliasList) {
4213 // Print the fields in successive locations. Pad to align if needed!
4214 uint64_t Size = DL.getTypeAllocSize(CS->getType());
4215 const StructLayout *Layout = DL.getStructLayout(CS->getType());
4216 uint64_t SizeSoFar = 0;
4217 for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
4218 const Constant *Field = CS->getOperand(I);
4219
4220 // Print the actual field value.
4221 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
4222 AliasList);
4223
4224 // Check if padding is needed and insert one or more 0s.
4225 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
4226 uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
4227 Layout->getElementOffset(I)) -
4228 FieldSize;
4229 SizeSoFar += FieldSize + PadSize;
4230
4231 // Insert padding - this may include padding to increase the size of the
4232 // current field up to the ABI size (if the struct is not packed) as well
4233 // as padding to ensure that the next field starts at the right offset.
4234 AP.OutStreamer->emitZeros(PadSize);
4235 }
4236 assert(SizeSoFar == Layout->getSizeInBytes() &&
4237 "Layout of constant struct may be incorrect!");
4238}
4239
4240static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
4241 assert(ET && "Unknown float type");
4242 APInt API = APF.bitcastToAPInt();
4243
4244 // First print a comment with what we think the original floating-point value
4245 // should have been.
4246 if (AP.isVerbose()) {
4247 SmallString<8> StrVal;
4248 APF.toString(StrVal);
4249 ET->print(AP.OutStreamer->getCommentOS());
4250 AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
4251 }
4252
4253 // Now iterate through the APInt chunks, emitting them in endian-correct
4254 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
4255 // floats).
4256 unsigned NumBytes = API.getBitWidth() / 8;
4257 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
4258 const uint64_t *p = API.getRawData();
4259
4260 // PPC's long double has odd notions of endianness compared to how LLVM
4261 // handles it: p[0] goes first for *big* endian on PPC.
4262 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
4263 int Chunk = API.getNumWords() - 1;
4264
4265 if (TrailingBytes)
4266 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
4267
4268 for (; Chunk >= 0; --Chunk)
4269 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4270 } else {
4271 unsigned Chunk;
4272 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
4273 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4274
4275 if (TrailingBytes)
4276 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
4277 }
4278
4279 // Emit the tail padding for the long double.
4280 const DataLayout &DL = AP.getDataLayout();
4281 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
4282}
4283
4284static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
4285 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
4286}
4287
4289 uint64_t TypeStoreSize,
4290 AsmPrinter &AP) {
4291 const DataLayout &DL = AP.getDataLayout();
4292 unsigned BitWidth = Val.getBitWidth();
4293
4294 // Copy the value as we may massage the layout for constants whose bit width
4295 // is not a multiple of 64-bits.
4296 APInt Realigned(Val);
4297 uint64_t ExtraBits = 0;
4298 unsigned ExtraBitsSize = BitWidth & 63;
4299
4300 if (ExtraBitsSize) {
4301 // The bit width of the data is not a multiple of 64-bits.
4302 // The extra bits are expected to be at the end of the chunk of the memory.
4303 // Little endian:
4304 // * Nothing to be done, just record the extra bits to emit.
4305 // Big endian:
4306 // * Record the extra bits to emit.
4307 // * Realign the raw data to emit the chunks of 64-bits.
4308 if (DL.isBigEndian()) {
4309 // Basically the structure of the raw data is a chunk of 64-bits cells:
4310 // 0 1 BitWidth / 64
4311 // [chunk1][chunk2] ... [chunkN].
4312 // The most significant chunk is chunkN and it should be emitted first.
4313 // However, due to the alignment issue chunkN contains useless bits.
4314 // Realign the chunks so that they contain only useful information:
4315 // ExtraBits 0 1 (BitWidth / 64) - 1
4316 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
4317 ExtraBitsSize = alignTo(ExtraBitsSize, 8);
4318 ExtraBits =
4319 Realigned.getRawData()[0] & (((uint64_t)-1) >> (64 - ExtraBitsSize));
4320 if (BitWidth >= 64)
4321 Realigned.lshrInPlace(ExtraBitsSize);
4322 } else
4323 ExtraBits = Realigned.getRawData()[BitWidth / 64];
4324 }
4325
4326 // We don't expect assemblers to support data directives
4327 // for more than 64 bits, so we emit the data in at most 64-bit
4328 // quantities at a time.
4329 const uint64_t *RawData = Realigned.getRawData();
4330 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
4331 uint64_t ChunkVal = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
4332 AP.OutStreamer->emitIntValue(ChunkVal, 8);
4333 }
4334
4335 if (ExtraBitsSize) {
4336 // Emit the extra bits after the 64-bits chunks.
4337
4338 // Emit a directive that fills the expected size.
4339 uint64_t Size = TypeStoreSize - (BitWidth / 64) * 8;
4340 assert(Size && Size * 8 >= ExtraBitsSize &&
4341 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) ==
4342 ExtraBits &&
4343 "Directive too small for extra bits.");
4344 AP.OutStreamer->emitIntValue(ExtraBits, Size);
4345 }
4346}
4347
4349 AsmPrinter &AP) {
4351 CB->getValue(), AP.getDataLayout().getTypeStoreSize(CB->getType()), AP);
4352}
4353
4358
4359/// Transform a not absolute MCExpr containing a reference to a GOT
4360/// equivalent global, by a target specific GOT pc relative access to the
4361/// final symbol.
4363 const Constant *BaseCst,
4364 uint64_t Offset) {
4365 // The global @foo below illustrates a global that uses a got equivalent.
4366 //
4367 // @bar = global i32 42
4368 // @gotequiv = private unnamed_addr constant i32* @bar
4369 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
4370 // i64 ptrtoint (i32* @foo to i64))
4371 // to i32)
4372 //
4373 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
4374 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
4375 // form:
4376 //
4377 // foo = cstexpr, where
4378 // cstexpr := <gotequiv> - "." + <cst>
4379 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
4380 //
4381 // After canonicalization by evaluateAsRelocatable `ME` turns into:
4382 //
4383 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
4384 // gotpcrelcst := <offset from @foo base> + <cst>
4385 MCValue MV;
4386 if (!(*ME)->evaluateAsRelocatable(MV, nullptr) || MV.isAbsolute())
4387 return;
4388 const MCSymbol *GOTEquivSym = MV.getAddSym();
4389 if (!GOTEquivSym)
4390 return;
4391
4392 // Check that GOT equivalent symbol is cached.
4393 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
4394 return;
4395
4396 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
4397 if (!BaseGV)
4398 return;
4399
4400 // Check for a valid base symbol
4401 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
4402 const MCSymbol *SymB = MV.getSubSym();
4403
4404 if (!SymB || BaseSym != SymB)
4405 return;
4406
4407 // Make sure to match:
4408 //
4409 // gotpcrelcst := <offset from @foo base> + <cst>
4410 //
4411 int64_t GOTPCRelCst = Offset + MV.getConstant();
4412 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
4413 return;
4414
4415 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
4416 //
4417 // bar:
4418 // .long 42
4419 // gotequiv:
4420 // .quad bar
4421 // foo:
4422 // .long gotequiv - "." + <cst>
4423 //
4424 // is replaced by the target specific equivalent to:
4425 //
4426 // bar:
4427 // .long 42
4428 // foo:
4429 // .long bar@GOTPCREL+<gotpcrelcst>
4430 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
4431 const GlobalVariable *GV = Result.first;
4432 int NumUses = (int)Result.second;
4433 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
4434 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
4436 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
4437
4438 // Update GOT equivalent usage information
4439 --NumUses;
4440 if (NumUses >= 0)
4441 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
4442}
4443
4444static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
4445 AsmPrinter &AP, const Constant *BaseCV,
4447 AsmPrinter::AliasMapTy *AliasList) {
4448 assert((!AliasList || AP.TM.getTargetTriple().isOSBinFormatXCOFF()) &&
4449 "AliasList only expected for XCOFF");
4450 emitGlobalAliasInline(AP, Offset, AliasList);
4451 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4452
4453 // Globals with sub-elements such as combinations of arrays and structs
4454 // are handled recursively by emitGlobalConstantImpl. Keep track of the
4455 // constant symbol base and the current position with BaseCV and Offset.
4456 if (!BaseCV && CV->hasOneUse())
4457 BaseCV = dyn_cast<Constant>(CV->user_back());
4458
4460 StructType *structType;
4461 if (AliasList && (structType = llvm::dyn_cast<StructType>(CV->getType()))) {
4462 unsigned numElements = {structType->getNumElements()};
4463 if (numElements != 0) {
4464 // Handle cases of aliases to direct struct elements
4465 const StructLayout *Layout = DL.getStructLayout(structType);
4466 uint64_t SizeSoFar = 0;
4467 for (unsigned int i = 0; i < numElements - 1; ++i) {
4468 uint64_t GapToNext = Layout->getElementOffset(i + 1) - SizeSoFar;
4469 AP.OutStreamer->emitZeros(GapToNext);
4470 SizeSoFar += GapToNext;
4471 emitGlobalAliasInline(AP, Offset + SizeSoFar, AliasList);
4472 }
4473 AP.OutStreamer->emitZeros(Size - SizeSoFar);
4474 return;
4475 }
4476 }
4477 return AP.OutStreamer->emitZeros(Size);
4478 }
4479
4480 if (isa<UndefValue>(CV))
4481 return AP.OutStreamer->emitZeros(Size);
4482
4483 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
4484 if (isa<VectorType>(CV->getType()))
4485 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4486
4487 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4488 if (StoreSize <= 8) {
4489 if (AP.isVerbose())
4490 AP.OutStreamer->getCommentOS()
4491 << format("0x%" PRIx64 "\n", CI->getZExtValue());
4492 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
4493 } else {
4495 }
4496
4497 // Emit tail padding if needed
4498 if (Size != StoreSize)
4499 AP.OutStreamer->emitZeros(Size - StoreSize);
4500
4501 return;
4502 }
4503
4504 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV)) {
4505 if (isa<VectorType>(CV->getType()))
4506 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4507
4508 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4509 if (StoreSize <= 8) {
4510 if (AP.isVerbose())
4511 AP.OutStreamer->getCommentOS()
4512 << format("0x%" PRIx64 "\n", CB->getZExtValue());
4513 AP.OutStreamer->emitIntValue(CB->getZExtValue(), StoreSize);
4514 } else {
4516 }
4517
4518 // Emit tail padding if needed
4519 if (Size != StoreSize)
4520 AP.OutStreamer->emitZeros(Size - StoreSize);
4521
4522 return;
4523 }
4524
4525 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
4526 if (isa<VectorType>(CV->getType()))
4527 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4528 else
4529 return emitGlobalConstantFP(CFP, AP);
4530 }
4531
4532 if (isa<ConstantPointerNull>(CV)) {
4533 AP.OutStreamer->emitIntValue(0, Size);
4534 return;
4535 }
4536
4538 return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
4539
4540 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
4541 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
4542
4543 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
4544 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
4545
4546 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
4547 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
4548 // vectors).
4549 if (CE->getOpcode() == Instruction::BitCast)
4550 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
4551
4552 if (Size > 8) {
4553 // If the constant expression's size is greater than 64-bits, then we have
4554 // to emit the value in chunks. Try to constant fold the value and emit it
4555 // that way.
4556 Constant *New = ConstantFoldConstant(CE, DL);
4557 if (New != CE)
4558 return emitGlobalConstantImpl(DL, New, AP);
4559 }
4560 }
4561
4562 if (isa<ConstantVector>(CV))
4563 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4564
4565 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
4566 // thread the streamer with EmitValue.
4567 const MCExpr *ME = AP.lowerConstant(CV, BaseCV, Offset);
4568
4569 // Since lowerConstant already folded and got rid of all IR pointer and
4570 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
4571 // directly.
4573 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
4574
4575 AP.OutStreamer->emitValue(ME, Size);
4576}
4577
4578/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
4580 AliasMapTy *AliasList) {
4581 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4582 if (Size)
4583 emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
4584 else if (MAI->hasSubsectionsViaSymbols()) {
4585 // If the global has zero size, emit a single byte so that two labels don't
4586 // look like they are at the same location.
4587 OutStreamer->emitIntValue(0, 1);
4588 }
4589 if (!AliasList)
4590 return;
4591 // TODO: These remaining aliases are not emitted in the correct location. Need
4592 // to handle the case where the alias offset doesn't refer to any sub-element.
4593 for (auto &AliasPair : *AliasList) {
4594 for (const GlobalAlias *GA : AliasPair.second)
4595 OutStreamer->emitLabel(getSymbol(GA));
4596 }
4597}
4598
4600 // Target doesn't support this yet!
4601 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
4602}
4603
4605 if (Offset > 0)
4606 OS << '+' << Offset;
4607 else if (Offset < 0)
4608 OS << Offset;
4609}
4610
4611void AsmPrinter::emitNops(unsigned N) {
4612 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
4613 for (; N; --N)
4615}
4616
4617//===----------------------------------------------------------------------===//
4618// Symbol Lowering Routines.
4619//===----------------------------------------------------------------------===//
4620
4622 return OutContext.createTempSymbol(Name, true);
4623}
4624
4626 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
4627 BA->getBasicBlock());
4628}
4629
4631 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
4632}
4633
4637
4638/// GetCPISymbol - Return the symbol for the specified constant pool entry.
4639MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
4640 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment() ||
4641 getSubtargetInfo().getTargetTriple().isUEFI()) {
4642 const MachineConstantPoolEntry &CPE =
4643 MF->getConstantPool()->getConstants()[CPID];
4644 if (!CPE.isMachineConstantPoolEntry()) {
4645 const DataLayout &DL = MF->getDataLayout();
4646 SectionKind Kind = CPE.getSectionKind(&DL);
4647 const Constant *C = CPE.Val.ConstVal;
4648 Align Alignment = CPE.Alignment;
4650 DL, Kind, C, Alignment, &MF->getFunction());
4651 if (S && TM.getTargetTriple().isOSBinFormatCOFF()) {
4652 if (MCSymbol *Sym =
4653 static_cast<const MCSectionCOFF *>(S)->getCOMDATSymbol()) {
4654 if (Sym->isUndefined())
4655 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
4656 return Sym;
4657 }
4658 }
4659 }
4660 }
4661
4662 const DataLayout &DL = getDataLayout();
4663 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4664 "CPI" + Twine(getFunctionNumber()) + "_" +
4665 Twine(CPID));
4666}
4667
4668/// GetJTISymbol - Return the symbol for the specified jump table entry.
4669MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
4670 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
4671}
4672
4673/// GetJTSetSymbol - Return the symbol for the specified jump table .set
4674/// FIXME: privatize to AsmPrinter.
4675MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
4676 const DataLayout &DL = getDataLayout();
4677 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4678 Twine(getFunctionNumber()) + "_" +
4679 Twine(UID) + "_set_" + Twine(MBBID));
4680}
4681
4686
4687/// Return the MCSymbol for the specified ExternalSymbol.
4689 SmallString<60> NameStr;
4691 return OutContext.getOrCreateSymbol(NameStr);
4692}
4693
4694/// PrintParentLoopComment - Print comments about parent loops of this one.
4696 unsigned FunctionNumber) {
4697 if (!Loop) return;
4698 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
4699 OS.indent(Loop->getLoopDepth()*2)
4700 << "Parent Loop BB" << FunctionNumber << "_"
4701 << Loop->getHeader()->getNumber()
4702 << " Depth=" << Loop->getLoopDepth() << '\n';
4703}
4704
4705/// PrintChildLoopComment - Print comments about child loops within
4706/// the loop for this basic block, with nesting.
4708 unsigned FunctionNumber) {
4709 // Add child loop information
4710 for (const MachineLoop *CL : *Loop) {
4711 OS.indent(CL->getLoopDepth()*2)
4712 << "Child Loop BB" << FunctionNumber << "_"
4713 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
4714 << '\n';
4715 PrintChildLoopComment(OS, CL, FunctionNumber);
4716 }
4717}
4718
4719/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
4721 const MachineLoopInfo *LI,
4722 const AsmPrinter &AP) {
4723 // Add loop depth information
4724 const MachineLoop *Loop = LI->getLoopFor(&MBB);
4725 if (!Loop) return;
4726
4727 MachineBasicBlock *Header = Loop->getHeader();
4728 assert(Header && "No header for loop");
4729
4730 // If this block is not a loop header, just print out what is the loop header
4731 // and return.
4732 if (Header != &MBB) {
4733 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
4734 Twine(AP.getFunctionNumber())+"_" +
4736 " Depth="+Twine(Loop->getLoopDepth()));
4737 return;
4738 }
4739
4740 // Otherwise, it is a loop header. Print out information about child and
4741 // parent loops.
4742 raw_ostream &OS = AP.OutStreamer->getCommentOS();
4743
4745
4746 OS << "=>";
4747 OS.indent(Loop->getLoopDepth()*2-2);
4748
4749 OS << "This ";
4750 if (Loop->isInnermost())
4751 OS << "Inner ";
4752 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
4753
4755}
4756
4757/// emitBasicBlockStart - This method prints the label for the specified
4758/// MachineBasicBlock, an alignment (if present) and a comment describing
4759/// it if appropriate.
4761 // End the previous funclet and start a new one.
4762 if (MBB.isEHFuncletEntry()) {
4763 for (auto &Handler : Handlers) {
4764 Handler->endFunclet();
4765 Handler->beginFunclet(MBB);
4766 }
4767 for (auto &Handler : EHHandlers) {
4768 Handler->endFunclet();
4769 Handler->beginFunclet(MBB);
4770 }
4771 }
4772
4773 // Switch to a new section if this basic block must begin a section. The
4774 // entry block is always placed in the function section and is handled
4775 // separately.
4776 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4777 OutStreamer->switchSection(
4778 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
4779 MBB, TM));
4780 CurrentSectionBeginSym = MBB.getSymbol();
4781 }
4782
4783 for (auto &Handler : Handlers)
4784 Handler->beginCodeAlignment(MBB);
4785
4786 // Emit an alignment directive for this block, if needed.
4787 const Align Alignment = MBB.getAlignment();
4788 if (Alignment != Align(1))
4789 emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
4790
4791 // If the block has its address taken, emit any labels that were used to
4792 // reference the block. It is possible that there is more than one label
4793 // here, because multiple LLVM BB's may have been RAUW'd to this block after
4794 // the references were generated.
4795 if (MBB.isIRBlockAddressTaken()) {
4796 if (isVerbose())
4797 OutStreamer->AddComment("Block address taken");
4798
4799 BasicBlock *BB = MBB.getAddressTakenIRBlock();
4800 assert(BB && BB->hasAddressTaken() && "Missing BB");
4801 for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
4802 OutStreamer->emitLabel(Sym);
4803 } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
4804 OutStreamer->AddComment("Block address taken");
4805 } else if (isVerbose() && MBB.isInlineAsmBrIndirectTarget()) {
4806 OutStreamer->AddComment("Inline asm indirect target");
4807 }
4808
4809 // Print some verbose block comments.
4810 if (isVerbose()) {
4811 if (const BasicBlock *BB = MBB.getBasicBlock()) {
4812 if (BB->hasName()) {
4813 BB->printAsOperand(OutStreamer->getCommentOS(),
4814 /*PrintType=*/false, BB->getModule());
4815 OutStreamer->getCommentOS() << '\n';
4816 }
4817 }
4818
4819 assert(MLI != nullptr && "MachineLoopInfo should has been computed");
4821 }
4822
4823 // Print the main label for the block.
4824 if (shouldEmitLabelForBasicBlock(MBB)) {
4825 if (isVerbose() && MBB.hasLabelMustBeEmitted())
4826 OutStreamer->AddComment("Label of block must be emitted");
4827 OutStreamer->emitLabel(MBB.getSymbol());
4828 } else {
4829 if (isVerbose()) {
4830 // NOTE: Want this comment at start of line, don't emit with AddComment.
4831 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
4832 false);
4833 }
4834 }
4835
4836 if (MBB.isEHContTarget() &&
4837 MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) {
4838 OutStreamer->emitLabel(MBB.getEHContSymbol());
4839 }
4840
4841 // With BB sections, each basic block must handle CFI information on its own
4842 // if it begins a section (Entry block call is handled separately, next to
4843 // beginFunction).
4844 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4845 for (auto &Handler : Handlers)
4846 Handler->beginBasicBlockSection(MBB);
4847 for (auto &Handler : EHHandlers)
4848 Handler->beginBasicBlockSection(MBB);
4849 }
4850}
4851
4853 // Check if CFI information needs to be updated for this MBB with basic block
4854 // sections.
4855 if (MBB.isEndSection()) {
4856 for (auto &Handler : Handlers)
4857 Handler->endBasicBlockSection(MBB);
4858 for (auto &Handler : EHHandlers)
4859 Handler->endBasicBlockSection(MBB);
4860 }
4861}
4862
4863void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
4864 bool IsDefinition) const {
4866
4867 switch (Visibility) {
4868 default: break;
4870 if (IsDefinition)
4871 Attr = MAI->getHiddenVisibilityAttr();
4872 else
4873 Attr = MAI->getHiddenDeclarationVisibilityAttr();
4874 break;
4876 Attr = MAI->getProtectedVisibilityAttr();
4877 break;
4878 }
4879
4880 if (Attr != MCSA_Invalid)
4881 OutStreamer->emitSymbolAttribute(Sym, Attr);
4882}
4883
4884bool AsmPrinter::shouldEmitLabelForBasicBlock(
4885 const MachineBasicBlock &MBB) const {
4886 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
4887 // in the labels mode (option `=labels`) and every section beginning in the
4888 // sections mode (`=all` and `=list=`).
4889 if ((MF->getTarget().Options.BBAddrMap || MBB.isBeginSection()) &&
4890 !MBB.isEntryBlock())
4891 return true;
4892 // A label is needed for any block with at least one predecessor (when that
4893 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
4894 // entry, or if a label is forced).
4895 return !MBB.pred_empty() &&
4896 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
4897 MBB.hasLabelMustBeEmitted());
4898}
4899
4900/// isBlockOnlyReachableByFallthough - Return true if the basic block has
4901/// exactly one predecessor and the control transfer mechanism between
4902/// the predecessor and this block is a fall-through.
4905 // If this is a landing pad, it isn't a fall through. If it has no preds,
4906 // then nothing falls through to it.
4907 if (MBB->isEHPad() || MBB->pred_empty())
4908 return false;
4909
4910 // If there isn't exactly one predecessor, it can't be a fall through.
4911 if (MBB->pred_size() > 1)
4912 return false;
4913
4914 // The predecessor has to be immediately before this block.
4915 MachineBasicBlock *Pred = *MBB->pred_begin();
4916 if (!Pred->isLayoutSuccessor(MBB))
4917 return false;
4918
4919 // If the block is completely empty, then it definitely does fall through.
4920 if (Pred->empty())
4921 return true;
4922
4923 // Check the terminators in the previous blocks
4924 for (const auto &MI : Pred->terminators()) {
4925 // If it is not a simple branch, we are in a table somewhere.
4926 if (!MI.isBranch() || MI.isIndirectBranch())
4927 return false;
4928
4929 // If we are the operands of one of the branches, this is not a fall
4930 // through. Note that targets with delay slots will usually bundle
4931 // terminators with the delay slot instruction.
4932 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
4933 if (OP->isJTI())
4934 return false;
4935 if (OP->isMBB() && OP->getMBB() == MBB)
4936 return false;
4937 }
4938 }
4939
4940 return true;
4941}
4942
4943GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
4944 if (!S.usesMetadata())
4945 return nullptr;
4946
4947 auto [GCPI, Inserted] = GCMetadataPrinters.try_emplace(&S);
4948 if (!Inserted)
4949 return GCPI->second.get();
4950
4951 auto Name = S.getName();
4952
4953 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
4955 if (Name == GCMetaPrinter.getName()) {
4956 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
4957 GMP->S = &S;
4958 GCPI->second = std::move(GMP);
4959 return GCPI->second.get();
4960 }
4961
4962 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
4963}
4964
4966 std::unique_ptr<AsmPrinterHandler> Handler) {
4967 Handlers.insert(Handlers.begin(), std::move(Handler));
4969}
4970
4971/// Pin vtables to this file.
4973
4975
4976// In the binary's "xray_instr_map" section, an array of these function entries
4977// describes each instrumentation point. When XRay patches your code, the index
4978// into this table will be given to your handler as a patch point identifier.
4980 auto Kind8 = static_cast<uint8_t>(Kind);
4981 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
4982 Out->emitBinaryData(
4983 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
4984 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
4985 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
4986 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
4987 Out->emitZeros(Padding);
4988}
4989
4991 if (Sleds.empty())
4992 return;
4993
4994 auto PrevSection = OutStreamer->getCurrentSectionOnly();
4995 const Function &F = MF->getFunction();
4996 MCSection *InstMap = nullptr;
4997 MCSection *FnSledIndex = nullptr;
4998 const Triple &TT = TM.getTargetTriple();
4999 // Use PC-relative addresses on all targets.
5000 if (TT.isOSBinFormatELF()) {
5001 auto LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5002 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
5003 StringRef GroupName;
5004 if (F.hasComdat()) {
5005 Flags |= ELF::SHF_GROUP;
5006 GroupName = F.getComdat()->getName();
5007 }
5008 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
5009 Flags, 0, GroupName, F.hasComdat(),
5010 MCSection::NonUniqueID, LinkedToSym);
5011
5012 if (TM.Options.XRayFunctionIndex)
5013 FnSledIndex = OutContext.getELFSection(
5014 "xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5015 MCSection::NonUniqueID, LinkedToSym);
5016 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
5017 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map",
5020 if (TM.Options.XRayFunctionIndex)
5021 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx",
5024 } else {
5025 llvm_unreachable("Unsupported target");
5026 }
5027
5028 auto WordSizeBytes = MAI->getCodePointerSize();
5029
5030 // Now we switch to the instrumentation map section. Because this is done
5031 // per-function, we are able to create an index entry that will represent the
5032 // range of sleds associated with a function.
5033 auto &Ctx = OutContext;
5034 MCSymbol *SledsStart =
5035 OutContext.createLinkerPrivateSymbol("xray_sleds_start");
5036 OutStreamer->switchSection(InstMap);
5037 OutStreamer->emitLabel(SledsStart);
5038 for (const auto &Sled : Sleds) {
5039 MCSymbol *Dot = Ctx.createTempSymbol();
5040 OutStreamer->emitLabel(Dot);
5041 OutStreamer->emitValueImpl(
5043 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5044 WordSizeBytes);
5045 OutStreamer->emitValueImpl(
5049 MCConstantExpr::create(WordSizeBytes, Ctx),
5050 Ctx),
5051 Ctx),
5052 WordSizeBytes);
5053 Sled.emit(WordSizeBytes, OutStreamer.get());
5054 }
5055 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
5056 OutStreamer->emitLabel(SledsEnd);
5057
5058 // We then emit a single entry in the index per function. We use the symbols
5059 // that bound the instrumentation map as the range for a specific function.
5060 // Each entry contains 2 words and needs to be word-aligned.
5061 if (FnSledIndex) {
5062 OutStreamer->switchSection(FnSledIndex);
5063 OutStreamer->emitValueToAlignment(Align(WordSizeBytes));
5064 // For Mach-O, use an "l" symbol as the atom of this subsection. The label
5065 // difference uses a SUBTRACTOR external relocation which references the
5066 // symbol.
5067 MCSymbol *Dot = Ctx.createLinkerPrivateSymbol("xray_fn_idx");
5068 OutStreamer->emitLabel(Dot);
5069 OutStreamer->emitValueImpl(
5071 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5072 WordSizeBytes);
5073 OutStreamer->emitValueImpl(MCConstantExpr::create(Sleds.size(), Ctx),
5074 WordSizeBytes);
5075 OutStreamer->switchSection(PrevSection);
5076 }
5077 Sleds.clear();
5078}
5079
5081 SledKind Kind, uint8_t Version) {
5082 const Function &F = MI.getMF()->getFunction();
5083 auto Attr = F.getFnAttribute("function-instrument");
5084 bool LogArgs = F.hasFnAttribute("xray-log-args");
5085 bool AlwaysInstrument =
5086 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
5087 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
5089 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
5090 AlwaysInstrument, &F, Version});
5091}
5092
5094 const Function &F = MF->getFunction();
5095 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
5096 (void)F.getFnAttribute("patchable-function-prefix")
5097 .getValueAsString()
5098 .getAsInteger(10, PatchableFunctionPrefix);
5099 (void)F.getFnAttribute("patchable-function-entry")
5100 .getValueAsString()
5101 .getAsInteger(10, PatchableFunctionEntry);
5102 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
5103 return;
5104 const unsigned PointerSize = getPointerSize();
5105 if (TM.getTargetTriple().isOSBinFormatELF()) {
5106 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
5107 const MCSymbolELF *LinkedToSym = nullptr;
5108 StringRef GroupName, SectionName;
5109
5110 if (F.hasFnAttribute("patchable-function-entry-section"))
5111 SectionName = F.getFnAttribute("patchable-function-entry-section")
5112 .getValueAsString();
5113 if (SectionName.empty())
5114 SectionName = "__patchable_function_entries";
5115
5116 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
5117 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
5118 if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
5119 Flags |= ELF::SHF_LINK_ORDER;
5120 if (F.hasComdat()) {
5121 Flags |= ELF::SHF_GROUP;
5122 GroupName = F.getComdat()->getName();
5123 }
5124 LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5125 }
5126 OutStreamer->switchSection(OutContext.getELFSection(
5127 SectionName, ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5128 MCSection::NonUniqueID, LinkedToSym));
5129 emitAlignment(Align(PointerSize));
5130 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
5131 }
5132}
5133
5135 return OutStreamer->getContext().getDwarfVersion();
5136}
5137
5139 OutStreamer->getContext().setDwarfVersion(Version);
5140}
5141
5143 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
5144}
5145
5148 OutStreamer->getContext().getDwarfFormat());
5149}
5150
5152 return {getDwarfVersion(), uint8_t(MAI->getCodePointerSize()),
5153 OutStreamer->getContext().getDwarfFormat(),
5155}
5156
5159 OutStreamer->getContext().getDwarfFormat());
5160}
5161
5162std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
5165 const MCSymbol *BranchLabel) const {
5166 const auto TLI = MF->getSubtarget().getTargetLowering();
5167 const auto BaseExpr =
5168 TLI->getPICJumpTableRelocBaseExpr(MF, JTI, MMI->getContext());
5169 const auto Base = &cast<MCSymbolRefExpr>(BaseExpr)->getSymbol();
5170
5171 // By default, for the architectures that support CodeView,
5172 // EK_LabelDifference32 is implemented as an Int32 from the base address.
5173 return std::make_tuple(Base, 0, BranchLabel,
5175}
5176
5178 const Triple &TT = TM.getTargetTriple();
5179 assert(TT.isOSBinFormatCOFF());
5180
5181 bool IsTargetArm64EC = TT.isWindowsArm64EC();
5183 SmallVector<MCSymbol *> FuncOverrideDefaultSymbols;
5184 bool SwitchedToDirectiveSection = false;
5185 for (const Function &F : M.functions()) {
5186 if (F.hasFnAttribute("loader-replaceable")) {
5187 if (!SwitchedToDirectiveSection) {
5188 OutStreamer->switchSection(
5189 OutContext.getObjectFileInfo()->getDrectveSection());
5190 SwitchedToDirectiveSection = true;
5191 }
5192
5193 StringRef Name = F.getName();
5194
5195 // For hybrid-patchable targets, strip the prefix so that we can mark
5196 // the real function as replaceable.
5197 if (IsTargetArm64EC && Name.ends_with(HybridPatchableTargetSuffix)) {
5198 Name = Name.drop_back(HybridPatchableTargetSuffix.size());
5199 }
5200
5201 MCSymbol *FuncOverrideSymbol =
5202 MMI->getContext().getOrCreateSymbol(Name + "_$fo$");
5203 OutStreamer->beginCOFFSymbolDef(FuncOverrideSymbol);
5204 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5205 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5206 OutStreamer->endCOFFSymbolDef();
5207
5208 MCSymbol *FuncOverrideDefaultSymbol =
5209 MMI->getContext().getOrCreateSymbol(Name + "_$fo_default$");
5210 OutStreamer->beginCOFFSymbolDef(FuncOverrideDefaultSymbol);
5211 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5212 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5213 OutStreamer->endCOFFSymbolDef();
5214 FuncOverrideDefaultSymbols.push_back(FuncOverrideDefaultSymbol);
5215
5216 OutStreamer->emitBytes((Twine(" /ALTERNATENAME:") +
5217 FuncOverrideSymbol->getName() + "=" +
5218 FuncOverrideDefaultSymbol->getName())
5219 .toStringRef(Buf));
5220 Buf.clear();
5221 }
5222 }
5223
5224 if (SwitchedToDirectiveSection)
5225 OutStreamer->popSection();
5226
5227 if (FuncOverrideDefaultSymbols.empty())
5228 return;
5229
5230 // MSVC emits the symbols for the default variables pointing at the start of
5231 // the .data section, but doesn't actually allocate any space for them. LLVM
5232 // can't do this, so have all of the variables pointing at a single byte
5233 // instead.
5234 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
5235 for (MCSymbol *Symbol : FuncOverrideDefaultSymbols) {
5236 OutStreamer->emitLabel(Symbol);
5237 }
5238 OutStreamer->emitZeros(1);
5239 OutStreamer->popSection();
5240}
5241
5243 const Triple &TT = TM.getTargetTriple();
5244 assert(TT.isOSBinFormatCOFF());
5245
5246 // Emit an absolute @feat.00 symbol.
5247 MCSymbol *S = MMI->getContext().getOrCreateSymbol(StringRef("@feat.00"));
5248 OutStreamer->beginCOFFSymbolDef(S);
5249 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
5250 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5251 OutStreamer->endCOFFSymbolDef();
5252 int64_t Feat00Value = 0;
5253
5254 if (TT.getArch() == Triple::x86) {
5255 // According to the PE-COFF spec, the LSB of this value marks the object
5256 // for "registered SEH". This means that all SEH handler entry points
5257 // must be registered in .sxdata. Use of any unregistered handlers will
5258 // cause the process to terminate immediately. LLVM does not know how to
5259 // register any SEH handlers, so its object files should be safe.
5260 Feat00Value |= COFF::Feat00Flags::SafeSEH;
5261 }
5262
5263 if (M.getControlFlowGuardMode() == ControlFlowGuardMode::Enabled) {
5264 // Object is CFG-aware. Only set if we actually inserted the checks.
5265 Feat00Value |= COFF::Feat00Flags::GuardCF;
5266 }
5267
5268 if (M.getModuleFlag("ehcontguard")) {
5269 // Object also has EHCont.
5270 Feat00Value |= COFF::Feat00Flags::GuardEHCont;
5271 }
5272
5273 if (M.getModuleFlag("ms-kernel")) {
5274 // Object is compiled with /kernel.
5275 Feat00Value |= COFF::Feat00Flags::Kernel;
5276 }
5277
5278 OutStreamer->emitSymbolAttribute(S, MCSA_Global);
5279 OutStreamer->emitAssignment(
5280 S, MCConstantExpr::create(Feat00Value, MMI->getContext()));
5281}
5282
5283namespace llvm {
5284namespace {
5286 MachineFunction &MF) {
5288 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
5291 MF.getFunction())
5292 .getManager();
5293 return MFAM;
5294}
5295} // anonymous namespace
5296
5299 MachineModuleInfo &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
5300 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5301 AsmPrinter.MMI = &MMI;
5302 AsmPrinter.GetORE = [&MAM, &M](MachineFunction &MF) {
5303 return &getMFAM(M, MAM, MF)
5305 };
5306 AsmPrinter.GetMDT = [&MAM, &M](MachineFunction &MF) {
5307 return &getMFAM(M, MAM, MF).getResult<MachineDominatorTreeAnalysis>(MF);
5308 };
5309 AsmPrinter.GetMLI = [&MAM, &M](MachineFunction &MF) {
5310 return &getMFAM(M, MAM, MF).getResult<MachineLoopAnalysis>(MF);
5311 };
5312 // TODO(boomanaiden154): Get GC working with the new pass manager.
5313 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5315 AsmPrinter.EmitStackMaps = [](Module &M) {};
5317}
5318
5320 MachineFunction &MF,
5322 const ModuleAnalysisManagerMachineFunctionProxy::Result &MAMProxy =
5324 MachineModuleInfo &MMI =
5325 MAMProxy
5326 .getCachedResult<MachineModuleAnalysis>(*MF.getFunction().getParent())
5327 ->getMMI();
5328 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5329 AsmPrinter.MMI = &MMI;
5330 AsmPrinter.GetORE = [&MFAM](MachineFunction &MF) {
5332 };
5333 AsmPrinter.GetMDT = [&MFAM](MachineFunction &MF) {
5334 return &MFAM.getResult<MachineDominatorTreeAnalysis>(MF);
5335 };
5336 AsmPrinter.GetMLI = [&MFAM](MachineFunction &MF) {
5337 return &MFAM.getResult<MachineLoopAnalysis>(MF);
5338 };
5339 // TODO(boomanaiden154): Get GC working with the new pass manager.
5340 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5342 AsmPrinter.EmitStackMaps = [](Module &M) {};
5344}
5345
5346} // 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:5890
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:5949
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:687
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:653
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:682
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:608
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:331
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:135
LLVM_ABI bool canBenefitFromLocalAlias() const
Definition Globals.cpp:117
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:469
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:563
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
MCFragment * getNext() const
Definition MCSection.h:163
size_t getFixedSize() const
Definition MCSection.h:209
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.
@ AllowOverEstimate
Allow the reported instruction size to be larger than the actual size.
@ NoVerify
Do not verify instruction size.
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:833
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:810
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:777
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.
@ 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:334
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 raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
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:221
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.