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