Bug Summary

File:llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
Warning:line 280, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name AsmPrinter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen/AsmPrinter -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/CodeGen/AsmPrinter -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
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/StringRef.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/Analysis/ConstantFolding.h"
33#include "llvm/Analysis/EHPersonalities.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/MachineBasicBlock.h"
42#include "llvm/CodeGen/MachineConstantPool.h"
43#include "llvm/CodeGen/MachineDominators.h"
44#include "llvm/CodeGen/MachineFrameInfo.h"
45#include "llvm/CodeGen/MachineFunction.h"
46#include "llvm/CodeGen/MachineFunctionPass.h"
47#include "llvm/CodeGen/MachineInstr.h"
48#include "llvm/CodeGen/MachineInstrBundle.h"
49#include "llvm/CodeGen/MachineJumpTableInfo.h"
50#include "llvm/CodeGen/MachineLoopInfo.h"
51#include "llvm/CodeGen/MachineMemOperand.h"
52#include "llvm/CodeGen/MachineModuleInfo.h"
53#include "llvm/CodeGen/MachineModuleInfoImpls.h"
54#include "llvm/CodeGen/MachineOperand.h"
55#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
56#include "llvm/CodeGen/StackMaps.h"
57#include "llvm/CodeGen/TargetFrameLowering.h"
58#include "llvm/CodeGen/TargetInstrInfo.h"
59#include "llvm/CodeGen/TargetLowering.h"
60#include "llvm/CodeGen/TargetOpcodes.h"
61#include "llvm/CodeGen/TargetRegisterInfo.h"
62#include "llvm/Config/config.h"
63#include "llvm/IR/BasicBlock.h"
64#include "llvm/IR/Comdat.h"
65#include "llvm/IR/Constant.h"
66#include "llvm/IR/Constants.h"
67#include "llvm/IR/DataLayout.h"
68#include "llvm/IR/DebugInfoMetadata.h"
69#include "llvm/IR/DerivedTypes.h"
70#include "llvm/IR/Function.h"
71#include "llvm/IR/GCStrategy.h"
72#include "llvm/IR/GlobalAlias.h"
73#include "llvm/IR/GlobalIFunc.h"
74#include "llvm/IR/GlobalObject.h"
75#include "llvm/IR/GlobalValue.h"
76#include "llvm/IR/GlobalVariable.h"
77#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Mangler.h"
79#include "llvm/IR/Metadata.h"
80#include "llvm/IR/Module.h"
81#include "llvm/IR/Operator.h"
82#include "llvm/IR/PseudoProbe.h"
83#include "llvm/IR/Type.h"
84#include "llvm/IR/Value.h"
85#include "llvm/MC/MCAsmInfo.h"
86#include "llvm/MC/MCContext.h"
87#include "llvm/MC/MCDirectives.h"
88#include "llvm/MC/MCDwarf.h"
89#include "llvm/MC/MCExpr.h"
90#include "llvm/MC/MCInst.h"
91#include "llvm/MC/MCSection.h"
92#include "llvm/MC/MCSectionCOFF.h"
93#include "llvm/MC/MCSectionELF.h"
94#include "llvm/MC/MCSectionMachO.h"
95#include "llvm/MC/MCSectionXCOFF.h"
96#include "llvm/MC/MCStreamer.h"
97#include "llvm/MC/MCSubtargetInfo.h"
98#include "llvm/MC/MCSymbol.h"
99#include "llvm/MC/MCSymbolELF.h"
100#include "llvm/MC/MCSymbolXCOFF.h"
101#include "llvm/MC/MCTargetOptions.h"
102#include "llvm/MC/MCValue.h"
103#include "llvm/MC/SectionKind.h"
104#include "llvm/MC/TargetRegistry.h"
105#include "llvm/Pass.h"
106#include "llvm/Remarks/Remark.h"
107#include "llvm/Remarks/RemarkFormat.h"
108#include "llvm/Remarks/RemarkStreamer.h"
109#include "llvm/Remarks/RemarkStringTable.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/Timer.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 <algorithm>
124#include <cassert>
125#include <cinttypes>
126#include <cstdint>
127#include <iterator>
128#include <limits>
129#include <memory>
130#include <string>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135
136#define DEBUG_TYPE"asm-printer" "asm-printer"
137
138// FIXME: this option currently only applies to DWARF, and not CodeView, tables
139static cl::opt<bool>
140 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
141 cl::desc("Disable debug info printing"));
142
143const char DWARFGroupName[] = "dwarf";
144const char DWARFGroupDescription[] = "DWARF Emission";
145const char DbgTimerName[] = "emit";
146const char DbgTimerDescription[] = "Debug Info Emission";
147const char EHTimerName[] = "write_exception";
148const char EHTimerDescription[] = "DWARF Exception Writer";
149const char CFGuardName[] = "Control Flow Guard";
150const char CFGuardDescription[] = "Control Flow Guard";
151const char CodeViewLineTablesGroupName[] = "linetables";
152const char CodeViewLineTablesGroupDescription[] = "CodeView Line Tables";
153const char PPTimerName[] = "emit";
154const char PPTimerDescription[] = "Pseudo Probe Emission";
155const char PPGroupName[] = "pseudo probe";
156const char PPGroupDescription[] = "Pseudo Probe Emission";
157
158STATISTIC(EmittedInsts, "Number of machine instrs printed")static llvm::Statistic EmittedInsts = {"asm-printer", "EmittedInsts"
, "Number of machine instrs printed"}
;
159
160char AsmPrinter::ID = 0;
161
162using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>;
163
164static gcp_map_type &getGCMap(void *&P) {
165 if (!P)
166 P = new gcp_map_type();
167 return *(gcp_map_type*)P;
168}
169
170/// getGVAlignment - Return the alignment to use for the specified global
171/// value. This rounds up to the preferred alignment if possible and legal.
172Align AsmPrinter::getGVAlignment(const GlobalObject *GV, const DataLayout &DL,
173 Align InAlign) {
174 Align Alignment;
175 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
176 Alignment = DL.getPreferredAlign(GVar);
177
178 // If InAlign is specified, round it to it.
179 if (InAlign > Alignment)
180 Alignment = InAlign;
181
182 // If the GV has a specified alignment, take it into account.
183 const MaybeAlign GVAlign(GV->getAlign());
184 if (!GVAlign)
185 return Alignment;
186
187 assert(GVAlign && "GVAlign must be set")(static_cast <bool> (GVAlign && "GVAlign must be set"
) ? void (0) : __assert_fail ("GVAlign && \"GVAlign must be set\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 187, __extension__
__PRETTY_FUNCTION__))
;
188
189 // If the GVAlign is larger than NumBits, or if we are required to obey
190 // NumBits because the GV has an assigned section, obey it.
191 if (*GVAlign > Alignment || GV->hasSection())
192 Alignment = *GVAlign;
193 return Alignment;
194}
195
196AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
197 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
198 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
199 VerboseAsm = OutStreamer->isVerboseAsm();
200}
201
202AsmPrinter::~AsmPrinter() {
203 assert(!DD && Handlers.size() == NumUserHandlers &&(static_cast <bool> (!DD && Handlers.size() == NumUserHandlers
&& "Debug/EH info didn't get finalized") ? void (0) :
__assert_fail ("!DD && Handlers.size() == NumUserHandlers && \"Debug/EH info didn't get finalized\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 204, __extension__
__PRETTY_FUNCTION__))
204 "Debug/EH info didn't get finalized")(static_cast <bool> (!DD && Handlers.size() == NumUserHandlers
&& "Debug/EH info didn't get finalized") ? void (0) :
__assert_fail ("!DD && Handlers.size() == NumUserHandlers && \"Debug/EH info didn't get finalized\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 204, __extension__
__PRETTY_FUNCTION__))
;
205
206 if (GCMetadataPrinters) {
207 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
208
209 delete &GCMap;
210 GCMetadataPrinters = nullptr;
211 }
212}
213
214bool AsmPrinter::isPositionIndependent() const {
215 return TM.isPositionIndependent();
216}
217
218/// getFunctionNumber - Return a unique ID for the current function.
219unsigned AsmPrinter::getFunctionNumber() const {
220 return MF->getFunctionNumber();
221}
222
223const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
224 return *TM.getObjFileLowering();
225}
226
227const DataLayout &AsmPrinter::getDataLayout() const {
228 return MMI->getModule()->getDataLayout();
229}
230
231// Do not use the cached DataLayout because some client use it without a Module
232// (dsymutil, llvm-dwarfdump).
233unsigned AsmPrinter::getPointerSize() const {
234 return TM.getPointerSize(0); // FIXME: Default address space
235}
236
237const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
238 assert(MF && "getSubtargetInfo requires a valid MachineFunction!")(static_cast <bool> (MF && "getSubtargetInfo requires a valid MachineFunction!"
) ? void (0) : __assert_fail ("MF && \"getSubtargetInfo requires a valid MachineFunction!\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 238, __extension__
__PRETTY_FUNCTION__))
;
239 return MF->getSubtarget<MCSubtargetInfo>();
240}
241
242void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
243 S.emitInstruction(Inst, getSubtargetInfo());
244}
245
246void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) {
247 if (DD) {
248 assert(OutStreamer->hasRawTextSupport() &&(static_cast <bool> (OutStreamer->hasRawTextSupport(
) && "Expected assembly output mode.") ? void (0) : __assert_fail
("OutStreamer->hasRawTextSupport() && \"Expected assembly output mode.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 249, __extension__
__PRETTY_FUNCTION__))
249 "Expected assembly output mode.")(static_cast <bool> (OutStreamer->hasRawTextSupport(
) && "Expected assembly output mode.") ? void (0) : __assert_fail
("OutStreamer->hasRawTextSupport() && \"Expected assembly output mode.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 249, __extension__
__PRETTY_FUNCTION__))
;
250 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
251 }
252}
253
254/// getCurrentSection() - Return the current section we are emitting to.
255const MCSection *AsmPrinter::getCurrentSection() const {
256 return OutStreamer->getCurrentSectionOnly();
257}
258
259void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
260 AU.setPreservesAll();
261 MachineFunctionPass::getAnalysisUsage(AU);
262 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
263 AU.addRequired<GCModuleInfo>();
264}
265
266bool AsmPrinter::doInitialization(Module &M) {
267 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
268 MMI = MMIWP
0.1
'MMIWP' is null
? &MMIWP->getMMI() : nullptr
;
1
'?' condition is false
2
Null pointer value stored to field 'MMI'
269
270 // Initialize TargetLoweringObjectFile.
271 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
272 .Initialize(OutContext, TM);
273
274 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
275 .getModuleMetadata(M);
276
277 OutStreamer->initSections(false, *TM.getMCSubtargetInfo());
278
279 if (DisableDebugInfoPrinting)
3
Assuming the condition is true
4
Taking true branch
280 MMI->setDebugInfoAvailability(false);
5
Called C++ object pointer is null
281
282 // Emit the version-min deployment target directive if needed.
283 //
284 // FIXME: If we end up with a collection of these sorts of Darwin-specific
285 // or ELF-specific things, it may make sense to have a platform helper class
286 // that will work with the target helper class. For now keep it here, as the
287 // alternative is duplicated code in each of the target asm printers that
288 // use the directive, where it would need the same conditionalization
289 // anyway.
290 const Triple &Target = TM.getTargetTriple();
291 Triple TVT(M.getDarwinTargetVariantTriple());
292 OutStreamer->emitVersionForTarget(
293 Target, M.getSDKVersion(),
294 M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
295 M.getDarwinTargetVariantSDKVersion());
296
297 // Allow the target to emit any magic that it wants at the start of the file.
298 emitStartOfAsmFile(M);
299
300 // Very minimal debug info. It is ignored if we emit actual debug info. If we
301 // don't, this at least helps the user find where a global came from.
302 if (MAI->hasSingleParameterDotFile()) {
303 // .file "foo.c"
304
305 SmallString<128> FileName;
306 if (MAI->hasBasenameOnlyForFileDirective())
307 FileName = llvm::sys::path::filename(M.getSourceFileName());
308 else
309 FileName = M.getSourceFileName();
310 if (MAI->hasFourStringsDotFile()) {
311#ifdef PACKAGE_VENDOR"Debian"
312 const char VerStr[] =
313 PACKAGE_VENDOR"Debian" " " PACKAGE_NAME"LLVM" " version " PACKAGE_VERSION"14.0.0";
314#else
315 const char VerStr[] = PACKAGE_NAME"LLVM" " version " PACKAGE_VERSION"14.0.0";
316#endif
317 // TODO: Add timestamp and description.
318 OutStreamer->emitFileDirective(FileName, VerStr, "", "");
319 } else {
320 OutStreamer->emitFileDirective(FileName);
321 }
322 }
323
324 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
325 assert(MI && "AsmPrinter didn't require GCModuleInfo?")(static_cast <bool> (MI && "AsmPrinter didn't require GCModuleInfo?"
) ? void (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 325, __extension__
__PRETTY_FUNCTION__))
;
326 for (auto &I : *MI)
327 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
328 MP->beginAssembly(M, *MI, *this);
329
330 // Emit module-level inline asm if it exists.
331 if (!M.getModuleInlineAsm().empty()) {
332 OutStreamer->AddComment("Start of file scope inline assembly");
333 OutStreamer->AddBlankLine();
334 emitInlineAsm(M.getModuleInlineAsm() + "\n", *TM.getMCSubtargetInfo(),
335 TM.Options.MCOptions);
336 OutStreamer->AddComment("End of file scope inline assembly");
337 OutStreamer->AddBlankLine();
338 }
339
340 if (MAI->doesSupportDebugInformation()) {
341 bool EmitCodeView = M.getCodeViewFlag();
342 if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
343 Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
344 DbgTimerName, DbgTimerDescription,
345 CodeViewLineTablesGroupName,
346 CodeViewLineTablesGroupDescription);
347 }
348 if (!EmitCodeView || M.getDwarfVersion()) {
349 if (!DisableDebugInfoPrinting) {
350 DD = new DwarfDebug(this);
351 Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
352 DbgTimerDescription, DWARFGroupName,
353 DWARFGroupDescription);
354 }
355 }
356 }
357
358 if (M.getNamedMetadata(PseudoProbeDescMetadataName)) {
359 PP = new PseudoProbeHandler(this);
360 Handlers.emplace_back(std::unique_ptr<PseudoProbeHandler>(PP), PPTimerName,
361 PPTimerDescription, PPGroupName, PPGroupDescription);
362 }
363
364 switch (MAI->getExceptionHandlingType()) {
365 case ExceptionHandling::None:
366 // We may want to emit CFI for debug.
367 LLVM_FALLTHROUGH[[gnu::fallthrough]];
368 case ExceptionHandling::SjLj:
369 case ExceptionHandling::DwarfCFI:
370 case ExceptionHandling::ARM:
371 for (auto &F : M.getFunctionList()) {
372 if (getFunctionCFISectionType(F) != CFISection::None)
373 ModuleCFISection = getFunctionCFISectionType(F);
374 // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
375 // the module needs .eh_frame. If we have found that case, we are done.
376 if (ModuleCFISection == CFISection::EH)
377 break;
378 }
379 assert(MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI ||(static_cast <bool> (MAI->getExceptionHandlingType()
== ExceptionHandling::DwarfCFI || ModuleCFISection != CFISection
::EH) ? void (0) : __assert_fail ("MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI || ModuleCFISection != CFISection::EH"
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 380, __extension__
__PRETTY_FUNCTION__))
380 ModuleCFISection != CFISection::EH)(static_cast <bool> (MAI->getExceptionHandlingType()
== ExceptionHandling::DwarfCFI || ModuleCFISection != CFISection
::EH) ? void (0) : __assert_fail ("MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI || ModuleCFISection != CFISection::EH"
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 380, __extension__
__PRETTY_FUNCTION__))
;
381 break;
382 default:
383 break;
384 }
385
386 EHStreamer *ES = nullptr;
387 switch (MAI->getExceptionHandlingType()) {
388 case ExceptionHandling::None:
389 if (!needsCFIForDebug())
390 break;
391 LLVM_FALLTHROUGH[[gnu::fallthrough]];
392 case ExceptionHandling::SjLj:
393 case ExceptionHandling::DwarfCFI:
394 ES = new DwarfCFIException(this);
395 break;
396 case ExceptionHandling::ARM:
397 ES = new ARMException(this);
398 break;
399 case ExceptionHandling::WinEH:
400 switch (MAI->getWinEHEncodingType()) {
401 default: llvm_unreachable("unsupported unwinding information encoding")::llvm::llvm_unreachable_internal("unsupported unwinding information encoding"
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 401)
;
402 case WinEH::EncodingType::Invalid:
403 break;
404 case WinEH::EncodingType::X86:
405 case WinEH::EncodingType::Itanium:
406 ES = new WinException(this);
407 break;
408 }
409 break;
410 case ExceptionHandling::Wasm:
411 ES = new WasmException(this);
412 break;
413 case ExceptionHandling::AIX:
414 ES = new AIXException(this);
415 break;
416 }
417 if (ES)
418 Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
419 EHTimerDescription, DWARFGroupName,
420 DWARFGroupDescription);
421
422 // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
423 if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
424 Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
425 CFGuardDescription, DWARFGroupName,
426 DWARFGroupDescription);
427
428 for (const HandlerInfo &HI : Handlers) {
429 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
430 HI.TimerGroupDescription, TimePassesIsEnabled);
431 HI.Handler->beginModule(&M);
432 }
433
434 return false;
435}
436
437static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
438 if (!MAI.hasWeakDefCanBeHiddenDirective())
439 return false;
440
441 return GV->canBeOmittedFromSymbolTable();
442}
443
444void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
445 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
446 switch (Linkage) {
447 case GlobalValue::CommonLinkage:
448 case GlobalValue::LinkOnceAnyLinkage:
449 case GlobalValue::LinkOnceODRLinkage:
450 case GlobalValue::WeakAnyLinkage:
451 case GlobalValue::WeakODRLinkage:
452 if (MAI->hasWeakDefDirective()) {
453 // .globl _foo
454 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
455
456 if (!canBeHidden(GV, *MAI))
457 // .weak_definition _foo
458 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
459 else
460 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
461 } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
462 // .globl _foo
463 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
464 //NOTE: linkonce is handled by the section the symbol was assigned to.
465 } else {
466 // .weak _foo
467 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
468 }
469 return;
470 case GlobalValue::ExternalLinkage:
471 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
472 return;
473 case GlobalValue::PrivateLinkage:
474 case GlobalValue::InternalLinkage:
475 return;
476 case GlobalValue::ExternalWeakLinkage:
477 case GlobalValue::AvailableExternallyLinkage:
478 case GlobalValue::AppendingLinkage:
479 llvm_unreachable("Should never emit this")::llvm::llvm_unreachable_internal("Should never emit this", "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 479)
;
480 }
481 llvm_unreachable("Unknown linkage type!")::llvm::llvm_unreachable_internal("Unknown linkage type!", "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 481)
;
482}
483
484void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
485 const GlobalValue *GV) const {
486 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
487}
488
489MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
490 return TM.getSymbol(GV);
491}
492
493MCSymbol *AsmPrinter::getSymbolPreferLocal(const GlobalValue &GV) const {
494 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
495 // exact definion (intersection of GlobalValue::hasExactDefinition() and
496 // !isInterposable()). These linkages include: external, appending, internal,
497 // private. It may be profitable to use a local alias for external. The
498 // assembler would otherwise be conservative and assume a global default
499 // visibility symbol can be interposable, even if the code generator already
500 // assumed it.
501 if (TM.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) {
502 const Module &M = *GV.getParent();
503 if (TM.getRelocationModel() != Reloc::Static &&
504 M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
505 return getSymbolWithGlobalValueBase(&GV, "$local");
506 }
507 return TM.getSymbol(&GV);
508}
509
510/// EmitGlobalVariable - Emit the specified global variable to the .s file.
511void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
512 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
513 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&(static_cast <bool> (!(IsEmuTLSVar && GV->hasCommonLinkage
()) && "No emulated TLS variables in the common section"
) ? void (0) : __assert_fail ("!(IsEmuTLSVar && GV->hasCommonLinkage()) && \"No emulated TLS variables in the common section\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 514, __extension__
__PRETTY_FUNCTION__))
514 "No emulated TLS variables in the common section")(static_cast <bool> (!(IsEmuTLSVar && GV->hasCommonLinkage
()) && "No emulated TLS variables in the common section"
) ? void (0) : __assert_fail ("!(IsEmuTLSVar && GV->hasCommonLinkage()) && \"No emulated TLS variables in the common section\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 514, __extension__
__PRETTY_FUNCTION__))
;
515
516 // Never emit TLS variable xyz in emulated TLS model.
517 // The initialization value is in __emutls_t.xyz instead of xyz.
518 if (IsEmuTLSVar)
519 return;
520
521 if (GV->hasInitializer()) {
522 // Check to see if this is a special global used by LLVM, if so, emit it.
523 if (emitSpecialLLVMGlobal(GV))
524 return;
525
526 // Skip the emission of global equivalents. The symbol can be emitted later
527 // on by emitGlobalGOTEquivs in case it turns out to be needed.
528 if (GlobalGOTEquivs.count(getSymbol(GV)))
529 return;
530
531 if (isVerbose()) {
532 // When printing the control variable __emutls_v.*,
533 // we don't need to print the original TLS variable name.
534 GV->printAsOperand(OutStreamer->GetCommentOS(),
535 /*PrintType=*/false, GV->getParent());
536 OutStreamer->GetCommentOS() << '\n';
537 }
538 }
539
540 MCSymbol *GVSym = getSymbol(GV);
541 MCSymbol *EmittedSym = GVSym;
542
543 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
544 // attributes.
545 // GV's or GVSym's attributes will be used for the EmittedSym.
546 emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
547
548 if (!GV->hasInitializer()) // External globals require no extra code.
549 return;
550
551 GVSym->redefineIfPossible();
552 if (GVSym->isDefined() || GVSym->isVariable())
553 OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
554 "' is already defined");
555
556 if (MAI->hasDotTypeDotSizeDirective())
557 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
558
559 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
560
561 const DataLayout &DL = GV->getParent()->getDataLayout();
562 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
563
564 // If the alignment is specified, we *must* obey it. Overaligning a global
565 // with a specified alignment is a prompt way to break globals emitted to
566 // sections and expected to be contiguous (e.g. ObjC metadata).
567 const Align Alignment = getGVAlignment(GV, DL);
568
569 for (const HandlerInfo &HI : Handlers) {
570 NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
571 HI.TimerGroupName, HI.TimerGroupDescription,
572 TimePassesIsEnabled);
573 HI.Handler->setSymbolSize(GVSym, Size);
574 }
575
576 // Handle common symbols
577 if (GVKind.isCommon()) {
578 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
579 // .comm _foo, 42, 4
580 const bool SupportsAlignment =
581 getObjFileLowering().getCommDirectiveSupportsAlignment();
582 OutStreamer->emitCommonSymbol(GVSym, Size,
583 SupportsAlignment ? Alignment.value() : 0);
584 return;
585 }
586
587 // Determine to which section this global should be emitted.
588 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
589
590 // If we have a bss global going to a section that supports the
591 // zerofill directive, do so here.
592 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
593 TheSection->isVirtualSection()) {
594 if (Size == 0)
595 Size = 1; // zerofill of 0 bytes is undefined.
596 emitLinkage(GV, GVSym);
597 // .zerofill __DATA, __bss, _foo, 400, 5
598 OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value());
599 return;
600 }
601
602 // If this is a BSS local symbol and we are emitting in the BSS
603 // section use .lcomm/.comm directive.
604 if (GVKind.isBSSLocal() &&
605 getObjFileLowering().getBSSSection() == TheSection) {
606 if (Size == 0)
607 Size = 1; // .comm Foo, 0 is undefined, avoid it.
608
609 // Use .lcomm only if it supports user-specified alignment.
610 // Otherwise, while it would still be correct to use .lcomm in some
611 // cases (e.g. when Align == 1), the external assembler might enfore
612 // some -unknown- default alignment behavior, which could cause
613 // spurious differences between external and integrated assembler.
614 // Prefer to simply fall back to .local / .comm in this case.
615 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
616 // .lcomm _foo, 42
617 OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value());
618 return;
619 }
620
621 // .local _foo
622 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
623 // .comm _foo, 42, 4
624 const bool SupportsAlignment =
625 getObjFileLowering().getCommDirectiveSupportsAlignment();
626 OutStreamer->emitCommonSymbol(GVSym, Size,
627 SupportsAlignment ? Alignment.value() : 0);
628 return;
629 }
630
631 // Handle thread local data for mach-o which requires us to output an
632 // additional structure of data and mangle the original symbol so that we
633 // can reference it later.
634 //
635 // TODO: This should become an "emit thread local global" method on TLOF.
636 // All of this macho specific stuff should be sunk down into TLOFMachO and
637 // stuff like "TLSExtraDataSection" should no longer be part of the parent
638 // TLOF class. This will also make it more obvious that stuff like
639 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
640 // specific code.
641 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
642 // Emit the .tbss symbol
643 MCSymbol *MangSym =
644 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
645
646 if (GVKind.isThreadBSS()) {
647 TheSection = getObjFileLowering().getTLSBSSSection();
648 OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value());
649 } else if (GVKind.isThreadData()) {
650 OutStreamer->SwitchSection(TheSection);
651
652 emitAlignment(Alignment, GV);
653 OutStreamer->emitLabel(MangSym);
654
655 emitGlobalConstant(GV->getParent()->getDataLayout(),
656 GV->getInitializer());
657 }
658
659 OutStreamer->AddBlankLine();
660
661 // Emit the variable struct for the runtime.
662 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
663
664 OutStreamer->SwitchSection(TLVSect);
665 // Emit the linkage here.
666 emitLinkage(GV, GVSym);
667 OutStreamer->emitLabel(GVSym);
668
669 // Three pointers in size:
670 // - __tlv_bootstrap - used to make sure support exists
671 // - spare pointer, used when mapped by the runtime
672 // - pointer to mangled symbol above with initializer
673 unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
674 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
675 PtrSize);
676 OutStreamer->emitIntValue(0, PtrSize);
677 OutStreamer->emitSymbolValue(MangSym, PtrSize);
678
679 OutStreamer->AddBlankLine();
680 return;
681 }
682
683 MCSymbol *EmittedInitSym = GVSym;
684
685 OutStreamer->SwitchSection(TheSection);
686
687 emitLinkage(GV, EmittedInitSym);
688 emitAlignment(Alignment, GV);
689
690 OutStreamer->emitLabel(EmittedInitSym);
691 MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
692 if (LocalAlias != EmittedInitSym)
693 OutStreamer->emitLabel(LocalAlias);
694
695 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
696
697 if (MAI->hasDotTypeDotSizeDirective())
698 // .size foo, 42
699 OutStreamer->emitELFSize(EmittedInitSym,
700 MCConstantExpr::create(Size, OutContext));
701
702 OutStreamer->AddBlankLine();
703}
704
705/// Emit the directive and value for debug thread local expression
706///
707/// \p Value - The value to emit.
708/// \p Size - The size of the integer (in bytes) to emit.
709void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
710 OutStreamer->emitValue(Value, Size);
711}
712
713void AsmPrinter::emitFunctionHeaderComment() {}
714
715/// EmitFunctionHeader - This method emits the header for the current
716/// function.
717void AsmPrinter::emitFunctionHeader() {
718 const Function &F = MF->getFunction();
719
720 if (isVerbose())
721 OutStreamer->GetCommentOS()
722 << "-- Begin function "
723 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
724
725 // Print out constants referenced by the function
726 emitConstantPool();
727
728 // Print the 'header' of function.
729 // If basic block sections are desired, explicitly request a unique section
730 // for this function's entry block.
731 if (MF->front().isBeginSection())
732 MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
733 else
734 MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
735 OutStreamer->SwitchSection(MF->getSection());
736
737 if (!MAI->hasVisibilityOnlyWithLinkage())
738 emitVisibility(CurrentFnSym, F.getVisibility());
739
740 if (MAI->needsFunctionDescriptors())
741 emitLinkage(&F, CurrentFnDescSym);
742
743 emitLinkage(&F, CurrentFnSym);
744 if (MAI->hasFunctionAlignment())
745 emitAlignment(MF->getAlignment(), &F);
746
747 if (MAI->hasDotTypeDotSizeDirective())
748 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
749
750 if (F.hasFnAttribute(Attribute::Cold))
751 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
752
753 if (isVerbose()) {
754 F.printAsOperand(OutStreamer->GetCommentOS(),
755 /*PrintType=*/false, F.getParent());
756 emitFunctionHeaderComment();
757 OutStreamer->GetCommentOS() << '\n';
758 }
759
760 // Emit the prefix data.
761 if (F.hasPrefixData()) {
762 if (MAI->hasSubsectionsViaSymbols()) {
763 // Preserving prefix data on platforms which use subsections-via-symbols
764 // is a bit tricky. Here we introduce a symbol for the prefix data
765 // and use the .alt_entry attribute to mark the function's real entry point
766 // as an alternative entry point to the prefix-data symbol.
767 MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
768 OutStreamer->emitLabel(PrefixSym);
769
770 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
771
772 // Emit an .alt_entry directive for the actual function symbol.
773 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
774 } else {
775 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
776 }
777 }
778
779 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
780 // place prefix data before NOPs.
781 unsigned PatchableFunctionPrefix = 0;
782 unsigned PatchableFunctionEntry = 0;
783 (void)F.getFnAttribute("patchable-function-prefix")
784 .getValueAsString()
785 .getAsInteger(10, PatchableFunctionPrefix);
786 (void)F.getFnAttribute("patchable-function-entry")
787 .getValueAsString()
788 .getAsInteger(10, PatchableFunctionEntry);
789 if (PatchableFunctionPrefix) {
790 CurrentPatchableFunctionEntrySym =
791 OutContext.createLinkerPrivateTempSymbol();
792 OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym);
793 emitNops(PatchableFunctionPrefix);
794 } else if (PatchableFunctionEntry) {
795 // May be reassigned when emitting the body, to reference the label after
796 // the initial BTI (AArch64) or endbr32/endbr64 (x86).
797 CurrentPatchableFunctionEntrySym = CurrentFnBegin;
798 }
799
800 // Emit the function descriptor. This is a virtual function to allow targets
801 // to emit their specific function descriptor. Right now it is only used by
802 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
803 // descriptors and should be converted to use this hook as well.
804 if (MAI->needsFunctionDescriptors())
805 emitFunctionDescriptor();
806
807 // Emit the CurrentFnSym. This is a virtual function to allow targets to do
808 // their wild and crazy things as required.
809 emitFunctionEntryLabel();
810
811 // If the function had address-taken blocks that got deleted, then we have
812 // references to the dangling symbols. Emit them at the start of the function
813 // so that we don't get references to undefined symbols.
814 std::vector<MCSymbol*> DeadBlockSyms;
815 MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
816 for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
817 OutStreamer->AddComment("Address taken block that was later removed");
818 OutStreamer->emitLabel(DeadBlockSym);
819 }
820
821 if (CurrentFnBegin) {
822 if (MAI->useAssignmentForEHBegin()) {
823 MCSymbol *CurPos = OutContext.createTempSymbol();
824 OutStreamer->emitLabel(CurPos);
825 OutStreamer->emitAssignment(CurrentFnBegin,
826 MCSymbolRefExpr::create(CurPos, OutContext));
827 } else {
828 OutStreamer->emitLabel(CurrentFnBegin);
829 }
830 }
831
832 // Emit pre-function debug and/or EH information.
833 for (const HandlerInfo &HI : Handlers) {
834 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
835 HI.TimerGroupDescription, TimePassesIsEnabled);
836 HI.Handler->beginFunction(MF);
837 }
838
839 // Emit the prologue data.
840 if (F.hasPrologueData())
841 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
842}
843
844/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
845/// function. This can be overridden by targets as required to do custom stuff.
846void AsmPrinter::emitFunctionEntryLabel() {
847 CurrentFnSym->redefineIfPossible();
848
849 // The function label could have already been emitted if two symbols end up
850 // conflicting due to asm renaming. Detect this and emit an error.
851 if (CurrentFnSym->isVariable())
852 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
853 "' is a protected alias");
854
855 OutStreamer->emitLabel(CurrentFnSym);
856
857 if (TM.getTargetTriple().isOSBinFormatELF()) {
858 MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction());
859 if (Sym != CurrentFnSym)
860 OutStreamer->emitLabel(Sym);
861 }
862}
863
864/// emitComments - Pretty-print comments for instructions.
865static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
866 const MachineFunction *MF = MI.getMF();
867 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
868
869 // Check for spills and reloads
870
871 // We assume a single instruction only has a spill or reload, not
872 // both.
873 Optional<unsigned> Size;
874 if ((Size = MI.getRestoreSize(TII))) {
875 CommentOS << *Size << "-byte Reload\n";
876 } else if ((Size = MI.getFoldedRestoreSize(TII))) {
877 if (*Size) {
878 if (*Size == unsigned(MemoryLocation::UnknownSize))
879 CommentOS << "Unknown-size Folded Reload\n";
880 else
881 CommentOS << *Size << "-byte Folded Reload\n";
882 }
883 } else if ((Size = MI.getSpillSize(TII))) {
884 CommentOS << *Size << "-byte Spill\n";
885 } else if ((Size = MI.getFoldedSpillSize(TII))) {
886 if (*Size) {
887 if (*Size == unsigned(MemoryLocation::UnknownSize))
888 CommentOS << "Unknown-size Folded Spill\n";
889 else
890 CommentOS << *Size << "-byte Folded Spill\n";
891 }
892 }
893
894 // Check for spill-induced copies
895 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
896 CommentOS << " Reload Reuse\n";
897}
898
899/// emitImplicitDef - This method emits the specified machine instruction
900/// that is an implicit def.
901void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
902 Register RegNo = MI->getOperand(0).getReg();
903
904 SmallString<128> Str;
905 raw_svector_ostream OS(Str);
906 OS << "implicit-def: "
907 << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
908
909 OutStreamer->AddComment(OS.str());
910 OutStreamer->AddBlankLine();
911}
912
913static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
914 std::string Str;
915 raw_string_ostream OS(Str);
916 OS << "kill:";
917 for (const MachineOperand &Op : MI->operands()) {
918 assert(Op.isReg() && "KILL instruction must have only register operands")(static_cast <bool> (Op.isReg() && "KILL instruction must have only register operands"
) ? void (0) : __assert_fail ("Op.isReg() && \"KILL instruction must have only register operands\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 918, __extension__
__PRETTY_FUNCTION__))
;
919 OS << ' ' << (Op.isDef() ? "def " : "killed ")
920 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
921 }
922 AP.OutStreamer->AddComment(OS.str());
923 AP.OutStreamer->AddBlankLine();
924}
925
926/// emitDebugValueComment - This method handles the target-independent form
927/// of DBG_VALUE, returning true if it was able to do so. A false return
928/// means the target will need to handle MI in EmitInstruction.
929static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
930 // This code handles only the 4-operand target-independent form.
931 if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
932 return false;
933
934 SmallString<128> Str;
935 raw_svector_ostream OS(Str);
936 OS << "DEBUG_VALUE: ";
937
938 const DILocalVariable *V = MI->getDebugVariable();
939 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
940 StringRef Name = SP->getName();
941 if (!Name.empty())
942 OS << Name << ":";
943 }
944 OS << V->getName();
945 OS << " <- ";
946
947 const DIExpression *Expr = MI->getDebugExpression();
948 if (Expr->getNumElements()) {
949 OS << '[';
950 ListSeparator LS;
951 for (auto Op : Expr->expr_ops()) {
952 OS << LS << dwarf::OperationEncodingString(Op.getOp());
953 for (unsigned I = 0; I < Op.getNumArgs(); ++I)
954 OS << ' ' << Op.getArg(I);
955 }
956 OS << "] ";
957 }
958
959 // Register or immediate value. Register 0 means undef.
960 for (const MachineOperand &Op : MI->debug_operands()) {
961 if (&Op != MI->debug_operands().begin())
962 OS << ", ";
963 switch (Op.getType()) {
964 case MachineOperand::MO_FPImmediate: {
965 APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
966 Type *ImmTy = Op.getFPImm()->getType();
967 if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
968 ImmTy->isDoubleTy()) {
969 OS << APF.convertToDouble();
970 } else {
971 // There is no good way to print long double. Convert a copy to
972 // double. Ah well, it's only a comment.
973 bool ignored;
974 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
975 &ignored);
976 OS << "(long double) " << APF.convertToDouble();
977 }
978 break;
979 }
980 case MachineOperand::MO_Immediate: {
981 OS << Op.getImm();
982 break;
983 }
984 case MachineOperand::MO_CImmediate: {
985 Op.getCImm()->getValue().print(OS, false /*isSigned*/);
986 break;
987 }
988 case MachineOperand::MO_TargetIndex: {
989 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
990 // NOTE: Want this comment at start of line, don't emit with AddComment.
991 AP.OutStreamer->emitRawComment(OS.str());
992 break;
993 }
994 case MachineOperand::MO_Register:
995 case MachineOperand::MO_FrameIndex: {
996 Register Reg;
997 Optional<StackOffset> Offset;
998 if (Op.isReg()) {
999 Reg = Op.getReg();
1000 } else {
1001 const TargetFrameLowering *TFI =
1002 AP.MF->getSubtarget().getFrameLowering();
1003 Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
1004 }
1005 if (!Reg) {
1006 // Suppress offset, it is not meaningful here.
1007 OS << "undef";
1008 break;
1009 }
1010 // The second operand is only an offset if it's an immediate.
1011 if (MI->isIndirectDebugValue())
1012 Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
1013 if (Offset)
1014 OS << '[';
1015 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
1016 if (Offset)
1017 OS << '+' << Offset->getFixed() << ']';
1018 break;
1019 }
1020 default:
1021 llvm_unreachable("Unknown operand type")::llvm::llvm_unreachable_internal("Unknown operand type", "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1021)
;
1022 }
1023 }
1024
1025 // NOTE: Want this comment at start of line, don't emit with AddComment.
1026 AP.OutStreamer->emitRawComment(OS.str());
1027 return true;
1028}
1029
1030/// This method handles the target-independent form of DBG_LABEL, returning
1031/// true if it was able to do so. A false return means the target will need
1032/// to handle MI in EmitInstruction.
1033static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
1034 if (MI->getNumOperands() != 1)
1035 return false;
1036
1037 SmallString<128> Str;
1038 raw_svector_ostream OS(Str);
1039 OS << "DEBUG_LABEL: ";
1040
1041 const DILabel *V = MI->getDebugLabel();
1042 if (auto *SP = dyn_cast<DISubprogram>(
1043 V->getScope()->getNonLexicalBlockFileScope())) {
1044 StringRef Name = SP->getName();
1045 if (!Name.empty())
1046 OS << Name << ":";
1047 }
1048 OS << V->getName();
1049
1050 // NOTE: Want this comment at start of line, don't emit with AddComment.
1051 AP.OutStreamer->emitRawComment(OS.str());
1052 return true;
1053}
1054
1055AsmPrinter::CFISection
1056AsmPrinter::getFunctionCFISectionType(const Function &F) const {
1057 // Ignore functions that won't get emitted.
1058 if (F.isDeclarationForLinker())
1059 return CFISection::None;
1060
1061 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
1062 F.needsUnwindTableEntry())
1063 return CFISection::EH;
1064
1065 if (MMI->hasDebugInfo() || TM.Options.ForceDwarfFrameSection)
1066 return CFISection::Debug;
1067
1068 return CFISection::None;
1069}
1070
1071AsmPrinter::CFISection
1072AsmPrinter::getFunctionCFISectionType(const MachineFunction &MF) const {
1073 return getFunctionCFISectionType(MF.getFunction());
1074}
1075
1076bool AsmPrinter::needsSEHMoves() {
1077 return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
1078}
1079
1080bool AsmPrinter::needsCFIForDebug() const {
1081 return MAI->getExceptionHandlingType() == ExceptionHandling::None &&
1082 MAI->doesUseCFIForDebug() && ModuleCFISection == CFISection::Debug;
1083}
1084
1085void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
1086 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
1087 if (!needsCFIForDebug() &&
1088 ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
1089 ExceptionHandlingType != ExceptionHandling::ARM)
1090 return;
1091
1092 if (getFunctionCFISectionType(*MF) == CFISection::None)
1093 return;
1094
1095 // If there is no "real" instruction following this CFI instruction, skip
1096 // emitting it; it would be beyond the end of the function's FDE range.
1097 auto *MBB = MI.getParent();
1098 auto I = std::next(MI.getIterator());
1099 while (I != MBB->end() && I->isTransient())
1100 ++I;
1101 if (I == MBB->instr_end() &&
1102 MBB->getReverseIterator() == MBB->getParent()->rbegin())
1103 return;
1104
1105 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1106 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1107 const MCCFIInstruction &CFI = Instrs[CFIIndex];
1108 emitCFIInstruction(CFI);
1109}
1110
1111void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
1112 // The operands are the MCSymbol and the frame offset of the allocation.
1113 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1114 int FrameOffset = MI.getOperand(1).getImm();
1115
1116 // Emit a symbol assignment.
1117 OutStreamer->emitAssignment(FrameAllocSym,
1118 MCConstantExpr::create(FrameOffset, OutContext));
1119}
1120
1121/// Returns the BB metadata to be emitted in the .llvm_bb_addr_map section for a
1122/// given basic block. This can be used to capture more precise profile
1123/// information. We use the last 4 bits (LSBs) to encode the following
1124/// information:
1125/// * (1): set if return block (ret or tail call).
1126/// * (2): set if ends with a tail call.
1127/// * (3): set if exception handling (EH) landing pad.
1128/// * (4): set if the block can fall through to its next.
1129/// The remaining bits are zero.
1130static unsigned getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
1131 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
1132 return ((unsigned)MBB.isReturnBlock()) |
1133 ((!MBB.empty() && TII->isTailCall(MBB.back())) << 1) |
1134 (MBB.isEHPad() << 2) |
1135 (const_cast<MachineBasicBlock &>(MBB).canFallThrough() << 3);
1136}
1137
1138void AsmPrinter::emitBBAddrMapSection(const MachineFunction &MF) {
1139 MCSection *BBAddrMapSection =
1140 getObjFileLowering().getBBAddrMapSection(*MF.getSection());
1141 assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.")(static_cast <bool> (BBAddrMapSection && ".llvm_bb_addr_map section is not initialized."
) ? void (0) : __assert_fail ("BBAddrMapSection && \".llvm_bb_addr_map section is not initialized.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1141, __extension__
__PRETTY_FUNCTION__))
;
1142
1143 const MCSymbol *FunctionSymbol = getFunctionBegin();
1144
1145 OutStreamer->PushSection();
1146 OutStreamer->SwitchSection(BBAddrMapSection);
1147 OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
1148 // Emit the total number of basic blocks in this function.
1149 OutStreamer->emitULEB128IntValue(MF.size());
1150 // Emit BB Information for each basic block in the funciton.
1151 for (const MachineBasicBlock &MBB : MF) {
1152 const MCSymbol *MBBSymbol =
1153 MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1154 // Emit the basic block offset.
1155 emitLabelDifferenceAsULEB128(MBBSymbol, FunctionSymbol);
1156 // Emit the basic block size. When BBs have alignments, their size cannot
1157 // always be computed from their offsets.
1158 emitLabelDifferenceAsULEB128(MBB.getEndSymbol(), MBBSymbol);
1159 OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
1160 }
1161 OutStreamer->PopSection();
1162}
1163
1164void AsmPrinter::emitPseudoProbe(const MachineInstr &MI) {
1165 auto GUID = MI.getOperand(0).getImm();
1166 auto Index = MI.getOperand(1).getImm();
1167 auto Type = MI.getOperand(2).getImm();
1168 auto Attr = MI.getOperand(3).getImm();
1169 DILocation *DebugLoc = MI.getDebugLoc();
1170 PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
1171}
1172
1173void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
1174 if (!MF.getTarget().Options.EmitStackSizeSection)
1175 return;
1176
1177 MCSection *StackSizeSection =
1178 getObjFileLowering().getStackSizesSection(*getCurrentSection());
1179 if (!StackSizeSection)
1180 return;
1181
1182 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1183 // Don't emit functions with dynamic stack allocations.
1184 if (FrameInfo.hasVarSizedObjects())
1185 return;
1186
1187 OutStreamer->PushSection();
1188 OutStreamer->SwitchSection(StackSizeSection);
1189
1190 const MCSymbol *FunctionSymbol = getFunctionBegin();
1191 uint64_t StackSize = FrameInfo.getStackSize();
1192 OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
1193 OutStreamer->emitULEB128IntValue(StackSize);
1194
1195 OutStreamer->PopSection();
1196}
1197
1198void AsmPrinter::emitStackUsage(const MachineFunction &MF) {
1199 const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
1200
1201 // OutputFilename empty implies -fstack-usage is not passed.
1202 if (OutputFilename.empty())
1203 return;
1204
1205 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1206 uint64_t StackSize = FrameInfo.getStackSize();
1207
1208 if (StackUsageStream == nullptr) {
1209 std::error_code EC;
1210 StackUsageStream =
1211 std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
1212 if (EC) {
1213 errs() << "Could not open file: " << EC.message();
1214 return;
1215 }
1216 }
1217
1218 *StackUsageStream << MF.getFunction().getParent()->getName();
1219 if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1220 *StackUsageStream << ':' << DSP->getLine();
1221
1222 *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1223 if (FrameInfo.hasVarSizedObjects())
1224 *StackUsageStream << "dynamic\n";
1225 else
1226 *StackUsageStream << "static\n";
1227}
1228
1229static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF) {
1230 MachineModuleInfo &MMI = MF.getMMI();
1231 if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI.hasDebugInfo())
1232 return true;
1233
1234 // We might emit an EH table that uses function begin and end labels even if
1235 // we don't have any landingpads.
1236 if (!MF.getFunction().hasPersonalityFn())
1237 return false;
1238 return !isNoOpWithoutInvoke(
1239 classifyEHPersonality(MF.getFunction().getPersonalityFn()));
1240}
1241
1242/// EmitFunctionBody - This method emits the body and trailer for a
1243/// function.
1244void AsmPrinter::emitFunctionBody() {
1245 emitFunctionHeader();
1246
1247 // Emit target-specific gunk before the function body.
1248 emitFunctionBodyStart();
1249
1250 if (isVerbose()) {
1251 // Get MachineDominatorTree or compute it on the fly if it's unavailable
1252 MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1253 if (!MDT) {
1254 OwnedMDT = std::make_unique<MachineDominatorTree>();
1255 OwnedMDT->getBase().recalculate(*MF);
1256 MDT = OwnedMDT.get();
1257 }
1258
1259 // Get MachineLoopInfo or compute it on the fly if it's unavailable
1260 MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1261 if (!MLI) {
1262 OwnedMLI = std::make_unique<MachineLoopInfo>();
1263 OwnedMLI->getBase().analyze(MDT->getBase());
1264 MLI = OwnedMLI.get();
1265 }
1266 }
1267
1268 // Print out code for the function.
1269 bool HasAnyRealCode = false;
1270 int NumInstsInFunction = 0;
1271
1272 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE"asm-printer");
1273 for (auto &MBB : *MF) {
1274 // Print a label for the basic block.
1275 emitBasicBlockStart(MBB);
1276 DenseMap<StringRef, unsigned> MnemonicCounts;
1277 for (auto &MI : MBB) {
1278 // Print the assembly for the instruction.
1279 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1280 !MI.isDebugInstr()) {
1281 HasAnyRealCode = true;
1282 ++NumInstsInFunction;
1283 }
1284
1285 // If there is a pre-instruction symbol, emit a label for it here.
1286 if (MCSymbol *S = MI.getPreInstrSymbol())
1287 OutStreamer->emitLabel(S);
1288
1289 for (const HandlerInfo &HI : Handlers) {
1290 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1291 HI.TimerGroupDescription, TimePassesIsEnabled);
1292 HI.Handler->beginInstruction(&MI);
1293 }
1294
1295 if (isVerbose())
1296 emitComments(MI, OutStreamer->GetCommentOS());
1297
1298 switch (MI.getOpcode()) {
1299 case TargetOpcode::CFI_INSTRUCTION:
1300 emitCFIInstruction(MI);
1301 break;
1302 case TargetOpcode::LOCAL_ESCAPE:
1303 emitFrameAlloc(MI);
1304 break;
1305 case TargetOpcode::ANNOTATION_LABEL:
1306 case TargetOpcode::EH_LABEL:
1307 case TargetOpcode::GC_LABEL:
1308 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
1309 break;
1310 case TargetOpcode::INLINEASM:
1311 case TargetOpcode::INLINEASM_BR:
1312 emitInlineAsm(&MI);
1313 break;
1314 case TargetOpcode::DBG_VALUE:
1315 case TargetOpcode::DBG_VALUE_LIST:
1316 if (isVerbose()) {
1317 if (!emitDebugValueComment(&MI, *this))
1318 emitInstruction(&MI);
1319 }
1320 break;
1321 case TargetOpcode::DBG_INSTR_REF:
1322 // This instruction reference will have been resolved to a machine
1323 // location, and a nearby DBG_VALUE created. We can safely ignore
1324 // the instruction reference.
1325 break;
1326 case TargetOpcode::DBG_PHI:
1327 // This instruction is only used to label a program point, it's purely
1328 // meta information.
1329 break;
1330 case TargetOpcode::DBG_LABEL:
1331 if (isVerbose()) {
1332 if (!emitDebugLabelComment(&MI, *this))
1333 emitInstruction(&MI);
1334 }
1335 break;
1336 case TargetOpcode::IMPLICIT_DEF:
1337 if (isVerbose()) emitImplicitDef(&MI);
1338 break;
1339 case TargetOpcode::KILL:
1340 if (isVerbose()) emitKill(&MI, *this);
1341 break;
1342 case TargetOpcode::PSEUDO_PROBE:
1343 emitPseudoProbe(MI);
1344 break;
1345 case TargetOpcode::ARITH_FENCE:
1346 if (isVerbose())
1347 OutStreamer->emitRawComment("ARITH_FENCE");
1348 break;
1349 default:
1350 emitInstruction(&MI);
1351 if (CanDoExtraAnalysis) {
1352 MCInst MCI;
1353 MCI.setOpcode(MI.getOpcode());
1354 auto Name = OutStreamer->getMnemonic(MCI);
1355 auto I = MnemonicCounts.insert({Name, 0u});
1356 I.first->second++;
1357 }
1358 break;
1359 }
1360
1361 // If there is a post-instruction symbol, emit a label for it here.
1362 if (MCSymbol *S = MI.getPostInstrSymbol())
1363 OutStreamer->emitLabel(S);
1364
1365 for (const HandlerInfo &HI : Handlers) {
1366 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1367 HI.TimerGroupDescription, TimePassesIsEnabled);
1368 HI.Handler->endInstruction();
1369 }
1370 }
1371
1372 // We must emit temporary symbol for the end of this basic block, if either
1373 // we have BBLabels enabled or if this basic blocks marks the end of a
1374 // section.
1375 if (MF->hasBBLabels() ||
1376 (MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection()))
1377 OutStreamer->emitLabel(MBB.getEndSymbol());
1378
1379 if (MBB.isEndSection()) {
1380 // The size directive for the section containing the entry block is
1381 // handled separately by the function section.
1382 if (!MBB.sameSection(&MF->front())) {
1383 if (MAI->hasDotTypeDotSizeDirective()) {
1384 // Emit the size directive for the basic block section.
1385 const MCExpr *SizeExp = MCBinaryExpr::createSub(
1386 MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext),
1387 MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
1388 OutContext);
1389 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
1390 }
1391 MBBSectionRanges[MBB.getSectionIDNum()] =
1392 MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
1393 }
1394 }
1395 emitBasicBlockEnd(MBB);
1396
1397 if (CanDoExtraAnalysis) {
1398 // Skip empty blocks.
1399 if (MBB.empty())
1400 continue;
1401
1402 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE"asm-printer", "InstructionMix",
1403 MBB.begin()->getDebugLoc(), &MBB);
1404
1405 // Generate instruction mix remark. First, sort counts in descending order
1406 // by count and name.
1407 SmallVector<std::pair<StringRef, unsigned>, 128> MnemonicVec;
1408 for (auto &KV : MnemonicCounts)
1409 MnemonicVec.emplace_back(KV.first, KV.second);
1410
1411 sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
1412 const std::pair<StringRef, unsigned> &B) {
1413 if (A.second > B.second)
1414 return true;
1415 if (A.second == B.second)
1416 return StringRef(A.first) < StringRef(B.first);
1417 return false;
1418 });
1419 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
1420 for (auto &KV : MnemonicVec) {
1421 auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
1422 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
1423 }
1424 ORE->emit(R);
1425 }
1426 }
1427
1428 EmittedInsts += NumInstsInFunction;
1429 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE"asm-printer", "InstructionCount",
1430 MF->getFunction().getSubprogram(),
1431 &MF->front());
1432 R << ore::NV("NumInstructions", NumInstsInFunction)
1433 << " instructions in function";
1434 ORE->emit(R);
1435
1436 // If the function is empty and the object file uses .subsections_via_symbols,
1437 // then we need to emit *something* to the function body to prevent the
1438 // labels from collapsing together. Just emit a noop.
1439 // Similarly, don't emit empty functions on Windows either. It can lead to
1440 // duplicate entries (two functions with the same RVA) in the Guard CF Table
1441 // after linking, causing the kernel not to load the binary:
1442 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1443 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1444 const Triple &TT = TM.getTargetTriple();
1445 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1446 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1447 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
1448
1449 // Targets can opt-out of emitting the noop here by leaving the opcode
1450 // unspecified.
1451 if (Noop.getOpcode()) {
1452 OutStreamer->AddComment("avoids zero-length function");
1453 emitNops(1);
1454 }
1455 }
1456
1457 // Switch to the original section in case basic block sections was used.
1458 OutStreamer->SwitchSection(MF->getSection());
1459
1460 const Function &F = MF->getFunction();
1461 for (const auto &BB : F) {
1462 if (!BB.hasAddressTaken())
1463 continue;
1464 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
1465 if (Sym->isDefined())
1466 continue;
1467 OutStreamer->AddComment("Address of block that was removed by CodeGen");
1468 OutStreamer->emitLabel(Sym);
1469 }
1470
1471 // Emit target-specific gunk after the function body.
1472 emitFunctionBodyEnd();
1473
1474 if (needFuncLabelsForEHOrDebugInfo(*MF) ||
1475 MAI->hasDotTypeDotSizeDirective()) {
1476 // Create a symbol for the end of function.
1477 CurrentFnEnd = createTempSymbol("func_end");
1478 OutStreamer->emitLabel(CurrentFnEnd);
1479 }
1480
1481 // If the target wants a .size directive for the size of the function, emit
1482 // it.
1483 if (MAI->hasDotTypeDotSizeDirective()) {
1484 // We can get the size as difference between the function label and the
1485 // temp label.
1486 const MCExpr *SizeExp = MCBinaryExpr::createSub(
1487 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1488 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
1489 OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1490 }
1491
1492 for (const HandlerInfo &HI : Handlers) {
1493 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1494 HI.TimerGroupDescription, TimePassesIsEnabled);
1495 HI.Handler->markFunctionEnd();
1496 }
1497
1498 MBBSectionRanges[MF->front().getSectionIDNum()] =
1499 MBBSectionRange{CurrentFnBegin, CurrentFnEnd};
1500
1501 // Print out jump tables referenced by the function.
1502 emitJumpTableInfo();
1503
1504 // Emit post-function debug and/or EH information.
1505 for (const HandlerInfo &HI : Handlers) {
1506 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1507 HI.TimerGroupDescription, TimePassesIsEnabled);
1508 HI.Handler->endFunction(MF);
1509 }
1510
1511 // Emit section containing BB address offsets and their metadata, when
1512 // BB labels are requested for this function. Skip empty functions.
1513 if (MF->hasBBLabels() && HasAnyRealCode)
1514 emitBBAddrMapSection(*MF);
1515
1516 // Emit section containing stack size metadata.
1517 emitStackSizeSection(*MF);
1518
1519 // Emit .su file containing function stack size information.
1520 emitStackUsage(*MF);
1521
1522 emitPatchableFunctionEntries();
1523
1524 if (isVerbose())
1525 OutStreamer->GetCommentOS() << "-- End function\n";
1526
1527 OutStreamer->AddBlankLine();
1528}
1529
1530/// Compute the number of Global Variables that uses a Constant.
1531static unsigned getNumGlobalVariableUses(const Constant *C) {
1532 if (!C)
1533 return 0;
1534
1535 if (isa<GlobalVariable>(C))
1536 return 1;
1537
1538 unsigned NumUses = 0;
1539 for (auto *CU : C->users())
1540 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1541
1542 return NumUses;
1543}
1544
1545/// Only consider global GOT equivalents if at least one user is a
1546/// cstexpr inside an initializer of another global variables. Also, don't
1547/// handle cstexpr inside instructions. During global variable emission,
1548/// candidates are skipped and are emitted later in case at least one cstexpr
1549/// isn't replaced by a PC relative GOT entry access.
1550static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
1551 unsigned &NumGOTEquivUsers) {
1552 // Global GOT equivalents are unnamed private globals with a constant
1553 // pointer initializer to another global symbol. They must point to a
1554 // GlobalVariable or Function, i.e., as GlobalValue.
1555 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1556 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1557 !isa<GlobalValue>(GV->getOperand(0)))
1558 return false;
1559
1560 // To be a got equivalent, at least one of its users need to be a constant
1561 // expression used by another global variable.
1562 for (auto *U : GV->users())
1563 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1564
1565 return NumGOTEquivUsers > 0;
1566}
1567
1568/// Unnamed constant global variables solely contaning a pointer to
1569/// another globals variable is equivalent to a GOT table entry; it contains the
1570/// the address of another symbol. Optimize it and replace accesses to these
1571/// "GOT equivalents" by using the GOT entry for the final global instead.
1572/// Compute GOT equivalent candidates among all global variables to avoid
1573/// emitting them if possible later on, after it use is replaced by a GOT entry
1574/// access.
1575void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
1576 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1577 return;
1578
1579 for (const auto &G : M.globals()) {
1580 unsigned NumGOTEquivUsers = 0;
1581 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1582 continue;
1583
1584 const MCSymbol *GOTEquivSym = getSymbol(&G);
1585 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1586 }
1587}
1588
1589/// Constant expressions using GOT equivalent globals may not be eligible
1590/// for PC relative GOT entry conversion, in such cases we need to emit such
1591/// globals we previously omitted in EmitGlobalVariable.
1592void AsmPrinter::emitGlobalGOTEquivs() {
1593 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1594 return;
1595
1596 SmallVector<const GlobalVariable *, 8> FailedCandidates;
1597 for (auto &I : GlobalGOTEquivs) {
1598 const GlobalVariable *GV = I.second.first;
1599 unsigned Cnt = I.second.second;
1600 if (Cnt)
1601 FailedCandidates.push_back(GV);
1602 }
1603 GlobalGOTEquivs.clear();
1604
1605 for (auto *GV : FailedCandidates)
1606 emitGlobalVariable(GV);
1607}
1608
1609void AsmPrinter::emitGlobalAlias(Module &M, const GlobalAlias &GA) {
1610 MCSymbol *Name = getSymbol(&GA);
1611 bool IsFunction = GA.getValueType()->isFunctionTy();
1612 // Treat bitcasts of functions as functions also. This is important at least
1613 // on WebAssembly where object and function addresses can't alias each other.
1614 if (!IsFunction)
1615 if (auto *CE = dyn_cast<ConstantExpr>(GA.getAliasee()))
1616 if (CE->getOpcode() == Instruction::BitCast)
1617 IsFunction =
1618 CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1619
1620 // AIX's assembly directive `.set` is not usable for aliasing purpose,
1621 // so AIX has to use the extra-label-at-definition strategy. At this
1622 // point, all the extra label is emitted, we just have to emit linkage for
1623 // those labels.
1624 if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
1625 assert(MAI->hasVisibilityOnlyWithLinkage() &&(static_cast <bool> (MAI->hasVisibilityOnlyWithLinkage
() && "Visibility should be handled with emitLinkage() on AIX."
) ? void (0) : __assert_fail ("MAI->hasVisibilityOnlyWithLinkage() && \"Visibility should be handled with emitLinkage() on AIX.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1626, __extension__
__PRETTY_FUNCTION__))
1626 "Visibility should be handled with emitLinkage() on AIX.")(static_cast <bool> (MAI->hasVisibilityOnlyWithLinkage
() && "Visibility should be handled with emitLinkage() on AIX."
) ? void (0) : __assert_fail ("MAI->hasVisibilityOnlyWithLinkage() && \"Visibility should be handled with emitLinkage() on AIX.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1626, __extension__
__PRETTY_FUNCTION__))
;
1627 emitLinkage(&GA, Name);
1628 // If it's a function, also emit linkage for aliases of function entry
1629 // point.
1630 if (IsFunction)
1631 emitLinkage(&GA,
1632 getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
1633 return;
1634 }
1635
1636 if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
1637 OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1638 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
1639 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1640 else
1641 assert(GA.hasLocalLinkage() && "Invalid alias linkage")(static_cast <bool> (GA.hasLocalLinkage() && "Invalid alias linkage"
) ? void (0) : __assert_fail ("GA.hasLocalLinkage() && \"Invalid alias linkage\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1641, __extension__
__PRETTY_FUNCTION__))
;
1642
1643 // Set the symbol type to function if the alias has a function type.
1644 // This affects codegen when the aliasee is not a function.
1645 if (IsFunction)
1646 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
1647
1648 emitVisibility(Name, GA.getVisibility());
1649
1650 const MCExpr *Expr = lowerConstant(GA.getAliasee());
1651
1652 if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1653 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
1654
1655 // Emit the directives as assignments aka .set:
1656 OutStreamer->emitAssignment(Name, Expr);
1657 MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
1658 if (LocalAlias != Name)
1659 OutStreamer->emitAssignment(LocalAlias, Expr);
1660
1661 // If the aliasee does not correspond to a symbol in the output, i.e. the
1662 // alias is not of an object or the aliased object is private, then set the
1663 // size of the alias symbol from the type of the alias. We don't do this in
1664 // other situations as the alias and aliasee having differing types but same
1665 // size may be intentional.
1666 const GlobalObject *BaseObject = GA.getAliaseeObject();
1667 if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
1668 (!BaseObject || BaseObject->hasPrivateLinkage())) {
1669 const DataLayout &DL = M.getDataLayout();
1670 uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
1671 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
1672 }
1673}
1674
1675void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
1676 assert(!TM.getTargetTriple().isOSBinFormatXCOFF() &&(static_cast <bool> (!TM.getTargetTriple().isOSBinFormatXCOFF
() && "IFunc is not supported on AIX.") ? void (0) : __assert_fail
("!TM.getTargetTriple().isOSBinFormatXCOFF() && \"IFunc is not supported on AIX.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1677, __extension__
__PRETTY_FUNCTION__))
1677 "IFunc is not supported on AIX.")(static_cast <bool> (!TM.getTargetTriple().isOSBinFormatXCOFF
() && "IFunc is not supported on AIX.") ? void (0) : __assert_fail
("!TM.getTargetTriple().isOSBinFormatXCOFF() && \"IFunc is not supported on AIX.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1677, __extension__
__PRETTY_FUNCTION__))
;
1678
1679 MCSymbol *Name = getSymbol(&GI);
1680
1681 if (GI.hasExternalLinkage() || !MAI->getWeakRefDirective())
1682 OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1683 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
1684 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1685 else
1686 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage")(static_cast <bool> (GI.hasLocalLinkage() && "Invalid ifunc linkage"
) ? void (0) : __assert_fail ("GI.hasLocalLinkage() && \"Invalid ifunc linkage\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1686, __extension__
__PRETTY_FUNCTION__))
;
1687
1688 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
1689 emitVisibility(Name, GI.getVisibility());
1690
1691 // Emit the directives as assignments aka .set:
1692 const MCExpr *Expr = lowerConstant(GI.getResolver());
1693 OutStreamer->emitAssignment(Name, Expr);
1694 MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
1695 if (LocalAlias != Name)
1696 OutStreamer->emitAssignment(LocalAlias, Expr);
1697}
1698
1699void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) {
1700 if (!RS.needsSection())
1701 return;
1702
1703 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
1704
1705 Optional<SmallString<128>> Filename;
1706 if (Optional<StringRef> FilenameRef = RS.getFilename()) {
1707 Filename = *FilenameRef;
1708 sys::fs::make_absolute(*Filename);
1709 assert(!Filename->empty() && "The filename can't be empty.")(static_cast <bool> (!Filename->empty() && "The filename can't be empty."
) ? void (0) : __assert_fail ("!Filename->empty() && \"The filename can't be empty.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1709, __extension__
__PRETTY_FUNCTION__))
;
1710 }
1711
1712 std::string Buf;
1713 raw_string_ostream OS(Buf);
1714 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
1715 Filename ? RemarkSerializer.metaSerializer(OS, Filename->str())
1716 : RemarkSerializer.metaSerializer(OS);
1717 MetaSerializer->emit();
1718
1719 // Switch to the remarks section.
1720 MCSection *RemarksSection =
1721 OutContext.getObjectFileInfo()->getRemarksSection();
1722 OutStreamer->SwitchSection(RemarksSection);
1723
1724 OutStreamer->emitBinaryData(OS.str());
1725}
1726
1727bool AsmPrinter::doFinalization(Module &M) {
1728 // Set the MachineFunction to nullptr so that we can catch attempted
1729 // accesses to MF specific features at the module level and so that
1730 // we can conditionalize accesses based on whether or not it is nullptr.
1731 MF = nullptr;
1732
1733 // Gather all GOT equivalent globals in the module. We really need two
1734 // passes over the globals: one to compute and another to avoid its emission
1735 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1736 // where the got equivalent shows up before its use.
1737 computeGlobalGOTEquivs(M);
1738
1739 // Emit global variables.
1740 for (const auto &G : M.globals())
1741 emitGlobalVariable(&G);
1742
1743 // Emit remaining GOT equivalent globals.
1744 emitGlobalGOTEquivs();
1745
1746 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1747
1748 // Emit linkage(XCOFF) and visibility info for declarations
1749 for (const Function &F : M) {
1750 if (!F.isDeclarationForLinker())
1751 continue;
1752
1753 MCSymbol *Name = getSymbol(&F);
1754 // Function getSymbol gives us the function descriptor symbol for XCOFF.
1755
1756 if (!TM.getTargetTriple().isOSBinFormatXCOFF()) {
1757 GlobalValue::VisibilityTypes V = F.getVisibility();
1758 if (V == GlobalValue::DefaultVisibility)
1759 continue;
1760
1761 emitVisibility(Name, V, false);
1762 continue;
1763 }
1764
1765 if (F.isIntrinsic())
1766 continue;
1767
1768 // Handle the XCOFF case.
1769 // Variable `Name` is the function descriptor symbol (see above). Get the
1770 // function entry point symbol.
1771 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
1772 // Emit linkage for the function entry point.
1773 emitLinkage(&F, FnEntryPointSym);
1774
1775 // Emit linkage for the function descriptor.
1776 emitLinkage(&F, Name);
1777 }
1778
1779 // Emit the remarks section contents.
1780 // FIXME: Figure out when is the safest time to emit this section. It should
1781 // not come after debug info.
1782 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
1783 emitRemarksSection(*RS);
1784
1785 TLOF.emitModuleMetadata(*OutStreamer, M);
1786
1787 if (TM.getTargetTriple().isOSBinFormatELF()) {
1788 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1789
1790 // Output stubs for external and common global variables.
1791 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1792 if (!Stubs.empty()) {
1793 OutStreamer->SwitchSection(TLOF.getDataSection());
1794 const DataLayout &DL = M.getDataLayout();
1795
1796 emitAlignment(Align(DL.getPointerSize()));
1797 for (const auto &Stub : Stubs) {
1798 OutStreamer->emitLabel(Stub.first);
1799 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1800 DL.getPointerSize());
1801 }
1802 }
1803 }
1804
1805 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
1806 MachineModuleInfoCOFF &MMICOFF =
1807 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
1808
1809 // Output stubs for external and common global variables.
1810 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
1811 if (!Stubs.empty()) {
1812 const DataLayout &DL = M.getDataLayout();
1813
1814 for (const auto &Stub : Stubs) {
1815 SmallString<256> SectionName = StringRef(".rdata$");
1816 SectionName += Stub.first->getName();
1817 OutStreamer->SwitchSection(OutContext.getCOFFSection(
1818 SectionName,
1819 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
1820 COFF::IMAGE_SCN_LNK_COMDAT,
1821 SectionKind::getReadOnly(), Stub.first->getName(),
1822 COFF::IMAGE_COMDAT_SELECT_ANY));
1823 emitAlignment(Align(DL.getPointerSize()));
1824 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
1825 OutStreamer->emitLabel(Stub.first);
1826 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1827 DL.getPointerSize());
1828 }
1829 }
1830 }
1831
1832 // This needs to happen before emitting debug information since that can end
1833 // arbitrary sections.
1834 if (auto *TS = OutStreamer->getTargetStreamer())
1835 TS->emitConstantPools();
1836
1837 // Finalize debug and EH information.
1838 for (const HandlerInfo &HI : Handlers) {
1839 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1840 HI.TimerGroupDescription, TimePassesIsEnabled);
1841 HI.Handler->endModule();
1842 }
1843
1844 // This deletes all the ephemeral handlers that AsmPrinter added, while
1845 // keeping all the user-added handlers alive until the AsmPrinter is
1846 // destroyed.
1847 Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
1848 DD = nullptr;
1849
1850 // If the target wants to know about weak references, print them all.
1851 if (MAI->getWeakRefDirective()) {
1852 // FIXME: This is not lazy, it would be nice to only print weak references
1853 // to stuff that is actually used. Note that doing so would require targets
1854 // to notice uses in operands (due to constant exprs etc). This should
1855 // happen with the MC stuff eventually.
1856
1857 // Print out module-level global objects here.
1858 for (const auto &GO : M.global_objects()) {
1859 if (!GO.hasExternalWeakLinkage())
1860 continue;
1861 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1862 }
1863 if (shouldEmitWeakSwiftAsyncExtendedFramePointerFlags()) {
1864 auto SymbolName = "swift_async_extendedFramePointerFlags";
1865 auto Global = M.getGlobalVariable(SymbolName);
1866 if (!Global) {
1867 auto Int8PtrTy = Type::getInt8PtrTy(M.getContext());
1868 Global = new GlobalVariable(M, Int8PtrTy, false,
1869 GlobalValue::ExternalWeakLinkage, nullptr,
1870 SymbolName);
1871 OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
1872 }
1873 }
1874 }
1875
1876 // Print aliases in topological order, that is, for each alias a = b,
1877 // b must be printed before a.
1878 // This is because on some targets (e.g. PowerPC) linker expects aliases in
1879 // such an order to generate correct TOC information.
1880 SmallVector<const GlobalAlias *, 16> AliasStack;
1881 SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
1882 for (const auto &Alias : M.aliases()) {
1883 for (const GlobalAlias *Cur = &Alias; Cur;
1884 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1885 if (!AliasVisited.insert(Cur).second)
1886 break;
1887 AliasStack.push_back(Cur);
1888 }
1889 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1890 emitGlobalAlias(M, *AncestorAlias);
1891 AliasStack.clear();
1892 }
1893 for (const auto &IFunc : M.ifuncs())
1894 emitGlobalIFunc(M, IFunc);
1895
1896 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1897 assert(MI && "AsmPrinter didn't require GCModuleInfo?")(static_cast <bool> (MI && "AsmPrinter didn't require GCModuleInfo?"
) ? void (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 1897, __extension__
__PRETTY_FUNCTION__))
;
1898 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1899 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1900 MP->finishAssembly(M, *MI, *this);
1901
1902 // Emit llvm.ident metadata in an '.ident' directive.
1903 emitModuleIdents(M);
1904
1905 // Emit bytes for llvm.commandline metadata.
1906 emitModuleCommandLines(M);
1907
1908 // Emit __morestack address if needed for indirect calls.
1909 if (MMI->usesMorestackAddr()) {
1910 Align Alignment(1);
1911 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1912 getDataLayout(), SectionKind::getReadOnly(),
1913 /*C=*/nullptr, Alignment);
1914 OutStreamer->SwitchSection(ReadOnlySection);
1915
1916 MCSymbol *AddrSymbol =
1917 OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1918 OutStreamer->emitLabel(AddrSymbol);
1919
1920 unsigned PtrSize = MAI->getCodePointerSize();
1921 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1922 PtrSize);
1923 }
1924
1925 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1926 // split-stack is used.
1927 if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) {
1928 OutStreamer->SwitchSection(
1929 OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1930 if (MMI->hasNosplitStack())
1931 OutStreamer->SwitchSection(
1932 OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1933 }
1934
1935 // If we don't have any trampolines, then we don't require stack memory
1936 // to be executable. Some targets have a directive to declare this.
1937 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1938 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1939 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1940 OutStreamer->SwitchSection(S);
1941
1942 if (TM.Options.EmitAddrsig) {
1943 // Emit address-significance attributes for all globals.
1944 OutStreamer->emitAddrsig();
1945 for (const GlobalValue &GV : M.global_values()) {
1946 if (!GV.use_empty() && !GV.isTransitiveUsedByMetadataOnly() &&
1947 !GV.isThreadLocal() && !GV.hasDLLImportStorageClass() &&
1948 !GV.getName().startswith("llvm.") && !GV.hasAtLeastLocalUnnamedAddr())
1949 OutStreamer->emitAddrsigSym(getSymbol(&GV));
1950 }
1951 }
1952
1953 // Emit symbol partition specifications (ELF only).
1954 if (TM.getTargetTriple().isOSBinFormatELF()) {
1955 unsigned UniqueID = 0;
1956 for (const GlobalValue &GV : M.global_values()) {
1957 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
1958 GV.getVisibility() != GlobalValue::DefaultVisibility)
1959 continue;
1960
1961 OutStreamer->SwitchSection(
1962 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
1963 "", false, ++UniqueID, nullptr));
1964 OutStreamer->emitBytes(GV.getPartition());
1965 OutStreamer->emitZeros(1);
1966 OutStreamer->emitValue(
1967 MCSymbolRefExpr::create(getSymbol(&GV), OutContext),
1968 MAI->getCodePointerSize());
1969 }
1970 }
1971
1972 // Allow the target to emit any magic that it wants at the end of the file,
1973 // after everything else has gone out.
1974 emitEndOfAsmFile(M);
1975
1976 MMI = nullptr;
1977
1978 OutStreamer->Finish();
1979 OutStreamer->reset();
1980 OwnedMLI.reset();
1981 OwnedMDT.reset();
1982
1983 return false;
1984}
1985
1986MCSymbol *AsmPrinter::getMBBExceptionSym(const MachineBasicBlock &MBB) {
1987 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum());
1988 if (Res.second)
1989 Res.first->second = createTempSymbol("exception");
1990 return Res.first->second;
1991}
1992
1993void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1994 this->MF = &MF;
1995 const Function &F = MF.getFunction();
1996
1997 // Get the function symbol.
1998 if (!MAI->needsFunctionDescriptors()) {
1999 CurrentFnSym = getSymbol(&MF.getFunction());
2000 } else {
2001 assert(TM.getTargetTriple().isOSAIX() &&(static_cast <bool> (TM.getTargetTriple().isOSAIX() &&
"Only AIX uses the function descriptor hooks.") ? void (0) :
__assert_fail ("TM.getTargetTriple().isOSAIX() && \"Only AIX uses the function descriptor hooks.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2002, __extension__
__PRETTY_FUNCTION__))
2002 "Only AIX uses the function descriptor hooks.")(static_cast <bool> (TM.getTargetTriple().isOSAIX() &&
"Only AIX uses the function descriptor hooks.") ? void (0) :
__assert_fail ("TM.getTargetTriple().isOSAIX() && \"Only AIX uses the function descriptor hooks.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2002, __extension__
__PRETTY_FUNCTION__))
;
2003 // AIX is unique here in that the name of the symbol emitted for the
2004 // function body does not have the same name as the source function's
2005 // C-linkage name.
2006 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"(static_cast <bool> (CurrentFnDescSym && "The function descriptor symbol needs to be"
" initalized first.") ? void (0) : __assert_fail ("CurrentFnDescSym && \"The function descriptor symbol needs to be\" \" initalized first.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2007, __extension__
__PRETTY_FUNCTION__))
2007 " initalized first.")(static_cast <bool> (CurrentFnDescSym && "The function descriptor symbol needs to be"
" initalized first.") ? void (0) : __assert_fail ("CurrentFnDescSym && \"The function descriptor symbol needs to be\" \" initalized first.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2007, __extension__
__PRETTY_FUNCTION__))
;
2008
2009 // Get the function entry point symbol.
2010 CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(&F, TM);
2011 }
2012
2013 CurrentFnSymForSize = CurrentFnSym;
2014 CurrentFnBegin = nullptr;
2015 CurrentSectionBeginSym = nullptr;
2016 MBBSectionRanges.clear();
2017 MBBSectionExceptionSyms.clear();
2018 bool NeedsLocalForSize = MAI->needsLocalForSize();
2019 if (F.hasFnAttribute("patchable-function-entry") ||
2020 F.hasFnAttribute("function-instrument") ||
2021 F.hasFnAttribute("xray-instruction-threshold") ||
2022 needFuncLabelsForEHOrDebugInfo(MF) || NeedsLocalForSize ||
2023 MF.getTarget().Options.EmitStackSizeSection || MF.hasBBLabels()) {
2024 CurrentFnBegin = createTempSymbol("func_begin");
2025 if (NeedsLocalForSize)
2026 CurrentFnSymForSize = CurrentFnBegin;
2027 }
2028
2029 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2030}
2031
2032namespace {
2033
2034// Keep track the alignment, constpool entries per Section.
2035 struct SectionCPs {
2036 MCSection *S;
2037 Align Alignment;
2038 SmallVector<unsigned, 4> CPEs;
2039
2040 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
2041 };
2042
2043} // end anonymous namespace
2044
2045/// EmitConstantPool - Print to the current output stream assembly
2046/// representations of the constants in the constant pool MCP. This is
2047/// used to print out constants which have been "spilled to memory" by
2048/// the code generator.
2049void AsmPrinter::emitConstantPool() {
2050 const MachineConstantPool *MCP = MF->getConstantPool();
2051 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
2052 if (CP.empty()) return;
2053
2054 // Calculate sections for constant pool entries. We collect entries to go into
2055 // the same section together to reduce amount of section switch statements.
2056 SmallVector<SectionCPs, 4> CPSections;
2057 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
2058 const MachineConstantPoolEntry &CPE = CP[i];
2059 Align Alignment = CPE.getAlign();
2060
2061 SectionKind Kind = CPE.getSectionKind(&getDataLayout());
2062
2063 const Constant *C = nullptr;
2064 if (!CPE.isMachineConstantPoolEntry())
2065 C = CPE.Val.ConstVal;
2066
2067 MCSection *S = getObjFileLowering().getSectionForConstant(
2068 getDataLayout(), Kind, C, Alignment);
2069
2070 // The number of sections are small, just do a linear search from the
2071 // last section to the first.
2072 bool Found = false;
2073 unsigned SecIdx = CPSections.size();
2074 while (SecIdx != 0) {
2075 if (CPSections[--SecIdx].S == S) {
2076 Found = true;
2077 break;
2078 }
2079 }
2080 if (!Found) {
2081 SecIdx = CPSections.size();
2082 CPSections.push_back(SectionCPs(S, Alignment));
2083 }
2084
2085 if (Alignment > CPSections[SecIdx].Alignment)
2086 CPSections[SecIdx].Alignment = Alignment;
2087 CPSections[SecIdx].CPEs.push_back(i);
2088 }
2089
2090 // Now print stuff into the calculated sections.
2091 const MCSection *CurSection = nullptr;
2092 unsigned Offset = 0;
2093 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
2094 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
2095 unsigned CPI = CPSections[i].CPEs[j];
2096 MCSymbol *Sym = GetCPISymbol(CPI);
2097 if (!Sym->isUndefined())
2098 continue;
2099
2100 if (CurSection != CPSections[i].S) {
2101 OutStreamer->SwitchSection(CPSections[i].S);
2102 emitAlignment(Align(CPSections[i].Alignment));
2103 CurSection = CPSections[i].S;
2104 Offset = 0;
2105 }
2106
2107 MachineConstantPoolEntry CPE = CP[CPI];
2108
2109 // Emit inter-object padding for alignment.
2110 unsigned NewOffset = alignTo(Offset, CPE.getAlign());
2111 OutStreamer->emitZeros(NewOffset - Offset);
2112
2113 Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
2114
2115 OutStreamer->emitLabel(Sym);
2116 if (CPE.isMachineConstantPoolEntry())
2117 emitMachineConstantPoolValue(CPE.Val.MachineCPVal);
2118 else
2119 emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
2120 }
2121 }
2122}
2123
2124// Print assembly representations of the jump tables used by the current
2125// function.
2126void AsmPrinter::emitJumpTableInfo() {
2127 const DataLayout &DL = MF->getDataLayout();
2128 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2129 if (!MJTI) return;
2130 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
2131 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2132 if (JT.empty()) return;
2133
2134 // Pick the directive to use to print the jump table entries, and switch to
2135 // the appropriate section.
2136 const Function &F = MF->getFunction();
2137 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
2138 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
2139 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
2140 F);
2141 if (JTInDiffSection) {
2142 // Drop it in the readonly section.
2143 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
2144 OutStreamer->SwitchSection(ReadOnlySection);
2145 }
2146
2147 emitAlignment(Align(MJTI->getEntryAlignment(DL)));
2148
2149 // Jump tables in code sections are marked with a data_region directive
2150 // where that's supported.
2151 if (!JTInDiffSection)
2152 OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
2153
2154 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2155 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2156
2157 // If this jump table was deleted, ignore it.
2158 if (JTBBs.empty()) continue;
2159
2160 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2161 /// emit a .set directive for each unique entry.
2162 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
2163 MAI->doesSetDirectiveSuppressReloc()) {
2164 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
2165 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2166 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
2167 for (const MachineBasicBlock *MBB : JTBBs) {
2168 if (!EmittedSets.insert(MBB).second)
2169 continue;
2170
2171 // .set LJTSet, LBB32-base
2172 const MCExpr *LHS =
2173 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2174 OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
2175 MCBinaryExpr::createSub(LHS, Base,
2176 OutContext));
2177 }
2178 }
2179
2180 // On some targets (e.g. Darwin) we want to emit two consecutive labels
2181 // before each jump table. The first label is never referenced, but tells
2182 // the assembler and linker the extents of the jump table object. The
2183 // second label is actually referenced by the code.
2184 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
2185 // FIXME: This doesn't have to have any specific name, just any randomly
2186 // named and numbered local label started with 'l' would work. Simplify
2187 // GetJTISymbol.
2188 OutStreamer->emitLabel(GetJTISymbol(JTI, true));
2189
2190 MCSymbol* JTISymbol = GetJTISymbol(JTI);
2191 OutStreamer->emitLabel(JTISymbol);
2192
2193 for (const MachineBasicBlock *MBB : JTBBs)
2194 emitJumpTableEntry(MJTI, MBB, JTI);
2195 }
2196 if (!JTInDiffSection)
2197 OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
2198}
2199
2200/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2201/// current stream.
2202void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
2203 const MachineBasicBlock *MBB,
2204 unsigned UID) const {
2205 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block")(static_cast <bool> (MBB && MBB->getNumber()
>= 0 && "Invalid basic block") ? void (0) : __assert_fail
("MBB && MBB->getNumber() >= 0 && \"Invalid basic block\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2205, __extension__
__PRETTY_FUNCTION__))
;
2206 const MCExpr *Value = nullptr;
2207 switch (MJTI->getEntryKind()) {
2208 case MachineJumpTableInfo::EK_Inline:
2209 llvm_unreachable("Cannot emit EK_Inline jump table entry")::llvm::llvm_unreachable_internal("Cannot emit EK_Inline jump table entry"
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2209)
;
2210 case MachineJumpTableInfo::EK_Custom32:
2211 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
2212 MJTI, MBB, UID, OutContext);
2213 break;
2214 case MachineJumpTableInfo::EK_BlockAddress:
2215 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
2216 // .word LBB123
2217 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2218 break;
2219 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
2220 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
2221 // with a relocation as gp-relative, e.g.:
2222 // .gprel32 LBB123
2223 MCSymbol *MBBSym = MBB->getSymbol();
2224 OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2225 return;
2226 }
2227
2228 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
2229 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
2230 // with a relocation as gp-relative, e.g.:
2231 // .gpdword LBB123
2232 MCSymbol *MBBSym = MBB->getSymbol();
2233 OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2234 return;
2235 }
2236
2237 case MachineJumpTableInfo::EK_LabelDifference32: {
2238 // Each entry is the address of the block minus the address of the jump
2239 // table. This is used for PIC jump tables where gprel32 is not supported.
2240 // e.g.:
2241 // .word LBB123 - LJTI1_2
2242 // If the .set directive avoids relocations, this is emitted as:
2243 // .set L4_5_set_123, LBB123 - LJTI1_2
2244 // .word L4_5_set_123
2245 if (MAI->doesSetDirectiveSuppressReloc()) {
2246 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
2247 OutContext);
2248 break;
2249 }
2250 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2251 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2252 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
2253 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
2254 break;
2255 }
2256 }
2257
2258 assert(Value && "Unknown entry kind!")(static_cast <bool> (Value && "Unknown entry kind!"
) ? void (0) : __assert_fail ("Value && \"Unknown entry kind!\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2258, __extension__
__PRETTY_FUNCTION__))
;
2259
2260 unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
2261 OutStreamer->emitValue(Value, EntrySize);
2262}
2263
2264/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
2265/// special global used by LLVM. If so, emit it and return true, otherwise
2266/// do nothing and return false.
2267bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) {
2268 if (GV->getName() == "llvm.used") {
2269 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
2270 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
2271 return true;
2272 }
2273
2274 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
2275 if (GV->getSection() == "llvm.metadata" ||
2276 GV->hasAvailableExternallyLinkage())
2277 return true;
2278
2279 if (!GV->hasAppendingLinkage()) return false;
2280
2281 assert(GV->hasInitializer() && "Not a special LLVM global!")(static_cast <bool> (GV->hasInitializer() &&
"Not a special LLVM global!") ? void (0) : __assert_fail ("GV->hasInitializer() && \"Not a special LLVM global!\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2281, __extension__
__PRETTY_FUNCTION__))
;
2282
2283 if (GV->getName() == "llvm.global_ctors") {
2284 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2285 /* isCtor */ true);
2286
2287 return true;
2288 }
2289
2290 if (GV->getName() == "llvm.global_dtors") {
2291 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2292 /* isCtor */ false);
2293
2294 return true;
2295 }
2296
2297 report_fatal_error("unknown special variable");
2298}
2299
2300/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2301/// global in the specified llvm.used list.
2302void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
2303 // Should be an array of 'i8*'.
2304 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2305 const GlobalValue *GV =
2306 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
2307 if (GV)
2308 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
2309 }
2310}
2311
2312void AsmPrinter::preprocessXXStructorList(const DataLayout &DL,
2313 const Constant *List,
2314 SmallVector<Structor, 8> &Structors) {
2315 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
2316 // the init priority.
2317 if (!isa<ConstantArray>(List))
2318 return;
2319
2320 // Gather the structors in a form that's convenient for sorting by priority.
2321 for (Value *O : cast<ConstantArray>(List)->operands()) {
2322 auto *CS = cast<ConstantStruct>(O);
2323 if (CS->getOperand(1)->isNullValue())
2324 break; // Found a null terminator, skip the rest.
2325 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2326 if (!Priority)
2327 continue; // Malformed.
2328 Structors.push_back(Structor());
2329 Structor &S = Structors.back();
2330 S.Priority = Priority->getLimitedValue(65535);
2331 S.Func = CS->getOperand(1);
2332 if (!CS->getOperand(2)->isNullValue()) {
2333 if (TM.getTargetTriple().isOSAIX())
2334 llvm::report_fatal_error(
2335 "associated data of XXStructor list is not yet supported on AIX");
2336 S.ComdatKey =
2337 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2338 }
2339 }
2340
2341 // Emit the function pointers in the target-specific order
2342 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2343 return L.Priority < R.Priority;
2344 });
2345}
2346
2347/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2348/// priority.
2349void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List,
2350 bool IsCtor) {
2351 SmallVector<Structor, 8> Structors;
2352 preprocessXXStructorList(DL, List, Structors);
2353 if (Structors.empty())
2354 return;
2355
2356 // Emit the structors in reverse order if we are using the .ctor/.dtor
2357 // initialization scheme.
2358 if (!TM.Options.UseInitArray)
2359 std::reverse(Structors.begin(), Structors.end());
2360
2361 const Align Align = DL.getPointerPrefAlignment();
2362 for (Structor &S : Structors) {
2363 const TargetLoweringObjectFile &Obj = getObjFileLowering();
2364 const MCSymbol *KeySym = nullptr;
2365 if (GlobalValue *GV = S.ComdatKey) {
2366 if (GV->isDeclarationForLinker())
2367 // If the associated variable is not defined in this module
2368 // (it might be available_externally, or have been an
2369 // available_externally definition that was dropped by the
2370 // EliminateAvailableExternally pass), some other TU
2371 // will provide its dynamic initializer.
2372 continue;
2373
2374 KeySym = getSymbol(GV);
2375 }
2376
2377 MCSection *OutputSection =
2378 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2379 : Obj.getStaticDtorSection(S.Priority, KeySym));
2380 OutStreamer->SwitchSection(OutputSection);
2381 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2382 emitAlignment(Align);
2383 emitXXStructor(DL, S.Func);
2384 }
2385}
2386
2387void AsmPrinter::emitModuleIdents(Module &M) {
2388 if (!MAI->hasIdentDirective())
2389 return;
2390
2391 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2392 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2393 const MDNode *N = NMD->getOperand(i);
2394 assert(N->getNumOperands() == 1 &&(static_cast <bool> (N->getNumOperands() == 1 &&
"llvm.ident metadata entry can have only one operand") ? void
(0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.ident metadata entry can have only one operand\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2395, __extension__
__PRETTY_FUNCTION__))
2395 "llvm.ident metadata entry can have only one operand")(static_cast <bool> (N->getNumOperands() == 1 &&
"llvm.ident metadata entry can have only one operand") ? void
(0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.ident metadata entry can have only one operand\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2395, __extension__
__PRETTY_FUNCTION__))
;
2396 const MDString *S = cast<MDString>(N->getOperand(0));
2397 OutStreamer->emitIdent(S->getString());
2398 }
2399 }
2400}
2401
2402void AsmPrinter::emitModuleCommandLines(Module &M) {
2403 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
2404 if (!CommandLine)
2405 return;
2406
2407 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2408 if (!NMD || !NMD->getNumOperands())
2409 return;
2410
2411 OutStreamer->PushSection();
2412 OutStreamer->SwitchSection(CommandLine);
2413 OutStreamer->emitZeros(1);
2414 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2415 const MDNode *N = NMD->getOperand(i);
2416 assert(N->getNumOperands() == 1 &&(static_cast <bool> (N->getNumOperands() == 1 &&
"llvm.commandline metadata entry can have only one operand")
? void (0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.commandline metadata entry can have only one operand\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2417, __extension__
__PRETTY_FUNCTION__))
2417 "llvm.commandline metadata entry can have only one operand")(static_cast <bool> (N->getNumOperands() == 1 &&
"llvm.commandline metadata entry can have only one operand")
? void (0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.commandline metadata entry can have only one operand\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2417, __extension__
__PRETTY_FUNCTION__))
;
2418 const MDString *S = cast<MDString>(N->getOperand(0));
2419 OutStreamer->emitBytes(S->getString());
2420 OutStreamer->emitZeros(1);
2421 }
2422 OutStreamer->PopSection();
2423}
2424
2425//===--------------------------------------------------------------------===//
2426// Emission and print routines
2427//
2428
2429/// Emit a byte directive and value.
2430///
2431void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
2432
2433/// Emit a short directive and value.
2434void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
2435
2436/// Emit a long directive and value.
2437void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
2438
2439/// Emit a long long directive and value.
2440void AsmPrinter::emitInt64(uint64_t Value) const {
2441 OutStreamer->emitInt64(Value);
2442}
2443
2444/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2445/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2446/// .set if it avoids relocations.
2447void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
2448 unsigned Size) const {
2449 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2450}
2451
2452/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2453/// where the size in bytes of the directive is specified by Size and Label
2454/// specifies the label. This implicitly uses .set if it is available.
2455void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
2456 unsigned Size,
2457 bool IsSectionRelative) const {
2458 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2459 OutStreamer->EmitCOFFSecRel32(Label, Offset);
2460 if (Size > 4)
2461 OutStreamer->emitZeros(Size - 4);
2462 return;
2463 }
2464
2465 // Emit Label+Offset (or just Label if Offset is zero)
2466 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2467 if (Offset)
2468 Expr = MCBinaryExpr::createAdd(
2469 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2470
2471 OutStreamer->emitValue(Expr, Size);
2472}
2473
2474//===----------------------------------------------------------------------===//
2475
2476// EmitAlignment - Emit an alignment directive to the specified power of
2477// two boundary. If a global value is specified, and if that global has
2478// an explicit alignment requested, it will override the alignment request
2479// if required for correctness.
2480void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV,
2481 unsigned MaxBytesToEmit) const {
2482 if (GV)
2483 Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2484
2485 if (Alignment == Align(1))
2486 return; // 1-byte aligned: no need to emit alignment.
2487
2488 if (getCurrentSection()->getKind().isText()) {
2489 const MCSubtargetInfo *STI = nullptr;
2490 if (this->MF)
2491 STI = &getSubtargetInfo();
2492 else
2493 STI = TM.getMCSubtargetInfo();
2494 OutStreamer->emitCodeAlignment(Alignment.value(), STI, MaxBytesToEmit);
2495 } else
2496 OutStreamer->emitValueToAlignment(Alignment.value(), 0, 1, MaxBytesToEmit);
2497}
2498
2499//===----------------------------------------------------------------------===//
2500// Constant emission.
2501//===----------------------------------------------------------------------===//
2502
2503const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
2504 MCContext &Ctx = OutContext;
2505
2506 if (CV->isNullValue() || isa<UndefValue>(CV))
2507 return MCConstantExpr::create(0, Ctx);
2508
2509 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2510 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2511
2512 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2513 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2514
2515 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2516 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
2517
2518 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
2519 return getObjFileLowering().lowerDSOLocalEquivalent(Equiv, TM);
2520
2521 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
2522 return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
2523
2524 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2525 if (!CE) {
2526 llvm_unreachable("Unknown constant value to lower!")::llvm::llvm_unreachable_internal("Unknown constant value to lower!"
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2526)
;
2527 }
2528
2529 switch (CE->getOpcode()) {
2530 case Instruction::AddrSpaceCast: {
2531 const Constant *Op = CE->getOperand(0);
2532 unsigned DstAS = CE->getType()->getPointerAddressSpace();
2533 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
2534 if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
2535 return lowerConstant(Op);
2536
2537 // Fallthrough to error.
2538 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2539 }
2540 default: {
2541 // If the code isn't optimized, there may be outstanding folding
2542 // opportunities. Attempt to fold the expression using DataLayout as a
2543 // last resort before giving up.
2544 Constant *C = ConstantFoldConstant(CE, getDataLayout());
2545 if (C != CE)
2546 return lowerConstant(C);
2547
2548 // Otherwise report the problem to the user.
2549 std::string S;
2550 raw_string_ostream OS(S);
2551 OS << "Unsupported expression in static initializer: ";
2552 CE->printAsOperand(OS, /*PrintType=*/false,
2553 !MF ? nullptr : MF->getFunction().getParent());
2554 report_fatal_error(Twine(OS.str()));
2555 }
2556 case Instruction::GetElementPtr: {
2557 // Generate a symbolic expression for the byte address
2558 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2559 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2560
2561 const MCExpr *Base = lowerConstant(CE->getOperand(0));
2562 if (!OffsetAI)
2563 return Base;
2564
2565 int64_t Offset = OffsetAI.getSExtValue();
2566 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2567 Ctx);
2568 }
2569
2570 case Instruction::Trunc:
2571 // We emit the value and depend on the assembler to truncate the generated
2572 // expression properly. This is important for differences between
2573 // blockaddress labels. Since the two labels are in the same function, it
2574 // is reasonable to treat their delta as a 32-bit value.
2575 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2576 case Instruction::BitCast:
2577 return lowerConstant(CE->getOperand(0));
2578
2579 case Instruction::IntToPtr: {
2580 const DataLayout &DL = getDataLayout();
2581
2582 // Handle casts to pointers by changing them into casts to the appropriate
2583 // integer type. This promotes constant folding and simplifies this code.
2584 Constant *Op = CE->getOperand(0);
2585 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2586 false/*ZExt*/);
2587 return lowerConstant(Op);
2588 }
2589
2590 case Instruction::PtrToInt: {
2591 const DataLayout &DL = getDataLayout();
2592
2593 // Support only foldable casts to/from pointers that can be eliminated by
2594 // changing the pointer to the appropriately sized integer type.
2595 Constant *Op = CE->getOperand(0);
2596 Type *Ty = CE->getType();
2597
2598 const MCExpr *OpExpr = lowerConstant(Op);
2599
2600 // We can emit the pointer value into this slot if the slot is an
2601 // integer slot equal to the size of the pointer.
2602 //
2603 // If the pointer is larger than the resultant integer, then
2604 // as with Trunc just depend on the assembler to truncate it.
2605 if (DL.getTypeAllocSize(Ty).getFixedSize() <=
2606 DL.getTypeAllocSize(Op->getType()).getFixedSize())
2607 return OpExpr;
2608
2609 // Otherwise the pointer is smaller than the resultant integer, mask off
2610 // the high bits so we are sure to get a proper truncation if the input is
2611 // a constant expr.
2612 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2613 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2614 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2615 }
2616
2617 case Instruction::Sub: {
2618 GlobalValue *LHSGV;
2619 APInt LHSOffset;
2620 DSOLocalEquivalent *DSOEquiv;
2621 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2622 getDataLayout(), &DSOEquiv)) {
2623 GlobalValue *RHSGV;
2624 APInt RHSOffset;
2625 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2626 getDataLayout())) {
2627 const MCExpr *RelocExpr =
2628 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2629 if (!RelocExpr) {
2630 const MCExpr *LHSExpr =
2631 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx);
2632 if (DSOEquiv &&
2633 getObjFileLowering().supportDSOLocalEquivalentLowering())
2634 LHSExpr =
2635 getObjFileLowering().lowerDSOLocalEquivalent(DSOEquiv, TM);
2636 RelocExpr = MCBinaryExpr::createSub(
2637 LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2638 }
2639 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2640 if (Addend != 0)
2641 RelocExpr = MCBinaryExpr::createAdd(
2642 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2643 return RelocExpr;
2644 }
2645 }
2646 }
2647 // else fallthrough
2648 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2649
2650 // The MC library also has a right-shift operator, but it isn't consistently
2651 // signed or unsigned between different targets.
2652 case Instruction::Add:
2653 case Instruction::Mul:
2654 case Instruction::SDiv:
2655 case Instruction::SRem:
2656 case Instruction::Shl:
2657 case Instruction::And:
2658 case Instruction::Or:
2659 case Instruction::Xor: {
2660 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2661 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2662 switch (CE->getOpcode()) {
2663 default: llvm_unreachable("Unknown binary operator constant cast expr")::llvm::llvm_unreachable_internal("Unknown binary operator constant cast expr"
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2663)
;
2664 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2665 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2666 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2667 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2668 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2669 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2670 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2671 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2672 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2673 }
2674 }
2675 }
2676}
2677
2678static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2679 AsmPrinter &AP,
2680 const Constant *BaseCV = nullptr,
2681 uint64_t Offset = 0);
2682
2683static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2684static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2685
2686/// isRepeatedByteSequence - Determine whether the given value is
2687/// composed of a repeated sequence of identical bytes and return the
2688/// byte value. If it is not a repeated sequence, return -1.
2689static int isRepeatedByteSequence(const ConstantDataSequential *V) {
2690 StringRef Data = V->getRawDataValues();
2691 assert(!Data.empty() && "Empty aggregates should be CAZ node")(static_cast <bool> (!Data.empty() && "Empty aggregates should be CAZ node"
) ? void (0) : __assert_fail ("!Data.empty() && \"Empty aggregates should be CAZ node\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2691, __extension__
__PRETTY_FUNCTION__))
;
2692 char C = Data[0];
2693 for (unsigned i = 1, e = Data.size(); i != e; ++i)
2694 if (Data[i] != C) return -1;
2695 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2696}
2697
2698/// isRepeatedByteSequence - Determine whether the given value is
2699/// composed of a repeated sequence of identical bytes and return the
2700/// byte value. If it is not a repeated sequence, return -1.
2701static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2702 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2703 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2704 assert(Size % 8 == 0)(static_cast <bool> (Size % 8 == 0) ? void (0) : __assert_fail
("Size % 8 == 0", "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2704, __extension__ __PRETTY_FUNCTION__))
;
2705
2706 // Extend the element to take zero padding into account.
2707 APInt Value = CI->getValue().zextOrSelf(Size);
2708 if (!Value.isSplat(8))
2709 return -1;
2710
2711 return Value.zextOrTrunc(8).getZExtValue();
2712 }
2713 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2714 // Make sure all array elements are sequences of the same repeated
2715 // byte.
2716 assert(CA->getNumOperands() != 0 && "Should be a CAZ")(static_cast <bool> (CA->getNumOperands() != 0 &&
"Should be a CAZ") ? void (0) : __assert_fail ("CA->getNumOperands() != 0 && \"Should be a CAZ\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2716, __extension__
__PRETTY_FUNCTION__))
;
2717 Constant *Op0 = CA->getOperand(0);
2718 int Byte = isRepeatedByteSequence(Op0, DL);
2719 if (Byte == -1)
2720 return -1;
2721
2722 // All array elements must be equal.
2723 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2724 if (CA->getOperand(i) != Op0)
2725 return -1;
2726 return Byte;
2727 }
2728
2729 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2730 return isRepeatedByteSequence(CDS);
2731
2732 return -1;
2733}
2734
2735static void emitGlobalConstantDataSequential(const DataLayout &DL,
2736 const ConstantDataSequential *CDS,
2737 AsmPrinter &AP) {
2738 // See if we can aggregate this into a .fill, if so, emit it as such.
2739 int Value = isRepeatedByteSequence(CDS, DL);
2740 if (Value != -1) {
2741 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2742 // Don't emit a 1-byte object as a .fill.
2743 if (Bytes > 1)
2744 return AP.OutStreamer->emitFill(Bytes, Value);
2745 }
2746
2747 // If this can be emitted with .ascii/.asciz, emit it as such.
2748 if (CDS->isString())
2749 return AP.OutStreamer->emitBytes(CDS->getAsString());
2750
2751 // Otherwise, emit the values in successive locations.
2752 unsigned ElementByteSize = CDS->getElementByteSize();
2753 if (isa<IntegerType>(CDS->getElementType())) {
2754 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2755 if (AP.isVerbose())
2756 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64"l" "x" "\n",
2757 CDS->getElementAsInteger(i));
2758 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i),
2759 ElementByteSize);
2760 }
2761 } else {
2762 Type *ET = CDS->getElementType();
2763 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2764 emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
2765 }
2766
2767 unsigned Size = DL.getTypeAllocSize(CDS->getType());
2768 unsigned EmittedSize =
2769 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
2770 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!")(static_cast <bool> (EmittedSize <= Size && "Size cannot be less than EmittedSize!"
) ? void (0) : __assert_fail ("EmittedSize <= Size && \"Size cannot be less than EmittedSize!\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2770, __extension__
__PRETTY_FUNCTION__))
;
2771 if (unsigned Padding = Size - EmittedSize)
2772 AP.OutStreamer->emitZeros(Padding);
2773}
2774
2775static void emitGlobalConstantArray(const DataLayout &DL,
2776 const ConstantArray *CA, AsmPrinter &AP,
2777 const Constant *BaseCV, uint64_t Offset) {
2778 // See if we can aggregate some values. Make sure it can be
2779 // represented as a series of bytes of the constant value.
2780 int Value = isRepeatedByteSequence(CA, DL);
2781
2782 if (Value != -1) {
2783 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2784 AP.OutStreamer->emitFill(Bytes, Value);
2785 }
2786 else {
2787 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2788 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2789 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2790 }
2791 }
2792}
2793
2794static void emitGlobalConstantVector(const DataLayout &DL,
2795 const ConstantVector *CV, AsmPrinter &AP) {
2796 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2797 emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2798
2799 unsigned Size = DL.getTypeAllocSize(CV->getType());
2800 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2801 CV->getType()->getNumElements();
2802 if (unsigned Padding = Size - EmittedSize)
2803 AP.OutStreamer->emitZeros(Padding);
2804}
2805
2806static void emitGlobalConstantStruct(const DataLayout &DL,
2807 const ConstantStruct *CS, AsmPrinter &AP,
2808 const Constant *BaseCV, uint64_t Offset) {
2809 // Print the fields in successive locations. Pad to align if needed!
2810 unsigned Size = DL.getTypeAllocSize(CS->getType());
2811 const StructLayout *Layout = DL.getStructLayout(CS->getType());
2812 uint64_t SizeSoFar = 0;
2813 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2814 const Constant *Field = CS->getOperand(i);
2815
2816 // Print the actual field value.
2817 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2818
2819 // Check if padding is needed and insert one or more 0s.
2820 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2821 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2822 - Layout->getElementOffset(i)) - FieldSize;
2823 SizeSoFar += FieldSize + PadSize;
2824
2825 // Insert padding - this may include padding to increase the size of the
2826 // current field up to the ABI size (if the struct is not packed) as well
2827 // as padding to ensure that the next field starts at the right offset.
2828 AP.OutStreamer->emitZeros(PadSize);
2829 }
2830 assert(SizeSoFar == Layout->getSizeInBytes() &&(static_cast <bool> (SizeSoFar == Layout->getSizeInBytes
() && "Layout of constant struct may be incorrect!") ?
void (0) : __assert_fail ("SizeSoFar == Layout->getSizeInBytes() && \"Layout of constant struct may be incorrect!\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2831, __extension__
__PRETTY_FUNCTION__))
2831 "Layout of constant struct may be incorrect!")(static_cast <bool> (SizeSoFar == Layout->getSizeInBytes
() && "Layout of constant struct may be incorrect!") ?
void (0) : __assert_fail ("SizeSoFar == Layout->getSizeInBytes() && \"Layout of constant struct may be incorrect!\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2831, __extension__
__PRETTY_FUNCTION__))
;
2832}
2833
2834static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2835 assert(ET && "Unknown float type")(static_cast <bool> (ET && "Unknown float type"
) ? void (0) : __assert_fail ("ET && \"Unknown float type\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2835, __extension__
__PRETTY_FUNCTION__))
;
2836 APInt API = APF.bitcastToAPInt();
2837
2838 // First print a comment with what we think the original floating-point value
2839 // should have been.
2840 if (AP.isVerbose()) {
2841 SmallString<8> StrVal;
2842 APF.toString(StrVal);
2843 ET->print(AP.OutStreamer->GetCommentOS());
2844 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2845 }
2846
2847 // Now iterate through the APInt chunks, emitting them in endian-correct
2848 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2849 // floats).
2850 unsigned NumBytes = API.getBitWidth() / 8;
2851 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2852 const uint64_t *p = API.getRawData();
2853
2854 // PPC's long double has odd notions of endianness compared to how LLVM
2855 // handles it: p[0] goes first for *big* endian on PPC.
2856 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2857 int Chunk = API.getNumWords() - 1;
2858
2859 if (TrailingBytes)
2860 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
2861
2862 for (; Chunk >= 0; --Chunk)
2863 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2864 } else {
2865 unsigned Chunk;
2866 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2867 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2868
2869 if (TrailingBytes)
2870 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
2871 }
2872
2873 // Emit the tail padding for the long double.
2874 const DataLayout &DL = AP.getDataLayout();
2875 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2876}
2877
2878static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2879 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2880}
2881
2882static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2883 const DataLayout &DL = AP.getDataLayout();
2884 unsigned BitWidth = CI->getBitWidth();
2885
2886 // Copy the value as we may massage the layout for constants whose bit width
2887 // is not a multiple of 64-bits.
2888 APInt Realigned(CI->getValue());
2889 uint64_t ExtraBits = 0;
2890 unsigned ExtraBitsSize = BitWidth & 63;
2891
2892 if (ExtraBitsSize) {
2893 // The bit width of the data is not a multiple of 64-bits.
2894 // The extra bits are expected to be at the end of the chunk of the memory.
2895 // Little endian:
2896 // * Nothing to be done, just record the extra bits to emit.
2897 // Big endian:
2898 // * Record the extra bits to emit.
2899 // * Realign the raw data to emit the chunks of 64-bits.
2900 if (DL.isBigEndian()) {
2901 // Basically the structure of the raw data is a chunk of 64-bits cells:
2902 // 0 1 BitWidth / 64
2903 // [chunk1][chunk2] ... [chunkN].
2904 // The most significant chunk is chunkN and it should be emitted first.
2905 // However, due to the alignment issue chunkN contains useless bits.
2906 // Realign the chunks so that they contain only useful information:
2907 // ExtraBits 0 1 (BitWidth / 64) - 1
2908 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2909 ExtraBitsSize = alignTo(ExtraBitsSize, 8);
2910 ExtraBits = Realigned.getRawData()[0] &
2911 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2912 Realigned.lshrInPlace(ExtraBitsSize);
2913 } else
2914 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2915 }
2916
2917 // We don't expect assemblers to support integer data directives
2918 // for more than 64 bits, so we emit the data in at most 64-bit
2919 // quantities at a time.
2920 const uint64_t *RawData = Realigned.getRawData();
2921 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2922 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2923 AP.OutStreamer->emitIntValue(Val, 8);
2924 }
2925
2926 if (ExtraBitsSize) {
2927 // Emit the extra bits after the 64-bits chunks.
2928
2929 // Emit a directive that fills the expected size.
2930 uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType());
2931 Size -= (BitWidth / 64) * 8;
2932 assert(Size && Size * 8 >= ExtraBitsSize &&(static_cast <bool> (Size && Size * 8 >= ExtraBitsSize
&& (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize
))) == ExtraBits && "Directive too small for extra bits."
) ? void (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2934, __extension__
__PRETTY_FUNCTION__))
2933 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))(static_cast <bool> (Size && Size * 8 >= ExtraBitsSize
&& (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize
))) == ExtraBits && "Directive too small for extra bits."
) ? void (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2934, __extension__
__PRETTY_FUNCTION__))
2934 == ExtraBits && "Directive too small for extra bits.")(static_cast <bool> (Size && Size * 8 >= ExtraBitsSize
&& (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize
))) == ExtraBits && "Directive too small for extra bits."
) ? void (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 2934, __extension__
__PRETTY_FUNCTION__))
;
2935 AP.OutStreamer->emitIntValue(ExtraBits, Size);
2936 }
2937}
2938
2939/// Transform a not absolute MCExpr containing a reference to a GOT
2940/// equivalent global, by a target specific GOT pc relative access to the
2941/// final symbol.
2942static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2943 const Constant *BaseCst,
2944 uint64_t Offset) {
2945 // The global @foo below illustrates a global that uses a got equivalent.
2946 //
2947 // @bar = global i32 42
2948 // @gotequiv = private unnamed_addr constant i32* @bar
2949 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2950 // i64 ptrtoint (i32* @foo to i64))
2951 // to i32)
2952 //
2953 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2954 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2955 // form:
2956 //
2957 // foo = cstexpr, where
2958 // cstexpr := <gotequiv> - "." + <cst>
2959 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2960 //
2961 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2962 //
2963 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2964 // gotpcrelcst := <offset from @foo base> + <cst>
2965 MCValue MV;
2966 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2967 return;
2968 const MCSymbolRefExpr *SymA = MV.getSymA();
2969 if (!SymA)
2970 return;
2971
2972 // Check that GOT equivalent symbol is cached.
2973 const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2974 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2975 return;
2976
2977 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2978 if (!BaseGV)
2979 return;
2980
2981 // Check for a valid base symbol
2982 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2983 const MCSymbolRefExpr *SymB = MV.getSymB();
2984
2985 if (!SymB || BaseSym != &SymB->getSymbol())
2986 return;
2987
2988 // Make sure to match:
2989 //
2990 // gotpcrelcst := <offset from @foo base> + <cst>
2991 //
2992 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2993 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2994 // if the target knows how to encode it.
2995 int64_t GOTPCRelCst = Offset + MV.getConstant();
2996 if (GOTPCRelCst < 0)
2997 return;
2998 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2999 return;
3000
3001 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
3002 //
3003 // bar:
3004 // .long 42
3005 // gotequiv:
3006 // .quad bar
3007 // foo:
3008 // .long gotequiv - "." + <cst>
3009 //
3010 // is replaced by the target specific equivalent to:
3011 //
3012 // bar:
3013 // .long 42
3014 // foo:
3015 // .long bar@GOTPCREL+<gotpcrelcst>
3016 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
3017 const GlobalVariable *GV = Result.first;
3018 int NumUses = (int)Result.second;
3019 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
3020 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
3021 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
3022 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
3023
3024 // Update GOT equivalent usage information
3025 --NumUses;
3026 if (NumUses >= 0)
3027 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
3028}
3029
3030static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
3031 AsmPrinter &AP, const Constant *BaseCV,
3032 uint64_t Offset) {
3033 uint64_t Size = DL.getTypeAllocSize(CV->getType());
3034
3035 // Globals with sub-elements such as combinations of arrays and structs
3036 // are handled recursively by emitGlobalConstantImpl. Keep track of the
3037 // constant symbol base and the current position with BaseCV and Offset.
3038 if (!BaseCV && CV->hasOneUse())
3039 BaseCV = dyn_cast<Constant>(CV->user_back());
3040
3041 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
3042 return AP.OutStreamer->emitZeros(Size);
3043
3044 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
3045 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
3046
3047 if (StoreSize <= 8) {
3048 if (AP.isVerbose())
3049 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64"l" "x" "\n",
3050 CI->getZExtValue());
3051 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
3052 } else {
3053 emitGlobalConstantLargeInt(CI, AP);
3054 }
3055
3056 // Emit tail padding if needed
3057 if (Size != StoreSize)
3058 AP.OutStreamer->emitZeros(Size - StoreSize);
3059
3060 return;
3061 }
3062
3063 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
3064 return emitGlobalConstantFP(CFP, AP);
3065
3066 if (isa<ConstantPointerNull>(CV)) {
3067 AP.OutStreamer->emitIntValue(0, Size);
3068 return;
3069 }
3070
3071 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
3072 return emitGlobalConstantDataSequential(DL, CDS, AP);
3073
3074 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
3075 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
3076
3077 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
3078 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
3079
3080 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
3081 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
3082 // vectors).
3083 if (CE->getOpcode() == Instruction::BitCast)
3084 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
3085
3086 if (Size > 8) {
3087 // If the constant expression's size is greater than 64-bits, then we have
3088 // to emit the value in chunks. Try to constant fold the value and emit it
3089 // that way.
3090 Constant *New = ConstantFoldConstant(CE, DL);
3091 if (New != CE)
3092 return emitGlobalConstantImpl(DL, New, AP);
3093 }
3094 }
3095
3096 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
3097 return emitGlobalConstantVector(DL, V, AP);
3098
3099 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
3100 // thread the streamer with EmitValue.
3101 const MCExpr *ME = AP.lowerConstant(CV);
3102
3103 // Since lowerConstant already folded and got rid of all IR pointer and
3104 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
3105 // directly.
3106 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
3107 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
3108
3109 AP.OutStreamer->emitValue(ME, Size);
3110}
3111
3112/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
3113void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV) {
3114 uint64_t Size = DL.getTypeAllocSize(CV->getType());
3115 if (Size)
3116 emitGlobalConstantImpl(DL, CV, *this);
3117 else if (MAI->hasSubsectionsViaSymbols()) {
3118 // If the global has zero size, emit a single byte so that two labels don't
3119 // look like they are at the same location.
3120 OutStreamer->emitIntValue(0, 1);
3121 }
3122}
3123
3124void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
3125 // Target doesn't support this yet!
3126 llvm_unreachable("Target does not support EmitMachineConstantPoolValue")::llvm::llvm_unreachable_internal("Target does not support EmitMachineConstantPoolValue"
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 3126)
;
3127}
3128
3129void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
3130 if (Offset > 0)
3131 OS << '+' << Offset;
3132 else if (Offset < 0)
3133 OS << Offset;
3134}
3135
3136void AsmPrinter::emitNops(unsigned N) {
3137 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
3138 for (; N; --N)
3139 EmitToStreamer(*OutStreamer, Nop);
3140}
3141
3142//===----------------------------------------------------------------------===//
3143// Symbol Lowering Routines.
3144//===----------------------------------------------------------------------===//
3145
3146MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
3147 return OutContext.createTempSymbol(Name, true);
3148}
3149
3150MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
3151 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
3152}
3153
3154MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
3155 return MMI->getAddrLabelSymbol(BB);
3156}
3157
3158/// GetCPISymbol - Return the symbol for the specified constant pool entry.
3159MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
3160 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
3161 const MachineConstantPoolEntry &CPE =
3162 MF->getConstantPool()->getConstants()[CPID];
3163 if (!CPE.isMachineConstantPoolEntry()) {
3164 const DataLayout &DL = MF->getDataLayout();
3165 SectionKind Kind = CPE.getSectionKind(&DL);
3166 const Constant *C = CPE.Val.ConstVal;
3167 Align Alignment = CPE.Alignment;
3168 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
3169 getObjFileLowering().getSectionForConstant(DL, Kind, C,
3170 Alignment))) {
3171 if (MCSymbol *Sym = S->getCOMDATSymbol()) {
3172 if (Sym->isUndefined())
3173 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
3174 return Sym;
3175 }
3176 }
3177 }
3178 }
3179
3180 const DataLayout &DL = getDataLayout();
3181 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3182 "CPI" + Twine(getFunctionNumber()) + "_" +
3183 Twine(CPID));
3184}
3185
3186/// GetJTISymbol - Return the symbol for the specified jump table entry.
3187MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
3188 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
3189}
3190
3191/// GetJTSetSymbol - Return the symbol for the specified jump table .set
3192/// FIXME: privatize to AsmPrinter.
3193MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
3194 const DataLayout &DL = getDataLayout();
3195 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3196 Twine(getFunctionNumber()) + "_" +
3197 Twine(UID) + "_set_" + Twine(MBBID));
3198}
3199
3200MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
3201 StringRef Suffix) const {
3202 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
3203}
3204
3205/// Return the MCSymbol for the specified ExternalSymbol.
3206MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
3207 SmallString<60> NameStr;
3208 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
3209 return OutContext.getOrCreateSymbol(NameStr);
3210}
3211
3212/// PrintParentLoopComment - Print comments about parent loops of this one.
3213static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
3214 unsigned FunctionNumber) {
3215 if (!Loop) return;
3216 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
3217 OS.indent(Loop->getLoopDepth()*2)
3218 << "Parent Loop BB" << FunctionNumber << "_"
3219 << Loop->getHeader()->getNumber()
3220 << " Depth=" << Loop->getLoopDepth() << '\n';
3221}
3222
3223/// PrintChildLoopComment - Print comments about child loops within
3224/// the loop for this basic block, with nesting.
3225static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
3226 unsigned FunctionNumber) {
3227 // Add child loop information
3228 for (const MachineLoop *CL : *Loop) {
3229 OS.indent(CL->getLoopDepth()*2)
3230 << "Child Loop BB" << FunctionNumber << "_"
3231 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
3232 << '\n';
3233 PrintChildLoopComment(OS, CL, FunctionNumber);
3234 }
3235}
3236
3237/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
3238static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
3239 const MachineLoopInfo *LI,
3240 const AsmPrinter &AP) {
3241 // Add loop depth information
3242 const MachineLoop *Loop = LI->getLoopFor(&MBB);
3243 if (!Loop) return;
3244
3245 MachineBasicBlock *Header = Loop->getHeader();
3246 assert(Header && "No header for loop")(static_cast <bool> (Header && "No header for loop"
) ? void (0) : __assert_fail ("Header && \"No header for loop\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 3246, __extension__
__PRETTY_FUNCTION__))
;
3247
3248 // If this block is not a loop header, just print out what is the loop header
3249 // and return.
3250 if (Header != &MBB) {
3251 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
3252 Twine(AP.getFunctionNumber())+"_" +
3253 Twine(Loop->getHeader()->getNumber())+
3254 " Depth="+Twine(Loop->getLoopDepth()));
3255 return;
3256 }
3257
3258 // Otherwise, it is a loop header. Print out information about child and
3259 // parent loops.
3260 raw_ostream &OS = AP.OutStreamer->GetCommentOS();
3261
3262 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
3263
3264 OS << "=>";
3265 OS.indent(Loop->getLoopDepth()*2-2);
3266
3267 OS << "This ";
3268 if (Loop->isInnermost())
3269 OS << "Inner ";
3270 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
3271
3272 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
3273}
3274
3275/// emitBasicBlockStart - This method prints the label for the specified
3276/// MachineBasicBlock, an alignment (if present) and a comment describing
3277/// it if appropriate.
3278void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
3279 // End the previous funclet and start a new one.
3280 if (MBB.isEHFuncletEntry()) {
3281 for (const HandlerInfo &HI : Handlers) {
3282 HI.Handler->endFunclet();
3283 HI.Handler->beginFunclet(MBB);
3284 }
3285 }
3286
3287 // Emit an alignment directive for this block, if needed.
3288 const Align Alignment = MBB.getAlignment();
3289 if (Alignment != Align(1))
3290 emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
3291
3292 // Switch to a new section if this basic block must begin a section. The
3293 // entry block is always placed in the function section and is handled
3294 // separately.
3295 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
3296 OutStreamer->SwitchSection(
3297 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
3298 MBB, TM));
3299 CurrentSectionBeginSym = MBB.getSymbol();
3300 }
3301
3302 // If the block has its address taken, emit any labels that were used to
3303 // reference the block. It is possible that there is more than one label
3304 // here, because multiple LLVM BB's may have been RAUW'd to this block after
3305 // the references were generated.
3306 const BasicBlock *BB = MBB.getBasicBlock();
3307 if (MBB.hasAddressTaken()) {
3308 if (isVerbose())
3309 OutStreamer->AddComment("Block address taken");
3310
3311 // MBBs can have their address taken as part of CodeGen without having
3312 // their corresponding BB's address taken in IR
3313 if (BB && BB->hasAddressTaken())
3314 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
3315 OutStreamer->emitLabel(Sym);
3316 }
3317
3318 // Print some verbose block comments.
3319 if (isVerbose()) {
3320 if (BB) {
3321 if (BB->hasName()) {
3322 BB->printAsOperand(OutStreamer->GetCommentOS(),
3323 /*PrintType=*/false, BB->getModule());
3324 OutStreamer->GetCommentOS() << '\n';
3325 }
3326 }
3327
3328 assert(MLI != nullptr && "MachineLoopInfo should has been computed")(static_cast <bool> (MLI != nullptr && "MachineLoopInfo should has been computed"
) ? void (0) : __assert_fail ("MLI != nullptr && \"MachineLoopInfo should has been computed\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 3328, __extension__
__PRETTY_FUNCTION__))
;
3329 emitBasicBlockLoopComments(MBB, MLI, *this);
3330 }
3331
3332 // Print the main label for the block.
3333 if (shouldEmitLabelForBasicBlock(MBB)) {
3334 if (isVerbose() && MBB.hasLabelMustBeEmitted())
3335 OutStreamer->AddComment("Label of block must be emitted");
3336 OutStreamer->emitLabel(MBB.getSymbol());
3337 } else {
3338 if (isVerbose()) {
3339 // NOTE: Want this comment at start of line, don't emit with AddComment.
3340 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3341 false);
3342 }
3343 }
3344
3345 if (MBB.isEHCatchretTarget() &&
3346 MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) {
3347 OutStreamer->emitLabel(MBB.getEHCatchretSymbol());
3348 }
3349
3350 // With BB sections, each basic block must handle CFI information on its own
3351 // if it begins a section (Entry block is handled separately by
3352 // AsmPrinterHandler::beginFunction).
3353 if (MBB.isBeginSection() && !MBB.isEntryBlock())
3354 for (const HandlerInfo &HI : Handlers)
3355 HI.Handler->beginBasicBlock(MBB);
3356}
3357
3358void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
3359 // Check if CFI information needs to be updated for this MBB with basic block
3360 // sections.
3361 if (MBB.isEndSection())
3362 for (const HandlerInfo &HI : Handlers)
3363 HI.Handler->endBasicBlock(MBB);
3364}
3365
3366void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
3367 bool IsDefinition) const {
3368 MCSymbolAttr Attr = MCSA_Invalid;
3369
3370 switch (Visibility) {
3371 default: break;
3372 case GlobalValue::HiddenVisibility:
3373 if (IsDefinition)
3374 Attr = MAI->getHiddenVisibilityAttr();
3375 else
3376 Attr = MAI->getHiddenDeclarationVisibilityAttr();
3377 break;
3378 case GlobalValue::ProtectedVisibility:
3379 Attr = MAI->getProtectedVisibilityAttr();
3380 break;
3381 }
3382
3383 if (Attr != MCSA_Invalid)
3384 OutStreamer->emitSymbolAttribute(Sym, Attr);
3385}
3386
3387bool AsmPrinter::shouldEmitLabelForBasicBlock(
3388 const MachineBasicBlock &MBB) const {
3389 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
3390 // in the labels mode (option `=labels`) and every section beginning in the
3391 // sections mode (`=all` and `=list=`).
3392 if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock())
3393 return true;
3394 // A label is needed for any block with at least one predecessor (when that
3395 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
3396 // entry, or if a label is forced).
3397 return !MBB.pred_empty() &&
3398 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
3399 MBB.hasLabelMustBeEmitted());
3400}
3401
3402/// isBlockOnlyReachableByFallthough - Return true if the basic block has
3403/// exactly one predecessor and the control transfer mechanism between
3404/// the predecessor and this block is a fall-through.
3405bool AsmPrinter::
3406isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
3407 // If this is a landing pad, it isn't a fall through. If it has no preds,
3408 // then nothing falls through to it.
3409 if (MBB->isEHPad() || MBB->pred_empty())
3410 return false;
3411
3412 // If there isn't exactly one predecessor, it can't be a fall through.
3413 if (MBB->pred_size() > 1)
3414 return false;
3415
3416 // The predecessor has to be immediately before this block.
3417 MachineBasicBlock *Pred = *MBB->pred_begin();
3418 if (!Pred->isLayoutSuccessor(MBB))
3419 return false;
3420
3421 // If the block is completely empty, then it definitely does fall through.
3422 if (Pred->empty())
3423 return true;
3424
3425 // Check the terminators in the previous blocks
3426 for (const auto &MI : Pred->terminators()) {
3427 // If it is not a simple branch, we are in a table somewhere.
3428 if (!MI.isBranch() || MI.isIndirectBranch())
3429 return false;
3430
3431 // If we are the operands of one of the branches, this is not a fall
3432 // through. Note that targets with delay slots will usually bundle
3433 // terminators with the delay slot instruction.
3434 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3435 if (OP->isJTI())
3436 return false;
3437 if (OP->isMBB() && OP->getMBB() == MBB)
3438 return false;
3439 }
3440 }
3441
3442 return true;
3443}
3444
3445GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3446 if (!S.usesMetadata())
3447 return nullptr;
3448
3449 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3450 gcp_map_type::iterator GCPI = GCMap.find(&S);
3451 if (GCPI != GCMap.end())
3452 return GCPI->second.get();
3453
3454 auto Name = S.getName();
3455
3456 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
3457 GCMetadataPrinterRegistry::entries())
3458 if (Name == GCMetaPrinter.getName()) {
3459 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
3460 GMP->S = &S;
3461 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3462 return IterBool.first->second.get();
3463 }
3464
3465 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3466}
3467
3468void AsmPrinter::emitStackMaps(StackMaps &SM) {
3469 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3470 assert(MI && "AsmPrinter didn't require GCModuleInfo?")(static_cast <bool> (MI && "AsmPrinter didn't require GCModuleInfo?"
) ? void (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 3470, __extension__
__PRETTY_FUNCTION__))
;
3471 bool NeedsDefault = false;
3472 if (MI->begin() == MI->end())
3473 // No GC strategy, use the default format.
3474 NeedsDefault = true;
3475 else
3476 for (auto &I : *MI) {
3477 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3478 if (MP->emitStackMaps(SM, *this))
3479 continue;
3480 // The strategy doesn't have printer or doesn't emit custom stack maps.
3481 // Use the default format.
3482 NeedsDefault = true;
3483 }
3484
3485 if (NeedsDefault)
3486 SM.serializeToStackMapSection();
3487}
3488
3489/// Pin vtable to this file.
3490AsmPrinterHandler::~AsmPrinterHandler() = default;
3491
3492void AsmPrinterHandler::markFunctionEnd() {}
3493
3494// In the binary's "xray_instr_map" section, an array of these function entries
3495// describes each instrumentation point. When XRay patches your code, the index
3496// into this table will be given to your handler as a patch point identifier.
3497void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const {
3498 auto Kind8 = static_cast<uint8_t>(Kind);
3499 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3500 Out->emitBinaryData(
3501 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3502 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3503 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3504 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size")(static_cast <bool> (Padding >= 0 && "Instrumentation map entry > 4 * Word Size"
) ? void (0) : __assert_fail ("Padding >= 0 && \"Instrumentation map entry > 4 * Word Size\""
, "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp", 3504, __extension__
__PRETTY_FUNCTION__))
;
3505 Out->emitZeros(Padding);
3506}
3507
3508void AsmPrinter::emitXRayTable() {
3509 if (Sleds.empty())
3510 return;
3511
3512 auto PrevSection = OutStreamer->getCurrentSectionOnly();
3513 const Function &F = MF->getFunction();
3514 MCSection *InstMap = nullptr;
3515 MCSection *FnSledIndex = nullptr;
3516 const Triple &TT = TM.getTargetTriple();
3517 // Use PC-relative addresses on all targets.
3518 if (TT.isOSBinFormatELF()) {
3519 auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3520 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3521 StringRef GroupName;
3522 if (F.hasComdat()) {
3523 Flags |= ELF::SHF_GROUP;
3524 GroupName = F.getComdat()->getName();
3525 }
3526 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
3527 Flags, 0, GroupName, F.hasComdat(),
3528 MCSection::NonUniqueID, LinkedToSym);
3529
3530 if (!TM.Options.XRayOmitFunctionIndex)
3531 FnSledIndex = OutContext.getELFSection(
3532 "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0,
3533 GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym);
3534 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3535 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3536 SectionKind::getReadOnlyWithRel());
3537 if (!TM.Options.XRayOmitFunctionIndex)
3538 FnSledIndex = OutContext.getMachOSection(
3539 "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
3540 } else {
3541 llvm_unreachable("Unsupported target")::llvm::llvm_unreachable_internal("Unsupported target", "llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3541)
;
3542 }
3543
3544 auto WordSizeBytes = MAI->getCodePointerSize();
3545
3546 // Now we switch to the instrumentation map section. Because this is done
3547 // per-function, we are able to create an index entry that will represent the
3548 // range of sleds associated with a function.
3549 auto &Ctx = OutContext;
3550 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3551 OutStreamer->SwitchSection(InstMap);
3552 OutStreamer->emitLabel(SledsStart);
3553 for (const auto &Sled : Sleds) {
3554 MCSymbol *Dot = Ctx.createTempSymbol();
3555 OutStreamer->emitLabel(Dot);
3556 OutStreamer->emitValueImpl(
3557 MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx),
3558 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
3559 WordSizeBytes);
3560 OutStreamer->emitValueImpl(
3561 MCBinaryExpr::createSub(
3562 MCSymbolRefExpr::create(CurrentFnBegin, Ctx),
3563 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(Dot, Ctx),
3564 MCConstantExpr::create(WordSizeBytes, Ctx),
3565 Ctx),
3566 Ctx),
3567 WordSizeBytes);
3568 Sled.emit(WordSizeBytes, OutStreamer.get());
3569 }
3570 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3571 OutStreamer->emitLabel(SledsEnd);
3572
3573 // We then emit a single entry in the index per function. We use the symbols
3574 // that bound the instrumentation map as the range for a specific function.
3575 // Each entry here will be 2 * word size aligned, as we're writing down two
3576 // pointers. This should work for both 32-bit and 64-bit platforms.
3577 if (FnSledIndex) {
3578 OutStreamer->SwitchSection(FnSledIndex);
3579 OutStreamer->emitCodeAlignment(2 * WordSizeBytes, &getSubtargetInfo());
3580 OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
3581 OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
3582 OutStreamer->SwitchSection(PrevSection);
3583 }
3584 Sleds.clear();
3585}
3586
3587void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
3588 SledKind Kind, uint8_t Version) {
3589 const Function &F = MI.getMF()->getFunction();
3590 auto Attr = F.getFnAttribute("function-instrument");
3591 bool LogArgs = F.hasFnAttribute("xray-log-args");
3592 bool AlwaysInstrument =
3593 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3594 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3595 Kind = SledKind::LOG_ARGS_ENTER;
3596 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3597 AlwaysInstrument, &F, Version});
3598}
3599
3600void AsmPrinter::emitPatchableFunctionEntries() {
3601 const Function &F = MF->getFunction();
3602 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3603 (void)F.getFnAttribute("patchable-function-prefix")
3604 .getValueAsString()
3605 .getAsInteger(10, PatchableFunctionPrefix);
3606 (void)F.getFnAttribute("patchable-function-entry")
3607 .getValueAsString()
3608 .getAsInteger(10, PatchableFunctionEntry);
3609 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3610 return;
3611 const unsigned PointerSize = getPointerSize();
3612 if (TM.getTargetTriple().isOSBinFormatELF()) {
3613 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3614 const MCSymbolELF *LinkedToSym = nullptr;
3615 StringRef GroupName;
3616
3617 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
3618 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
3619 if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
3620 Flags |= ELF::SHF_LINK_ORDER;
3621 if (F.hasComdat()) {
3622 Flags |= ELF::SHF_GROUP;
3623 GroupName = F.getComdat()->getName();
3624 }
3625 LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3626 }
3627 OutStreamer->SwitchSection(OutContext.getELFSection(
3628 "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
3629 F.hasComdat(), MCSection::NonUniqueID, LinkedToSym));
3630 emitAlignment(Align(PointerSize));
3631 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
3632 }
3633}
3634
3635uint16_t AsmPrinter::getDwarfVersion() const {
3636 return OutStreamer->getContext().getDwarfVersion();
3637}
3638
3639void AsmPrinter::setDwarfVersion(uint16_t Version) {
3640 OutStreamer->getContext().setDwarfVersion(Version);
3641}
3642
3643bool AsmPrinter::isDwarf64() const {
3644 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
3645}
3646
3647unsigned int AsmPrinter::getDwarfOffsetByteSize() const {
3648 return dwarf::getDwarfOffsetByteSize(
3649 OutStreamer->getContext().getDwarfFormat());
3650}
3651
3652dwarf::FormParams AsmPrinter::getDwarfFormParams() const {
3653 return {getDwarfVersion(), uint8_t(getPointerSize()),
3654 OutStreamer->getContext().getDwarfFormat(),
3655 MAI->doesDwarfUseRelocationsAcrossSections()};
3656}
3657
3658unsigned int AsmPrinter::getUnitLengthFieldByteSize() const {
3659 return dwarf::getUnitLengthFieldByteSize(
3660 OutStreamer->getContext().getDwarfFormat());
3661}