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