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