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