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