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