Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
Warning:line 281, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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