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