LLVM 20.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"
64#include "llvm/Config/config.h"
65#include "llvm/IR/BasicBlock.h"
66#include "llvm/IR/Comdat.h"
67#include "llvm/IR/Constant.h"
68#include "llvm/IR/Constants.h"
69#include "llvm/IR/DataLayout.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/GCStrategy.h"
75#include "llvm/IR/GlobalAlias.h"
76#include "llvm/IR/GlobalIFunc.h"
78#include "llvm/IR/GlobalValue.h"
80#include "llvm/IR/Instruction.h"
81#include "llvm/IR/Mangler.h"
82#include "llvm/IR/Metadata.h"
83#include "llvm/IR/Module.h"
84#include "llvm/IR/Operator.h"
85#include "llvm/IR/PseudoProbe.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/Value.h"
88#include "llvm/IR/ValueHandle.h"
89#include "llvm/MC/MCAsmInfo.h"
90#include "llvm/MC/MCContext.h"
92#include "llvm/MC/MCExpr.h"
93#include "llvm/MC/MCInst.h"
94#include "llvm/MC/MCSchedule.h"
95#include "llvm/MC/MCSection.h"
100#include "llvm/MC/MCStreamer.h"
102#include "llvm/MC/MCSymbol.h"
103#include "llvm/MC/MCSymbolELF.h"
105#include "llvm/MC/MCValue.h"
106#include "llvm/MC/SectionKind.h"
107#include "llvm/Object/ELFTypes.h"
108#include "llvm/Pass.h"
110#include "llvm/Support/Casting.h"
115#include "llvm/Support/Format.h"
117#include "llvm/Support/Path.h"
118#include "llvm/Support/VCSRevision.h"
124#include <algorithm>
125#include <cassert>
126#include <cinttypes>
127#include <cstdint>
128#include <iterator>
129#include <memory>
130#include <optional>
131#include <string>
132#include <utility>
133#include <vector>
134
135using namespace llvm;
136
137#define DEBUG_TYPE "asm-printer"
138
139// This is a replication of fields of object::PGOAnalysisMap::Features. It
140// should match the order of the fields so that
141// `object::PGOAnalysisMap::Features::decode(PgoAnalysisMapFeatures.getBits())`
142// succeeds.
144 None,
146 BBFreq,
147 BrProb,
148 All,
149};
151 "pgo-analysis-map", cl::Hidden, cl::CommaSeparated,
153 clEnumValN(PGOMapFeaturesEnum::None, "none", "Disable all options"),
155 "Function Entry Count"),
157 "Basic Block Frequency"),
158 clEnumValN(PGOMapFeaturesEnum::BrProb, "br-prob", "Branch Probability"),
159 clEnumValN(PGOMapFeaturesEnum::All, "all", "Enable all options")),
160 cl::desc(
161 "Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is "
162 "extracted from PGO related analysis."));
163
165 "basic-block-address-map-skip-bb-entries",
166 cl::desc("Skip emitting basic block entries in the SHT_LLVM_BB_ADDR_MAP "
167 "section. It's used to save binary size when BB entries are "
168 "unnecessary for some PGOAnalysisMap features."),
169 cl::Hidden, cl::init(false));
170
172 "emit-jump-table-sizes-section",
173 cl::desc("Emit a section containing jump table addresses and sizes"),
174 cl::Hidden, cl::init(false));
175
176// This isn't turned on by default, since several of the scheduling models are
177// not completely accurate, and we don't want to be misleading.
179 "asm-print-latency",
180 cl::desc("Print instruction latencies as verbose asm comments"), cl::Hidden,
181 cl::init(false));
182
183STATISTIC(EmittedInsts, "Number of machine instrs printed");
184
185char AsmPrinter::ID = 0;
186
187namespace {
188class AddrLabelMapCallbackPtr final : CallbackVH {
189 AddrLabelMap *Map = nullptr;
190
191public:
192 AddrLabelMapCallbackPtr() = default;
193 AddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
194
195 void setPtr(BasicBlock *BB) {
197 }
198
199 void setMap(AddrLabelMap *map) { Map = map; }
200
201 void deleted() override;
202 void allUsesReplacedWith(Value *V2) override;
203};
204} // namespace
205
207 MCContext &Context;
208 struct AddrLabelSymEntry {
209 /// The symbols for the label.
211
212 Function *Fn; // The containing function of the BasicBlock.
213 unsigned Index; // The index in BBCallbacks for the BasicBlock.
214 };
215
216 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
217
218 /// Callbacks for the BasicBlock's that we have entries for. We use this so
219 /// we get notified if a block is deleted or RAUWd.
220 std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
221
222 /// This is a per-function list of symbols whose corresponding BasicBlock got
223 /// deleted. These symbols need to be emitted at some point in the file, so
224 /// AsmPrinter emits them after the function body.
225 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>
226 DeletedAddrLabelsNeedingEmission;
227
228public:
229 AddrLabelMap(MCContext &context) : Context(context) {}
230
232 assert(DeletedAddrLabelsNeedingEmission.empty() &&
233 "Some labels for deleted blocks never got emitted");
234 }
235
237
239 std::vector<MCSymbol *> &Result);
240
243};
244
246 assert(BB->hasAddressTaken() &&
247 "Shouldn't get label for block without address taken");
248 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
249
250 // If we already had an entry for this block, just return it.
251 if (!Entry.Symbols.empty()) {
252 assert(BB->getParent() == Entry.Fn && "Parent changed");
253 return Entry.Symbols;
254 }
255
256 // Otherwise, this is a new entry, create a new symbol for it and add an
257 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
258 BBCallbacks.emplace_back(BB);
259 BBCallbacks.back().setMap(this);
260 Entry.Index = BBCallbacks.size() - 1;
261 Entry.Fn = BB->getParent();
263 : Context.createTempSymbol();
264 Entry.Symbols.push_back(Sym);
265 return Entry.Symbols;
266}
267
268/// If we have any deleted symbols for F, return them.
270 Function *F, std::vector<MCSymbol *> &Result) {
271 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>::iterator I =
272 DeletedAddrLabelsNeedingEmission.find(F);
273
274 // If there are no entries for the function, just return.
275 if (I == DeletedAddrLabelsNeedingEmission.end())
276 return;
277
278 // Otherwise, take the list.
279 std::swap(Result, I->second);
280 DeletedAddrLabelsNeedingEmission.erase(I);
281}
282
283//===- Address of Block Management ----------------------------------------===//
284
287 // Lazily create AddrLabelSymbols.
288 if (!AddrLabelSymbols)
289 AddrLabelSymbols = std::make_unique<AddrLabelMap>(OutContext);
290 return AddrLabelSymbols->getAddrLabelSymbolToEmit(
291 const_cast<BasicBlock *>(BB));
292}
293
295 const Function *F, std::vector<MCSymbol *> &Result) {
296 // If no blocks have had their addresses taken, we're done.
297 if (!AddrLabelSymbols)
298 return;
299 return AddrLabelSymbols->takeDeletedSymbolsForFunction(
300 const_cast<Function *>(F), Result);
301}
302
304 // If the block got deleted, there is no need for the symbol. If the symbol
305 // was already emitted, we can just forget about it, otherwise we need to
306 // queue it up for later emission when the function is output.
307 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
308 AddrLabelSymbols.erase(BB);
309 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
310 BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
311
312#if !LLVM_MEMORY_SANITIZER_BUILD
313 // BasicBlock is destroyed already, so this access is UB detectable by msan.
314 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
315 "Block/parent mismatch");
316#endif
317
318 for (MCSymbol *Sym : Entry.Symbols) {
319 if (Sym->isDefined())
320 return;
321
322 // If the block is not yet defined, we need to emit it at the end of the
323 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
324 // for the containing Function. Since the block is being deleted, its
325 // parent may already be removed, we have to get the function from 'Entry'.
326 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
327 }
328}
329
331 // Get the entry for the RAUW'd block and remove it from our map.
332 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
333 AddrLabelSymbols.erase(Old);
334 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
335
336 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
337
338 // If New is not address taken, just move our symbol over to it.
339 if (NewEntry.Symbols.empty()) {
340 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
341 NewEntry = std::move(OldEntry); // Set New's entry.
342 return;
343 }
344
345 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
346
347 // Otherwise, we need to add the old symbols to the new block's set.
348 llvm::append_range(NewEntry.Symbols, OldEntry.Symbols);
349}
350
351void AddrLabelMapCallbackPtr::deleted() {
352 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
353}
354
355void AddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
356 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
357}
358
359/// getGVAlignment - Return the alignment to use for the specified global
360/// value. This rounds up to the preferred alignment if possible and legal.
362 Align InAlign) {
363 Align Alignment;
364 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
365 Alignment = DL.getPreferredAlign(GVar);
366
367 // If InAlign is specified, round it to it.
368 if (InAlign > Alignment)
369 Alignment = InAlign;
370
371 // If the GV has a specified alignment, take it into account.
372 const MaybeAlign GVAlign(GV->getAlign());
373 if (!GVAlign)
374 return Alignment;
375
376 assert(GVAlign && "GVAlign must be set");
377
378 // If the GVAlign is larger than NumBits, or if we are required to obey
379 // NumBits because the GV has an assigned section, obey it.
380 if (*GVAlign > Alignment || GV->hasSection())
381 Alignment = *GVAlign;
382 return Alignment;
383}
384
385AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
386 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
387 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
388 SM(*this) {
389 VerboseAsm = OutStreamer->isVerboseAsm();
390 DwarfUsesRelocationsAcrossSections =
392}
393
395 assert(!DD && Handlers.size() == NumUserHandlers &&
396 "Debug/EH info didn't get finalized");
397}
398
400 return TM.isPositionIndependent();
401}
402
403/// getFunctionNumber - Return a unique ID for the current function.
405 return MF->getFunctionNumber();
406}
407
409 return *TM.getObjFileLowering();
410}
411
413 assert(MMI && "MMI could not be nullptr!");
414 return MMI->getModule()->getDataLayout();
415}
416
417// Do not use the cached DataLayout because some client use it without a Module
418// (dsymutil, llvm-dwarfdump).
420 return TM.getPointerSize(0); // FIXME: Default address space
421}
422
424 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
426}
427
430}
431
433 if (DD) {
434 assert(OutStreamer->hasRawTextSupport() &&
435 "Expected assembly output mode.");
436 // This is NVPTX specific and it's unclear why.
437 // PR51079: If we have code without debug information we need to give up.
439 if (!MFSP)
440 return;
441 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
442 }
443}
444
445/// getCurrentSection() - Return the current section we are emitting to.
447 return OutStreamer->getCurrentSectionOnly();
448}
449
451 AU.setPreservesAll();
457}
458
460 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
461 MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
462 HasSplitStack = false;
463 HasNoSplitStack = false;
464 DbgInfoAvailable = !M.debug_compile_units().empty();
465
466 AddrLabelSymbols = nullptr;
467
468 // Initialize TargetLoweringObjectFile.
470 .Initialize(OutContext, TM);
471
473 .getModuleMetadata(M);
474
475 // On AIX, we delay emitting any section information until
476 // after emitting the .file pseudo-op. This allows additional
477 // information (such as the embedded command line) to be associated
478 // with all sections in the object file rather than a single section.
480 OutStreamer->initSections(false, *TM.getMCSubtargetInfo());
481
482 // Emit the version-min deployment target directive if needed.
483 //
484 // FIXME: If we end up with a collection of these sorts of Darwin-specific
485 // or ELF-specific things, it may make sense to have a platform helper class
486 // that will work with the target helper class. For now keep it here, as the
487 // alternative is duplicated code in each of the target asm printers that
488 // use the directive, where it would need the same conditionalization
489 // anyway.
490 const Triple &Target = TM.getTargetTriple();
491 if (Target.isOSBinFormatMachO() && Target.isOSDarwin()) {
492 Triple TVT(M.getDarwinTargetVariantTriple());
493 OutStreamer->emitVersionForTarget(
494 Target, M.getSDKVersion(),
495 M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
496 M.getDarwinTargetVariantSDKVersion());
497 }
498
499 // Allow the target to emit any magic that it wants at the start of the file.
501
502 // Very minimal debug info. It is ignored if we emit actual debug info. If we
503 // don't, this at least helps the user find where a global came from.
505 // .file "foo.c"
506
507 SmallString<128> FileName;
509 FileName = llvm::sys::path::filename(M.getSourceFileName());
510 else
511 FileName = M.getSourceFileName();
512 if (MAI->hasFourStringsDotFile()) {
513 const char VerStr[] =
514#ifdef PACKAGE_VENDOR
515 PACKAGE_VENDOR " "
516#endif
517 PACKAGE_NAME " version " PACKAGE_VERSION
518#ifdef LLVM_REVISION
519 " (" LLVM_REVISION ")"
520#endif
521 ;
522 // TODO: Add timestamp and description.
523 OutStreamer->emitFileDirective(FileName, VerStr, "", "");
524 } else {
525 OutStreamer->emitFileDirective(FileName);
526 }
527 }
528
529 // On AIX, emit bytes for llvm.commandline metadata after .file so that the
530 // C_INFO symbol is preserved if any csect is kept by the linker.
532 emitModuleCommandLines(M);
533 // Now we can generate section information.
534 OutStreamer->switchSection(
536
537 // To work around an AIX assembler and/or linker bug, generate
538 // a rename for the default text-section symbol name. This call has
539 // no effect when generating object code directly.
540 MCSection *TextSection =
541 OutStreamer->getContext().getObjectFileInfo()->getTextSection();
542 MCSymbolXCOFF *XSym =
543 static_cast<MCSectionXCOFF *>(TextSection)->getQualNameSymbol();
544 if (XSym->hasRename())
545 OutStreamer->emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
546 }
547
548 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
549 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
550 for (const auto &I : *MI)
551 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*I))
552 MP->beginAssembly(M, *MI, *this);
553
554 // Emit module-level inline asm if it exists.
555 if (!M.getModuleInlineAsm().empty()) {
556 OutStreamer->AddComment("Start of file scope inline assembly");
557 OutStreamer->addBlankLine();
558 emitInlineAsm(
559 M.getModuleInlineAsm() + "\n", *TM.getMCSubtargetInfo(),
560 TM.Options.MCOptions, nullptr,
562 OutStreamer->AddComment("End of file scope inline assembly");
563 OutStreamer->addBlankLine();
564 }
565
567 bool EmitCodeView = M.getCodeViewFlag();
568 if (EmitCodeView && TM.getTargetTriple().isOSWindows())
569 DebugHandlers.push_back(std::make_unique<CodeViewDebug>(this));
570 if (!EmitCodeView || M.getDwarfVersion()) {
571 if (hasDebugInfo()) {
572 DD = new DwarfDebug(this);
573 DebugHandlers.push_back(std::unique_ptr<DwarfDebug>(DD));
574 }
575 }
576 }
577
578 if (M.getNamedMetadata(PseudoProbeDescMetadataName))
579 PP = std::make_unique<PseudoProbeHandler>(this);
580
581 switch (MAI->getExceptionHandlingType()) {
583 // We may want to emit CFI for debug.
584 [[fallthrough]];
588 for (auto &F : M.getFunctionList()) {
590 ModuleCFISection = getFunctionCFISectionType(F);
591 // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
592 // the module needs .eh_frame. If we have found that case, we are done.
593 if (ModuleCFISection == CFISection::EH)
594 break;
595 }
597 usesCFIWithoutEH() || ModuleCFISection != CFISection::EH);
598 break;
599 default:
600 break;
601 }
602
603 EHStreamer *ES = nullptr;
604 switch (MAI->getExceptionHandlingType()) {
606 if (!usesCFIWithoutEH())
607 break;
608 [[fallthrough]];
612 ES = new DwarfCFIException(this);
613 break;
615 ES = new ARMException(this);
616 break;
618 switch (MAI->getWinEHEncodingType()) {
619 default: llvm_unreachable("unsupported unwinding information encoding");
621 break;
624 ES = new WinException(this);
625 break;
626 }
627 break;
629 ES = new WasmException(this);
630 break;
632 ES = new AIXException(this);
633 break;
634 }
635 if (ES)
636 Handlers.push_back(std::unique_ptr<EHStreamer>(ES));
637
638 // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
639 if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
640 Handlers.push_back(std::make_unique<WinCFGuard>(this));
641
642 for (auto &Handler : DebugHandlers)
643 Handler->beginModule(&M);
644 for (auto &Handler : Handlers)
645 Handler->beginModule(&M);
646
647 return false;
648}
649
650static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
652 return false;
653
654 return GV->canBeOmittedFromSymbolTable();
655}
656
657void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
659 switch (Linkage) {
665 if (MAI->isMachO()) {
666 // .globl _foo
667 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
668
669 if (!canBeHidden(GV, *MAI))
670 // .weak_definition _foo
671 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
672 else
673 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
674 } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
675 // .globl _foo
676 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
677 //NOTE: linkonce is handled by the section the symbol was assigned to.
678 } else {
679 // .weak _foo
680 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
681 }
682 return;
684 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
685 return;
688 return;
692 llvm_unreachable("Should never emit this");
693 }
694 llvm_unreachable("Unknown linkage type!");
695}
696
698 const GlobalValue *GV) const {
699 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
700}
701
703 return TM.getSymbol(GV);
704}
705
707 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
708 // exact definion (intersection of GlobalValue::hasExactDefinition() and
709 // !isInterposable()). These linkages include: external, appending, internal,
710 // private. It may be profitable to use a local alias for external. The
711 // assembler would otherwise be conservative and assume a global default
712 // visibility symbol can be interposable, even if the code generator already
713 // assumed it.
715 const Module &M = *GV.getParent();
717 M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
718 return getSymbolWithGlobalValueBase(&GV, "$local");
719 }
720 return TM.getSymbol(&GV);
721}
722
723/// EmitGlobalVariable - Emit the specified global variable to the .s file.
725 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
726 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
727 "No emulated TLS variables in the common section");
728
729 // Never emit TLS variable xyz in emulated TLS model.
730 // The initialization value is in __emutls_t.xyz instead of xyz.
731 if (IsEmuTLSVar)
732 return;
733
734 if (GV->hasInitializer()) {
735 // Check to see if this is a special global used by LLVM, if so, emit it.
736 if (emitSpecialLLVMGlobal(GV))
737 return;
738
739 // Skip the emission of global equivalents. The symbol can be emitted later
740 // on by emitGlobalGOTEquivs in case it turns out to be needed.
741 if (GlobalGOTEquivs.count(getSymbol(GV)))
742 return;
743
744 if (isVerbose()) {
745 // When printing the control variable __emutls_v.*,
746 // we don't need to print the original TLS variable name.
747 GV->printAsOperand(OutStreamer->getCommentOS(),
748 /*PrintType=*/false, GV->getParent());
749 OutStreamer->getCommentOS() << '\n';
750 }
751 }
752
753 MCSymbol *GVSym = getSymbol(GV);
754 MCSymbol *EmittedSym = GVSym;
755
756 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
757 // attributes.
758 // GV's or GVSym's attributes will be used for the EmittedSym.
759 emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
760
761 if (GV->isTagged()) {
763
764 if (T.getArch() != Triple::aarch64 || !T.isAndroid())
766 "tagged symbols (-fsanitize=memtag-globals) are "
767 "only supported on AArch64 Android");
768 OutStreamer->emitSymbolAttribute(EmittedSym, MAI->getMemtagAttr());
769 }
770
771 if (!GV->hasInitializer()) // External globals require no extra code.
772 return;
773
774 GVSym->redefineIfPossible();
775 if (GVSym->isDefined() || GVSym->isVariable())
776 OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
777 "' is already defined");
778
780 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
781
783
784 const DataLayout &DL = GV->getDataLayout();
785 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
786
787 // If the alignment is specified, we *must* obey it. Overaligning a global
788 // with a specified alignment is a prompt way to break globals emitted to
789 // sections and expected to be contiguous (e.g. ObjC metadata).
790 const Align Alignment = getGVAlignment(GV, DL);
791
792 for (auto &Handler : DebugHandlers)
793 Handler->setSymbolSize(GVSym, Size);
794
795 // Handle common symbols
796 if (GVKind.isCommon()) {
797 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
798 // .comm _foo, 42, 4
799 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
800 return;
801 }
802
803 // Determine to which section this global should be emitted.
804 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
805
806 // If we have a bss global going to a section that supports the
807 // zerofill directive, do so here.
808 if (GVKind.isBSS() && MAI->isMachO() && TheSection->isVirtualSection()) {
809 if (Size == 0)
810 Size = 1; // zerofill of 0 bytes is undefined.
811 emitLinkage(GV, GVSym);
812 // .zerofill __DATA, __bss, _foo, 400, 5
813 OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment);
814 return;
815 }
816
817 // If this is a BSS local symbol and we are emitting in the BSS
818 // section use .lcomm/.comm directive.
819 if (GVKind.isBSSLocal() &&
820 getObjFileLowering().getBSSSection() == TheSection) {
821 if (Size == 0)
822 Size = 1; // .comm Foo, 0 is undefined, avoid it.
823
824 // Use .lcomm only if it supports user-specified alignment.
825 // Otherwise, while it would still be correct to use .lcomm in some
826 // cases (e.g. when Align == 1), the external assembler might enfore
827 // some -unknown- default alignment behavior, which could cause
828 // spurious differences between external and integrated assembler.
829 // Prefer to simply fall back to .local / .comm in this case.
831 // .lcomm _foo, 42
832 OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment);
833 return;
834 }
835
836 // .local _foo
837 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
838 // .comm _foo, 42, 4
839 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
840 return;
841 }
842
843 // Handle thread local data for mach-o which requires us to output an
844 // additional structure of data and mangle the original symbol so that we
845 // can reference it later.
846 //
847 // TODO: This should become an "emit thread local global" method on TLOF.
848 // All of this macho specific stuff should be sunk down into TLOFMachO and
849 // stuff like "TLSExtraDataSection" should no longer be part of the parent
850 // TLOF class. This will also make it more obvious that stuff like
851 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
852 // specific code.
853 if (GVKind.isThreadLocal() && MAI->isMachO()) {
854 // Emit the .tbss symbol
855 MCSymbol *MangSym =
856 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
857
858 if (GVKind.isThreadBSS()) {
859 TheSection = getObjFileLowering().getTLSBSSSection();
860 OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment);
861 } else if (GVKind.isThreadData()) {
862 OutStreamer->switchSection(TheSection);
863
864 emitAlignment(Alignment, GV);
865 OutStreamer->emitLabel(MangSym);
866
868 GV->getInitializer());
869 }
870
871 OutStreamer->addBlankLine();
872
873 // Emit the variable struct for the runtime.
875
876 OutStreamer->switchSection(TLVSect);
877 // Emit the linkage here.
878 emitLinkage(GV, GVSym);
879 OutStreamer->emitLabel(GVSym);
880
881 // Three pointers in size:
882 // - __tlv_bootstrap - used to make sure support exists
883 // - spare pointer, used when mapped by the runtime
884 // - pointer to mangled symbol above with initializer
885 unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
886 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
887 PtrSize);
888 OutStreamer->emitIntValue(0, PtrSize);
889 OutStreamer->emitSymbolValue(MangSym, PtrSize);
890
891 OutStreamer->addBlankLine();
892 return;
893 }
894
895 MCSymbol *EmittedInitSym = GVSym;
896
897 OutStreamer->switchSection(TheSection);
898
899 emitLinkage(GV, EmittedInitSym);
900 emitAlignment(Alignment, GV);
901
902 OutStreamer->emitLabel(EmittedInitSym);
903 MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
904 if (LocalAlias != EmittedInitSym)
905 OutStreamer->emitLabel(LocalAlias);
906
908
910 // .size foo, 42
911 OutStreamer->emitELFSize(EmittedInitSym,
913
914 OutStreamer->addBlankLine();
915}
916
917/// Emit the directive and value for debug thread local expression
918///
919/// \p Value - The value to emit.
920/// \p Size - The size of the integer (in bytes) to emit.
921void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
922 OutStreamer->emitValue(Value, Size);
923}
924
925void AsmPrinter::emitFunctionHeaderComment() {}
926
927void AsmPrinter::emitFunctionPrefix(ArrayRef<const Constant *> Prefix) {
928 const Function &F = MF->getFunction();
930 for (auto &C : Prefix)
931 emitGlobalConstant(F.getDataLayout(), C);
932 return;
933 }
934 // Preserving prefix-like data on platforms which use subsections-via-symbols
935 // is a bit tricky. Here we introduce a symbol for the prefix-like data
936 // and use the .alt_entry attribute to mark the function's real entry point
937 // as an alternative entry point to the symbol that precedes the function..
939
940 for (auto &C : Prefix) {
941 emitGlobalConstant(F.getDataLayout(), C);
942 }
943
944 // Emit an .alt_entry directive for the actual function symbol.
945 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
946}
947
948/// EmitFunctionHeader - This method emits the header for the current
949/// function.
950void AsmPrinter::emitFunctionHeader() {
951 const Function &F = MF->getFunction();
952
953 if (isVerbose())
954 OutStreamer->getCommentOS()
955 << "-- Begin function "
956 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
957
958 // Print out constants referenced by the function
960
961 // Print the 'header' of function.
962 // If basic block sections are desired, explicitly request a unique section
963 // for this function's entry block.
964 if (MF->front().isBeginSection())
965 MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
966 else
967 MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
968 OutStreamer->switchSection(MF->getSection());
969
971 emitVisibility(CurrentFnSym, F.getVisibility());
972
975
979
981 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
982
983 if (F.hasFnAttribute(Attribute::Cold))
984 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
985
986 // Emit the prefix data.
987 if (F.hasPrefixData())
988 emitFunctionPrefix({F.getPrefixData()});
989
990 // Emit KCFI type information before patchable-function-prefix nops.
992
993 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
994 // place prefix data before NOPs.
995 unsigned PatchableFunctionPrefix = 0;
996 unsigned PatchableFunctionEntry = 0;
997 (void)F.getFnAttribute("patchable-function-prefix")
998 .getValueAsString()
999 .getAsInteger(10, PatchableFunctionPrefix);
1000 (void)F.getFnAttribute("patchable-function-entry")
1001 .getValueAsString()
1002 .getAsInteger(10, PatchableFunctionEntry);
1003 if (PatchableFunctionPrefix) {
1007 emitNops(PatchableFunctionPrefix);
1008 } else if (PatchableFunctionEntry) {
1009 // May be reassigned when emitting the body, to reference the label after
1010 // the initial BTI (AArch64) or endbr32/endbr64 (x86).
1012 }
1013
1014 // Emit the function prologue data for the indirect call sanitizer.
1015 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_func_sanitize)) {
1016 assert(MD->getNumOperands() == 2);
1017
1018 auto *PrologueSig = mdconst::extract<Constant>(MD->getOperand(0));
1019 auto *TypeHash = mdconst::extract<Constant>(MD->getOperand(1));
1020 emitFunctionPrefix({PrologueSig, TypeHash});
1021 }
1022
1023 if (isVerbose()) {
1024 F.printAsOperand(OutStreamer->getCommentOS(),
1025 /*PrintType=*/false, F.getParent());
1026 emitFunctionHeaderComment();
1027 OutStreamer->getCommentOS() << '\n';
1028 }
1029
1030 // Emit the function descriptor. This is a virtual function to allow targets
1031 // to emit their specific function descriptor. Right now it is only used by
1032 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
1033 // descriptors and should be converted to use this hook as well.
1036
1037 // Emit the CurrentFnSym. This is a virtual function to allow targets to do
1038 // their wild and crazy things as required.
1040
1041 // If the function had address-taken blocks that got deleted, then we have
1042 // references to the dangling symbols. Emit them at the start of the function
1043 // so that we don't get references to undefined symbols.
1044 std::vector<MCSymbol*> DeadBlockSyms;
1045 takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
1046 for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
1047 OutStreamer->AddComment("Address taken block that was later removed");
1048 OutStreamer->emitLabel(DeadBlockSym);
1049 }
1050
1051 if (CurrentFnBegin) {
1054 OutStreamer->emitLabel(CurPos);
1055 OutStreamer->emitAssignment(CurrentFnBegin,
1057 } else {
1058 OutStreamer->emitLabel(CurrentFnBegin);
1059 }
1060 }
1061
1062 // Emit pre-function debug and/or EH information.
1063 for (auto &Handler : DebugHandlers) {
1064 Handler->beginFunction(MF);
1065 Handler->beginBasicBlockSection(MF->front());
1066 }
1067 for (auto &Handler : Handlers)
1068 Handler->beginFunction(MF);
1069 for (auto &Handler : Handlers)
1070 Handler->beginBasicBlockSection(MF->front());
1071
1072 // Emit the prologue data.
1073 if (F.hasPrologueData())
1074 emitGlobalConstant(F.getDataLayout(), F.getPrologueData());
1075}
1076
1077/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
1078/// function. This can be overridden by targets as required to do custom stuff.
1081
1082 // The function label could have already been emitted if two symbols end up
1083 // conflicting due to asm renaming. Detect this and emit an error.
1084 if (CurrentFnSym->isVariable())
1086 "' is a protected alias");
1087
1088 OutStreamer->emitLabel(CurrentFnSym);
1089
1092 if (Sym != CurrentFnSym) {
1093 cast<MCSymbolELF>(Sym)->setType(ELF::STT_FUNC);
1095 OutStreamer->emitLabel(Sym);
1097 OutStreamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeFunction);
1098 }
1099 }
1100}
1101
1102/// emitComments - Pretty-print comments for instructions.
1103static void emitComments(const MachineInstr &MI, const MCSubtargetInfo *STI,
1104 raw_ostream &CommentOS) {
1105 const MachineFunction *MF = MI.getMF();
1107
1108 // Check for spills and reloads
1109
1110 // We assume a single instruction only has a spill or reload, not
1111 // both.
1112 std::optional<LocationSize> Size;
1113 if ((Size = MI.getRestoreSize(TII))) {
1114 CommentOS << Size->getValue() << "-byte Reload\n";
1115 } else if ((Size = MI.getFoldedRestoreSize(TII))) {
1116 if (!Size->hasValue())
1117 CommentOS << "Unknown-size Folded Reload\n";
1118 else if (Size->getValue())
1119 CommentOS << Size->getValue() << "-byte Folded Reload\n";
1120 } else if ((Size = MI.getSpillSize(TII))) {
1121 CommentOS << Size->getValue() << "-byte Spill\n";
1122 } else if ((Size = MI.getFoldedSpillSize(TII))) {
1123 if (!Size->hasValue())
1124 CommentOS << "Unknown-size Folded Spill\n";
1125 else if (Size->getValue())
1126 CommentOS << Size->getValue() << "-byte Folded Spill\n";
1127 }
1128
1129 // Check for spill-induced copies
1130 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
1131 CommentOS << " Reload Reuse\n";
1132
1133 if (PrintLatency) {
1135 const MCSchedModel &SCModel = STI->getSchedModel();
1138 *STI, *TII, MI);
1139 // Report only interesting latencies.
1140 if (1 < Latency)
1141 CommentOS << " Latency: " << Latency << "\n";
1142 }
1143}
1144
1145/// emitImplicitDef - This method emits the specified machine instruction
1146/// that is an implicit def.
1148 Register RegNo = MI->getOperand(0).getReg();
1149
1150 SmallString<128> Str;
1152 OS << "implicit-def: "
1153 << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
1154
1155 OutStreamer->AddComment(OS.str());
1156 OutStreamer->addBlankLine();
1157}
1158
1159static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
1160 std::string Str;
1162 OS << "kill:";
1163 for (const MachineOperand &Op : MI->operands()) {
1164 assert(Op.isReg() && "KILL instruction must have only register operands");
1165 OS << ' ' << (Op.isDef() ? "def " : "killed ")
1166 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
1167 }
1168 AP.OutStreamer->AddComment(Str);
1169 AP.OutStreamer->addBlankLine();
1170}
1171
1172static void emitFakeUse(const MachineInstr *MI, AsmPrinter &AP) {
1173 std::string Str;
1175 OS << "fake_use:";
1176 for (const MachineOperand &Op : MI->operands()) {
1177 // In some circumstances we can end up with fake uses of constants; skip
1178 // these.
1179 if (!Op.isReg())
1180 continue;
1181 OS << ' ' << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
1182 }
1183 AP.OutStreamer->AddComment(OS.str());
1184 AP.OutStreamer->addBlankLine();
1185}
1186
1187/// emitDebugValueComment - This method handles the target-independent form
1188/// of DBG_VALUE, returning true if it was able to do so. A false return
1189/// means the target will need to handle MI in EmitInstruction.
1191 // This code handles only the 4-operand target-independent form.
1192 if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
1193 return false;
1194
1195 SmallString<128> Str;
1197 OS << "DEBUG_VALUE: ";
1198
1199 const DILocalVariable *V = MI->getDebugVariable();
1200 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
1201 StringRef Name = SP->getName();
1202 if (!Name.empty())
1203 OS << Name << ":";
1204 }
1205 OS << V->getName();
1206 OS << " <- ";
1207
1208 const DIExpression *Expr = MI->getDebugExpression();
1209 // First convert this to a non-variadic expression if possible, to simplify
1210 // the output.
1211 if (auto NonVariadicExpr = DIExpression::convertToNonVariadicExpression(Expr))
1212 Expr = *NonVariadicExpr;
1213 // Then, output the possibly-simplified expression.
1214 if (Expr->getNumElements()) {
1215 OS << '[';
1216 ListSeparator LS;
1217 for (auto &Op : Expr->expr_ops()) {
1218 OS << LS << dwarf::OperationEncodingString(Op.getOp());
1219 for (unsigned I = 0; I < Op.getNumArgs(); ++I)
1220 OS << ' ' << Op.getArg(I);
1221 }
1222 OS << "] ";
1223 }
1224
1225 // Register or immediate value. Register 0 means undef.
1226 for (const MachineOperand &Op : MI->debug_operands()) {
1227 if (&Op != MI->debug_operands().begin())
1228 OS << ", ";
1229 switch (Op.getType()) {
1231 APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
1232 Type *ImmTy = Op.getFPImm()->getType();
1233 if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
1234 ImmTy->isDoubleTy()) {
1235 OS << APF.convertToDouble();
1236 } else {
1237 // There is no good way to print long double. Convert a copy to
1238 // double. Ah well, it's only a comment.
1239 bool ignored;
1241 &ignored);
1242 OS << "(long double) " << APF.convertToDouble();
1243 }
1244 break;
1245 }
1247 OS << Op.getImm();
1248 break;
1249 }
1251 Op.getCImm()->getValue().print(OS, false /*isSigned*/);
1252 break;
1253 }
1255 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
1256 break;
1257 }
1260 Register Reg;
1261 std::optional<StackOffset> Offset;
1262 if (Op.isReg()) {
1263 Reg = Op.getReg();
1264 } else {
1265 const TargetFrameLowering *TFI =
1267 Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
1268 }
1269 if (!Reg) {
1270 // Suppress offset, it is not meaningful here.
1271 OS << "undef";
1272 break;
1273 }
1274 // The second operand is only an offset if it's an immediate.
1275 if (MI->isIndirectDebugValue())
1276 Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
1277 if (Offset)
1278 OS << '[';
1279 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
1280 if (Offset)
1281 OS << '+' << Offset->getFixed() << ']';
1282 break;
1283 }
1284 default:
1285 llvm_unreachable("Unknown operand type");
1286 }
1287 }
1288
1289 // NOTE: Want this comment at start of line, don't emit with AddComment.
1290 AP.OutStreamer->emitRawComment(Str);
1291 return true;
1292}
1293
1294/// This method handles the target-independent form of DBG_LABEL, returning
1295/// true if it was able to do so. A false return means the target will need
1296/// to handle MI in EmitInstruction.
1298 if (MI->getNumOperands() != 1)
1299 return false;
1300
1301 SmallString<128> Str;
1303 OS << "DEBUG_LABEL: ";
1304
1305 const DILabel *V = MI->getDebugLabel();
1306 if (auto *SP = dyn_cast<DISubprogram>(
1307 V->getScope()->getNonLexicalBlockFileScope())) {
1308 StringRef Name = SP->getName();
1309 if (!Name.empty())
1310 OS << Name << ":";
1311 }
1312 OS << V->getName();
1313
1314 // NOTE: Want this comment at start of line, don't emit with AddComment.
1315 AP.OutStreamer->emitRawComment(OS.str());
1316 return true;
1317}
1318
1321 // Ignore functions that won't get emitted.
1322 if (F.isDeclarationForLinker())
1323 return CFISection::None;
1324
1326 F.needsUnwindTableEntry())
1327 return CFISection::EH;
1328
1329 if (MAI->usesCFIWithoutEH() && F.hasUWTable())
1330 return CFISection::EH;
1331
1333 return CFISection::Debug;
1334
1335 return CFISection::None;
1336}
1337
1341}
1342
1345}
1346
1348 return MAI->usesCFIWithoutEH() && ModuleCFISection != CFISection::None;
1349}
1350
1352 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
1353 if (!usesCFIWithoutEH() &&
1354 ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
1355 ExceptionHandlingType != ExceptionHandling::ARM)
1356 return;
1357
1359 return;
1360
1361 // If there is no "real" instruction following this CFI instruction, skip
1362 // emitting it; it would be beyond the end of the function's FDE range.
1363 auto *MBB = MI.getParent();
1364 auto I = std::next(MI.getIterator());
1365 while (I != MBB->end() && I->isTransient())
1366 ++I;
1367 if (I == MBB->instr_end() &&
1369 return;
1370
1371 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1372 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1373 const MCCFIInstruction &CFI = Instrs[CFIIndex];
1374 emitCFIInstruction(CFI);
1375}
1376
1378 // The operands are the MCSymbol and the frame offset of the allocation.
1379 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1380 int FrameOffset = MI.getOperand(1).getImm();
1381
1382 // Emit a symbol assignment.
1383 OutStreamer->emitAssignment(FrameAllocSym,
1384 MCConstantExpr::create(FrameOffset, OutContext));
1385}
1386
1387/// Returns the BB metadata to be emitted in the SHT_LLVM_BB_ADDR_MAP section
1388/// for a given basic block. This can be used to capture more precise profile
1389/// information.
1394 MBB.isEHPad(), const_cast<MachineBasicBlock &>(MBB).canFallThrough(),
1395 !MBB.empty() && MBB.rbegin()->isIndirectBranch()}
1396 .encode();
1397}
1398
1400getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges) {
1401 // Ensure that the user has not passed in additional options while also
1402 // specifying all or none.
1403 if ((PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::None) ||
1404 PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::All)) &&
1405 popcount(PgoAnalysisMapFeatures.getBits()) != 1) {
1407 "-pgo-anaylsis-map can accept only all or none with no additional "
1408 "values.");
1409 }
1410
1411 bool NoFeatures = PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::None);
1412 bool AllFeatures = PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::All);
1413 bool FuncEntryCountEnabled =
1414 AllFeatures || (!NoFeatures && PgoAnalysisMapFeatures.isSet(
1415 PGOMapFeaturesEnum::FuncEntryCount));
1416 bool BBFreqEnabled =
1417 AllFeatures ||
1418 (!NoFeatures && PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::BBFreq));
1419 bool BrProbEnabled =
1420 AllFeatures ||
1421 (!NoFeatures && PgoAnalysisMapFeatures.isSet(PGOMapFeaturesEnum::BrProb));
1422
1423 if ((BBFreqEnabled || BrProbEnabled) && BBAddrMapSkipEmitBBEntries) {
1425 "BB entries info is required for BBFreq and BrProb "
1426 "features");
1427 }
1428 return {FuncEntryCountEnabled, BBFreqEnabled, BrProbEnabled,
1429 MF.hasBBSections() && NumMBBSectionRanges > 1,
1430 static_cast<bool>(BBAddrMapSkipEmitBBEntries)};
1431}
1432
1434 MCSection *BBAddrMapSection =
1436 assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
1437
1438 const MCSymbol *FunctionSymbol = getFunctionBegin();
1439
1440 OutStreamer->pushSection();
1441 OutStreamer->switchSection(BBAddrMapSection);
1442 OutStreamer->AddComment("version");
1443 uint8_t BBAddrMapVersion = OutStreamer->getContext().getBBAddrMapVersion();
1444 OutStreamer->emitInt8(BBAddrMapVersion);
1445 OutStreamer->AddComment("feature");
1446 auto Features = getBBAddrMapFeature(MF, MBBSectionRanges.size());
1447 OutStreamer->emitInt8(Features.encode());
1448 // Emit BB Information for each basic block in the function.
1449 if (Features.MultiBBRange) {
1450 OutStreamer->AddComment("number of basic block ranges");
1451 OutStreamer->emitULEB128IntValue(MBBSectionRanges.size());
1452 }
1453 // Number of blocks in each MBB section.
1454 MapVector<MBBSectionID, unsigned> MBBSectionNumBlocks;
1455 const MCSymbol *PrevMBBEndSymbol = nullptr;
1456 if (!Features.MultiBBRange) {
1457 OutStreamer->AddComment("function address");
1458 OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
1459 OutStreamer->AddComment("number of basic blocks");
1460 OutStreamer->emitULEB128IntValue(MF.size());
1461 PrevMBBEndSymbol = FunctionSymbol;
1462 } else {
1463 unsigned BBCount = 0;
1464 for (const MachineBasicBlock &MBB : MF) {
1465 BBCount++;
1466 if (MBB.isEndSection()) {
1467 // Store each section's basic block count when it ends.
1468 MBBSectionNumBlocks[MBB.getSectionID()] = BBCount;
1469 // Reset the count for the next section.
1470 BBCount = 0;
1471 }
1472 }
1473 }
1474 // Emit the BB entry for each basic block in the function.
1475 for (const MachineBasicBlock &MBB : MF) {
1476 const MCSymbol *MBBSymbol =
1477 MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1478 bool IsBeginSection =
1479 Features.MultiBBRange && (MBB.isBeginSection() || MBB.isEntryBlock());
1480 if (IsBeginSection) {
1481 OutStreamer->AddComment("base address");
1482 OutStreamer->emitSymbolValue(MBBSymbol, getPointerSize());
1483 OutStreamer->AddComment("number of basic blocks");
1484 OutStreamer->emitULEB128IntValue(MBBSectionNumBlocks[MBB.getSectionID()]);
1485 PrevMBBEndSymbol = MBBSymbol;
1486 }
1487
1488 if (!Features.OmitBBEntries) {
1489 // TODO: Remove this check when version 1 is deprecated.
1490 if (BBAddrMapVersion > 1) {
1491 OutStreamer->AddComment("BB id");
1492 // Emit the BB ID for this basic block.
1493 // We only emit BaseID since CloneID is unset for
1494 // -basic-block-adress-map.
1495 // TODO: Emit the full BBID when labels and sections can be mixed
1496 // together.
1497 OutStreamer->emitULEB128IntValue(MBB.getBBID()->BaseID);
1498 }
1499 // Emit the basic block offset relative to the end of the previous block.
1500 // This is zero unless the block is padded due to alignment.
1501 emitLabelDifferenceAsULEB128(MBBSymbol, PrevMBBEndSymbol);
1502 // Emit the basic block size. When BBs have alignments, their size cannot
1503 // always be computed from their offsets.
1505 // Emit the Metadata.
1506 OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
1507 }
1508
1509 PrevMBBEndSymbol = MBB.getEndSymbol();
1510 }
1511
1512 if (Features.hasPGOAnalysis()) {
1513 assert(BBAddrMapVersion >= 2 &&
1514 "PGOAnalysisMap only supports version 2 or later");
1515
1516 if (Features.FuncEntryCount) {
1517 OutStreamer->AddComment("function entry count");
1518 auto MaybeEntryCount = MF.getFunction().getEntryCount();
1519 OutStreamer->emitULEB128IntValue(
1520 MaybeEntryCount ? MaybeEntryCount->getCount() : 0);
1521 }
1522 const MachineBlockFrequencyInfo *MBFI =
1523 Features.BBFreq
1524 ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
1525 : nullptr;
1526 const MachineBranchProbabilityInfo *MBPI =
1527 Features.BrProb
1528 ? &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI()
1529 : nullptr;
1530
1531 if (Features.BBFreq || Features.BrProb) {
1532 for (const MachineBasicBlock &MBB : MF) {
1533 if (Features.BBFreq) {
1534 OutStreamer->AddComment("basic block frequency");
1535 OutStreamer->emitULEB128IntValue(
1536 MBFI->getBlockFreq(&MBB).getFrequency());
1537 }
1538 if (Features.BrProb) {
1539 unsigned SuccCount = MBB.succ_size();
1540 OutStreamer->AddComment("basic block successor count");
1541 OutStreamer->emitULEB128IntValue(SuccCount);
1542 for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
1543 OutStreamer->AddComment("successor BB ID");
1544 OutStreamer->emitULEB128IntValue(SuccMBB->getBBID()->BaseID);
1545 OutStreamer->AddComment("successor branch probability");
1546 OutStreamer->emitULEB128IntValue(
1547 MBPI->getEdgeProbability(&MBB, SuccMBB).getNumerator());
1548 }
1549 }
1550 }
1551 }
1552 }
1553
1554 OutStreamer->popSection();
1555}
1556
1558 const MCSymbol *Symbol) {
1559 MCSection *Section =
1561 if (!Section)
1562 return;
1563
1564 OutStreamer->pushSection();
1565 OutStreamer->switchSection(Section);
1566
1568 OutStreamer->emitLabel(Loc);
1569 OutStreamer->emitAbsoluteSymbolDiff(Symbol, Loc, 4);
1570
1571 OutStreamer->popSection();
1572}
1573
1575 const Function &F = MF.getFunction();
1576 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_kcfi_type))
1577 emitGlobalConstant(F.getDataLayout(),
1578 mdconst::extract<ConstantInt>(MD->getOperand(0)));
1579}
1580
1582 if (PP) {
1583 auto GUID = MI.getOperand(0).getImm();
1584 auto Index = MI.getOperand(1).getImm();
1585 auto Type = MI.getOperand(2).getImm();
1586 auto Attr = MI.getOperand(3).getImm();
1587 DILocation *DebugLoc = MI.getDebugLoc();
1588 PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
1589 }
1590}
1591
1594 return;
1595
1596 MCSection *StackSizeSection =
1598 if (!StackSizeSection)
1599 return;
1600
1601 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1602 // Don't emit functions with dynamic stack allocations.
1603 if (FrameInfo.hasVarSizedObjects())
1604 return;
1605
1606 OutStreamer->pushSection();
1607 OutStreamer->switchSection(StackSizeSection);
1608
1609 const MCSymbol *FunctionSymbol = getFunctionBegin();
1610 uint64_t StackSize =
1611 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1612 OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
1613 OutStreamer->emitULEB128IntValue(StackSize);
1614
1615 OutStreamer->popSection();
1616}
1617
1619 const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
1620
1621 // OutputFilename empty implies -fstack-usage is not passed.
1622 if (OutputFilename.empty())
1623 return;
1624
1625 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1626 uint64_t StackSize =
1627 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1628
1629 if (StackUsageStream == nullptr) {
1630 std::error_code EC;
1631 StackUsageStream =
1632 std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
1633 if (EC) {
1634 errs() << "Could not open file: " << EC.message();
1635 return;
1636 }
1637 }
1638
1639 if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1640 *StackUsageStream << DSP->getFilename() << ':' << DSP->getLine();
1641 else
1642 *StackUsageStream << MF.getFunction().getParent()->getName();
1643
1644 *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1645 if (FrameInfo.hasVarSizedObjects())
1646 *StackUsageStream << "dynamic\n";
1647 else
1648 *StackUsageStream << "static\n";
1649}
1650
1652 const MDNode &MD) {
1653 MCSymbol *S = MF.getContext().createTempSymbol("pcsection");
1654 OutStreamer->emitLabel(S);
1655 PCSectionsSymbols[&MD].emplace_back(S);
1656}
1657
1659 const Function &F = MF.getFunction();
1660 if (PCSectionsSymbols.empty() && !F.hasMetadata(LLVMContext::MD_pcsections))
1661 return;
1662
1664 const unsigned RelativeRelocSize =
1666 : 4;
1667
1668 // Switch to PCSection, short-circuiting the common case where the current
1669 // section is still valid (assume most MD_pcsections contain just 1 section).
1670 auto SwitchSection = [&, Prev = StringRef()](const StringRef &Sec) mutable {
1671 if (Sec == Prev)
1672 return;
1674 assert(S && "PC section is not initialized");
1675 OutStreamer->switchSection(S);
1676 Prev = Sec;
1677 };
1678 // Emit symbols into sections and data as specified in the pcsections MDNode.
1679 auto EmitForMD = [&](const MDNode &MD, ArrayRef<const MCSymbol *> Syms,
1680 bool Deltas) {
1681 // Expect the first operand to be a section name. After that, a tuple of
1682 // constants may appear, which will simply be emitted into the current
1683 // section (the user of MD_pcsections decides the format of encoded data).
1684 assert(isa<MDString>(MD.getOperand(0)) && "first operand not a string");
1685 bool ConstULEB128 = false;
1686 for (const MDOperand &MDO : MD.operands()) {
1687 if (auto *S = dyn_cast<MDString>(MDO)) {
1688 // Found string, start of new section!
1689 // Find options for this section "<section>!<opts>" - supported options:
1690 // C = Compress constant integers of size 2-8 bytes as ULEB128.
1691 const StringRef SecWithOpt = S->getString();
1692 const size_t OptStart = SecWithOpt.find('!'); // likely npos
1693 const StringRef Sec = SecWithOpt.substr(0, OptStart);
1694 const StringRef Opts = SecWithOpt.substr(OptStart); // likely empty
1695 ConstULEB128 = Opts.contains('C');
1696#ifndef NDEBUG
1697 for (char O : Opts)
1698 assert((O == '!' || O == 'C') && "Invalid !pcsections options");
1699#endif
1700 SwitchSection(Sec);
1701 const MCSymbol *Prev = Syms.front();
1702 for (const MCSymbol *Sym : Syms) {
1703 if (Sym == Prev || !Deltas) {
1704 // Use the entry itself as the base of the relative offset.
1705 MCSymbol *Base = MF.getContext().createTempSymbol("pcsection_base");
1706 OutStreamer->emitLabel(Base);
1707 // Emit relative relocation `addr - base`, which avoids a dynamic
1708 // relocation in the final binary. User will get the address with
1709 // `base + addr`.
1710 emitLabelDifference(Sym, Base, RelativeRelocSize);
1711 } else {
1712 // Emit delta between symbol and previous symbol.
1713 if (ConstULEB128)
1715 else
1716 emitLabelDifference(Sym, Prev, 4);
1717 }
1718 Prev = Sym;
1719 }
1720 } else {
1721 // Emit auxiliary data after PC.
1722 assert(isa<MDNode>(MDO) && "expecting either string or tuple");
1723 const auto *AuxMDs = cast<MDNode>(MDO);
1724 for (const MDOperand &AuxMDO : AuxMDs->operands()) {
1725 assert(isa<ConstantAsMetadata>(AuxMDO) && "expecting a constant");
1726 const Constant *C = cast<ConstantAsMetadata>(AuxMDO)->getValue();
1727 const DataLayout &DL = F.getDataLayout();
1728 const uint64_t Size = DL.getTypeStoreSize(C->getType());
1729
1730 if (auto *CI = dyn_cast<ConstantInt>(C);
1731 CI && ConstULEB128 && Size > 1 && Size <= 8) {
1732 emitULEB128(CI->getZExtValue());
1733 } else {
1735 }
1736 }
1737 }
1738 }
1739 };
1740
1741 OutStreamer->pushSection();
1742 // Emit PCs for function start and function size.
1743 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_pcsections))
1744 EmitForMD(*MD, {getFunctionBegin(), getFunctionEnd()}, true);
1745 // Emit PCs for instructions collected.
1746 for (const auto &MS : PCSectionsSymbols)
1747 EmitForMD(*MS.first, MS.second, false);
1748 OutStreamer->popSection();
1749 PCSectionsSymbols.clear();
1750}
1751
1752/// Returns true if function begin and end labels should be emitted.
1753static bool needFuncLabels(const MachineFunction &MF, const AsmPrinter &Asm) {
1754 if (Asm.hasDebugInfo() || !MF.getLandingPads().empty() ||
1755 MF.hasEHFunclets() ||
1756 MF.getFunction().hasMetadata(LLVMContext::MD_pcsections))
1757 return true;
1758
1759 // We might emit an EH table that uses function begin and end labels even if
1760 // we don't have any landingpads.
1761 if (!MF.getFunction().hasPersonalityFn())
1762 return false;
1763 return !isNoOpWithoutInvoke(
1765}
1766
1767// Return the mnemonic of a MachineInstr if available, or the MachineInstr
1768// opcode name otherwise.
1770 const TargetInstrInfo *TII =
1771 MI.getParent()->getParent()->getSubtarget().getInstrInfo();
1772 MCInst MCI;
1773 MCI.setOpcode(MI.getOpcode());
1774 if (StringRef Name = Streamer.getMnemonic(MCI); !Name.empty())
1775 return Name;
1776 StringRef Name = TII->getName(MI.getOpcode());
1777 assert(!Name.empty() && "Missing mnemonic and name for opcode");
1778 return Name;
1779}
1780
1781/// EmitFunctionBody - This method emits the body and trailer for a
1782/// function.
1784 emitFunctionHeader();
1785
1786 // Emit target-specific gunk before the function body.
1788
1789 if (isVerbose()) {
1790 // Get MachineDominatorTree or compute it on the fly if it's unavailable
1791 auto MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
1792 MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
1793 if (!MDT) {
1794 OwnedMDT = std::make_unique<MachineDominatorTree>();
1795 OwnedMDT->recalculate(*MF);
1796 MDT = OwnedMDT.get();
1797 }
1798
1799 // Get MachineLoopInfo or compute it on the fly if it's unavailable
1800 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
1801 MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
1802 if (!MLI) {
1803 OwnedMLI = std::make_unique<MachineLoopInfo>();
1804 OwnedMLI->analyze(*MDT);
1805 MLI = OwnedMLI.get();
1806 }
1807 }
1808
1809 // Print out code for the function.
1810 bool HasAnyRealCode = false;
1811 int NumInstsInFunction = 0;
1812 bool IsEHa = MMI->getModule()->getModuleFlag("eh-asynch");
1813
1814 const MCSubtargetInfo *STI = nullptr;
1815 if (this->MF)
1816 STI = &getSubtargetInfo();
1817 else
1818 STI = TM.getMCSubtargetInfo();
1819
1820 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1821 // Create a slot for the entry basic block section so that the section
1822 // order is preserved when iterating over MBBSectionRanges.
1823 if (!MF->empty())
1826
1827 for (auto &MBB : *MF) {
1828 // Print a label for the basic block.
1830 DenseMap<StringRef, unsigned> MnemonicCounts;
1831 for (auto &MI : MBB) {
1832 // Print the assembly for the instruction.
1833 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1834 !MI.isDebugInstr()) {
1835 HasAnyRealCode = true;
1836 }
1837
1838 // If there is a pre-instruction symbol, emit a label for it here.
1839 if (MCSymbol *S = MI.getPreInstrSymbol())
1840 OutStreamer->emitLabel(S);
1841
1842 if (MDNode *MD = MI.getPCSections())
1843 emitPCSectionsLabel(*MF, *MD);
1844
1845 for (auto &Handler : DebugHandlers)
1846 Handler->beginInstruction(&MI);
1847
1848 if (isVerbose())
1849 emitComments(MI, STI, OutStreamer->getCommentOS());
1850
1851 switch (MI.getOpcode()) {
1852 case TargetOpcode::CFI_INSTRUCTION:
1854 break;
1855 case TargetOpcode::LOCAL_ESCAPE:
1857 break;
1858 case TargetOpcode::ANNOTATION_LABEL:
1859 case TargetOpcode::GC_LABEL:
1860 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
1861 break;
1862 case TargetOpcode::EH_LABEL:
1863 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
1864 // For AsynchEH, insert a Nop if followed by a trap inst
1865 // Or the exception won't be caught.
1866 // (see MCConstantExpr::create(1,..) in WinException.cpp)
1867 // Ignore SDiv/UDiv because a DIV with Const-0 divisor
1868 // must have being turned into an UndefValue.
1869 // Div with variable opnds won't be the first instruction in
1870 // an EH region as it must be led by at least a Load
1871 {
1872 auto MI2 = std::next(MI.getIterator());
1873 if (IsEHa && MI2 != MBB.end() &&
1874 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
1875 emitNops(1);
1876 }
1877 break;
1878 case TargetOpcode::INLINEASM:
1879 case TargetOpcode::INLINEASM_BR:
1880 emitInlineAsm(&MI);
1881 break;
1882 case TargetOpcode::DBG_VALUE:
1883 case TargetOpcode::DBG_VALUE_LIST:
1884 if (isVerbose()) {
1885 if (!emitDebugValueComment(&MI, *this))
1887 }
1888 break;
1889 case TargetOpcode::DBG_INSTR_REF:
1890 // This instruction reference will have been resolved to a machine
1891 // location, and a nearby DBG_VALUE created. We can safely ignore
1892 // the instruction reference.
1893 break;
1894 case TargetOpcode::DBG_PHI:
1895 // This instruction is only used to label a program point, it's purely
1896 // meta information.
1897 break;
1898 case TargetOpcode::DBG_LABEL:
1899 if (isVerbose()) {
1900 if (!emitDebugLabelComment(&MI, *this))
1902 }
1903 break;
1904 case TargetOpcode::IMPLICIT_DEF:
1905 if (isVerbose()) emitImplicitDef(&MI);
1906 break;
1907 case TargetOpcode::KILL:
1908 if (isVerbose()) emitKill(&MI, *this);
1909 break;
1910 case TargetOpcode::FAKE_USE:
1911 if (isVerbose())
1912 emitFakeUse(&MI, *this);
1913 break;
1914 case TargetOpcode::PSEUDO_PROBE:
1916 break;
1917 case TargetOpcode::ARITH_FENCE:
1918 if (isVerbose())
1919 OutStreamer->emitRawComment("ARITH_FENCE");
1920 break;
1921 case TargetOpcode::MEMBARRIER:
1922 OutStreamer->emitRawComment("MEMBARRIER");
1923 break;
1924 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
1925 // This instruction is only used to note jump table debug info, it's
1926 // purely meta information.
1927 break;
1928 case TargetOpcode::INIT_UNDEF:
1929 // This is only used to influence register allocation behavior, no
1930 // actual initialization is needed.
1931 break;
1932 default:
1934
1935 auto CountInstruction = [&](const MachineInstr &MI) {
1936 // Skip Meta instructions inside bundles.
1937 if (MI.isMetaInstruction())
1938 return;
1939 ++NumInstsInFunction;
1940 if (CanDoExtraAnalysis) {
1942 ++MnemonicCounts[Name];
1943 }
1944 };
1945 if (!MI.isBundle()) {
1946 CountInstruction(MI);
1947 break;
1948 }
1949 // Separately count all the instructions in a bundle.
1950 for (auto It = std::next(MI.getIterator());
1951 It != MBB.end() && It->isInsideBundle(); ++It) {
1952 CountInstruction(*It);
1953 }
1954 break;
1955 }
1956
1957 // If there is a post-instruction symbol, emit a label for it here.
1958 if (MCSymbol *S = MI.getPostInstrSymbol())
1959 OutStreamer->emitLabel(S);
1960
1961 for (auto &Handler : DebugHandlers)
1962 Handler->endInstruction();
1963 }
1964
1965 // We must emit temporary symbol for the end of this basic block, if either
1966 // we have BBLabels enabled or if this basic blocks marks the end of a
1967 // section.
1968 if (MF->getTarget().Options.BBAddrMap ||
1970 OutStreamer->emitLabel(MBB.getEndSymbol());
1971
1972 if (MBB.isEndSection()) {
1973 // The size directive for the section containing the entry block is
1974 // handled separately by the function section.
1975 if (!MBB.sameSection(&MF->front())) {
1977 // Emit the size directive for the basic block section.
1978 const MCExpr *SizeExp = MCBinaryExpr::createSub(
1980 MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
1981 OutContext);
1982 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
1983 }
1984 assert(!MBBSectionRanges.contains(MBB.getSectionID()) &&
1985 "Overwrite section range");
1987 MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
1988 }
1989 }
1991
1992 if (CanDoExtraAnalysis) {
1993 // Skip empty blocks.
1994 if (MBB.empty())
1995 continue;
1996
1998 MBB.begin()->getDebugLoc(), &MBB);
1999
2000 // Generate instruction mix remark. First, sort counts in descending order
2001 // by count and name.
2003 for (auto &KV : MnemonicCounts)
2004 MnemonicVec.emplace_back(KV.first, KV.second);
2005
2006 sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
2007 const std::pair<StringRef, unsigned> &B) {
2008 if (A.second > B.second)
2009 return true;
2010 if (A.second == B.second)
2011 return StringRef(A.first) < StringRef(B.first);
2012 return false;
2013 });
2014 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
2015 for (auto &KV : MnemonicVec) {
2016 auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
2017 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
2018 }
2019 ORE->emit(R);
2020 }
2021 }
2022
2023 EmittedInsts += NumInstsInFunction;
2024 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
2026 &MF->front());
2027 R << ore::NV("NumInstructions", NumInstsInFunction)
2028 << " instructions in function";
2029 ORE->emit(R);
2030
2031 // If the function is empty and the object file uses .subsections_via_symbols,
2032 // then we need to emit *something* to the function body to prevent the
2033 // labels from collapsing together. Just emit a noop.
2034 // Similarly, don't emit empty functions on Windows either. It can lead to
2035 // duplicate entries (two functions with the same RVA) in the Guard CF Table
2036 // after linking, causing the kernel not to load the binary:
2037 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
2038 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
2039 const Triple &TT = TM.getTargetTriple();
2040 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
2041 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
2042 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
2043
2044 // Targets can opt-out of emitting the noop here by leaving the opcode
2045 // unspecified.
2046 if (Noop.getOpcode()) {
2047 OutStreamer->AddComment("avoids zero-length function");
2048 emitNops(1);
2049 }
2050 }
2051
2052 // Switch to the original section in case basic block sections was used.
2053 OutStreamer->switchSection(MF->getSection());
2054
2055 const Function &F = MF->getFunction();
2056 for (const auto &BB : F) {
2057 if (!BB.hasAddressTaken())
2058 continue;
2060 if (Sym->isDefined())
2061 continue;
2062 OutStreamer->AddComment("Address of block that was removed by CodeGen");
2063 OutStreamer->emitLabel(Sym);
2064 }
2065
2066 // Emit target-specific gunk after the function body.
2068
2069 // Even though wasm supports .type and .size in general, function symbols
2070 // are automatically sized.
2071 bool EmitFunctionSize = MAI->hasDotTypeDotSizeDirective() && !TT.isWasm();
2072
2073 // SPIR-V supports label instructions only inside a block, not after the
2074 // function body.
2075 if (TT.getObjectFormat() != Triple::SPIRV &&
2076 (EmitFunctionSize || needFuncLabels(*MF, *this))) {
2077 // Create a symbol for the end of function.
2078 CurrentFnEnd = createTempSymbol("func_end");
2079 OutStreamer->emitLabel(CurrentFnEnd);
2080 }
2081
2082 // If the target wants a .size directive for the size of the function, emit
2083 // it.
2084 if (EmitFunctionSize) {
2085 // We can get the size as difference between the function label and the
2086 // temp label.
2087 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2088 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
2090 OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
2092 OutStreamer->emitELFSize(CurrentFnBeginLocal, SizeExp);
2093 }
2094
2095 // Call endBasicBlockSection on the last block now, if it wasn't already
2096 // called.
2097 if (!MF->back().isEndSection()) {
2098 for (auto &Handler : DebugHandlers)
2099 Handler->endBasicBlockSection(MF->back());
2100 for (auto &Handler : Handlers)
2101 Handler->endBasicBlockSection(MF->back());
2102 }
2103 for (auto &Handler : Handlers)
2104 Handler->markFunctionEnd();
2105 // Update the end label of the entry block's section.
2106 MBBSectionRanges[MF->front().getSectionID()].EndLabel = CurrentFnEnd;
2107
2108 // Print out jump tables referenced by the function.
2110
2111 // Emit post-function debug and/or EH information.
2112 for (auto &Handler : DebugHandlers)
2113 Handler->endFunction(MF);
2114 for (auto &Handler : Handlers)
2115 Handler->endFunction(MF);
2116
2117 // Emit section containing BB address offsets and their metadata, when
2118 // BB labels are requested for this function. Skip empty functions.
2119 if (HasAnyRealCode) {
2122 else if (PgoAnalysisMapFeatures.getBits() != 0)
2124 SMLoc(), "pgo-analysis-map is enabled for function " + MF->getName() +
2125 " but it does not have labels");
2126 }
2127
2128 // Emit sections containing instruction and function PCs.
2130
2131 // Emit section containing stack size metadata.
2133
2134 // Emit .su file containing function stack size information.
2136
2138
2139 if (isVerbose())
2140 OutStreamer->getCommentOS() << "-- End function\n";
2141
2142 OutStreamer->addBlankLine();
2143}
2144
2145/// Compute the number of Global Variables that uses a Constant.
2146static unsigned getNumGlobalVariableUses(const Constant *C) {
2147 if (!C)
2148 return 0;
2149
2150 if (isa<GlobalVariable>(C))
2151 return 1;
2152
2153 unsigned NumUses = 0;
2154 for (const auto *CU : C->users())
2155 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
2156
2157 return NumUses;
2158}
2159
2160/// Only consider global GOT equivalents if at least one user is a
2161/// cstexpr inside an initializer of another global variables. Also, don't
2162/// handle cstexpr inside instructions. During global variable emission,
2163/// candidates are skipped and are emitted later in case at least one cstexpr
2164/// isn't replaced by a PC relative GOT entry access.
2166 unsigned &NumGOTEquivUsers) {
2167 // Global GOT equivalents are unnamed private globals with a constant
2168 // pointer initializer to another global symbol. They must point to a
2169 // GlobalVariable or Function, i.e., as GlobalValue.
2170 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
2171 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
2172 !isa<GlobalValue>(GV->getOperand(0)))
2173 return false;
2174
2175 // To be a got equivalent, at least one of its users need to be a constant
2176 // expression used by another global variable.
2177 for (const auto *U : GV->users())
2178 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
2179
2180 return NumGOTEquivUsers > 0;
2181}
2182
2183/// Unnamed constant global variables solely contaning a pointer to
2184/// another globals variable is equivalent to a GOT table entry; it contains the
2185/// the address of another symbol. Optimize it and replace accesses to these
2186/// "GOT equivalents" by using the GOT entry for the final global instead.
2187/// Compute GOT equivalent candidates among all global variables to avoid
2188/// emitting them if possible later on, after it use is replaced by a GOT entry
2189/// access.
2191 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2192 return;
2193
2194 for (const auto &G : M.globals()) {
2195 unsigned NumGOTEquivUsers = 0;
2196 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
2197 continue;
2198
2199 const MCSymbol *GOTEquivSym = getSymbol(&G);
2200 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
2201 }
2202}
2203
2204/// Constant expressions using GOT equivalent globals may not be eligible
2205/// for PC relative GOT entry conversion, in such cases we need to emit such
2206/// globals we previously omitted in EmitGlobalVariable.
2208 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2209 return;
2210
2212 for (auto &I : GlobalGOTEquivs) {
2213 const GlobalVariable *GV = I.second.first;
2214 unsigned Cnt = I.second.second;
2215 if (Cnt)
2216 FailedCandidates.push_back(GV);
2217 }
2218 GlobalGOTEquivs.clear();
2219
2220 for (const auto *GV : FailedCandidates)
2222}
2223
2225 MCSymbol *Name = getSymbol(&GA);
2226 bool IsFunction = GA.getValueType()->isFunctionTy();
2227 // Treat bitcasts of functions as functions also. This is important at least
2228 // on WebAssembly where object and function addresses can't alias each other.
2229 if (!IsFunction)
2230 IsFunction = isa<Function>(GA.getAliasee()->stripPointerCasts());
2231
2232 // AIX's assembly directive `.set` is not usable for aliasing purpose,
2233 // so AIX has to use the extra-label-at-definition strategy. At this
2234 // point, all the extra label is emitted, we just have to emit linkage for
2235 // those labels.
2238 "Visibility should be handled with emitLinkage() on AIX.");
2239
2240 // Linkage for alias of global variable has been emitted.
2241 if (isa<GlobalVariable>(GA.getAliaseeObject()))
2242 return;
2243
2244 emitLinkage(&GA, Name);
2245 // If it's a function, also emit linkage for aliases of function entry
2246 // point.
2247 if (IsFunction)
2248 emitLinkage(&GA,
2249 getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
2250 return;
2251 }
2252
2254 OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
2255 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
2256 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
2257 else
2258 assert(GA.hasLocalLinkage() && "Invalid alias linkage");
2259
2260 // Set the symbol type to function if the alias has a function type.
2261 // This affects codegen when the aliasee is not a function.
2262 if (IsFunction) {
2263 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
2265 OutStreamer->beginCOFFSymbolDef(Name);
2266 OutStreamer->emitCOFFSymbolStorageClass(
2271 OutStreamer->endCOFFSymbolDef();
2272 }
2273 }
2274
2276
2277 const MCExpr *Expr = lowerConstant(GA.getAliasee());
2278
2279 if (MAI->isMachO() && isa<MCBinaryExpr>(Expr))
2280 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
2281
2282 // Emit the directives as assignments aka .set:
2283 OutStreamer->emitAssignment(Name, Expr);
2284 MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
2285 if (LocalAlias != Name)
2286 OutStreamer->emitAssignment(LocalAlias, Expr);
2287
2288 // If the aliasee does not correspond to a symbol in the output, i.e. the
2289 // alias is not of an object or the aliased object is private, then set the
2290 // size of the alias symbol from the type of the alias. We don't do this in
2291 // other situations as the alias and aliasee having differing types but same
2292 // size may be intentional.
2293 const GlobalObject *BaseObject = GA.getAliaseeObject();
2295 (!BaseObject || BaseObject->hasPrivateLinkage())) {
2296 const DataLayout &DL = M.getDataLayout();
2297 uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
2299 }
2300}
2301
2302void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
2304 "IFunc is not supported on AIX.");
2305
2306 auto EmitLinkage = [&](MCSymbol *Sym) {
2308 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
2309 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
2310 OutStreamer->emitSymbolAttribute(Sym, MCSA_WeakReference);
2311 else
2312 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
2313 };
2314
2316 MCSymbol *Name = getSymbol(&GI);
2317 EmitLinkage(Name);
2318 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
2320
2321 // Emit the directives as assignments aka .set:
2322 const MCExpr *Expr = lowerConstant(GI.getResolver());
2323 OutStreamer->emitAssignment(Name, Expr);
2324 MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
2325 if (LocalAlias != Name)
2326 OutStreamer->emitAssignment(LocalAlias, Expr);
2327
2328 return;
2329 }
2330
2332 llvm::report_fatal_error("IFuncs are not supported on this platform");
2333
2334 // On Darwin platforms, emit a manually-constructed .symbol_resolver that
2335 // implements the symbol resolution duties of the IFunc.
2336 //
2337 // Normally, this would be handled by linker magic, but unfortunately there
2338 // are a few limitations in ld64 and ld-prime's implementation of
2339 // .symbol_resolver that mean we can't always use them:
2340 //
2341 // * resolvers cannot be the target of an alias
2342 // * resolvers cannot have private linkage
2343 // * resolvers cannot have linkonce linkage
2344 // * resolvers cannot appear in executables
2345 // * resolvers cannot appear in bundles
2346 //
2347 // This works around that by emitting a close approximation of what the
2348 // linker would have done.
2349
2350 MCSymbol *LazyPointer =
2351 GetExternalSymbolSymbol(GI.getName() + ".lazy_pointer");
2352 MCSymbol *StubHelper = GetExternalSymbolSymbol(GI.getName() + ".stub_helper");
2353
2355
2356 const DataLayout &DL = M.getDataLayout();
2357 emitAlignment(Align(DL.getPointerSize()));
2358 OutStreamer->emitLabel(LazyPointer);
2359 emitVisibility(LazyPointer, GI.getVisibility());
2360 OutStreamer->emitValue(MCSymbolRefExpr::create(StubHelper, OutContext), 8);
2361
2363
2364 const TargetSubtargetInfo *STI =
2366 const TargetLowering *TLI = STI->getTargetLowering();
2367 Align TextAlign(TLI->getMinFunctionAlignment());
2368
2369 MCSymbol *Stub = getSymbol(&GI);
2370 EmitLinkage(Stub);
2371 OutStreamer->emitCodeAlignment(TextAlign, getIFuncMCSubtargetInfo());
2372 OutStreamer->emitLabel(Stub);
2373 emitVisibility(Stub, GI.getVisibility());
2374 emitMachOIFuncStubBody(M, GI, LazyPointer);
2375
2376 OutStreamer->emitCodeAlignment(TextAlign, getIFuncMCSubtargetInfo());
2377 OutStreamer->emitLabel(StubHelper);
2378 emitVisibility(StubHelper, GI.getVisibility());
2379 emitMachOIFuncStubHelperBody(M, GI, LazyPointer);
2380}
2381
2383 if (!RS.needsSection())
2384 return;
2385
2386 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
2387
2388 std::optional<SmallString<128>> Filename;
2389 if (std::optional<StringRef> FilenameRef = RS.getFilename()) {
2390 Filename = *FilenameRef;
2391 sys::fs::make_absolute(*Filename);
2392 assert(!Filename->empty() && "The filename can't be empty.");
2393 }
2394
2395 std::string Buf;
2397 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2398 Filename ? RemarkSerializer.metaSerializer(OS, Filename->str())
2399 : RemarkSerializer.metaSerializer(OS);
2400 MetaSerializer->emit();
2401
2402 // Switch to the remarks section.
2403 MCSection *RemarksSection =
2405 OutStreamer->switchSection(RemarksSection);
2406
2407 OutStreamer->emitBinaryData(Buf);
2408}
2409
2411 Constant *Initializer = G->getInitializer();
2412 uint64_t SizeInBytes =
2413 M.getDataLayout().getTypeAllocSize(Initializer->getType());
2414
2415 uint64_t NewSize = alignTo(SizeInBytes, 16);
2416 if (SizeInBytes != NewSize) {
2417 // Pad the initializer out to the next multiple of 16 bytes.
2418 llvm::SmallVector<uint8_t> Init(NewSize - SizeInBytes, 0);
2419 Constant *Padding = ConstantDataArray::get(M.getContext(), Init);
2420 Initializer = ConstantStruct::getAnon({Initializer, Padding});
2421 auto *NewGV = new GlobalVariable(
2422 M, Initializer->getType(), G->isConstant(), G->getLinkage(),
2423 Initializer, "", G, G->getThreadLocalMode(), G->getAddressSpace());
2424 NewGV->copyAttributesFrom(G);
2425 NewGV->setComdat(G->getComdat());
2426 NewGV->copyMetadata(G, 0);
2427
2428 NewGV->takeName(G);
2429 G->replaceAllUsesWith(NewGV);
2430 G->eraseFromParent();
2431 G = NewGV;
2432 }
2433
2434 if (G->getAlign().valueOrOne() < 16)
2435 G->setAlignment(Align(16));
2436
2437 // Ensure that tagged globals don't get merged by ICF - as they should have
2438 // different tags at runtime.
2439 G->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2440}
2441
2443 // Set the MachineFunction to nullptr so that we can catch attempted
2444 // accesses to MF specific features at the module level and so that
2445 // we can conditionalize accesses based on whether or not it is nullptr.
2446 MF = nullptr;
2447
2448 std::vector<GlobalVariable *> GlobalsToTag;
2449 for (GlobalVariable &G : M.globals()) {
2450 if (G.isDeclaration() || !G.isTagged())
2451 continue;
2452 GlobalsToTag.push_back(&G);
2453 }
2454 for (GlobalVariable *G : GlobalsToTag)
2456
2457 // Gather all GOT equivalent globals in the module. We really need two
2458 // passes over the globals: one to compute and another to avoid its emission
2459 // in EmitGlobalVariable, otherwise we would not be able to handle cases
2460 // where the got equivalent shows up before its use.
2462
2463 // Emit global variables.
2464 for (const auto &G : M.globals())
2466
2467 // Emit remaining GOT equivalent globals.
2469
2471
2472 // Emit linkage(XCOFF) and visibility info for declarations
2473 for (const Function &F : M) {
2474 if (!F.isDeclarationForLinker())
2475 continue;
2476
2477 MCSymbol *Name = getSymbol(&F);
2478 // Function getSymbol gives us the function descriptor symbol for XCOFF.
2479
2481 GlobalValue::VisibilityTypes V = F.getVisibility();
2483 continue;
2484
2485 emitVisibility(Name, V, false);
2486 continue;
2487 }
2488
2489 if (F.isIntrinsic())
2490 continue;
2491
2492 // Handle the XCOFF case.
2493 // Variable `Name` is the function descriptor symbol (see above). Get the
2494 // function entry point symbol.
2495 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
2496 // Emit linkage for the function entry point.
2497 emitLinkage(&F, FnEntryPointSym);
2498
2499 // If a function's address is taken, which means it may be called via a
2500 // function pointer, we need the function descriptor for it.
2501 if (F.hasAddressTaken())
2502 emitLinkage(&F, Name);
2503 }
2504
2505 // Emit the remarks section contents.
2506 // FIXME: Figure out when is the safest time to emit this section. It should
2507 // not come after debug info.
2508 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
2509 emitRemarksSection(*RS);
2510
2512
2515
2516 // Output stubs for external and common global variables.
2518 if (!Stubs.empty()) {
2519 OutStreamer->switchSection(TLOF.getDataSection());
2520 const DataLayout &DL = M.getDataLayout();
2521
2522 emitAlignment(Align(DL.getPointerSize()));
2523 for (const auto &Stub : Stubs) {
2524 OutStreamer->emitLabel(Stub.first);
2525 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2526 DL.getPointerSize());
2527 }
2528 }
2529 }
2530
2532 MachineModuleInfoCOFF &MMICOFF =
2534
2535 // Output stubs for external and common global variables.
2537 if (!Stubs.empty()) {
2538 const DataLayout &DL = M.getDataLayout();
2539
2540 for (const auto &Stub : Stubs) {
2542 SectionName += Stub.first->getName();
2543 OutStreamer->switchSection(OutContext.getCOFFSection(
2547 Stub.first->getName(), COFF::IMAGE_COMDAT_SELECT_ANY));
2548 emitAlignment(Align(DL.getPointerSize()));
2549 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
2550 OutStreamer->emitLabel(Stub.first);
2551 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2552 DL.getPointerSize());
2553 }
2554 }
2555 }
2556
2557 // This needs to happen before emitting debug information since that can end
2558 // arbitrary sections.
2559 if (auto *TS = OutStreamer->getTargetStreamer())
2560 TS->emitConstantPools();
2561
2562 // Emit Stack maps before any debug info. Mach-O requires that no data or
2563 // text sections come after debug info has been emitted. This matters for
2564 // stack maps as they are arbitrary data, and may even have a custom format
2565 // through user plugins.
2566 emitStackMaps();
2567
2568 // Print aliases in topological order, that is, for each alias a = b,
2569 // b must be printed before a.
2570 // This is because on some targets (e.g. PowerPC) linker expects aliases in
2571 // such an order to generate correct TOC information.
2574 for (const auto &Alias : M.aliases()) {
2575 if (Alias.hasAvailableExternallyLinkage())
2576 continue;
2577 for (const GlobalAlias *Cur = &Alias; Cur;
2578 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
2579 if (!AliasVisited.insert(Cur).second)
2580 break;
2581 AliasStack.push_back(Cur);
2582 }
2583 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
2584 emitGlobalAlias(M, *AncestorAlias);
2585 AliasStack.clear();
2586 }
2587
2588 // IFuncs must come before deubginfo in case the backend decides to emit them
2589 // as actual functions, since on Mach-O targets, we cannot create regular
2590 // sections after DWARF.
2591 for (const auto &IFunc : M.ifuncs())
2592 emitGlobalIFunc(M, IFunc);
2593
2594 // Finalize debug and EH information.
2595 for (auto &Handler : DebugHandlers)
2596 Handler->endModule();
2597 for (auto &Handler : Handlers)
2598 Handler->endModule();
2599
2600 // This deletes all the ephemeral handlers that AsmPrinter added, while
2601 // keeping all the user-added handlers alive until the AsmPrinter is
2602 // destroyed.
2603 Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
2605 DebugHandlers.end());
2606 DD = nullptr;
2607
2608 // If the target wants to know about weak references, print them all.
2609 if (MAI->getWeakRefDirective()) {
2610 // FIXME: This is not lazy, it would be nice to only print weak references
2611 // to stuff that is actually used. Note that doing so would require targets
2612 // to notice uses in operands (due to constant exprs etc). This should
2613 // happen with the MC stuff eventually.
2614
2615 // Print out module-level global objects here.
2616 for (const auto &GO : M.global_objects()) {
2617 if (!GO.hasExternalWeakLinkage())
2618 continue;
2619 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
2620 }
2622 auto SymbolName = "swift_async_extendedFramePointerFlags";
2623 auto Global = M.getGlobalVariable(SymbolName);
2624 if (!Global) {
2625 auto PtrTy = PointerType::getUnqual(M.getContext());
2626 Global = new GlobalVariable(M, PtrTy, false,
2628 SymbolName);
2629 OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
2630 }
2631 }
2632 }
2633
2634 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
2635 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
2636 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
2637 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(**--I))
2638 MP->finishAssembly(M, *MI, *this);
2639
2640 // Emit llvm.ident metadata in an '.ident' directive.
2641 emitModuleIdents(M);
2642
2643 // Emit bytes for llvm.commandline metadata.
2644 // The command line metadata is emitted earlier on XCOFF.
2646 emitModuleCommandLines(M);
2647
2648 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
2649 // split-stack is used.
2650 if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
2651 OutStreamer->switchSection(OutContext.getELFSection(".note.GNU-split-stack",
2652 ELF::SHT_PROGBITS, 0));
2653 if (HasNoSplitStack)
2654 OutStreamer->switchSection(OutContext.getELFSection(
2655 ".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
2656 }
2657
2658 // If we don't have any trampolines, then we don't require stack memory
2659 // to be executable. Some targets have a directive to declare this.
2660 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
2661 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
2663 OutStreamer->switchSection(S);
2664
2665 if (TM.Options.EmitAddrsig) {
2666 // Emit address-significance attributes for all globals.
2667 OutStreamer->emitAddrsig();
2668 for (const GlobalValue &GV : M.global_values()) {
2669 if (!GV.use_empty() && !GV.isThreadLocal() &&
2670 !GV.hasDLLImportStorageClass() &&
2671 !GV.getName().starts_with("llvm.") &&
2672 !GV.hasAtLeastLocalUnnamedAddr())
2673 OutStreamer->emitAddrsigSym(getSymbol(&GV));
2674 }
2675 }
2676
2677 // Emit symbol partition specifications (ELF only).
2679 unsigned UniqueID = 0;
2680 for (const GlobalValue &GV : M.global_values()) {
2681 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
2682 GV.getVisibility() != GlobalValue::DefaultVisibility)
2683 continue;
2684
2685 OutStreamer->switchSection(
2686 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
2687 "", false, ++UniqueID, nullptr));
2688 OutStreamer->emitBytes(GV.getPartition());
2689 OutStreamer->emitZeros(1);
2690 OutStreamer->emitValue(
2693 }
2694 }
2695
2696 // Allow the target to emit any magic that it wants at the end of the file,
2697 // after everything else has gone out.
2699
2700 MMI = nullptr;
2701 AddrLabelSymbols = nullptr;
2702
2703 OutStreamer->finish();
2704 OutStreamer->reset();
2705 OwnedMLI.reset();
2706 OwnedMDT.reset();
2707
2708 return false;
2709}
2710
2712 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionID());
2713 if (Res.second)
2714 Res.first->second = createTempSymbol("exception");
2715 return Res.first->second;
2716}
2717
2719 this->MF = &MF;
2720 const Function &F = MF.getFunction();
2721
2722 // Record that there are split-stack functions, so we will emit a special
2723 // section to tell the linker.
2724 if (MF.shouldSplitStack()) {
2725 HasSplitStack = true;
2726
2728 HasNoSplitStack = true;
2729 } else
2730 HasNoSplitStack = true;
2731
2732 // Get the function symbol.
2733 if (!MAI->needsFunctionDescriptors()) {
2735 } else {
2737 "Only AIX uses the function descriptor hooks.");
2738 // AIX is unique here in that the name of the symbol emitted for the
2739 // function body does not have the same name as the source function's
2740 // C-linkage name.
2741 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
2742 " initalized first.");
2743
2744 // Get the function entry point symbol.
2746 }
2747
2749 CurrentFnBegin = nullptr;
2750 CurrentFnBeginLocal = nullptr;
2751 CurrentSectionBeginSym = nullptr;
2752 MBBSectionRanges.clear();
2753 MBBSectionExceptionSyms.clear();
2754 bool NeedsLocalForSize = MAI->needsLocalForSize();
2755 if (F.hasFnAttribute("patchable-function-entry") ||
2756 F.hasFnAttribute("function-instrument") ||
2757 F.hasFnAttribute("xray-instruction-threshold") ||
2758 needFuncLabels(MF, *this) || NeedsLocalForSize ||
2761 CurrentFnBegin = createTempSymbol("func_begin");
2762 if (NeedsLocalForSize)
2764 }
2765
2766 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2767}
2768
2769namespace {
2770
2771// Keep track the alignment, constpool entries per Section.
2772 struct SectionCPs {
2773 MCSection *S;
2774 Align Alignment;
2776
2777 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
2778 };
2779
2780} // end anonymous namespace
2781
2782/// EmitConstantPool - Print to the current output stream assembly
2783/// representations of the constants in the constant pool MCP. This is
2784/// used to print out constants which have been "spilled to memory" by
2785/// the code generator.
2787 const MachineConstantPool *MCP = MF->getConstantPool();
2788 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
2789 if (CP.empty()) return;
2790
2791 // Calculate sections for constant pool entries. We collect entries to go into
2792 // the same section together to reduce amount of section switch statements.
2793 SmallVector<SectionCPs, 4> CPSections;
2794 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
2795 const MachineConstantPoolEntry &CPE = CP[i];
2796 Align Alignment = CPE.getAlign();
2797
2799
2800 const Constant *C = nullptr;
2801 if (!CPE.isMachineConstantPoolEntry())
2802 C = CPE.Val.ConstVal;
2803
2805 getDataLayout(), Kind, C, Alignment);
2806
2807 // The number of sections are small, just do a linear search from the
2808 // last section to the first.
2809 bool Found = false;
2810 unsigned SecIdx = CPSections.size();
2811 while (SecIdx != 0) {
2812 if (CPSections[--SecIdx].S == S) {
2813 Found = true;
2814 break;
2815 }
2816 }
2817 if (!Found) {
2818 SecIdx = CPSections.size();
2819 CPSections.push_back(SectionCPs(S, Alignment));
2820 }
2821
2822 if (Alignment > CPSections[SecIdx].Alignment)
2823 CPSections[SecIdx].Alignment = Alignment;
2824 CPSections[SecIdx].CPEs.push_back(i);
2825 }
2826
2827 // Now print stuff into the calculated sections.
2828 const MCSection *CurSection = nullptr;
2829 unsigned Offset = 0;
2830 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
2831 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
2832 unsigned CPI = CPSections[i].CPEs[j];
2833 MCSymbol *Sym = GetCPISymbol(CPI);
2834 if (!Sym->isUndefined())
2835 continue;
2836
2837 if (CurSection != CPSections[i].S) {
2838 OutStreamer->switchSection(CPSections[i].S);
2839 emitAlignment(Align(CPSections[i].Alignment));
2840 CurSection = CPSections[i].S;
2841 Offset = 0;
2842 }
2843
2844 MachineConstantPoolEntry CPE = CP[CPI];
2845
2846 // Emit inter-object padding for alignment.
2847 unsigned NewOffset = alignTo(Offset, CPE.getAlign());
2848 OutStreamer->emitZeros(NewOffset - Offset);
2849
2850 Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
2851
2852 OutStreamer->emitLabel(Sym);
2855 else
2857 }
2858 }
2859}
2860
2861// Print assembly representations of the jump tables used by the current
2862// function.
2864 const DataLayout &DL = MF->getDataLayout();
2865 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2866 if (!MJTI) return;
2867 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
2868 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2869 if (JT.empty()) return;
2870
2871 // Pick the directive to use to print the jump table entries, and switch to
2872 // the appropriate section.
2873 const Function &F = MF->getFunction();
2875 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
2878 F);
2879 if (JTInDiffSection) {
2880 // Drop it in the readonly section.
2881 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
2882 OutStreamer->switchSection(ReadOnlySection);
2883 }
2884
2886
2887 // Jump tables in code sections are marked with a data_region directive
2888 // where that's supported.
2889 if (!JTInDiffSection)
2890 OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
2891
2892 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2893 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2894
2895 // If this jump table was deleted, ignore it.
2896 if (JTBBs.empty()) continue;
2897
2898 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2899 /// emit a .set directive for each unique entry.
2905 for (const MachineBasicBlock *MBB : JTBBs) {
2906 if (!EmittedSets.insert(MBB).second)
2907 continue;
2908
2909 // .set LJTSet, LBB32-base
2910 const MCExpr *LHS =
2912 OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
2914 OutContext));
2915 }
2916 }
2917
2918 // On some targets (e.g. Darwin) we want to emit two consecutive labels
2919 // before each jump table. The first label is never referenced, but tells
2920 // the assembler and linker the extents of the jump table object. The
2921 // second label is actually referenced by the code.
2922 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
2923 // FIXME: This doesn't have to have any specific name, just any randomly
2924 // named and numbered local label started with 'l' would work. Simplify
2925 // GetJTISymbol.
2926 OutStreamer->emitLabel(GetJTISymbol(JTI, true));
2927
2928 MCSymbol* JTISymbol = GetJTISymbol(JTI);
2929 OutStreamer->emitLabel(JTISymbol);
2930
2931 // Defer MCAssembler based constant folding due to a performance issue. The
2932 // label differences will be evaluated at write time.
2933 for (const MachineBasicBlock *MBB : JTBBs)
2934 emitJumpTableEntry(MJTI, MBB, JTI);
2935 }
2936
2938 emitJumpTableSizesSection(MJTI, F);
2939
2940 if (!JTInDiffSection)
2941 OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
2942}
2943
2944void AsmPrinter::emitJumpTableSizesSection(const MachineJumpTableInfo *MJTI,
2945 const Function &F) const {
2946 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2947
2948 if (JT.empty())
2949 return;
2950
2951 StringRef GroupName = F.hasComdat() ? F.getComdat()->getName() : "";
2952 MCSection *JumpTableSizesSection = nullptr;
2953 StringRef sectionName = ".llvm_jump_table_sizes";
2954
2955 bool isElf = TM.getTargetTriple().isOSBinFormatELF();
2956 bool isCoff = TM.getTargetTriple().isOSBinFormatCOFF();
2957
2958 if (!isCoff && !isElf)
2959 return;
2960
2961 if (isElf) {
2962 MCSymbolELF *LinkedToSym = dyn_cast<MCSymbolELF>(CurrentFnSym);
2963 int Flags = F.hasComdat() ? static_cast<int>(ELF::SHF_GROUP) : 0;
2964
2965 JumpTableSizesSection = OutContext.getELFSection(
2966 sectionName, ELF::SHT_LLVM_JT_SIZES, Flags, 0, GroupName, F.hasComdat(),
2967 MCSection::NonUniqueID, LinkedToSym);
2968 } else if (isCoff) {
2969 if (F.hasComdat()) {
2970 JumpTableSizesSection = OutContext.getCOFFSection(
2971 sectionName,
2974 F.getComdat()->getName(), COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
2975 } else {
2976 JumpTableSizesSection = OutContext.getCOFFSection(
2980 }
2981 }
2982
2983 OutStreamer->switchSection(JumpTableSizesSection);
2984
2985 for (unsigned JTI = 0, E = JT.size(); JTI != E; ++JTI) {
2986 const std::vector<MachineBasicBlock *> &JTBBs = JT[JTI].MBBs;
2987 OutStreamer->emitSymbolValue(GetJTISymbol(JTI), TM.getProgramPointerSize());
2988 OutStreamer->emitIntValue(JTBBs.size(), TM.getProgramPointerSize());
2989 }
2990}
2991
2992/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2993/// current stream.
2994void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
2995 const MachineBasicBlock *MBB,
2996 unsigned UID) const {
2997 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
2998 const MCExpr *Value = nullptr;
2999 switch (MJTI->getEntryKind()) {
3001 llvm_unreachable("Cannot emit EK_Inline jump table entry");
3004 MJTI, MBB, UID, OutContext);
3005 break;
3007 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
3008 // .word LBB123
3010 break;
3012 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
3013 // with a relocation as gp-relative, e.g.:
3014 // .gprel32 LBB123
3015 MCSymbol *MBBSym = MBB->getSymbol();
3016 OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
3017 return;
3018 }
3019
3021 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
3022 // with a relocation as gp-relative, e.g.:
3023 // .gpdword LBB123
3024 MCSymbol *MBBSym = MBB->getSymbol();
3025 OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
3026 return;
3027 }
3028
3031 // Each entry is the address of the block minus the address of the jump
3032 // table. This is used for PIC jump tables where gprel32 is not supported.
3033 // e.g.:
3034 // .word LBB123 - LJTI1_2
3035 // If the .set directive avoids relocations, this is emitted as:
3036 // .set L4_5_set_123, LBB123 - LJTI1_2
3037 // .word L4_5_set_123
3041 OutContext);
3042 break;
3043 }
3048 break;
3049 }
3050 }
3051
3052 assert(Value && "Unknown entry kind!");
3053
3054 unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
3055 OutStreamer->emitValue(Value, EntrySize);
3056}
3057
3058/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
3059/// special global used by LLVM. If so, emit it and return true, otherwise
3060/// do nothing and return false.
3062 if (GV->getName() == "llvm.used") {
3063 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
3064 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
3065 return true;
3066 }
3067
3068 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
3069 if (GV->getSection() == "llvm.metadata" ||
3071 return true;
3072
3073 if (GV->getName() == "llvm.arm64ec.symbolmap") {
3074 // For ARM64EC, print the table that maps between symbols and the
3075 // corresponding thunks to translate between x64 and AArch64 code.
3076 // This table is generated by AArch64Arm64ECCallLowering.
3077 OutStreamer->switchSection(
3079 auto *Arr = cast<ConstantArray>(GV->getInitializer());
3080 for (auto &U : Arr->operands()) {
3081 auto *C = cast<Constant>(U);
3082 auto *Src = cast<GlobalValue>(C->getOperand(0)->stripPointerCasts());
3083 auto *Dst = cast<GlobalValue>(C->getOperand(1)->stripPointerCasts());
3084 int Kind = cast<ConstantInt>(C->getOperand(2))->getZExtValue();
3085
3086 if (Src->hasDLLImportStorageClass()) {
3087 // For now, we assume dllimport functions aren't directly called.
3088 // (We might change this later to match MSVC.)
3089 OutStreamer->emitCOFFSymbolIndex(
3090 OutContext.getOrCreateSymbol("__imp_" + Src->getName()));
3091 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3092 OutStreamer->emitInt32(Kind);
3093 } else {
3094 // FIXME: For non-dllimport functions, MSVC emits the same entry
3095 // twice, for reasons I don't understand. I have to assume the linker
3096 // ignores the redundant entry; there aren't any reasonable semantics
3097 // to attach to it.
3098 OutStreamer->emitCOFFSymbolIndex(getSymbol(Src));
3099 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3100 OutStreamer->emitInt32(Kind);
3101 }
3102 }
3103 return true;
3104 }
3105
3106 if (!GV->hasAppendingLinkage()) return false;
3107
3108 assert(GV->hasInitializer() && "Not a special LLVM global!");
3109
3110 if (GV->getName() == "llvm.global_ctors") {
3112 /* isCtor */ true);
3113
3114 return true;
3115 }
3116
3117 if (GV->getName() == "llvm.global_dtors") {
3119 /* isCtor */ false);
3120
3121 return true;
3122 }
3123
3124 report_fatal_error("unknown special variable with appending linkage");
3125}
3126
3127/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
3128/// global in the specified llvm.used list.
3129void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
3130 // Should be an array of 'i8*'.
3131 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
3132 const GlobalValue *GV =
3133 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
3134 if (GV)
3135 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
3136 }
3137}
3138
3140 const Constant *List,
3141 SmallVector<Structor, 8> &Structors) {
3142 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
3143 // the init priority.
3144 if (!isa<ConstantArray>(List))
3145 return;
3146
3147 // Gather the structors in a form that's convenient for sorting by priority.
3148 for (Value *O : cast<ConstantArray>(List)->operands()) {
3149 auto *CS = cast<ConstantStruct>(O);
3150 if (CS->getOperand(1)->isNullValue())
3151 break; // Found a null terminator, skip the rest.
3152 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
3153 if (!Priority)
3154 continue; // Malformed.
3155 Structors.push_back(Structor());
3156 Structor &S = Structors.back();
3157 S.Priority = Priority->getLimitedValue(65535);
3158 S.Func = CS->getOperand(1);
3159 if (!CS->getOperand(2)->isNullValue()) {
3160 if (TM.getTargetTriple().isOSAIX())
3162 "associated data of XXStructor list is not yet supported on AIX");
3163 S.ComdatKey =
3164 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
3165 }
3166 }
3167
3168 // Emit the function pointers in the target-specific order
3169 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
3170 return L.Priority < R.Priority;
3171 });
3172}
3173
3174/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
3175/// priority.
3177 bool IsCtor) {
3178 SmallVector<Structor, 8> Structors;
3179 preprocessXXStructorList(DL, List, Structors);
3180 if (Structors.empty())
3181 return;
3182
3183 // Emit the structors in reverse order if we are using the .ctor/.dtor
3184 // initialization scheme.
3185 if (!TM.Options.UseInitArray)
3186 std::reverse(Structors.begin(), Structors.end());
3187
3188 const Align Align = DL.getPointerPrefAlignment();
3189 for (Structor &S : Structors) {
3191 const MCSymbol *KeySym = nullptr;
3192 if (GlobalValue *GV = S.ComdatKey) {
3193 if (GV->isDeclarationForLinker())
3194 // If the associated variable is not defined in this module
3195 // (it might be available_externally, or have been an
3196 // available_externally definition that was dropped by the
3197 // EliminateAvailableExternally pass), some other TU
3198 // will provide its dynamic initializer.
3199 continue;
3200
3201 KeySym = getSymbol(GV);
3202 }
3203
3204 MCSection *OutputSection =
3205 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
3206 : Obj.getStaticDtorSection(S.Priority, KeySym));
3207 OutStreamer->switchSection(OutputSection);
3208 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
3210 emitXXStructor(DL, S.Func);
3211 }
3212}
3213
3214void AsmPrinter::emitModuleIdents(Module &M) {
3215 if (!MAI->hasIdentDirective())
3216 return;
3217
3218 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
3219 for (const MDNode *N : NMD->operands()) {
3220 assert(N->getNumOperands() == 1 &&
3221 "llvm.ident metadata entry can have only one operand");
3222 const MDString *S = cast<MDString>(N->getOperand(0));
3223 OutStreamer->emitIdent(S->getString());
3224 }
3225 }
3226}
3227
3228void AsmPrinter::emitModuleCommandLines(Module &M) {
3230 if (!CommandLine)
3231 return;
3232
3233 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3234 if (!NMD || !NMD->getNumOperands())
3235 return;
3236
3237 OutStreamer->pushSection();
3238 OutStreamer->switchSection(CommandLine);
3239 OutStreamer->emitZeros(1);
3240 for (const MDNode *N : NMD->operands()) {
3241 assert(N->getNumOperands() == 1 &&
3242 "llvm.commandline metadata entry can have only one operand");
3243 const MDString *S = cast<MDString>(N->getOperand(0));
3244 OutStreamer->emitBytes(S->getString());
3245 OutStreamer->emitZeros(1);
3246 }
3247 OutStreamer->popSection();
3248}
3249
3250//===--------------------------------------------------------------------===//
3251// Emission and print routines
3252//
3253
3254/// Emit a byte directive and value.
3255///
3256void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
3257
3258/// Emit a short directive and value.
3259void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
3260
3261/// Emit a long directive and value.
3262void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
3263
3264/// EmitSLEB128 - emit the specified signed leb128 value.
3265void AsmPrinter::emitSLEB128(int64_t Value, const char *Desc) const {
3266 if (isVerbose() && Desc)
3267 OutStreamer->AddComment(Desc);
3268
3269 OutStreamer->emitSLEB128IntValue(Value);
3270}
3271
3273 unsigned PadTo) const {
3274 if (isVerbose() && Desc)
3275 OutStreamer->AddComment(Desc);
3276
3277 OutStreamer->emitULEB128IntValue(Value, PadTo);
3278}
3279
3280/// Emit a long long directive and value.
3282 OutStreamer->emitInt64(Value);
3283}
3284
3285/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
3286/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
3287/// .set if it avoids relocations.
3289 unsigned Size) const {
3290 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
3291}
3292
3293/// Emit something like ".uleb128 Hi-Lo".
3295 const MCSymbol *Lo) const {
3296 OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
3297}
3298
3299/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
3300/// where the size in bytes of the directive is specified by Size and Label
3301/// specifies the label. This implicitly uses .set if it is available.
3303 unsigned Size,
3304 bool IsSectionRelative) const {
3305 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
3306 OutStreamer->emitCOFFSecRel32(Label, Offset);
3307 if (Size > 4)
3308 OutStreamer->emitZeros(Size - 4);
3309 return;
3310 }
3311
3312 // Emit Label+Offset (or just Label if Offset is zero)
3313 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
3314 if (Offset)
3317
3318 OutStreamer->emitValue(Expr, Size);
3319}
3320
3321//===----------------------------------------------------------------------===//
3322
3323// EmitAlignment - Emit an alignment directive to the specified power of
3324// two boundary. If a global value is specified, and if that global has
3325// an explicit alignment requested, it will override the alignment request
3326// if required for correctness.
3328 unsigned MaxBytesToEmit) const {
3329 if (GV)
3330 Alignment = getGVAlignment(GV, GV->getDataLayout(), Alignment);
3331
3332 if (Alignment == Align(1))
3333 return; // 1-byte aligned: no need to emit alignment.
3334
3335 if (getCurrentSection()->isText()) {
3336 const MCSubtargetInfo *STI = nullptr;
3337 if (this->MF)
3338 STI = &getSubtargetInfo();
3339 else
3340 STI = TM.getMCSubtargetInfo();
3341 OutStreamer->emitCodeAlignment(Alignment, STI, MaxBytesToEmit);
3342 } else
3343 OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
3344}
3345
3346//===----------------------------------------------------------------------===//
3347// Constant emission.
3348//===----------------------------------------------------------------------===//
3349
3351 MCContext &Ctx = OutContext;
3352
3353 if (CV->isNullValue() || isa<UndefValue>(CV))
3354 return MCConstantExpr::create(0, Ctx);
3355
3356 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
3357 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
3358
3359 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV))
3360 return lowerConstantPtrAuth(*CPA);
3361
3362 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
3363 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
3364
3365 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
3366 return lowerBlockAddressConstant(*BA);
3367
3368 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
3370
3371 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
3372 return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
3373
3374 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
3375 if (!CE) {
3376 llvm_unreachable("Unknown constant value to lower!");
3377 }
3378
3379 // The constant expression opcodes are limited to those that are necessary
3380 // to represent relocations on supported targets. Expressions involving only
3381 // constant addresses are constant folded instead.
3382 switch (CE->getOpcode()) {
3383 default:
3384 break; // Error
3385 case Instruction::AddrSpaceCast: {
3386 const Constant *Op = CE->getOperand(0);
3387 unsigned DstAS = CE->getType()->getPointerAddressSpace();
3388 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
3389 if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
3390 return lowerConstant(Op);
3391
3392 break; // Error
3393 }
3394 case Instruction::GetElementPtr: {
3395 // Generate a symbolic expression for the byte address
3396 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
3397 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
3398
3399 const MCExpr *Base = lowerConstant(CE->getOperand(0));
3400 if (!OffsetAI)
3401 return Base;
3402
3403 int64_t Offset = OffsetAI.getSExtValue();
3405 Ctx);
3406 }
3407
3408 case Instruction::Trunc:
3409 // We emit the value and depend on the assembler to truncate the generated
3410 // expression properly. This is important for differences between
3411 // blockaddress labels. Since the two labels are in the same function, it
3412 // is reasonable to treat their delta as a 32-bit value.
3413 [[fallthrough]];
3414 case Instruction::BitCast:
3415 return lowerConstant(CE->getOperand(0));
3416
3417 case Instruction::IntToPtr: {
3418 const DataLayout &DL = getDataLayout();
3419
3420 // Handle casts to pointers by changing them into casts to the appropriate
3421 // integer type. This promotes constant folding and simplifies this code.
3422 Constant *Op = CE->getOperand(0);
3423 Op = ConstantFoldIntegerCast(Op, DL.getIntPtrType(CV->getType()),
3424 /*IsSigned*/ false, DL);
3425 if (Op)
3426 return lowerConstant(Op);
3427
3428 break; // Error
3429 }
3430
3431 case Instruction::PtrToInt: {
3432 const DataLayout &DL = getDataLayout();
3433
3434 // Support only foldable casts to/from pointers that can be eliminated by
3435 // changing the pointer to the appropriately sized integer type.
3436 Constant *Op = CE->getOperand(0);
3437 Type *Ty = CE->getType();
3438
3439 const MCExpr *OpExpr = lowerConstant(Op);
3440
3441 // We can emit the pointer value into this slot if the slot is an
3442 // integer slot equal to the size of the pointer.
3443 //
3444 // If the pointer is larger than the resultant integer, then
3445 // as with Trunc just depend on the assembler to truncate it.
3446 if (DL.getTypeAllocSize(Ty).getFixedValue() <=
3447 DL.getTypeAllocSize(Op->getType()).getFixedValue())
3448 return OpExpr;
3449
3450 break; // Error
3451 }
3452
3453 case Instruction::Sub: {
3454 GlobalValue *LHSGV;
3455 APInt LHSOffset;
3456 DSOLocalEquivalent *DSOEquiv;
3457 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
3458 getDataLayout(), &DSOEquiv)) {
3459 GlobalValue *RHSGV;
3460 APInt RHSOffset;
3461 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
3462 getDataLayout())) {
3463 const MCExpr *RelocExpr =
3465 if (!RelocExpr) {
3466 const MCExpr *LHSExpr =
3468 if (DSOEquiv &&
3469 getObjFileLowering().supportDSOLocalEquivalentLowering())
3470 LHSExpr =
3472 RelocExpr = MCBinaryExpr::createSub(
3473 LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
3474 }
3475 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
3476 if (Addend != 0)
3477 RelocExpr = MCBinaryExpr::createAdd(
3478 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
3479 return RelocExpr;
3480 }
3481 }
3482
3483 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
3484 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
3485 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
3486 break;
3487 }
3488
3489 case Instruction::Add: {
3490 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
3491 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
3492 return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
3493 }
3494 }
3495
3496 // If the code isn't optimized, there may be outstanding folding
3497 // opportunities. Attempt to fold the expression using DataLayout as a
3498 // last resort before giving up.
3500 if (C != CE)
3501 return lowerConstant(C);
3502
3503 // Otherwise report the problem to the user.
3504 std::string S;
3506 OS << "Unsupported expression in static initializer: ";
3507 CE->printAsOperand(OS, /*PrintType=*/false,
3508 !MF ? nullptr : MF->getFunction().getParent());
3510}
3511
3512static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
3513 AsmPrinter &AP,
3514 const Constant *BaseCV = nullptr,
3515 uint64_t Offset = 0,
3516 AsmPrinter::AliasMapTy *AliasList = nullptr);
3517
3518static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
3519static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
3520
3521/// isRepeatedByteSequence - Determine whether the given value is
3522/// composed of a repeated sequence of identical bytes and return the
3523/// byte value. If it is not a repeated sequence, return -1.
3525 StringRef Data = V->getRawDataValues();
3526 assert(!Data.empty() && "Empty aggregates should be CAZ node");
3527 char C = Data[0];
3528 for (unsigned i = 1, e = Data.size(); i != e; ++i)
3529 if (Data[i] != C) return -1;
3530 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
3531}
3532
3533/// isRepeatedByteSequence - Determine whether the given value is
3534/// composed of a repeated sequence of identical bytes and return the
3535/// byte value. If it is not a repeated sequence, return -1.
3536static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
3537 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3538 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
3539 assert(Size % 8 == 0);
3540
3541 // Extend the element to take zero padding into account.
3542 APInt Value = CI->getValue().zext(Size);
3543 if (!Value.isSplat(8))
3544 return -1;
3545
3546 return Value.zextOrTrunc(8).getZExtValue();
3547 }
3548 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
3549 // Make sure all array elements are sequences of the same repeated
3550 // byte.
3551 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
3552 Constant *Op0 = CA->getOperand(0);
3553 int Byte = isRepeatedByteSequence(Op0, DL);
3554 if (Byte == -1)
3555 return -1;
3556
3557 // All array elements must be equal.
3558 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
3559 if (CA->getOperand(i) != Op0)
3560 return -1;
3561 return Byte;
3562 }
3563
3564 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
3565 return isRepeatedByteSequence(CDS);
3566
3567 return -1;
3568}
3569
3571 AsmPrinter::AliasMapTy *AliasList) {
3572 if (AliasList) {
3573 auto AliasIt = AliasList->find(Offset);
3574 if (AliasIt != AliasList->end()) {
3575 for (const GlobalAlias *GA : AliasIt->second)
3576 AP.OutStreamer->emitLabel(AP.getSymbol(GA));
3577 AliasList->erase(Offset);
3578 }
3579 }
3580}
3581
3583 const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
3584 AsmPrinter::AliasMapTy *AliasList) {
3585 // See if we can aggregate this into a .fill, if so, emit it as such.
3586 int Value = isRepeatedByteSequence(CDS, DL);
3587 if (Value != -1) {
3588 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
3589 // Don't emit a 1-byte object as a .fill.
3590 if (Bytes > 1)
3591 return AP.OutStreamer->emitFill(Bytes, Value);
3592 }
3593
3594 // If this can be emitted with .ascii/.asciz, emit it as such.
3595 if (CDS->isString())
3596 return AP.OutStreamer->emitBytes(CDS->getAsString());
3597
3598 // Otherwise, emit the values in successive locations.
3599 unsigned ElementByteSize = CDS->getElementByteSize();
3600 if (isa<IntegerType>(CDS->getElementType())) {
3601 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
3602 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
3603 if (AP.isVerbose())
3604 AP.OutStreamer->getCommentOS()
3605 << format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
3606 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
3607 ElementByteSize);
3608 }
3609 } else {
3610 Type *ET = CDS->getElementType();
3611 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
3612 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
3614 }
3615 }
3616
3617 unsigned Size = DL.getTypeAllocSize(CDS->getType());
3618 unsigned EmittedSize =
3619 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
3620 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
3621 if (unsigned Padding = Size - EmittedSize)
3622 AP.OutStreamer->emitZeros(Padding);
3623}
3624
3626 const ConstantArray *CA, AsmPrinter &AP,
3627 const Constant *BaseCV, uint64_t Offset,
3628 AsmPrinter::AliasMapTy *AliasList) {
3629 // See if we can aggregate some values. Make sure it can be
3630 // represented as a series of bytes of the constant value.
3631 int Value = isRepeatedByteSequence(CA, DL);
3632
3633 if (Value != -1) {
3634 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
3635 AP.OutStreamer->emitFill(Bytes, Value);
3636 } else {
3637 for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
3638 emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
3639 AliasList);
3640 Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
3641 }
3642 }
3643}
3644
3645static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
3646
3647static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV,
3648 AsmPrinter &AP,
3649 AsmPrinter::AliasMapTy *AliasList) {
3650 auto *VTy = cast<FixedVectorType>(CV->getType());
3651 Type *ElementType = VTy->getElementType();
3652 uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
3653 uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
3654 uint64_t EmittedSize;
3655 if (ElementSizeInBits != ElementAllocSizeInBits) {
3656 // If the allocation size of an element is different from the size in bits,
3657 // printing each element separately will insert incorrect padding.
3658 //
3659 // The general algorithm here is complicated; instead of writing it out
3660 // here, just use the existing code in ConstantFolding.
3661 Type *IntT =
3662 IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
3663 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(ConstantFoldConstant(
3664 ConstantExpr::getBitCast(const_cast<Constant *>(CV), IntT), DL));
3665 if (!CI) {
3667 "Cannot lower vector global with unusual element type");
3668 }
3669 emitGlobalAliasInline(AP, 0, AliasList);
3671 EmittedSize = DL.getTypeStoreSize(CV->getType());
3672 } else {
3673 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
3674 emitGlobalAliasInline(AP, DL.getTypeAllocSize(CV->getType()) * I, AliasList);
3676 }
3677 EmittedSize = DL.getTypeAllocSize(ElementType) * VTy->getNumElements();
3678 }
3679
3680 unsigned Size = DL.getTypeAllocSize(CV->getType());
3681 if (unsigned Padding = Size - EmittedSize)
3682 AP.OutStreamer->emitZeros(Padding);
3683}
3684
3686 const ConstantStruct *CS, AsmPrinter &AP,
3687 const Constant *BaseCV, uint64_t Offset,
3688 AsmPrinter::AliasMapTy *AliasList) {
3689 // Print the fields in successive locations. Pad to align if needed!
3690 uint64_t Size = DL.getTypeAllocSize(CS->getType());
3691 const StructLayout *Layout = DL.getStructLayout(CS->getType());
3692 uint64_t SizeSoFar = 0;
3693 for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
3694 const Constant *Field = CS->getOperand(I);
3695
3696 // Print the actual field value.
3697 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
3698 AliasList);
3699
3700 // Check if padding is needed and insert one or more 0s.
3701 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
3702 uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
3703 Layout->getElementOffset(I)) -
3704 FieldSize;
3705 SizeSoFar += FieldSize + PadSize;
3706
3707 // Insert padding - this may include padding to increase the size of the
3708 // current field up to the ABI size (if the struct is not packed) as well
3709 // as padding to ensure that the next field starts at the right offset.
3710 AP.OutStreamer->emitZeros(PadSize);
3711 }
3712 assert(SizeSoFar == Layout->getSizeInBytes() &&
3713 "Layout of constant struct may be incorrect!");
3714}
3715
3716static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
3717 assert(ET && "Unknown float type");
3718 APInt API = APF.bitcastToAPInt();
3719
3720 // First print a comment with what we think the original floating-point value
3721 // should have been.
3722 if (AP.isVerbose()) {
3723 SmallString<8> StrVal;
3724 APF.toString(StrVal);
3725 ET->print(AP.OutStreamer->getCommentOS());
3726 AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
3727 }
3728
3729 // Now iterate through the APInt chunks, emitting them in endian-correct
3730 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
3731 // floats).
3732 unsigned NumBytes = API.getBitWidth() / 8;
3733 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
3734 const uint64_t *p = API.getRawData();
3735
3736 // PPC's long double has odd notions of endianness compared to how LLVM
3737 // handles it: p[0] goes first for *big* endian on PPC.
3738 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
3739 int Chunk = API.getNumWords() - 1;
3740
3741 if (TrailingBytes)
3742 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
3743
3744 for (; Chunk >= 0; --Chunk)
3745 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
3746 } else {
3747 unsigned Chunk;
3748 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
3749 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
3750
3751 if (TrailingBytes)
3752 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
3753 }
3754
3755 // Emit the tail padding for the long double.
3756 const DataLayout &DL = AP.getDataLayout();
3757 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
3758}
3759
3760static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
3761 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
3762}
3763
3765 const DataLayout &DL = AP.getDataLayout();
3766 unsigned BitWidth = CI->getBitWidth();
3767
3768 // Copy the value as we may massage the layout for constants whose bit width
3769 // is not a multiple of 64-bits.
3770 APInt Realigned(CI->getValue());
3771 uint64_t ExtraBits = 0;
3772 unsigned ExtraBitsSize = BitWidth & 63;
3773
3774 if (ExtraBitsSize) {
3775 // The bit width of the data is not a multiple of 64-bits.
3776 // The extra bits are expected to be at the end of the chunk of the memory.
3777 // Little endian:
3778 // * Nothing to be done, just record the extra bits to emit.
3779 // Big endian:
3780 // * Record the extra bits to emit.
3781 // * Realign the raw data to emit the chunks of 64-bits.
3782 if (DL.isBigEndian()) {
3783 // Basically the structure of the raw data is a chunk of 64-bits cells:
3784 // 0 1 BitWidth / 64
3785 // [chunk1][chunk2] ... [chunkN].
3786 // The most significant chunk is chunkN and it should be emitted first.
3787 // However, due to the alignment issue chunkN contains useless bits.
3788 // Realign the chunks so that they contain only useful information:
3789 // ExtraBits 0 1 (BitWidth / 64) - 1
3790 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
3791 ExtraBitsSize = alignTo(ExtraBitsSize, 8);
3792 ExtraBits = Realigned.getRawData()[0] &
3793 (((uint64_t)-1) >> (64 - ExtraBitsSize));
3794 if (BitWidth >= 64)
3795 Realigned.lshrInPlace(ExtraBitsSize);
3796 } else
3797 ExtraBits = Realigned.getRawData()[BitWidth / 64];
3798 }
3799
3800 // We don't expect assemblers to support integer data directives
3801 // for more than 64 bits, so we emit the data in at most 64-bit
3802 // quantities at a time.
3803 const uint64_t *RawData = Realigned.getRawData();
3804 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
3805 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
3806 AP.OutStreamer->emitIntValue(Val, 8);
3807 }
3808
3809 if (ExtraBitsSize) {
3810 // Emit the extra bits after the 64-bits chunks.
3811
3812 // Emit a directive that fills the expected size.
3814 Size -= (BitWidth / 64) * 8;
3815 assert(Size && Size * 8 >= ExtraBitsSize &&
3816 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
3817 == ExtraBits && "Directive too small for extra bits.");
3818 AP.OutStreamer->emitIntValue(ExtraBits, Size);
3819 }
3820}
3821
3822/// Transform a not absolute MCExpr containing a reference to a GOT
3823/// equivalent global, by a target specific GOT pc relative access to the
3824/// final symbol.
3826 const Constant *BaseCst,
3827 uint64_t Offset) {
3828 // The global @foo below illustrates a global that uses a got equivalent.
3829 //
3830 // @bar = global i32 42
3831 // @gotequiv = private unnamed_addr constant i32* @bar
3832 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
3833 // i64 ptrtoint (i32* @foo to i64))
3834 // to i32)
3835 //
3836 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
3837 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
3838 // form:
3839 //
3840 // foo = cstexpr, where
3841 // cstexpr := <gotequiv> - "." + <cst>
3842 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
3843 //
3844 // After canonicalization by evaluateAsRelocatable `ME` turns into:
3845 //
3846 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
3847 // gotpcrelcst := <offset from @foo base> + <cst>
3848 MCValue MV;
3849 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
3850 return;
3851 const MCSymbolRefExpr *SymA = MV.getSymA();
3852 if (!SymA)
3853 return;
3854
3855 // Check that GOT equivalent symbol is cached.
3856 const MCSymbol *GOTEquivSym = &SymA->getSymbol();
3857 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
3858 return;
3859
3860 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
3861 if (!BaseGV)
3862 return;
3863
3864 // Check for a valid base symbol
3865 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
3866 const MCSymbolRefExpr *SymB = MV.getSymB();
3867
3868 if (!SymB || BaseSym != &SymB->getSymbol())
3869 return;
3870
3871 // Make sure to match:
3872 //
3873 // gotpcrelcst := <offset from @foo base> + <cst>
3874 //
3875 int64_t GOTPCRelCst = Offset + MV.getConstant();
3876 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
3877 return;
3878
3879 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
3880 //
3881 // bar:
3882 // .long 42
3883 // gotequiv:
3884 // .quad bar
3885 // foo:
3886 // .long gotequiv - "." + <cst>
3887 //
3888 // is replaced by the target specific equivalent to:
3889 //
3890 // bar:
3891 // .long 42
3892 // foo:
3893 // .long bar@GOTPCREL+<gotpcrelcst>
3894 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
3895 const GlobalVariable *GV = Result.first;
3896 int NumUses = (int)Result.second;
3897 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
3898 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
3900 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
3901
3902 // Update GOT equivalent usage information
3903 --NumUses;
3904 if (NumUses >= 0)
3905 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
3906}
3907
3908static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
3909 AsmPrinter &AP, const Constant *BaseCV,
3911 AsmPrinter::AliasMapTy *AliasList) {
3912 assert((!AliasList || AP.TM.getTargetTriple().isOSBinFormatXCOFF()) &&
3913 "AliasList only expected for XCOFF");
3914 emitGlobalAliasInline(AP, Offset, AliasList);
3915 uint64_t Size = DL.getTypeAllocSize(CV->getType());
3916
3917 // Globals with sub-elements such as combinations of arrays and structs
3918 // are handled recursively by emitGlobalConstantImpl. Keep track of the
3919 // constant symbol base and the current position with BaseCV and Offset.
3920 if (!BaseCV && CV->hasOneUse())
3921 BaseCV = dyn_cast<Constant>(CV->user_back());
3922
3923 if (isa<ConstantAggregateZero>(CV)) {
3924 StructType *structType;
3925 if (AliasList && (structType = llvm::dyn_cast<StructType>(CV->getType()))) {
3926 // Handle cases of aliases to direct struct elements
3927 const StructLayout *Layout = DL.getStructLayout(structType);
3928 uint64_t SizeSoFar = 0;
3929 for (unsigned int i = 0, n = structType->getNumElements(); i < n - 1;
3930 ++i) {
3931 uint64_t GapToNext = Layout->getElementOffset(i + 1) - SizeSoFar;
3932 AP.OutStreamer->emitZeros(GapToNext);
3933 SizeSoFar += GapToNext;
3934 emitGlobalAliasInline(AP, Offset + SizeSoFar, AliasList);
3935 }
3936 AP.OutStreamer->emitZeros(Size - SizeSoFar);
3937 return;
3938 } else {
3939 return AP.OutStreamer->emitZeros(Size);
3940 }
3941 }
3942
3943 if (isa<UndefValue>(CV))
3944 return AP.OutStreamer->emitZeros(Size);
3945
3946 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
3947 if (isa<VectorType>(CV->getType()))
3948 return emitGlobalConstantVector(DL, CV, AP, AliasList);
3949
3950 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
3951 if (StoreSize <= 8) {
3952 if (AP.isVerbose())
3953 AP.OutStreamer->getCommentOS()
3954 << format("0x%" PRIx64 "\n", CI->getZExtValue());
3955 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
3956 } else {
3958 }
3959
3960 // Emit tail padding if needed
3961 if (Size != StoreSize)
3962 AP.OutStreamer->emitZeros(Size - StoreSize);
3963
3964 return;
3965 }
3966
3967 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
3968 if (isa<VectorType>(CV->getType()))
3969 return emitGlobalConstantVector(DL, CV, AP, AliasList);
3970 else
3971 return emitGlobalConstantFP(CFP, AP);
3972 }
3973
3974 if (isa<ConstantPointerNull>(CV)) {
3975 AP.OutStreamer->emitIntValue(0, Size);
3976 return;
3977 }
3978
3979 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
3980 return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
3981
3982 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
3983 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
3984
3985 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
3986 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
3987
3988 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
3989 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
3990 // vectors).
3991 if (CE->getOpcode() == Instruction::BitCast)
3992 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
3993
3994 if (Size > 8) {
3995 // If the constant expression's size is greater than 64-bits, then we have
3996 // to emit the value in chunks. Try to constant fold the value and emit it
3997 // that way.
3998 Constant *New = ConstantFoldConstant(CE, DL);
3999 if (New != CE)
4000 return emitGlobalConstantImpl(DL, New, AP);
4001 }
4002 }
4003
4004 if (isa<ConstantVector>(CV))
4005 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4006
4007 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
4008 // thread the streamer with EmitValue.
4009 const MCExpr *ME = AP.lowerConstant(CV);
4010
4011 // Since lowerConstant already folded and got rid of all IR pointer and
4012 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
4013 // directly.
4015 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
4016
4017 AP.OutStreamer->emitValue(ME, Size);
4018}
4019
4020/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
4022 AliasMapTy *AliasList) {
4023 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4024 if (Size)
4025 emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
4026 else if (MAI->hasSubsectionsViaSymbols()) {
4027 // If the global has zero size, emit a single byte so that two labels don't
4028 // look like they are at the same location.
4029 OutStreamer->emitIntValue(0, 1);
4030 }
4031 if (!AliasList)
4032 return;
4033 // TODO: These remaining aliases are not emitted in the correct location. Need
4034 // to handle the case where the alias offset doesn't refer to any sub-element.
4035 for (auto &AliasPair : *AliasList) {
4036 for (const GlobalAlias *GA : AliasPair.second)
4037 OutStreamer->emitLabel(getSymbol(GA));
4038 }
4039}
4040
4042 // Target doesn't support this yet!
4043 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
4044}
4045
4047 if (Offset > 0)
4048 OS << '+' << Offset;
4049 else if (Offset < 0)
4050 OS << Offset;
4051}
4052
4053void AsmPrinter::emitNops(unsigned N) {
4055 for (; N; --N)
4057}
4058
4059//===----------------------------------------------------------------------===//
4060// Symbol Lowering Routines.
4061//===----------------------------------------------------------------------===//
4062
4064 return OutContext.createTempSymbol(Name, true);
4065}
4066
4068 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
4069 BA->getBasicBlock());
4070}
4071
4073 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
4074}
4075
4078}
4079
4080/// GetCPISymbol - Return the symbol for the specified constant pool entry.
4081MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
4082 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
4083 const MachineConstantPoolEntry &CPE =
4084 MF->getConstantPool()->getConstants()[CPID];
4085 if (!CPE.isMachineConstantPoolEntry()) {
4086 const DataLayout &DL = MF->getDataLayout();
4087 SectionKind Kind = CPE.getSectionKind(&DL);
4088 const Constant *C = CPE.Val.ConstVal;
4089 Align Alignment = CPE.Alignment;
4090 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
4091 getObjFileLowering().getSectionForConstant(DL, Kind, C,
4092 Alignment))) {
4093 if (MCSymbol *Sym = S->getCOMDATSymbol()) {
4094 if (Sym->isUndefined())
4095 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
4096 return Sym;
4097 }
4098 }
4099 }
4100 }
4101
4102 const DataLayout &DL = getDataLayout();
4103 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
4104 "CPI" + Twine(getFunctionNumber()) + "_" +
4105 Twine(CPID));
4106}
4107
4108/// GetJTISymbol - Return the symbol for the specified jump table entry.
4109MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
4110 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
4111}
4112
4113/// GetJTSetSymbol - Return the symbol for the specified jump table .set
4114/// FIXME: privatize to AsmPrinter.
4115MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
4116 const DataLayout &DL = getDataLayout();
4117 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
4118 Twine(getFunctionNumber()) + "_" +
4119 Twine(UID) + "_set_" + Twine(MBBID));
4120}
4121
4123 StringRef Suffix) const {
4125}
4126
4127/// Return the MCSymbol for the specified ExternalSymbol.
4129 SmallString<60> NameStr;
4131 return OutContext.getOrCreateSymbol(NameStr);
4132}
4133
4134/// PrintParentLoopComment - Print comments about parent loops of this one.
4136 unsigned FunctionNumber) {
4137 if (!Loop) return;
4138 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
4140 << "Parent Loop BB" << FunctionNumber << "_"
4141 << Loop->getHeader()->getNumber()
4142 << " Depth=" << Loop->getLoopDepth() << '\n';
4143}
4144
4145/// PrintChildLoopComment - Print comments about child loops within
4146/// the loop for this basic block, with nesting.
4148 unsigned FunctionNumber) {
4149 // Add child loop information
4150 for (const MachineLoop *CL : *Loop) {
4151 OS.indent(CL->getLoopDepth()*2)
4152 << "Child Loop BB" << FunctionNumber << "_"
4153 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
4154 << '\n';
4155 PrintChildLoopComment(OS, CL, FunctionNumber);
4156 }
4157}
4158
4159/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
4161 const MachineLoopInfo *LI,
4162 const AsmPrinter &AP) {
4163 // Add loop depth information
4164 const MachineLoop *Loop = LI->getLoopFor(&MBB);
4165 if (!Loop) return;
4166
4167 MachineBasicBlock *Header = Loop->getHeader();
4168 assert(Header && "No header for loop");
4169
4170 // If this block is not a loop header, just print out what is the loop header
4171 // and return.
4172 if (Header != &MBB) {
4173 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
4174 Twine(AP.getFunctionNumber())+"_" +
4176 " Depth="+Twine(Loop->getLoopDepth()));
4177 return;
4178 }
4179
4180 // Otherwise, it is a loop header. Print out information about child and
4181 // parent loops.
4182 raw_ostream &OS = AP.OutStreamer->getCommentOS();
4183
4185
4186 OS << "=>";
4187 OS.indent(Loop->getLoopDepth()*2-2);
4188
4189 OS << "This ";
4190 if (Loop->isInnermost())
4191 OS << "Inner ";
4192 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
4193
4195}
4196
4197/// emitBasicBlockStart - This method prints the label for the specified
4198/// MachineBasicBlock, an alignment (if present) and a comment describing
4199/// it if appropriate.
4201 // End the previous funclet and start a new one.
4202 if (MBB.isEHFuncletEntry()) {
4203 for (auto &Handler : Handlers) {
4204 Handler->endFunclet();
4205 Handler->beginFunclet(MBB);
4206 }
4207 }
4208
4209 // Switch to a new section if this basic block must begin a section. The
4210 // entry block is always placed in the function section and is handled
4211 // separately.
4212 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4213 OutStreamer->switchSection(
4214 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
4215 MBB, TM));
4216 CurrentSectionBeginSym = MBB.getSymbol();
4217 }
4218
4219 for (auto &Handler : DebugHandlers)
4220 Handler->beginCodeAlignment(MBB);
4221
4222 // Emit an alignment directive for this block, if needed.
4223 const Align Alignment = MBB.getAlignment();
4224 if (Alignment != Align(1))
4225 emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
4226
4227 // If the block has its address taken, emit any labels that were used to
4228 // reference the block. It is possible that there is more than one label
4229 // here, because multiple LLVM BB's may have been RAUW'd to this block after
4230 // the references were generated.
4231 if (MBB.isIRBlockAddressTaken()) {
4232 if (isVerbose())
4233 OutStreamer->AddComment("Block address taken");
4234
4236 assert(BB && BB->hasAddressTaken() && "Missing BB");
4238 OutStreamer->emitLabel(Sym);
4239 } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
4240 OutStreamer->AddComment("Block address taken");
4241 }
4242
4243 // Print some verbose block comments.
4244 if (isVerbose()) {
4245 if (const BasicBlock *BB = MBB.getBasicBlock()) {
4246 if (BB->hasName()) {
4247 BB->printAsOperand(OutStreamer->getCommentOS(),
4248 /*PrintType=*/false, BB->getModule());
4249 OutStreamer->getCommentOS() << '\n';
4250 }
4251 }
4252
4253 assert(MLI != nullptr && "MachineLoopInfo should has been computed");
4255 }
4256
4257 // Print the main label for the block.
4258 if (shouldEmitLabelForBasicBlock(MBB)) {
4260 OutStreamer->AddComment("Label of block must be emitted");
4261 OutStreamer->emitLabel(MBB.getSymbol());
4262 } else {
4263 if (isVerbose()) {
4264 // NOTE: Want this comment at start of line, don't emit with AddComment.
4265 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
4266 false);
4267 }
4268 }
4269
4270 if (MBB.isEHCatchretTarget() &&
4272 OutStreamer->emitLabel(MBB.getEHCatchretSymbol());
4273 }
4274
4275 // With BB sections, each basic block must handle CFI information on its own
4276 // if it begins a section (Entry block call is handled separately, next to
4277 // beginFunction).
4278 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4279 for (auto &Handler : DebugHandlers)
4280 Handler->beginBasicBlockSection(MBB);
4281 for (auto &Handler : Handlers)
4282 Handler->beginBasicBlockSection(MBB);
4283 }
4284}
4285
4287 // Check if CFI information needs to be updated for this MBB with basic block
4288 // sections.
4289 if (MBB.isEndSection()) {
4290 for (auto &Handler : DebugHandlers)
4291 Handler->endBasicBlockSection(MBB);
4292 for (auto &Handler : Handlers)
4293 Handler->endBasicBlockSection(MBB);
4294 }
4295}
4296
4297void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
4298 bool IsDefinition) const {
4300
4301 switch (Visibility) {
4302 default: break;
4304 if (IsDefinition)
4305 Attr = MAI->getHiddenVisibilityAttr();
4306 else
4308 break;
4311 break;
4312 }
4313
4314 if (Attr != MCSA_Invalid)
4315 OutStreamer->emitSymbolAttribute(Sym, Attr);
4316}
4317
4318bool AsmPrinter::shouldEmitLabelForBasicBlock(
4319 const MachineBasicBlock &MBB) const {
4320 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
4321 // in the labels mode (option `=labels`) and every section beginning in the
4322 // sections mode (`=all` and `=list=`).
4324 !MBB.isEntryBlock())
4325 return true;
4326 // A label is needed for any block with at least one predecessor (when that
4327 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
4328 // entry, or if a label is forced).
4329 return !MBB.pred_empty() &&
4332}
4333
4334/// isBlockOnlyReachableByFallthough - Return true if the basic block has
4335/// exactly one predecessor and the control transfer mechanism between
4336/// the predecessor and this block is a fall-through.
4339 // If this is a landing pad, it isn't a fall through. If it has no preds,
4340 // then nothing falls through to it.
4341 if (MBB->isEHPad() || MBB->pred_empty())
4342 return false;
4343
4344 // If there isn't exactly one predecessor, it can't be a fall through.
4345 if (MBB->pred_size() > 1)
4346 return false;
4347
4348 // The predecessor has to be immediately before this block.
4349 MachineBasicBlock *Pred = *MBB->pred_begin();
4350 if (!Pred->isLayoutSuccessor(MBB))
4351 return false;
4352
4353 // If the block is completely empty, then it definitely does fall through.
4354 if (Pred->empty())
4355 return true;
4356
4357 // Check the terminators in the previous blocks
4358 for (const auto &MI : Pred->terminators()) {
4359 // If it is not a simple branch, we are in a table somewhere.
4360 if (!MI.isBranch() || MI.isIndirectBranch())
4361 return false;
4362
4363 // If we are the operands of one of the branches, this is not a fall
4364 // through. Note that targets with delay slots will usually bundle
4365 // terminators with the delay slot instruction.
4366 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
4367 if (OP->isJTI())
4368 return false;
4369 if (OP->isMBB() && OP->getMBB() == MBB)
4370 return false;
4371 }
4372 }
4373
4374 return true;
4375}
4376
4377GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
4378 if (!S.usesMetadata())
4379 return nullptr;
4380
4381 auto [GCPI, Inserted] = GCMetadataPrinters.insert({&S, nullptr});
4382 if (!Inserted)
4383 return GCPI->second.get();
4384
4385 auto Name = S.getName();
4386
4387 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
4389 if (Name == GCMetaPrinter.getName()) {
4390 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
4391 GMP->S = &S;
4392 GCPI->second = std::move(GMP);
4393 return GCPI->second.get();
4394 }
4395
4396 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
4397}
4398
4400 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
4401 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
4402 bool NeedsDefault = false;
4403 if (MI->begin() == MI->end())
4404 // No GC strategy, use the default format.
4405 NeedsDefault = true;
4406 else
4407 for (const auto &I : *MI) {
4408 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*I))
4409 if (MP->emitStackMaps(SM, *this))
4410 continue;
4411 // The strategy doesn't have printer or doesn't emit custom stack maps.
4412 // Use the default format.
4413 NeedsDefault = true;
4414 }
4415
4416 if (NeedsDefault)
4418}
4419
4421 std::unique_ptr<AsmPrinterHandler> Handler) {
4422 Handlers.insert(Handlers.begin(), std::move(Handler));
4424}
4425
4426void AsmPrinter::addDebugHandler(std::unique_ptr<DebugHandlerBase> Handler) {
4427 DebugHandlers.insert(DebugHandlers.begin(), std::move(Handler));
4429}
4430
4431/// Pin vtable to this file.
4433
4435
4436// In the binary's "xray_instr_map" section, an array of these function entries
4437// describes each instrumentation point. When XRay patches your code, the index
4438// into this table will be given to your handler as a patch point identifier.
4440 auto Kind8 = static_cast<uint8_t>(