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