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