1 | //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// |
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 coordinates the per-module state used while generating code. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #include "CodeGenModule.h" |
14 | #include "ABIInfo.h" |
15 | #include "CGBlocks.h" |
16 | #include "CGCUDARuntime.h" |
17 | #include "CGCXXABI.h" |
18 | #include "CGCall.h" |
19 | #include "CGDebugInfo.h" |
20 | #include "CGHLSLRuntime.h" |
21 | #include "CGObjCRuntime.h" |
22 | #include "CGOpenCLRuntime.h" |
23 | #include "CGOpenMPRuntime.h" |
24 | #include "CGOpenMPRuntimeGPU.h" |
25 | #include "CodeGenFunction.h" |
26 | #include "CodeGenPGO.h" |
27 | #include "ConstantEmitter.h" |
28 | #include "CoverageMappingGen.h" |
29 | #include "TargetInfo.h" |
30 | #include "clang/AST/ASTContext.h" |
31 | #include "clang/AST/ASTLambda.h" |
32 | #include "clang/AST/CharUnits.h" |
33 | #include "clang/AST/Decl.h" |
34 | #include "clang/AST/DeclCXX.h" |
35 | #include "clang/AST/DeclObjC.h" |
36 | #include "clang/AST/DeclTemplate.h" |
37 | #include "clang/AST/Mangle.h" |
38 | #include "clang/AST/RecursiveASTVisitor.h" |
39 | #include "clang/AST/StmtVisitor.h" |
40 | #include "clang/Basic/Builtins.h" |
41 | #include "clang/Basic/CharInfo.h" |
42 | #include "clang/Basic/CodeGenOptions.h" |
43 | #include "clang/Basic/Diagnostic.h" |
44 | #include "clang/Basic/FileManager.h" |
45 | #include "clang/Basic/Module.h" |
46 | #include "clang/Basic/SourceManager.h" |
47 | #include "clang/Basic/TargetInfo.h" |
48 | #include "clang/Basic/Version.h" |
49 | #include "clang/CodeGen/BackendUtil.h" |
50 | #include "clang/CodeGen/ConstantInitBuilder.h" |
51 | #include "clang/Frontend/FrontendDiagnostic.h" |
52 | #include "llvm/ADT/STLExtras.h" |
53 | #include "llvm/ADT/StringExtras.h" |
54 | #include "llvm/ADT/StringSwitch.h" |
55 | #include "llvm/Analysis/TargetLibraryInfo.h" |
56 | #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" |
57 | #include "llvm/IR/AttributeMask.h" |
58 | #include "llvm/IR/CallingConv.h" |
59 | #include "llvm/IR/DataLayout.h" |
60 | #include "llvm/IR/Intrinsics.h" |
61 | #include "llvm/IR/LLVMContext.h" |
62 | #include "llvm/IR/Module.h" |
63 | #include "llvm/IR/ProfileSummary.h" |
64 | #include "llvm/ProfileData/InstrProfReader.h" |
65 | #include "llvm/ProfileData/SampleProf.h" |
66 | #include "llvm/Support/CRC.h" |
67 | #include "llvm/Support/CodeGen.h" |
68 | #include "llvm/Support/CommandLine.h" |
69 | #include "llvm/Support/ConvertUTF.h" |
70 | #include "llvm/Support/ErrorHandling.h" |
71 | #include "llvm/Support/RISCVISAInfo.h" |
72 | #include "llvm/Support/TimeProfiler.h" |
73 | #include "llvm/Support/xxhash.h" |
74 | #include "llvm/TargetParser/Triple.h" |
75 | #include "llvm/TargetParser/X86TargetParser.h" |
76 | #include <optional> |
77 | |
78 | using namespace clang; |
79 | using namespace CodeGen; |
80 | |
81 | static llvm::cl::opt<bool> LimitedCoverage( |
82 | "limited-coverage-experimental" , llvm::cl::Hidden, |
83 | llvm::cl::desc("Emit limited coverage mapping information (experimental)" )); |
84 | |
85 | static const char AnnotationSection[] = "llvm.metadata" ; |
86 | |
87 | static CGCXXABI *createCXXABI(CodeGenModule &CGM) { |
88 | switch (CGM.getContext().getCXXABIKind()) { |
89 | case TargetCXXABI::AppleARM64: |
90 | case TargetCXXABI::Fuchsia: |
91 | case TargetCXXABI::GenericAArch64: |
92 | case TargetCXXABI::GenericARM: |
93 | case TargetCXXABI::iOS: |
94 | case TargetCXXABI::WatchOS: |
95 | case TargetCXXABI::GenericMIPS: |
96 | case TargetCXXABI::GenericItanium: |
97 | case TargetCXXABI::WebAssembly: |
98 | case TargetCXXABI::XL: |
99 | return CreateItaniumCXXABI(CGM); |
100 | case TargetCXXABI::Microsoft: |
101 | return CreateMicrosoftCXXABI(CGM); |
102 | } |
103 | |
104 | llvm_unreachable("invalid C++ ABI kind" ); |
105 | } |
106 | |
107 | static std::unique_ptr<TargetCodeGenInfo> |
108 | createTargetCodeGenInfo(CodeGenModule &CGM) { |
109 | const TargetInfo &Target = CGM.getTarget(); |
110 | const llvm::Triple &Triple = Target.getTriple(); |
111 | const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts(); |
112 | |
113 | switch (Triple.getArch()) { |
114 | default: |
115 | return createDefaultTargetCodeGenInfo(CGM); |
116 | |
117 | case llvm::Triple::le32: |
118 | return createPNaClTargetCodeGenInfo(CGM); |
119 | case llvm::Triple::m68k: |
120 | return createM68kTargetCodeGenInfo(CGM); |
121 | case llvm::Triple::mips: |
122 | case llvm::Triple::mipsel: |
123 | if (Triple.getOS() == llvm::Triple::NaCl) |
124 | return createPNaClTargetCodeGenInfo(CGM); |
125 | return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true); |
126 | |
127 | case llvm::Triple::mips64: |
128 | case llvm::Triple::mips64el: |
129 | return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false); |
130 | |
131 | case llvm::Triple::avr: { |
132 | // For passing parameters, R8~R25 are used on avr, and R18~R25 are used |
133 | // on avrtiny. For passing return value, R18~R25 are used on avr, and |
134 | // R22~R25 are used on avrtiny. |
135 | unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18; |
136 | unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8; |
137 | return createAVRTargetCodeGenInfo(CGM, NPR, NRR); |
138 | } |
139 | |
140 | case llvm::Triple::aarch64: |
141 | case llvm::Triple::aarch64_32: |
142 | case llvm::Triple::aarch64_be: { |
143 | AArch64ABIKind Kind = AArch64ABIKind::AAPCS; |
144 | if (Target.getABI() == "darwinpcs" ) |
145 | Kind = AArch64ABIKind::DarwinPCS; |
146 | else if (Triple.isOSWindows()) |
147 | return createWindowsAArch64TargetCodeGenInfo(CGM, K: AArch64ABIKind::Win64); |
148 | |
149 | return createAArch64TargetCodeGenInfo(CGM, Kind); |
150 | } |
151 | |
152 | case llvm::Triple::wasm32: |
153 | case llvm::Triple::wasm64: { |
154 | WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP; |
155 | if (Target.getABI() == "experimental-mv" ) |
156 | Kind = WebAssemblyABIKind::ExperimentalMV; |
157 | return createWebAssemblyTargetCodeGenInfo(CGM, K: Kind); |
158 | } |
159 | |
160 | case llvm::Triple::arm: |
161 | case llvm::Triple::armeb: |
162 | case llvm::Triple::thumb: |
163 | case llvm::Triple::thumbeb: { |
164 | if (Triple.getOS() == llvm::Triple::Win32) |
165 | return createWindowsARMTargetCodeGenInfo(CGM, K: ARMABIKind::AAPCS_VFP); |
166 | |
167 | ARMABIKind Kind = ARMABIKind::AAPCS; |
168 | StringRef ABIStr = Target.getABI(); |
169 | if (ABIStr == "apcs-gnu" ) |
170 | Kind = ARMABIKind::APCS; |
171 | else if (ABIStr == "aapcs16" ) |
172 | Kind = ARMABIKind::AAPCS16_VFP; |
173 | else if (CodeGenOpts.FloatABI == "hard" || |
174 | (CodeGenOpts.FloatABI != "soft" && |
175 | (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || |
176 | Triple.getEnvironment() == llvm::Triple::MuslEABIHF || |
177 | Triple.getEnvironment() == llvm::Triple::EABIHF))) |
178 | Kind = ARMABIKind::AAPCS_VFP; |
179 | |
180 | return createARMTargetCodeGenInfo(CGM, Kind); |
181 | } |
182 | |
183 | case llvm::Triple::ppc: { |
184 | if (Triple.isOSAIX()) |
185 | return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false); |
186 | |
187 | bool IsSoftFloat = |
188 | CodeGenOpts.FloatABI == "soft" || Target.hasFeature(Feature: "spe" ); |
189 | return createPPC32TargetCodeGenInfo(CGM, SoftFloatABI: IsSoftFloat); |
190 | } |
191 | case llvm::Triple::ppcle: { |
192 | bool IsSoftFloat = CodeGenOpts.FloatABI == "soft" ; |
193 | return createPPC32TargetCodeGenInfo(CGM, SoftFloatABI: IsSoftFloat); |
194 | } |
195 | case llvm::Triple::ppc64: |
196 | if (Triple.isOSAIX()) |
197 | return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true); |
198 | |
199 | if (Triple.isOSBinFormatELF()) { |
200 | PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1; |
201 | if (Target.getABI() == "elfv2" ) |
202 | Kind = PPC64_SVR4_ABIKind::ELFv2; |
203 | bool IsSoftFloat = CodeGenOpts.FloatABI == "soft" ; |
204 | |
205 | return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, SoftFloatABI: IsSoftFloat); |
206 | } |
207 | return createPPC64TargetCodeGenInfo(CGM); |
208 | case llvm::Triple::ppc64le: { |
209 | assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!" ); |
210 | PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2; |
211 | if (Target.getABI() == "elfv1" ) |
212 | Kind = PPC64_SVR4_ABIKind::ELFv1; |
213 | bool IsSoftFloat = CodeGenOpts.FloatABI == "soft" ; |
214 | |
215 | return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, SoftFloatABI: IsSoftFloat); |
216 | } |
217 | |
218 | case llvm::Triple::nvptx: |
219 | case llvm::Triple::nvptx64: |
220 | return createNVPTXTargetCodeGenInfo(CGM); |
221 | |
222 | case llvm::Triple::msp430: |
223 | return createMSP430TargetCodeGenInfo(CGM); |
224 | |
225 | case llvm::Triple::riscv32: |
226 | case llvm::Triple::riscv64: { |
227 | StringRef ABIStr = Target.getABI(); |
228 | unsigned XLen = Target.getPointerWidth(AddrSpace: LangAS::Default); |
229 | unsigned ABIFLen = 0; |
230 | if (ABIStr.ends_with(Suffix: "f" )) |
231 | ABIFLen = 32; |
232 | else if (ABIStr.ends_with(Suffix: "d" )) |
233 | ABIFLen = 64; |
234 | bool EABI = ABIStr.ends_with(Suffix: "e" ); |
235 | return createRISCVTargetCodeGenInfo(CGM, XLen, FLen: ABIFLen, EABI); |
236 | } |
237 | |
238 | case llvm::Triple::systemz: { |
239 | bool SoftFloat = CodeGenOpts.FloatABI == "soft" ; |
240 | bool HasVector = !SoftFloat && Target.getABI() == "vector" ; |
241 | return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloatABI: SoftFloat); |
242 | } |
243 | |
244 | case llvm::Triple::tce: |
245 | case llvm::Triple::tcele: |
246 | return createTCETargetCodeGenInfo(CGM); |
247 | |
248 | case llvm::Triple::x86: { |
249 | bool IsDarwinVectorABI = Triple.isOSDarwin(); |
250 | bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); |
251 | |
252 | if (Triple.getOS() == llvm::Triple::Win32) { |
253 | return createWinX86_32TargetCodeGenInfo( |
254 | CGM, DarwinVectorABI: IsDarwinVectorABI, Win32StructABI: IsWin32FloatStructABI, |
255 | NumRegisterParameters: CodeGenOpts.NumRegisterParameters); |
256 | } |
257 | return createX86_32TargetCodeGenInfo( |
258 | CGM, DarwinVectorABI: IsDarwinVectorABI, Win32StructABI: IsWin32FloatStructABI, |
259 | NumRegisterParameters: CodeGenOpts.NumRegisterParameters, SoftFloatABI: CodeGenOpts.FloatABI == "soft" ); |
260 | } |
261 | |
262 | case llvm::Triple::x86_64: { |
263 | StringRef ABI = Target.getABI(); |
264 | X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 |
265 | : ABI == "avx" ? X86AVXABILevel::AVX |
266 | : X86AVXABILevel::None); |
267 | |
268 | switch (Triple.getOS()) { |
269 | case llvm::Triple::Win32: |
270 | return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel); |
271 | default: |
272 | return createX86_64TargetCodeGenInfo(CGM, AVXLevel); |
273 | } |
274 | } |
275 | case llvm::Triple::hexagon: |
276 | return createHexagonTargetCodeGenInfo(CGM); |
277 | case llvm::Triple::lanai: |
278 | return createLanaiTargetCodeGenInfo(CGM); |
279 | case llvm::Triple::r600: |
280 | return createAMDGPUTargetCodeGenInfo(CGM); |
281 | case llvm::Triple::amdgcn: |
282 | return createAMDGPUTargetCodeGenInfo(CGM); |
283 | case llvm::Triple::sparc: |
284 | return createSparcV8TargetCodeGenInfo(CGM); |
285 | case llvm::Triple::sparcv9: |
286 | return createSparcV9TargetCodeGenInfo(CGM); |
287 | case llvm::Triple::xcore: |
288 | return createXCoreTargetCodeGenInfo(CGM); |
289 | case llvm::Triple::arc: |
290 | return createARCTargetCodeGenInfo(CGM); |
291 | case llvm::Triple::spir: |
292 | case llvm::Triple::spir64: |
293 | return createCommonSPIRTargetCodeGenInfo(CGM); |
294 | case llvm::Triple::spirv32: |
295 | case llvm::Triple::spirv64: |
296 | return createSPIRVTargetCodeGenInfo(CGM); |
297 | case llvm::Triple::ve: |
298 | return createVETargetCodeGenInfo(CGM); |
299 | case llvm::Triple::csky: { |
300 | bool IsSoftFloat = !Target.hasFeature(Feature: "hard-float-abi" ); |
301 | bool hasFP64 = |
302 | Target.hasFeature(Feature: "fpuv2_df" ) || Target.hasFeature(Feature: "fpuv3_df" ); |
303 | return createCSKYTargetCodeGenInfo(CGM, FLen: IsSoftFloat ? 0 |
304 | : hasFP64 ? 64 |
305 | : 32); |
306 | } |
307 | case llvm::Triple::bpfeb: |
308 | case llvm::Triple::bpfel: |
309 | return createBPFTargetCodeGenInfo(CGM); |
310 | case llvm::Triple::loongarch32: |
311 | case llvm::Triple::loongarch64: { |
312 | StringRef ABIStr = Target.getABI(); |
313 | unsigned ABIFRLen = 0; |
314 | if (ABIStr.ends_with(Suffix: "f" )) |
315 | ABIFRLen = 32; |
316 | else if (ABIStr.ends_with(Suffix: "d" )) |
317 | ABIFRLen = 64; |
318 | return createLoongArchTargetCodeGenInfo( |
319 | CGM, GRLen: Target.getPointerWidth(AddrSpace: LangAS::Default), FLen: ABIFRLen); |
320 | } |
321 | } |
322 | } |
323 | |
324 | const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { |
325 | if (!TheTargetCodeGenInfo) |
326 | TheTargetCodeGenInfo = createTargetCodeGenInfo(CGM&: *this); |
327 | return *TheTargetCodeGenInfo; |
328 | } |
329 | |
330 | CodeGenModule::(ASTContext &C, |
331 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, |
332 | const HeaderSearchOptions &HSO, |
333 | const PreprocessorOptions &PPO, |
334 | const CodeGenOptions &CGO, llvm::Module &M, |
335 | DiagnosticsEngine &diags, |
336 | CoverageSourceInfo *CoverageInfo) |
337 | : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO), |
338 | PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), |
339 | Target(C.getTargetInfo()), ABI(createCXXABI(CGM&: *this)), |
340 | VMContext(M.getContext()), Types(*this), VTables(*this), |
341 | SanitizerMD(new SanitizerMetadata(*this)) { |
342 | |
343 | // Initialize the type cache. |
344 | llvm::LLVMContext &LLVMContext = M.getContext(); |
345 | VoidTy = llvm::Type::getVoidTy(C&: LLVMContext); |
346 | Int8Ty = llvm::Type::getInt8Ty(C&: LLVMContext); |
347 | Int16Ty = llvm::Type::getInt16Ty(C&: LLVMContext); |
348 | Int32Ty = llvm::Type::getInt32Ty(C&: LLVMContext); |
349 | Int64Ty = llvm::Type::getInt64Ty(C&: LLVMContext); |
350 | HalfTy = llvm::Type::getHalfTy(C&: LLVMContext); |
351 | BFloatTy = llvm::Type::getBFloatTy(C&: LLVMContext); |
352 | FloatTy = llvm::Type::getFloatTy(C&: LLVMContext); |
353 | DoubleTy = llvm::Type::getDoubleTy(C&: LLVMContext); |
354 | PointerWidthInBits = C.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default); |
355 | PointerAlignInBytes = |
356 | C.toCharUnitsFromBits(BitSize: C.getTargetInfo().getPointerAlign(AddrSpace: LangAS::Default)) |
357 | .getQuantity(); |
358 | SizeSizeInBytes = |
359 | C.toCharUnitsFromBits(BitSize: C.getTargetInfo().getMaxPointerWidth()).getQuantity(); |
360 | IntAlignInBytes = |
361 | C.toCharUnitsFromBits(BitSize: C.getTargetInfo().getIntAlign()).getQuantity(); |
362 | CharTy = |
363 | llvm::IntegerType::get(C&: LLVMContext, NumBits: C.getTargetInfo().getCharWidth()); |
364 | IntTy = llvm::IntegerType::get(C&: LLVMContext, NumBits: C.getTargetInfo().getIntWidth()); |
365 | IntPtrTy = llvm::IntegerType::get(C&: LLVMContext, |
366 | NumBits: C.getTargetInfo().getMaxPointerWidth()); |
367 | Int8PtrTy = llvm::PointerType::get(C&: LLVMContext, AddressSpace: 0); |
368 | const llvm::DataLayout &DL = M.getDataLayout(); |
369 | AllocaInt8PtrTy = |
370 | llvm::PointerType::get(C&: LLVMContext, AddressSpace: DL.getAllocaAddrSpace()); |
371 | GlobalsInt8PtrTy = |
372 | llvm::PointerType::get(C&: LLVMContext, AddressSpace: DL.getDefaultGlobalsAddressSpace()); |
373 | ConstGlobalsPtrTy = llvm::PointerType::get( |
374 | C&: LLVMContext, AddressSpace: C.getTargetAddressSpace(AS: GetGlobalConstantAddressSpace())); |
375 | ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); |
376 | |
377 | // Build C++20 Module initializers. |
378 | // TODO: Add Microsoft here once we know the mangling required for the |
379 | // initializers. |
380 | CXX20ModuleInits = |
381 | LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() == |
382 | ItaniumMangleContext::MK_Itanium; |
383 | |
384 | RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); |
385 | |
386 | if (LangOpts.ObjC) |
387 | createObjCRuntime(); |
388 | if (LangOpts.OpenCL) |
389 | createOpenCLRuntime(); |
390 | if (LangOpts.OpenMP) |
391 | createOpenMPRuntime(); |
392 | if (LangOpts.CUDA) |
393 | createCUDARuntime(); |
394 | if (LangOpts.HLSL) |
395 | createHLSLRuntime(); |
396 | |
397 | // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. |
398 | if (LangOpts.Sanitize.has(K: SanitizerKind::Thread) || |
399 | (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) |
400 | TBAA.reset(p: new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), |
401 | getCXXABI().getMangleContext())); |
402 | |
403 | // If debug info or coverage generation is enabled, create the CGDebugInfo |
404 | // object. |
405 | if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo || |
406 | CodeGenOpts.CoverageNotesFile.size() || |
407 | CodeGenOpts.CoverageDataFile.size()) |
408 | DebugInfo.reset(p: new CGDebugInfo(*this)); |
409 | |
410 | Block.GlobalUniqueCount = 0; |
411 | |
412 | if (C.getLangOpts().ObjC) |
413 | ObjCData.reset(p: new ObjCEntrypoints()); |
414 | |
415 | if (CodeGenOpts.hasProfileClangUse()) { |
416 | auto ReaderOrErr = llvm::IndexedInstrProfReader::create( |
417 | Path: CodeGenOpts.ProfileInstrumentUsePath, FS&: *FS, |
418 | RemappingPath: CodeGenOpts.ProfileRemappingFile); |
419 | // We're checking for profile read errors in CompilerInvocation, so if |
420 | // there was an error it should've already been caught. If it hasn't been |
421 | // somehow, trip an assertion. |
422 | assert(ReaderOrErr); |
423 | PGOReader = std::move(ReaderOrErr.get()); |
424 | } |
425 | |
426 | // If coverage mapping generation is enabled, create the |
427 | // CoverageMappingModuleGen object. |
428 | if (CodeGenOpts.CoverageMapping) |
429 | CoverageMapping.reset(p: new CoverageMappingModuleGen(*this, *CoverageInfo)); |
430 | |
431 | // Generate the module name hash here if needed. |
432 | if (CodeGenOpts.UniqueInternalLinkageNames && |
433 | !getModule().getSourceFileName().empty()) { |
434 | std::string Path = getModule().getSourceFileName(); |
435 | // Check if a path substitution is needed from the MacroPrefixMap. |
436 | for (const auto &Entry : LangOpts.MacroPrefixMap) |
437 | if (Path.rfind(str: Entry.first, pos: 0) != std::string::npos) { |
438 | Path = Entry.second + Path.substr(pos: Entry.first.size()); |
439 | break; |
440 | } |
441 | ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(FName: Path); |
442 | } |
443 | } |
444 | |
445 | CodeGenModule::~CodeGenModule() {} |
446 | |
447 | void CodeGenModule::createObjCRuntime() { |
448 | // This is just isGNUFamily(), but we want to force implementors of |
449 | // new ABIs to decide how best to do this. |
450 | switch (LangOpts.ObjCRuntime.getKind()) { |
451 | case ObjCRuntime::GNUstep: |
452 | case ObjCRuntime::GCC: |
453 | case ObjCRuntime::ObjFW: |
454 | ObjCRuntime.reset(p: CreateGNUObjCRuntime(CGM&: *this)); |
455 | return; |
456 | |
457 | case ObjCRuntime::FragileMacOSX: |
458 | case ObjCRuntime::MacOSX: |
459 | case ObjCRuntime::iOS: |
460 | case ObjCRuntime::WatchOS: |
461 | ObjCRuntime.reset(p: CreateMacObjCRuntime(CGM&: *this)); |
462 | return; |
463 | } |
464 | llvm_unreachable("bad runtime kind" ); |
465 | } |
466 | |
467 | void CodeGenModule::createOpenCLRuntime() { |
468 | OpenCLRuntime.reset(p: new CGOpenCLRuntime(*this)); |
469 | } |
470 | |
471 | void CodeGenModule::createOpenMPRuntime() { |
472 | // Select a specialized code generation class based on the target, if any. |
473 | // If it does not exist use the default implementation. |
474 | switch (getTriple().getArch()) { |
475 | case llvm::Triple::nvptx: |
476 | case llvm::Triple::nvptx64: |
477 | case llvm::Triple::amdgcn: |
478 | assert(getLangOpts().OpenMPIsTargetDevice && |
479 | "OpenMP AMDGPU/NVPTX is only prepared to deal with device code." ); |
480 | OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); |
481 | break; |
482 | default: |
483 | if (LangOpts.OpenMPSimd) |
484 | OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); |
485 | else |
486 | OpenMPRuntime.reset(p: new CGOpenMPRuntime(*this)); |
487 | break; |
488 | } |
489 | } |
490 | |
491 | void CodeGenModule::createCUDARuntime() { |
492 | CUDARuntime.reset(p: CreateNVCUDARuntime(CGM&: *this)); |
493 | } |
494 | |
495 | void CodeGenModule::createHLSLRuntime() { |
496 | HLSLRuntime.reset(p: new CGHLSLRuntime(*this)); |
497 | } |
498 | |
499 | void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { |
500 | Replacements[Name] = C; |
501 | } |
502 | |
503 | void CodeGenModule::applyReplacements() { |
504 | for (auto &I : Replacements) { |
505 | StringRef MangledName = I.first; |
506 | llvm::Constant *Replacement = I.second; |
507 | llvm::GlobalValue *Entry = GetGlobalValue(Ref: MangledName); |
508 | if (!Entry) |
509 | continue; |
510 | auto *OldF = cast<llvm::Function>(Val: Entry); |
511 | auto *NewF = dyn_cast<llvm::Function>(Val: Replacement); |
512 | if (!NewF) { |
513 | if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Val: Replacement)) { |
514 | NewF = dyn_cast<llvm::Function>(Val: Alias->getAliasee()); |
515 | } else { |
516 | auto *CE = cast<llvm::ConstantExpr>(Val: Replacement); |
517 | assert(CE->getOpcode() == llvm::Instruction::BitCast || |
518 | CE->getOpcode() == llvm::Instruction::GetElementPtr); |
519 | NewF = dyn_cast<llvm::Function>(Val: CE->getOperand(i_nocapture: 0)); |
520 | } |
521 | } |
522 | |
523 | // Replace old with new, but keep the old order. |
524 | OldF->replaceAllUsesWith(V: Replacement); |
525 | if (NewF) { |
526 | NewF->removeFromParent(); |
527 | OldF->getParent()->getFunctionList().insertAfter(where: OldF->getIterator(), |
528 | New: NewF); |
529 | } |
530 | OldF->eraseFromParent(); |
531 | } |
532 | } |
533 | |
534 | void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { |
535 | GlobalValReplacements.push_back(Elt: std::make_pair(x&: GV, y&: C)); |
536 | } |
537 | |
538 | void CodeGenModule::applyGlobalValReplacements() { |
539 | for (auto &I : GlobalValReplacements) { |
540 | llvm::GlobalValue *GV = I.first; |
541 | llvm::Constant *C = I.second; |
542 | |
543 | GV->replaceAllUsesWith(V: C); |
544 | GV->eraseFromParent(); |
545 | } |
546 | } |
547 | |
548 | // This is only used in aliases that we created and we know they have a |
549 | // linear structure. |
550 | static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { |
551 | const llvm::Constant *C; |
552 | if (auto *GA = dyn_cast<llvm::GlobalAlias>(Val: GV)) |
553 | C = GA->getAliasee(); |
554 | else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(Val: GV)) |
555 | C = GI->getResolver(); |
556 | else |
557 | return GV; |
558 | |
559 | const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(Val: C->stripPointerCasts()); |
560 | if (!AliaseeGV) |
561 | return nullptr; |
562 | |
563 | const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); |
564 | if (FinalGV == GV) |
565 | return nullptr; |
566 | |
567 | return FinalGV; |
568 | } |
569 | |
570 | static bool checkAliasedGlobal( |
571 | const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, |
572 | bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, |
573 | const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames, |
574 | SourceRange AliasRange) { |
575 | GV = getAliasedGlobal(GV: Alias); |
576 | if (!GV) { |
577 | Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; |
578 | return false; |
579 | } |
580 | |
581 | if (GV->hasCommonLinkage()) { |
582 | const llvm::Triple &Triple = Context.getTargetInfo().getTriple(); |
583 | if (Triple.getObjectFormat() == llvm::Triple::XCOFF) { |
584 | Diags.Report(Location, diag::err_alias_to_common); |
585 | return false; |
586 | } |
587 | } |
588 | |
589 | if (GV->isDeclaration()) { |
590 | Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; |
591 | Diags.Report(Location, diag::note_alias_requires_mangled_name) |
592 | << IsIFunc << IsIFunc; |
593 | // Provide a note if the given function is not found and exists as a |
594 | // mangled name. |
595 | for (const auto &[Decl, Name] : MangledDeclNames) { |
596 | if (const auto *ND = dyn_cast<NamedDecl>(Val: Decl.getDecl())) { |
597 | if (ND->getName() == GV->getName()) { |
598 | Diags.Report(Location, diag::note_alias_mangled_name_alternative) |
599 | << Name |
600 | << FixItHint::CreateReplacement( |
601 | AliasRange, |
602 | (Twine(IsIFunc ? "ifunc" : "alias" ) + "(\"" + Name + "\")" ) |
603 | .str()); |
604 | } |
605 | } |
606 | } |
607 | return false; |
608 | } |
609 | |
610 | if (IsIFunc) { |
611 | // Check resolver function type. |
612 | const auto *F = dyn_cast<llvm::Function>(Val: GV); |
613 | if (!F) { |
614 | Diags.Report(Location, diag::err_alias_to_undefined) |
615 | << IsIFunc << IsIFunc; |
616 | return false; |
617 | } |
618 | |
619 | llvm::FunctionType *FTy = F->getFunctionType(); |
620 | if (!FTy->getReturnType()->isPointerTy()) { |
621 | Diags.Report(Location, diag::err_ifunc_resolver_return); |
622 | return false; |
623 | } |
624 | } |
625 | |
626 | return true; |
627 | } |
628 | |
629 | void CodeGenModule::checkAliases() { |
630 | // Check if the constructed aliases are well formed. It is really unfortunate |
631 | // that we have to do this in CodeGen, but we only construct mangled names |
632 | // and aliases during codegen. |
633 | bool Error = false; |
634 | DiagnosticsEngine &Diags = getDiags(); |
635 | for (const GlobalDecl &GD : Aliases) { |
636 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
637 | SourceLocation Location; |
638 | SourceRange Range; |
639 | bool IsIFunc = D->hasAttr<IFuncAttr>(); |
640 | if (const Attr *A = D->getDefiningAttr()) { |
641 | Location = A->getLocation(); |
642 | Range = A->getRange(); |
643 | } else |
644 | llvm_unreachable("Not an alias or ifunc?" ); |
645 | |
646 | StringRef MangledName = getMangledName(GD); |
647 | llvm::GlobalValue *Alias = GetGlobalValue(Ref: MangledName); |
648 | const llvm::GlobalValue *GV = nullptr; |
649 | if (!checkAliasedGlobal(Context: getContext(), Diags, Location, IsIFunc, Alias, GV, |
650 | MangledDeclNames, AliasRange: Range)) { |
651 | Error = true; |
652 | continue; |
653 | } |
654 | |
655 | llvm::Constant *Aliasee = |
656 | IsIFunc ? cast<llvm::GlobalIFunc>(Val: Alias)->getResolver() |
657 | : cast<llvm::GlobalAlias>(Val: Alias)->getAliasee(); |
658 | |
659 | llvm::GlobalValue *AliaseeGV; |
660 | if (auto CE = dyn_cast<llvm::ConstantExpr>(Val: Aliasee)) |
661 | AliaseeGV = cast<llvm::GlobalValue>(Val: CE->getOperand(i_nocapture: 0)); |
662 | else |
663 | AliaseeGV = cast<llvm::GlobalValue>(Val: Aliasee); |
664 | |
665 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { |
666 | StringRef AliasSection = SA->getName(); |
667 | if (AliasSection != AliaseeGV->getSection()) |
668 | Diags.Report(SA->getLocation(), diag::warn_alias_with_section) |
669 | << AliasSection << IsIFunc << IsIFunc; |
670 | } |
671 | |
672 | // We have to handle alias to weak aliases in here. LLVM itself disallows |
673 | // this since the object semantics would not match the IL one. For |
674 | // compatibility with gcc we implement it by just pointing the alias |
675 | // to its aliasee's aliasee. We also warn, since the user is probably |
676 | // expecting the link to be weak. |
677 | if (auto *GA = dyn_cast<llvm::GlobalAlias>(Val: AliaseeGV)) { |
678 | if (GA->isInterposable()) { |
679 | Diags.Report(Location, diag::warn_alias_to_weak_alias) |
680 | << GV->getName() << GA->getName() << IsIFunc; |
681 | Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
682 | C: GA->getAliasee(), Ty: Alias->getType()); |
683 | |
684 | if (IsIFunc) |
685 | cast<llvm::GlobalIFunc>(Val: Alias)->setResolver(Aliasee); |
686 | else |
687 | cast<llvm::GlobalAlias>(Val: Alias)->setAliasee(Aliasee); |
688 | } |
689 | } |
690 | } |
691 | if (!Error) |
692 | return; |
693 | |
694 | for (const GlobalDecl &GD : Aliases) { |
695 | StringRef MangledName = getMangledName(GD); |
696 | llvm::GlobalValue *Alias = GetGlobalValue(Ref: MangledName); |
697 | Alias->replaceAllUsesWith(V: llvm::UndefValue::get(T: Alias->getType())); |
698 | Alias->eraseFromParent(); |
699 | } |
700 | } |
701 | |
702 | void CodeGenModule::clear() { |
703 | DeferredDeclsToEmit.clear(); |
704 | EmittedDeferredDecls.clear(); |
705 | DeferredAnnotations.clear(); |
706 | if (OpenMPRuntime) |
707 | OpenMPRuntime->clear(); |
708 | } |
709 | |
710 | void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, |
711 | StringRef MainFile) { |
712 | if (!hasDiagnostics()) |
713 | return; |
714 | if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { |
715 | if (MainFile.empty()) |
716 | MainFile = "<stdin>" ; |
717 | Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; |
718 | } else { |
719 | if (Mismatched > 0) |
720 | Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; |
721 | |
722 | if (Missing > 0) |
723 | Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; |
724 | } |
725 | } |
726 | |
727 | static std::optional<llvm::GlobalValue::VisibilityTypes> |
728 | getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) { |
729 | // Map to LLVM visibility. |
730 | switch (K) { |
731 | case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep: |
732 | return std::nullopt; |
733 | case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default: |
734 | return llvm::GlobalValue::DefaultVisibility; |
735 | case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden: |
736 | return llvm::GlobalValue::HiddenVisibility; |
737 | case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected: |
738 | return llvm::GlobalValue::ProtectedVisibility; |
739 | } |
740 | llvm_unreachable("unknown option value!" ); |
741 | } |
742 | |
743 | void setLLVMVisibility(llvm::GlobalValue &GV, |
744 | std::optional<llvm::GlobalValue::VisibilityTypes> V) { |
745 | if (!V) |
746 | return; |
747 | |
748 | // Reset DSO locality before setting the visibility. This removes |
749 | // any effects that visibility options and annotations may have |
750 | // had on the DSO locality. Setting the visibility will implicitly set |
751 | // appropriate globals to DSO Local; however, this will be pessimistic |
752 | // w.r.t. to the normal compiler IRGen. |
753 | GV.setDSOLocal(false); |
754 | GV.setVisibility(*V); |
755 | } |
756 | |
757 | static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, |
758 | llvm::Module &M) { |
759 | if (!LO.VisibilityFromDLLStorageClass) |
760 | return; |
761 | |
762 | std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility = |
763 | getLLVMVisibility(K: LO.getDLLExportVisibility()); |
764 | |
765 | std::optional<llvm::GlobalValue::VisibilityTypes> |
766 | NoDLLStorageClassVisibility = |
767 | getLLVMVisibility(K: LO.getNoDLLStorageClassVisibility()); |
768 | |
769 | std::optional<llvm::GlobalValue::VisibilityTypes> |
770 | ExternDeclDLLImportVisibility = |
771 | getLLVMVisibility(K: LO.getExternDeclDLLImportVisibility()); |
772 | |
773 | std::optional<llvm::GlobalValue::VisibilityTypes> |
774 | ExternDeclNoDLLStorageClassVisibility = |
775 | getLLVMVisibility(K: LO.getExternDeclNoDLLStorageClassVisibility()); |
776 | |
777 | for (llvm::GlobalValue &GV : M.global_values()) { |
778 | if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) |
779 | continue; |
780 | |
781 | if (GV.isDeclarationForLinker()) |
782 | setLLVMVisibility(GV, V: GV.getDLLStorageClass() == |
783 | llvm::GlobalValue::DLLImportStorageClass |
784 | ? ExternDeclDLLImportVisibility |
785 | : ExternDeclNoDLLStorageClassVisibility); |
786 | else |
787 | setLLVMVisibility(GV, V: GV.getDLLStorageClass() == |
788 | llvm::GlobalValue::DLLExportStorageClass |
789 | ? DLLExportVisibility |
790 | : NoDLLStorageClassVisibility); |
791 | |
792 | GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
793 | } |
794 | } |
795 | |
796 | static bool isStackProtectorOn(const LangOptions &LangOpts, |
797 | const llvm::Triple &Triple, |
798 | clang::LangOptions::StackProtectorMode Mode) { |
799 | if (Triple.isAMDGPU() || Triple.isNVPTX()) |
800 | return false; |
801 | return LangOpts.getStackProtector() == Mode; |
802 | } |
803 | |
804 | void CodeGenModule::Release() { |
805 | Module *Primary = getContext().getCurrentNamedModule(); |
806 | if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule()) |
807 | EmitModuleInitializers(Primary); |
808 | EmitDeferred(); |
809 | DeferredDecls.insert(I: EmittedDeferredDecls.begin(), |
810 | E: EmittedDeferredDecls.end()); |
811 | EmittedDeferredDecls.clear(); |
812 | EmitVTablesOpportunistically(); |
813 | applyGlobalValReplacements(); |
814 | applyReplacements(); |
815 | emitMultiVersionFunctions(); |
816 | |
817 | if (Context.getLangOpts().IncrementalExtensions && |
818 | GlobalTopLevelStmtBlockInFlight.first) { |
819 | const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second; |
820 | GlobalTopLevelStmtBlockInFlight.first->FinishFunction(EndLoc: TLSD->getEndLoc()); |
821 | GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr}; |
822 | } |
823 | |
824 | // Module implementations are initialized the same way as a regular TU that |
825 | // imports one or more modules. |
826 | if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition()) |
827 | EmitCXXModuleInitFunc(Primary); |
828 | else |
829 | EmitCXXGlobalInitFunc(); |
830 | EmitCXXGlobalCleanUpFunc(); |
831 | registerGlobalDtorsWithAtExit(); |
832 | EmitCXXThreadLocalInitFunc(); |
833 | if (ObjCRuntime) |
834 | if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) |
835 | AddGlobalCtor(Ctor: ObjCInitFunction); |
836 | if (Context.getLangOpts().CUDA && CUDARuntime) { |
837 | if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) |
838 | AddGlobalCtor(Ctor: CudaCtorFunction); |
839 | } |
840 | if (OpenMPRuntime) { |
841 | if (llvm::Function *OpenMPRequiresDirectiveRegFun = |
842 | OpenMPRuntime->emitRequiresDirectiveRegFun()) { |
843 | AddGlobalCtor(Ctor: OpenMPRequiresDirectiveRegFun, Priority: 0); |
844 | } |
845 | OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); |
846 | OpenMPRuntime->clear(); |
847 | } |
848 | if (PGOReader) { |
849 | getModule().setProfileSummary( |
850 | M: PGOReader->getSummary(/* UseCS */ false).getMD(Context&: VMContext), |
851 | Kind: llvm::ProfileSummary::PSK_Instr); |
852 | if (PGOStats.hasDiagnostics()) |
853 | PGOStats.reportDiagnostics(Diags&: getDiags(), MainFile: getCodeGenOpts().MainFileName); |
854 | } |
855 | llvm::stable_sort(Range&: GlobalCtors, C: [](const Structor &L, const Structor &R) { |
856 | return L.LexOrder < R.LexOrder; |
857 | }); |
858 | EmitCtorList(Fns&: GlobalCtors, GlobalName: "llvm.global_ctors" ); |
859 | EmitCtorList(Fns&: GlobalDtors, GlobalName: "llvm.global_dtors" ); |
860 | EmitGlobalAnnotations(); |
861 | EmitStaticExternCAliases(); |
862 | checkAliases(); |
863 | EmitDeferredUnusedCoverageMappings(); |
864 | CodeGenPGO(*this).setValueProfilingFlag(getModule()); |
865 | if (CoverageMapping) |
866 | CoverageMapping->emit(); |
867 | if (CodeGenOpts.SanitizeCfiCrossDso) { |
868 | CodeGenFunction(*this).EmitCfiCheckFail(); |
869 | CodeGenFunction(*this).EmitCfiCheckStub(); |
870 | } |
871 | if (LangOpts.Sanitize.has(K: SanitizerKind::KCFI)) |
872 | finalizeKCFITypes(); |
873 | emitAtAvailableLinkGuard(); |
874 | if (Context.getTargetInfo().getTriple().isWasm()) |
875 | EmitMainVoidAlias(); |
876 | |
877 | if (getTriple().isAMDGPU()) { |
878 | // Emit amdgpu_code_object_version module flag, which is code object version |
879 | // times 100. |
880 | if (getTarget().getTargetOpts().CodeObjectVersion != |
881 | llvm::CodeObjectVersionKind::COV_None) { |
882 | getModule().addModuleFlag(Behavior: llvm::Module::Error, |
883 | Key: "amdgpu_code_object_version" , |
884 | Val: getTarget().getTargetOpts().CodeObjectVersion); |
885 | } |
886 | |
887 | // Currently, "-mprintf-kind" option is only supported for HIP |
888 | if (LangOpts.HIP) { |
889 | auto *MDStr = llvm::MDString::get( |
890 | Context&: getLLVMContext(), Str: (getTarget().getTargetOpts().AMDGPUPrintfKindVal == |
891 | TargetOptions::AMDGPUPrintfKind::Hostcall) |
892 | ? "hostcall" |
893 | : "buffered" ); |
894 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "amdgpu_printf_kind" , |
895 | Val: MDStr); |
896 | } |
897 | } |
898 | |
899 | // Emit a global array containing all external kernels or device variables |
900 | // used by host functions and mark it as used for CUDA/HIP. This is necessary |
901 | // to get kernels or device variables in archives linked in even if these |
902 | // kernels or device variables are only used in host functions. |
903 | if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) { |
904 | SmallVector<llvm::Constant *, 8> UsedArray; |
905 | for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) { |
906 | GlobalDecl GD; |
907 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
908 | GD = GlobalDecl(FD, KernelReferenceKind::Kernel); |
909 | else |
910 | GD = GlobalDecl(D); |
911 | UsedArray.push_back(Elt: llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
912 | C: GetAddrOfGlobal(GD), Ty: Int8PtrTy)); |
913 | } |
914 | |
915 | llvm::ArrayType *ATy = llvm::ArrayType::get(ElementType: Int8PtrTy, NumElements: UsedArray.size()); |
916 | |
917 | auto *GV = new llvm::GlobalVariable( |
918 | getModule(), ATy, false, llvm::GlobalValue::InternalLinkage, |
919 | llvm::ConstantArray::get(T: ATy, V: UsedArray), "__clang_gpu_used_external" ); |
920 | addCompilerUsedGlobal(GV); |
921 | } |
922 | |
923 | emitLLVMUsed(); |
924 | if (SanStats) |
925 | SanStats->finish(); |
926 | |
927 | if (CodeGenOpts.Autolink && |
928 | (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { |
929 | EmitModuleLinkOptions(); |
930 | } |
931 | |
932 | // On ELF we pass the dependent library specifiers directly to the linker |
933 | // without manipulating them. This is in contrast to other platforms where |
934 | // they are mapped to a specific linker option by the compiler. This |
935 | // difference is a result of the greater variety of ELF linkers and the fact |
936 | // that ELF linkers tend to handle libraries in a more complicated fashion |
937 | // than on other platforms. This forces us to defer handling the dependent |
938 | // libs to the linker. |
939 | // |
940 | // CUDA/HIP device and host libraries are different. Currently there is no |
941 | // way to differentiate dependent libraries for host or device. Existing |
942 | // usage of #pragma comment(lib, *) is intended for host libraries on |
943 | // Windows. Therefore emit llvm.dependent-libraries only for host. |
944 | if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { |
945 | auto *NMD = getModule().getOrInsertNamedMetadata(Name: "llvm.dependent-libraries" ); |
946 | for (auto *MD : ELFDependentLibraries) |
947 | NMD->addOperand(M: MD); |
948 | } |
949 | |
950 | // Record mregparm value now so it is visible through rest of codegen. |
951 | if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) |
952 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "NumRegisterParameters" , |
953 | Val: CodeGenOpts.NumRegisterParameters); |
954 | |
955 | if (CodeGenOpts.DwarfVersion) { |
956 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "Dwarf Version" , |
957 | Val: CodeGenOpts.DwarfVersion); |
958 | } |
959 | |
960 | if (CodeGenOpts.Dwarf64) |
961 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "DWARF64" , Val: 1); |
962 | |
963 | if (Context.getLangOpts().SemanticInterposition) |
964 | // Require various optimization to respect semantic interposition. |
965 | getModule().setSemanticInterposition(true); |
966 | |
967 | if (CodeGenOpts.EmitCodeView) { |
968 | // Indicate that we want CodeView in the metadata. |
969 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "CodeView" , Val: 1); |
970 | } |
971 | if (CodeGenOpts.CodeViewGHash) { |
972 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "CodeViewGHash" , Val: 1); |
973 | } |
974 | if (CodeGenOpts.ControlFlowGuard) { |
975 | // Function ID tables and checks for Control Flow Guard (cfguard=2). |
976 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "cfguard" , Val: 2); |
977 | } else if (CodeGenOpts.ControlFlowGuardNoChecks) { |
978 | // Function ID tables for Control Flow Guard (cfguard=1). |
979 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "cfguard" , Val: 1); |
980 | } |
981 | if (CodeGenOpts.EHContGuard) { |
982 | // Function ID tables for EH Continuation Guard. |
983 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "ehcontguard" , Val: 1); |
984 | } |
985 | if (Context.getLangOpts().Kernel) { |
986 | // Note if we are compiling with /kernel. |
987 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "ms-kernel" , Val: 1); |
988 | } |
989 | if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { |
990 | // We don't support LTO with 2 with different StrictVTablePointers |
991 | // FIXME: we could support it by stripping all the information introduced |
992 | // by StrictVTablePointers. |
993 | |
994 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "StrictVTablePointers" ,Val: 1); |
995 | |
996 | llvm::Metadata *Ops[2] = { |
997 | llvm::MDString::get(Context&: VMContext, Str: "StrictVTablePointers" ), |
998 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
999 | Ty: llvm::Type::getInt32Ty(C&: VMContext), V: 1))}; |
1000 | |
1001 | getModule().addModuleFlag(Behavior: llvm::Module::Require, |
1002 | Key: "StrictVTablePointersRequirement" , |
1003 | Val: llvm::MDNode::get(Context&: VMContext, MDs: Ops)); |
1004 | } |
1005 | if (getModuleDebugInfo()) |
1006 | // We support a single version in the linked module. The LLVM |
1007 | // parser will drop debug info with a different version number |
1008 | // (and warn about it, too). |
1009 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "Debug Info Version" , |
1010 | Val: llvm::DEBUG_METADATA_VERSION); |
1011 | |
1012 | // We need to record the widths of enums and wchar_t, so that we can generate |
1013 | // the correct build attributes in the ARM backend. wchar_size is also used by |
1014 | // TargetLibraryInfo. |
1015 | uint64_t WCharWidth = |
1016 | Context.getTypeSizeInChars(T: Context.getWideCharType()).getQuantity(); |
1017 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "wchar_size" , Val: WCharWidth); |
1018 | |
1019 | if (getTriple().isOSzOS()) { |
1020 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, |
1021 | Key: "zos_product_major_version" , |
1022 | Val: uint32_t(CLANG_VERSION_MAJOR)); |
1023 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, |
1024 | Key: "zos_product_minor_version" , |
1025 | Val: uint32_t(CLANG_VERSION_MINOR)); |
1026 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "zos_product_patchlevel" , |
1027 | Val: uint32_t(CLANG_VERSION_PATCHLEVEL)); |
1028 | std::string ProductId = getClangVendor() + "clang" ; |
1029 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "zos_product_id" , |
1030 | Val: llvm::MDString::get(Context&: VMContext, Str: ProductId)); |
1031 | |
1032 | // Record the language because we need it for the PPA2. |
1033 | StringRef lang_str = languageToString( |
1034 | L: LangStandard::getLangStandardForKind(K: LangOpts.LangStd).Language); |
1035 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "zos_cu_language" , |
1036 | Val: llvm::MDString::get(Context&: VMContext, Str: lang_str)); |
1037 | |
1038 | time_t TT = PreprocessorOpts.SourceDateEpoch |
1039 | ? *PreprocessorOpts.SourceDateEpoch |
1040 | : std::time(timer: nullptr); |
1041 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "zos_translation_time" , |
1042 | Val: static_cast<uint64_t>(TT)); |
1043 | |
1044 | // Multiple modes will be supported here. |
1045 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "zos_le_char_mode" , |
1046 | Val: llvm::MDString::get(Context&: VMContext, Str: "ascii" )); |
1047 | } |
1048 | |
1049 | llvm::Triple T = Context.getTargetInfo().getTriple(); |
1050 | if (T.isARM() || T.isThumb()) { |
1051 | // The minimum width of an enum in bytes |
1052 | uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; |
1053 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "min_enum_size" , Val: EnumWidth); |
1054 | } |
1055 | |
1056 | if (T.isRISCV()) { |
1057 | StringRef ABIStr = Target.getABI(); |
1058 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
1059 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "target-abi" , |
1060 | Val: llvm::MDString::get(Context&: Ctx, Str: ABIStr)); |
1061 | |
1062 | // Add the canonical ISA string as metadata so the backend can set the ELF |
1063 | // attributes correctly. We use AppendUnique so LTO will keep all of the |
1064 | // unique ISA strings that were linked together. |
1065 | const std::vector<std::string> &Features = |
1066 | getTarget().getTargetOpts().Features; |
1067 | auto ParseResult = |
1068 | llvm::RISCVISAInfo::parseFeatures(XLen: T.isRISCV64() ? 64 : 32, Features); |
1069 | if (!errorToBool(Err: ParseResult.takeError())) |
1070 | getModule().addModuleFlag( |
1071 | Behavior: llvm::Module::AppendUnique, Key: "riscv-isa" , |
1072 | Val: llvm::MDNode::get( |
1073 | Context&: Ctx, MDs: llvm::MDString::get(Context&: Ctx, Str: (*ParseResult)->toString()))); |
1074 | } |
1075 | |
1076 | if (CodeGenOpts.SanitizeCfiCrossDso) { |
1077 | // Indicate that we want cross-DSO control flow integrity checks. |
1078 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "Cross-DSO CFI" , Val: 1); |
1079 | } |
1080 | |
1081 | if (CodeGenOpts.WholeProgramVTables) { |
1082 | // Indicate whether VFE was enabled for this module, so that the |
1083 | // vcall_visibility metadata added under whole program vtables is handled |
1084 | // appropriately in the optimizer. |
1085 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "Virtual Function Elim" , |
1086 | Val: CodeGenOpts.VirtualFunctionElimination); |
1087 | } |
1088 | |
1089 | if (LangOpts.Sanitize.has(K: SanitizerKind::CFIICall)) { |
1090 | getModule().addModuleFlag(Behavior: llvm::Module::Override, |
1091 | Key: "CFI Canonical Jump Tables" , |
1092 | Val: CodeGenOpts.SanitizeCfiCanonicalJumpTables); |
1093 | } |
1094 | |
1095 | if (LangOpts.Sanitize.has(K: SanitizerKind::KCFI)) { |
1096 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "kcfi" , Val: 1); |
1097 | // KCFI assumes patchable-function-prefix is the same for all indirectly |
1098 | // called functions. Store the expected offset for code generation. |
1099 | if (CodeGenOpts.PatchableFunctionEntryOffset) |
1100 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "kcfi-offset" , |
1101 | Val: CodeGenOpts.PatchableFunctionEntryOffset); |
1102 | } |
1103 | |
1104 | if (CodeGenOpts.CFProtectionReturn && |
1105 | Target.checkCFProtectionReturnSupported(Diags&: getDiags())) { |
1106 | // Indicate that we want to instrument return control flow protection. |
1107 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "cf-protection-return" , |
1108 | Val: 1); |
1109 | } |
1110 | |
1111 | if (CodeGenOpts.CFProtectionBranch && |
1112 | Target.checkCFProtectionBranchSupported(Diags&: getDiags())) { |
1113 | // Indicate that we want to instrument branch control flow protection. |
1114 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "cf-protection-branch" , |
1115 | Val: 1); |
1116 | } |
1117 | |
1118 | if (CodeGenOpts.FunctionReturnThunks) |
1119 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "function_return_thunk_extern" , Val: 1); |
1120 | |
1121 | if (CodeGenOpts.IndirectBranchCSPrefix) |
1122 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "indirect_branch_cs_prefix" , Val: 1); |
1123 | |
1124 | // Add module metadata for return address signing (ignoring |
1125 | // non-leaf/all) and stack tagging. These are actually turned on by function |
1126 | // attributes, but we use module metadata to emit build attributes. This is |
1127 | // needed for LTO, where the function attributes are inside bitcode |
1128 | // serialised into a global variable by the time build attributes are |
1129 | // emitted, so we can't access them. LTO objects could be compiled with |
1130 | // different flags therefore module flags are set to "Min" behavior to achieve |
1131 | // the same end result of the normal build where e.g BTI is off if any object |
1132 | // doesn't support it. |
1133 | if (Context.getTargetInfo().hasFeature(Feature: "ptrauth" ) && |
1134 | LangOpts.getSignReturnAddressScope() != |
1135 | LangOptions::SignReturnAddressScopeKind::None) |
1136 | getModule().addModuleFlag(Behavior: llvm::Module::Override, |
1137 | Key: "sign-return-address-buildattr" , Val: 1); |
1138 | if (LangOpts.Sanitize.has(K: SanitizerKind::MemtagStack)) |
1139 | getModule().addModuleFlag(Behavior: llvm::Module::Override, |
1140 | Key: "tag-stack-memory-buildattr" , Val: 1); |
1141 | |
1142 | if (T.isARM() || T.isThumb() || T.isAArch64()) { |
1143 | if (LangOpts.BranchTargetEnforcement) |
1144 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "branch-target-enforcement" , |
1145 | Val: 1); |
1146 | if (LangOpts.BranchProtectionPAuthLR) |
1147 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "branch-protection-pauth-lr" , |
1148 | Val: 1); |
1149 | if (LangOpts.GuardedControlStack) |
1150 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "guarded-control-stack" , Val: 1); |
1151 | if (LangOpts.hasSignReturnAddress()) |
1152 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "sign-return-address" , Val: 1); |
1153 | if (LangOpts.isSignReturnAddressScopeAll()) |
1154 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "sign-return-address-all" , |
1155 | Val: 1); |
1156 | if (!LangOpts.isSignReturnAddressWithAKey()) |
1157 | getModule().addModuleFlag(Behavior: llvm::Module::Min, |
1158 | Key: "sign-return-address-with-bkey" , Val: 1); |
1159 | } |
1160 | |
1161 | if (CodeGenOpts.StackClashProtector) |
1162 | getModule().addModuleFlag( |
1163 | Behavior: llvm::Module::Override, Key: "probe-stack" , |
1164 | Val: llvm::MDString::get(Context&: TheModule.getContext(), Str: "inline-asm" )); |
1165 | |
1166 | if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) |
1167 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "stack-probe-size" , |
1168 | Val: CodeGenOpts.StackProbeSize); |
1169 | |
1170 | if (!CodeGenOpts.MemoryProfileOutput.empty()) { |
1171 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
1172 | getModule().addModuleFlag( |
1173 | Behavior: llvm::Module::Error, Key: "MemProfProfileFilename" , |
1174 | Val: llvm::MDString::get(Context&: Ctx, Str: CodeGenOpts.MemoryProfileOutput)); |
1175 | } |
1176 | |
1177 | if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { |
1178 | // Indicate whether __nvvm_reflect should be configured to flush denormal |
1179 | // floating point values to 0. (This corresponds to its "__CUDA_FTZ" |
1180 | // property.) |
1181 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "nvvm-reflect-ftz" , |
1182 | Val: CodeGenOpts.FP32DenormalMode.Output != |
1183 | llvm::DenormalMode::IEEE); |
1184 | } |
1185 | |
1186 | if (LangOpts.EHAsynch) |
1187 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "eh-asynch" , Val: 1); |
1188 | |
1189 | // Indicate whether this Module was compiled with -fopenmp |
1190 | if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) |
1191 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "openmp" , Val: LangOpts.OpenMP); |
1192 | if (getLangOpts().OpenMPIsTargetDevice) |
1193 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "openmp-device" , |
1194 | Val: LangOpts.OpenMP); |
1195 | |
1196 | // Emit OpenCL specific module metadata: OpenCL/SPIR version. |
1197 | if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { |
1198 | EmitOpenCLMetadata(); |
1199 | // Emit SPIR version. |
1200 | if (getTriple().isSPIR()) { |
1201 | // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the |
1202 | // opencl.spir.version named metadata. |
1203 | // C++ for OpenCL has a distinct mapping for version compatibility with |
1204 | // OpenCL. |
1205 | auto Version = LangOpts.getOpenCLCompatibleVersion(); |
1206 | llvm::Metadata *SPIRVerElts[] = { |
1207 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
1208 | Ty: Int32Ty, V: Version / 100)), |
1209 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
1210 | Ty: Int32Ty, V: (Version / 100 > 1) ? 0 : 2))}; |
1211 | llvm::NamedMDNode *SPIRVerMD = |
1212 | TheModule.getOrInsertNamedMetadata(Name: "opencl.spir.version" ); |
1213 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
1214 | SPIRVerMD->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: SPIRVerElts)); |
1215 | } |
1216 | } |
1217 | |
1218 | // HLSL related end of code gen work items. |
1219 | if (LangOpts.HLSL) |
1220 | getHLSLRuntime().finishCodeGen(); |
1221 | |
1222 | if (uint32_t PLevel = Context.getLangOpts().PICLevel) { |
1223 | assert(PLevel < 3 && "Invalid PIC Level" ); |
1224 | getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); |
1225 | if (Context.getLangOpts().PIE) |
1226 | getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); |
1227 | } |
1228 | |
1229 | if (getCodeGenOpts().CodeModel.size() > 0) { |
1230 | unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) |
1231 | .Case(S: "tiny" , Value: llvm::CodeModel::Tiny) |
1232 | .Case(S: "small" , Value: llvm::CodeModel::Small) |
1233 | .Case(S: "kernel" , Value: llvm::CodeModel::Kernel) |
1234 | .Case(S: "medium" , Value: llvm::CodeModel::Medium) |
1235 | .Case(S: "large" , Value: llvm::CodeModel::Large) |
1236 | .Default(Value: ~0u); |
1237 | if (CM != ~0u) { |
1238 | llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); |
1239 | getModule().setCodeModel(codeModel); |
1240 | |
1241 | if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) && |
1242 | Context.getTargetInfo().getTriple().getArch() == |
1243 | llvm::Triple::x86_64) { |
1244 | getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold); |
1245 | } |
1246 | } |
1247 | } |
1248 | |
1249 | if (CodeGenOpts.NoPLT) |
1250 | getModule().setRtLibUseGOT(); |
1251 | if (getTriple().isOSBinFormatELF() && |
1252 | CodeGenOpts.DirectAccessExternalData != |
1253 | getModule().getDirectAccessExternalData()) { |
1254 | getModule().setDirectAccessExternalData( |
1255 | CodeGenOpts.DirectAccessExternalData); |
1256 | } |
1257 | if (CodeGenOpts.UnwindTables) |
1258 | getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables)); |
1259 | |
1260 | switch (CodeGenOpts.getFramePointer()) { |
1261 | case CodeGenOptions::FramePointerKind::None: |
1262 | // 0 ("none") is the default. |
1263 | break; |
1264 | case CodeGenOptions::FramePointerKind::NonLeaf: |
1265 | getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); |
1266 | break; |
1267 | case CodeGenOptions::FramePointerKind::All: |
1268 | getModule().setFramePointer(llvm::FramePointerKind::All); |
1269 | break; |
1270 | } |
1271 | |
1272 | SimplifyPersonality(); |
1273 | |
1274 | if (getCodeGenOpts().EmitDeclMetadata) |
1275 | EmitDeclMetadata(); |
1276 | |
1277 | if (getCodeGenOpts().CoverageNotesFile.size() || |
1278 | getCodeGenOpts().CoverageDataFile.size()) |
1279 | EmitCoverageFile(); |
1280 | |
1281 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
1282 | DI->finalize(); |
1283 | |
1284 | if (getCodeGenOpts().EmitVersionIdentMetadata) |
1285 | EmitVersionIdentMetadata(); |
1286 | |
1287 | if (!getCodeGenOpts().RecordCommandLine.empty()) |
1288 | EmitCommandLineMetadata(); |
1289 | |
1290 | if (!getCodeGenOpts().StackProtectorGuard.empty()) |
1291 | getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); |
1292 | if (!getCodeGenOpts().StackProtectorGuardReg.empty()) |
1293 | getModule().setStackProtectorGuardReg( |
1294 | getCodeGenOpts().StackProtectorGuardReg); |
1295 | if (!getCodeGenOpts().StackProtectorGuardSymbol.empty()) |
1296 | getModule().setStackProtectorGuardSymbol( |
1297 | getCodeGenOpts().StackProtectorGuardSymbol); |
1298 | if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) |
1299 | getModule().setStackProtectorGuardOffset( |
1300 | getCodeGenOpts().StackProtectorGuardOffset); |
1301 | if (getCodeGenOpts().StackAlignment) |
1302 | getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); |
1303 | if (getCodeGenOpts().SkipRaxSetup) |
1304 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "SkipRaxSetup" , Val: 1); |
1305 | if (getLangOpts().RegCall4) |
1306 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "RegCallv4" , Val: 1); |
1307 | |
1308 | if (getContext().getTargetInfo().getMaxTLSAlign()) |
1309 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "MaxTLSAlign" , |
1310 | Val: getContext().getTargetInfo().getMaxTLSAlign()); |
1311 | |
1312 | getTargetCodeGenInfo().emitTargetGlobals(CGM&: *this); |
1313 | |
1314 | getTargetCodeGenInfo().emitTargetMetadata(CGM&: *this, MangledDeclNames); |
1315 | |
1316 | EmitBackendOptionsMetadata(CodeGenOpts: getCodeGenOpts()); |
1317 | |
1318 | // If there is device offloading code embed it in the host now. |
1319 | EmbedObject(M: &getModule(), CGOpts: CodeGenOpts, Diags&: getDiags()); |
1320 | |
1321 | // Set visibility from DLL storage class |
1322 | // We do this at the end of LLVM IR generation; after any operation |
1323 | // that might affect the DLL storage class or the visibility, and |
1324 | // before anything that might act on these. |
1325 | setVisibilityFromDLLStorageClass(LO: LangOpts, M&: getModule()); |
1326 | } |
1327 | |
1328 | void CodeGenModule::EmitOpenCLMetadata() { |
1329 | // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the |
1330 | // opencl.ocl.version named metadata node. |
1331 | // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. |
1332 | auto Version = LangOpts.getOpenCLCompatibleVersion(); |
1333 | llvm::Metadata *OCLVerElts[] = { |
1334 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
1335 | Ty: Int32Ty, V: Version / 100)), |
1336 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
1337 | Ty: Int32Ty, V: (Version % 100) / 10))}; |
1338 | llvm::NamedMDNode *OCLVerMD = |
1339 | TheModule.getOrInsertNamedMetadata(Name: "opencl.ocl.version" ); |
1340 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
1341 | OCLVerMD->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: OCLVerElts)); |
1342 | } |
1343 | |
1344 | void CodeGenModule::EmitBackendOptionsMetadata( |
1345 | const CodeGenOptions &CodeGenOpts) { |
1346 | if (getTriple().isRISCV()) { |
1347 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "SmallDataLimit" , |
1348 | Val: CodeGenOpts.SmallDataLimit); |
1349 | } |
1350 | } |
1351 | |
1352 | void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { |
1353 | // Make sure that this type is translated. |
1354 | Types.UpdateCompletedType(TD); |
1355 | } |
1356 | |
1357 | void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { |
1358 | // Make sure that this type is translated. |
1359 | Types.RefreshTypeCacheForClass(RD); |
1360 | } |
1361 | |
1362 | llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { |
1363 | if (!TBAA) |
1364 | return nullptr; |
1365 | return TBAA->getTypeInfo(QTy); |
1366 | } |
1367 | |
1368 | TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { |
1369 | if (!TBAA) |
1370 | return TBAAAccessInfo(); |
1371 | if (getLangOpts().CUDAIsDevice) { |
1372 | // As CUDA builtin surface/texture types are replaced, skip generating TBAA |
1373 | // access info. |
1374 | if (AccessType->isCUDADeviceBuiltinSurfaceType()) { |
1375 | if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != |
1376 | nullptr) |
1377 | return TBAAAccessInfo(); |
1378 | } else if (AccessType->isCUDADeviceBuiltinTextureType()) { |
1379 | if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != |
1380 | nullptr) |
1381 | return TBAAAccessInfo(); |
1382 | } |
1383 | } |
1384 | return TBAA->getAccessInfo(AccessType); |
1385 | } |
1386 | |
1387 | TBAAAccessInfo |
1388 | CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { |
1389 | if (!TBAA) |
1390 | return TBAAAccessInfo(); |
1391 | return TBAA->getVTablePtrAccessInfo(VTablePtrType); |
1392 | } |
1393 | |
1394 | llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { |
1395 | if (!TBAA) |
1396 | return nullptr; |
1397 | return TBAA->getTBAAStructInfo(QTy); |
1398 | } |
1399 | |
1400 | llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { |
1401 | if (!TBAA) |
1402 | return nullptr; |
1403 | return TBAA->getBaseTypeInfo(QTy); |
1404 | } |
1405 | |
1406 | llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { |
1407 | if (!TBAA) |
1408 | return nullptr; |
1409 | return TBAA->getAccessTagInfo(Info); |
1410 | } |
1411 | |
1412 | TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, |
1413 | TBAAAccessInfo TargetInfo) { |
1414 | if (!TBAA) |
1415 | return TBAAAccessInfo(); |
1416 | return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); |
1417 | } |
1418 | |
1419 | TBAAAccessInfo |
1420 | CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, |
1421 | TBAAAccessInfo InfoB) { |
1422 | if (!TBAA) |
1423 | return TBAAAccessInfo(); |
1424 | return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); |
1425 | } |
1426 | |
1427 | TBAAAccessInfo |
1428 | CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, |
1429 | TBAAAccessInfo SrcInfo) { |
1430 | if (!TBAA) |
1431 | return TBAAAccessInfo(); |
1432 | return TBAA->mergeTBAAInfoForConditionalOperator(InfoA: DestInfo, InfoB: SrcInfo); |
1433 | } |
1434 | |
1435 | void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, |
1436 | TBAAAccessInfo TBAAInfo) { |
1437 | if (llvm::MDNode *Tag = getTBAAAccessTagInfo(Info: TBAAInfo)) |
1438 | Inst->setMetadata(KindID: llvm::LLVMContext::MD_tbaa, Node: Tag); |
1439 | } |
1440 | |
1441 | void CodeGenModule::DecorateInstructionWithInvariantGroup( |
1442 | llvm::Instruction *I, const CXXRecordDecl *RD) { |
1443 | I->setMetadata(KindID: llvm::LLVMContext::MD_invariant_group, |
1444 | Node: llvm::MDNode::get(Context&: getLLVMContext(), MDs: {})); |
1445 | } |
1446 | |
1447 | void CodeGenModule::Error(SourceLocation loc, StringRef message) { |
1448 | unsigned diagID = getDiags().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0" ); |
1449 | getDiags().Report(Loc: Context.getFullLoc(Loc: loc), DiagID: diagID) << message; |
1450 | } |
1451 | |
1452 | /// ErrorUnsupported - Print out an error that codegen doesn't support the |
1453 | /// specified stmt yet. |
1454 | void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { |
1455 | unsigned DiagID = getDiags().getCustomDiagID(L: DiagnosticsEngine::Error, |
1456 | FormatString: "cannot compile this %0 yet" ); |
1457 | std::string Msg = Type; |
1458 | getDiags().Report(Loc: Context.getFullLoc(Loc: S->getBeginLoc()), DiagID) |
1459 | << Msg << S->getSourceRange(); |
1460 | } |
1461 | |
1462 | /// ErrorUnsupported - Print out an error that codegen doesn't support the |
1463 | /// specified decl yet. |
1464 | void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { |
1465 | unsigned DiagID = getDiags().getCustomDiagID(L: DiagnosticsEngine::Error, |
1466 | FormatString: "cannot compile this %0 yet" ); |
1467 | std::string Msg = Type; |
1468 | getDiags().Report(Loc: Context.getFullLoc(Loc: D->getLocation()), DiagID) << Msg; |
1469 | } |
1470 | |
1471 | llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { |
1472 | return llvm::ConstantInt::get(Ty: SizeTy, V: size.getQuantity()); |
1473 | } |
1474 | |
1475 | void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, |
1476 | const NamedDecl *D) const { |
1477 | // Internal definitions always have default visibility. |
1478 | if (GV->hasLocalLinkage()) { |
1479 | GV->setVisibility(llvm::GlobalValue::DefaultVisibility); |
1480 | return; |
1481 | } |
1482 | if (!D) |
1483 | return; |
1484 | |
1485 | // Set visibility for definitions, and for declarations if requested globally |
1486 | // or set explicitly. |
1487 | LinkageInfo LV = D->getLinkageAndVisibility(); |
1488 | |
1489 | // OpenMP declare target variables must be visible to the host so they can |
1490 | // be registered. We require protected visibility unless the variable has |
1491 | // the DT_nohost modifier and does not need to be registered. |
1492 | if (Context.getLangOpts().OpenMP && |
1493 | Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) && |
1494 | D->hasAttr<OMPDeclareTargetDeclAttr>() && |
1495 | D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() != |
1496 | OMPDeclareTargetDeclAttr::DT_NoHost && |
1497 | LV.getVisibility() == HiddenVisibility) { |
1498 | GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); |
1499 | return; |
1500 | } |
1501 | |
1502 | if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) { |
1503 | // Reject incompatible dlllstorage and visibility annotations. |
1504 | if (!LV.isVisibilityExplicit()) |
1505 | return; |
1506 | if (GV->hasDLLExportStorageClass()) { |
1507 | if (LV.getVisibility() == HiddenVisibility) |
1508 | getDiags().Report(D->getLocation(), |
1509 | diag::err_hidden_visibility_dllexport); |
1510 | } else if (LV.getVisibility() != DefaultVisibility) { |
1511 | getDiags().Report(D->getLocation(), |
1512 | diag::err_non_default_visibility_dllimport); |
1513 | } |
1514 | return; |
1515 | } |
1516 | |
1517 | if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || |
1518 | !GV->isDeclarationForLinker()) |
1519 | GV->setVisibility(GetLLVMVisibility(V: LV.getVisibility())); |
1520 | } |
1521 | |
1522 | static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, |
1523 | llvm::GlobalValue *GV) { |
1524 | if (GV->hasLocalLinkage()) |
1525 | return true; |
1526 | |
1527 | if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) |
1528 | return true; |
1529 | |
1530 | // DLLImport explicitly marks the GV as external. |
1531 | if (GV->hasDLLImportStorageClass()) |
1532 | return false; |
1533 | |
1534 | const llvm::Triple &TT = CGM.getTriple(); |
1535 | const auto &CGOpts = CGM.getCodeGenOpts(); |
1536 | if (TT.isWindowsGNUEnvironment()) { |
1537 | // In MinGW, variables without DLLImport can still be automatically |
1538 | // imported from a DLL by the linker; don't mark variables that |
1539 | // potentially could come from another DLL as DSO local. |
1540 | |
1541 | // With EmulatedTLS, TLS variables can be autoimported from other DLLs |
1542 | // (and this actually happens in the public interface of libstdc++), so |
1543 | // such variables can't be marked as DSO local. (Native TLS variables |
1544 | // can't be dllimported at all, though.) |
1545 | if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(Val: GV) && |
1546 | (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) && |
1547 | CGOpts.AutoImport) |
1548 | return false; |
1549 | } |
1550 | |
1551 | // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols |
1552 | // remain unresolved in the link, they can be resolved to zero, which is |
1553 | // outside the current DSO. |
1554 | if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) |
1555 | return false; |
1556 | |
1557 | // Every other GV is local on COFF. |
1558 | // Make an exception for windows OS in the triple: Some firmware builds use |
1559 | // *-win32-macho triples. This (accidentally?) produced windows relocations |
1560 | // without GOT tables in older clang versions; Keep this behaviour. |
1561 | // FIXME: even thread local variables? |
1562 | if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) |
1563 | return true; |
1564 | |
1565 | // Only handle COFF and ELF for now. |
1566 | if (!TT.isOSBinFormatELF()) |
1567 | return false; |
1568 | |
1569 | // If this is not an executable, don't assume anything is local. |
1570 | llvm::Reloc::Model RM = CGOpts.RelocationModel; |
1571 | const auto &LOpts = CGM.getLangOpts(); |
1572 | if (RM != llvm::Reloc::Static && !LOpts.PIE) { |
1573 | // On ELF, if -fno-semantic-interposition is specified and the target |
1574 | // supports local aliases, there will be neither CC1 |
1575 | // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set |
1576 | // dso_local on the function if using a local alias is preferable (can avoid |
1577 | // PLT indirection). |
1578 | if (!(isa<llvm::Function>(Val: GV) && GV->canBenefitFromLocalAlias())) |
1579 | return false; |
1580 | return !(CGM.getLangOpts().SemanticInterposition || |
1581 | CGM.getLangOpts().HalfNoSemanticInterposition); |
1582 | } |
1583 | |
1584 | // A definition cannot be preempted from an executable. |
1585 | if (!GV->isDeclarationForLinker()) |
1586 | return true; |
1587 | |
1588 | // Most PIC code sequences that assume that a symbol is local cannot produce a |
1589 | // 0 if it turns out the symbol is undefined. While this is ABI and relocation |
1590 | // depended, it seems worth it to handle it here. |
1591 | if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) |
1592 | return false; |
1593 | |
1594 | // PowerPC64 prefers TOC indirection to avoid copy relocations. |
1595 | if (TT.isPPC64()) |
1596 | return false; |
1597 | |
1598 | if (CGOpts.DirectAccessExternalData) { |
1599 | // If -fdirect-access-external-data (default for -fno-pic), set dso_local |
1600 | // for non-thread-local variables. If the symbol is not defined in the |
1601 | // executable, a copy relocation will be needed at link time. dso_local is |
1602 | // excluded for thread-local variables because they generally don't support |
1603 | // copy relocations. |
1604 | if (auto *Var = dyn_cast<llvm::GlobalVariable>(Val: GV)) |
1605 | if (!Var->isThreadLocal()) |
1606 | return true; |
1607 | |
1608 | // -fno-pic sets dso_local on a function declaration to allow direct |
1609 | // accesses when taking its address (similar to a data symbol). If the |
1610 | // function is not defined in the executable, a canonical PLT entry will be |
1611 | // needed at link time. -fno-direct-access-external-data can avoid the |
1612 | // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as |
1613 | // it could just cause trouble without providing perceptible benefits. |
1614 | if (isa<llvm::Function>(Val: GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) |
1615 | return true; |
1616 | } |
1617 | |
1618 | // If we can use copy relocations we can assume it is local. |
1619 | |
1620 | // Otherwise don't assume it is local. |
1621 | return false; |
1622 | } |
1623 | |
1624 | void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { |
1625 | GV->setDSOLocal(shouldAssumeDSOLocal(CGM: *this, GV)); |
1626 | } |
1627 | |
1628 | void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, |
1629 | GlobalDecl GD) const { |
1630 | const auto *D = dyn_cast<NamedDecl>(Val: GD.getDecl()); |
1631 | // C++ destructors have a few C++ ABI specific special cases. |
1632 | if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(Val: D)) { |
1633 | getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, DT: GD.getDtorType()); |
1634 | return; |
1635 | } |
1636 | setDLLImportDLLExport(GV, D); |
1637 | } |
1638 | |
1639 | void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, |
1640 | const NamedDecl *D) const { |
1641 | if (D && D->isExternallyVisible()) { |
1642 | if (D->hasAttr<DLLImportAttr>()) |
1643 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); |
1644 | else if ((D->hasAttr<DLLExportAttr>() || |
1645 | shouldMapVisibilityToDLLExport(D)) && |
1646 | !GV->isDeclarationForLinker()) |
1647 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); |
1648 | } |
1649 | } |
1650 | |
1651 | void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, |
1652 | GlobalDecl GD) const { |
1653 | setDLLImportDLLExport(GV, GD); |
1654 | setGVPropertiesAux(GV, D: dyn_cast<NamedDecl>(Val: GD.getDecl())); |
1655 | } |
1656 | |
1657 | void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, |
1658 | const NamedDecl *D) const { |
1659 | setDLLImportDLLExport(GV, D); |
1660 | setGVPropertiesAux(GV, D); |
1661 | } |
1662 | |
1663 | void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, |
1664 | const NamedDecl *D) const { |
1665 | setGlobalVisibility(GV, D); |
1666 | setDSOLocal(GV); |
1667 | GV->setPartition(CodeGenOpts.SymbolPartition); |
1668 | } |
1669 | |
1670 | static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { |
1671 | return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) |
1672 | .Case(S: "global-dynamic" , Value: llvm::GlobalVariable::GeneralDynamicTLSModel) |
1673 | .Case(S: "local-dynamic" , Value: llvm::GlobalVariable::LocalDynamicTLSModel) |
1674 | .Case(S: "initial-exec" , Value: llvm::GlobalVariable::InitialExecTLSModel) |
1675 | .Case(S: "local-exec" , Value: llvm::GlobalVariable::LocalExecTLSModel); |
1676 | } |
1677 | |
1678 | llvm::GlobalVariable::ThreadLocalMode |
1679 | CodeGenModule::GetDefaultLLVMTLSModel() const { |
1680 | switch (CodeGenOpts.getDefaultTLSModel()) { |
1681 | case CodeGenOptions::GeneralDynamicTLSModel: |
1682 | return llvm::GlobalVariable::GeneralDynamicTLSModel; |
1683 | case CodeGenOptions::LocalDynamicTLSModel: |
1684 | return llvm::GlobalVariable::LocalDynamicTLSModel; |
1685 | case CodeGenOptions::InitialExecTLSModel: |
1686 | return llvm::GlobalVariable::InitialExecTLSModel; |
1687 | case CodeGenOptions::LocalExecTLSModel: |
1688 | return llvm::GlobalVariable::LocalExecTLSModel; |
1689 | } |
1690 | llvm_unreachable("Invalid TLS model!" ); |
1691 | } |
1692 | |
1693 | void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { |
1694 | assert(D.getTLSKind() && "setting TLS mode on non-TLS var!" ); |
1695 | |
1696 | llvm::GlobalValue::ThreadLocalMode TLM; |
1697 | TLM = GetDefaultLLVMTLSModel(); |
1698 | |
1699 | // Override the TLS model if it is explicitly specified. |
1700 | if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { |
1701 | TLM = GetLLVMTLSModel(Attr->getModel()); |
1702 | } |
1703 | |
1704 | GV->setThreadLocalMode(TLM); |
1705 | } |
1706 | |
1707 | static std::string getCPUSpecificMangling(const CodeGenModule &CGM, |
1708 | StringRef Name) { |
1709 | const TargetInfo &Target = CGM.getTarget(); |
1710 | return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); |
1711 | } |
1712 | |
1713 | static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, |
1714 | const CPUSpecificAttr *Attr, |
1715 | unsigned CPUIndex, |
1716 | raw_ostream &Out) { |
1717 | // cpu_specific gets the current name, dispatch gets the resolver if IFunc is |
1718 | // supported. |
1719 | if (Attr) |
1720 | Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); |
1721 | else if (CGM.getTarget().supportsIFunc()) |
1722 | Out << ".resolver" ; |
1723 | } |
1724 | |
1725 | static void AppendTargetVersionMangling(const CodeGenModule &CGM, |
1726 | const TargetVersionAttr *Attr, |
1727 | raw_ostream &Out) { |
1728 | if (Attr->isDefaultVersion()) { |
1729 | Out << ".default" ; |
1730 | return; |
1731 | } |
1732 | Out << "._" ; |
1733 | const TargetInfo &TI = CGM.getTarget(); |
1734 | llvm::SmallVector<StringRef, 8> Feats; |
1735 | Attr->getFeatures(Feats); |
1736 | llvm::stable_sort(Range&: Feats, C: [&TI](const StringRef FeatL, const StringRef FeatR) { |
1737 | return TI.multiVersionSortPriority(Name: FeatL) < |
1738 | TI.multiVersionSortPriority(Name: FeatR); |
1739 | }); |
1740 | for (const auto &Feat : Feats) { |
1741 | Out << 'M'; |
1742 | Out << Feat; |
1743 | } |
1744 | } |
1745 | |
1746 | static void AppendTargetMangling(const CodeGenModule &CGM, |
1747 | const TargetAttr *Attr, raw_ostream &Out) { |
1748 | if (Attr->isDefaultVersion()) |
1749 | return; |
1750 | |
1751 | Out << '.'; |
1752 | const TargetInfo &Target = CGM.getTarget(); |
1753 | ParsedTargetAttr Info = Target.parseTargetAttr(Str: Attr->getFeaturesStr()); |
1754 | llvm::sort(C&: Info.Features, Comp: [&Target](StringRef LHS, StringRef RHS) { |
1755 | // Multiversioning doesn't allow "no-${feature}", so we can |
1756 | // only have "+" prefixes here. |
1757 | assert(LHS.starts_with("+" ) && RHS.starts_with("+" ) && |
1758 | "Features should always have a prefix." ); |
1759 | return Target.multiVersionSortPriority(Name: LHS.substr(Start: 1)) > |
1760 | Target.multiVersionSortPriority(Name: RHS.substr(Start: 1)); |
1761 | }); |
1762 | |
1763 | bool IsFirst = true; |
1764 | |
1765 | if (!Info.CPU.empty()) { |
1766 | IsFirst = false; |
1767 | Out << "arch_" << Info.CPU; |
1768 | } |
1769 | |
1770 | for (StringRef Feat : Info.Features) { |
1771 | if (!IsFirst) |
1772 | Out << '_'; |
1773 | IsFirst = false; |
1774 | Out << Feat.substr(1); |
1775 | } |
1776 | } |
1777 | |
1778 | // Returns true if GD is a function decl with internal linkage and |
1779 | // needs a unique suffix after the mangled name. |
1780 | static bool isUniqueInternalLinkageDecl(GlobalDecl GD, |
1781 | CodeGenModule &CGM) { |
1782 | const Decl *D = GD.getDecl(); |
1783 | return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(Val: D) && |
1784 | (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); |
1785 | } |
1786 | |
1787 | static void AppendTargetClonesMangling(const CodeGenModule &CGM, |
1788 | const TargetClonesAttr *Attr, |
1789 | unsigned VersionIndex, |
1790 | raw_ostream &Out) { |
1791 | const TargetInfo &TI = CGM.getTarget(); |
1792 | if (TI.getTriple().isAArch64()) { |
1793 | StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); |
1794 | if (FeatureStr == "default" ) { |
1795 | Out << ".default" ; |
1796 | return; |
1797 | } |
1798 | Out << "._" ; |
1799 | SmallVector<StringRef, 8> Features; |
1800 | FeatureStr.split(A&: Features, Separator: "+" ); |
1801 | llvm::stable_sort(Range&: Features, |
1802 | C: [&TI](const StringRef FeatL, const StringRef FeatR) { |
1803 | return TI.multiVersionSortPriority(Name: FeatL) < |
1804 | TI.multiVersionSortPriority(Name: FeatR); |
1805 | }); |
1806 | for (auto &Feat : Features) { |
1807 | Out << 'M'; |
1808 | Out << Feat; |
1809 | } |
1810 | } else { |
1811 | Out << '.'; |
1812 | StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); |
1813 | if (FeatureStr.starts_with(Prefix: "arch=" )) |
1814 | Out << "arch_" << FeatureStr.substr(Start: sizeof("arch=" ) - 1); |
1815 | else |
1816 | Out << FeatureStr; |
1817 | |
1818 | Out << '.' << Attr->getMangledIndex(VersionIndex); |
1819 | } |
1820 | } |
1821 | |
1822 | static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, |
1823 | const NamedDecl *ND, |
1824 | bool OmitMultiVersionMangling = false) { |
1825 | SmallString<256> Buffer; |
1826 | llvm::raw_svector_ostream Out(Buffer); |
1827 | MangleContext &MC = CGM.getCXXABI().getMangleContext(); |
1828 | if (!CGM.getModuleNameHash().empty()) |
1829 | MC.needsUniqueInternalLinkageNames(); |
1830 | bool ShouldMangle = MC.shouldMangleDeclName(D: ND); |
1831 | if (ShouldMangle) |
1832 | MC.mangleName(GD: GD.getWithDecl(ND), Out); |
1833 | else { |
1834 | IdentifierInfo *II = ND->getIdentifier(); |
1835 | assert(II && "Attempt to mangle unnamed decl." ); |
1836 | const auto *FD = dyn_cast<FunctionDecl>(Val: ND); |
1837 | |
1838 | if (FD && |
1839 | FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { |
1840 | if (CGM.getLangOpts().RegCall4) |
1841 | Out << "__regcall4__" << II->getName(); |
1842 | else |
1843 | Out << "__regcall3__" << II->getName(); |
1844 | } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && |
1845 | GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { |
1846 | Out << "__device_stub__" << II->getName(); |
1847 | } else { |
1848 | Out << II->getName(); |
1849 | } |
1850 | } |
1851 | |
1852 | // Check if the module name hash should be appended for internal linkage |
1853 | // symbols. This should come before multi-version target suffixes are |
1854 | // appended. This is to keep the name and module hash suffix of the |
1855 | // internal linkage function together. The unique suffix should only be |
1856 | // added when name mangling is done to make sure that the final name can |
1857 | // be properly demangled. For example, for C functions without prototypes, |
1858 | // name mangling is not done and the unique suffix should not be appeneded |
1859 | // then. |
1860 | if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { |
1861 | assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && |
1862 | "Hash computed when not explicitly requested" ); |
1863 | Out << CGM.getModuleNameHash(); |
1864 | } |
1865 | |
1866 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) |
1867 | if (FD->isMultiVersion() && !OmitMultiVersionMangling) { |
1868 | switch (FD->getMultiVersionKind()) { |
1869 | case MultiVersionKind::CPUDispatch: |
1870 | case MultiVersionKind::CPUSpecific: |
1871 | AppendCPUSpecificCPUDispatchMangling(CGM, |
1872 | FD->getAttr<CPUSpecificAttr>(), |
1873 | GD.getMultiVersionIndex(), Out); |
1874 | break; |
1875 | case MultiVersionKind::Target: |
1876 | AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); |
1877 | break; |
1878 | case MultiVersionKind::TargetVersion: |
1879 | AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out); |
1880 | break; |
1881 | case MultiVersionKind::TargetClones: |
1882 | AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), |
1883 | GD.getMultiVersionIndex(), Out); |
1884 | break; |
1885 | case MultiVersionKind::None: |
1886 | llvm_unreachable("None multiversion type isn't valid here" ); |
1887 | } |
1888 | } |
1889 | |
1890 | // Make unique name for device side static file-scope variable for HIP. |
1891 | if (CGM.getContext().shouldExternalize(ND) && |
1892 | CGM.getLangOpts().GPURelocatableDeviceCode && |
1893 | CGM.getLangOpts().CUDAIsDevice) |
1894 | CGM.printPostfixForExternalizedDecl(Out, ND); |
1895 | |
1896 | return std::string(Out.str()); |
1897 | } |
1898 | |
1899 | void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, |
1900 | const FunctionDecl *FD, |
1901 | StringRef &CurName) { |
1902 | if (!FD->isMultiVersion()) |
1903 | return; |
1904 | |
1905 | // Get the name of what this would be without the 'target' attribute. This |
1906 | // allows us to lookup the version that was emitted when this wasn't a |
1907 | // multiversion function. |
1908 | std::string NonTargetName = |
1909 | getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); |
1910 | GlobalDecl OtherGD; |
1911 | if (lookupRepresentativeDecl(MangledName: NonTargetName, Result&: OtherGD)) { |
1912 | assert(OtherGD.getCanonicalDecl() |
1913 | .getDecl() |
1914 | ->getAsFunction() |
1915 | ->isMultiVersion() && |
1916 | "Other GD should now be a multiversioned function" ); |
1917 | // OtherFD is the version of this function that was mangled BEFORE |
1918 | // becoming a MultiVersion function. It potentially needs to be updated. |
1919 | const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() |
1920 | .getDecl() |
1921 | ->getAsFunction() |
1922 | ->getMostRecentDecl(); |
1923 | std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); |
1924 | // This is so that if the initial version was already the 'default' |
1925 | // version, we don't try to update it. |
1926 | if (OtherName != NonTargetName) { |
1927 | // Remove instead of erase, since others may have stored the StringRef |
1928 | // to this. |
1929 | const auto ExistingRecord = Manglings.find(Key: NonTargetName); |
1930 | if (ExistingRecord != std::end(cont&: Manglings)) |
1931 | Manglings.remove(KeyValue: &(*ExistingRecord)); |
1932 | auto Result = Manglings.insert(KV: std::make_pair(x&: OtherName, y&: OtherGD)); |
1933 | StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = |
1934 | Result.first->first(); |
1935 | // If this is the current decl is being created, make sure we update the name. |
1936 | if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) |
1937 | CurName = OtherNameRef; |
1938 | if (llvm::GlobalValue *Entry = GetGlobalValue(Ref: NonTargetName)) |
1939 | Entry->setName(OtherName); |
1940 | } |
1941 | } |
1942 | } |
1943 | |
1944 | StringRef CodeGenModule::getMangledName(GlobalDecl GD) { |
1945 | GlobalDecl CanonicalGD = GD.getCanonicalDecl(); |
1946 | |
1947 | // Some ABIs don't have constructor variants. Make sure that base and |
1948 | // complete constructors get mangled the same. |
1949 | if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: CanonicalGD.getDecl())) { |
1950 | if (!getTarget().getCXXABI().hasConstructorVariants()) { |
1951 | CXXCtorType OrigCtorType = GD.getCtorType(); |
1952 | assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); |
1953 | if (OrigCtorType == Ctor_Base) |
1954 | CanonicalGD = GlobalDecl(CD, Ctor_Complete); |
1955 | } |
1956 | } |
1957 | |
1958 | // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a |
1959 | // static device variable depends on whether the variable is referenced by |
1960 | // a host or device host function. Therefore the mangled name cannot be |
1961 | // cached. |
1962 | if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(D: GD.getDecl())) { |
1963 | auto FoundName = MangledDeclNames.find(Key: CanonicalGD); |
1964 | if (FoundName != MangledDeclNames.end()) |
1965 | return FoundName->second; |
1966 | } |
1967 | |
1968 | // Keep the first result in the case of a mangling collision. |
1969 | const auto *ND = cast<NamedDecl>(Val: GD.getDecl()); |
1970 | std::string MangledName = getMangledNameImpl(CGM&: *this, GD, ND); |
1971 | |
1972 | // Ensure either we have different ABIs between host and device compilations, |
1973 | // says host compilation following MSVC ABI but device compilation follows |
1974 | // Itanium C++ ABI or, if they follow the same ABI, kernel names after |
1975 | // mangling should be the same after name stubbing. The later checking is |
1976 | // very important as the device kernel name being mangled in host-compilation |
1977 | // is used to resolve the device binaries to be executed. Inconsistent naming |
1978 | // result in undefined behavior. Even though we cannot check that naming |
1979 | // directly between host- and device-compilations, the host- and |
1980 | // device-mangling in host compilation could help catching certain ones. |
1981 | assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || |
1982 | getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || |
1983 | (getContext().getAuxTargetInfo() && |
1984 | (getContext().getAuxTargetInfo()->getCXXABI() != |
1985 | getContext().getTargetInfo().getCXXABI())) || |
1986 | getCUDARuntime().getDeviceSideName(ND) == |
1987 | getMangledNameImpl( |
1988 | *this, |
1989 | GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), |
1990 | ND)); |
1991 | |
1992 | auto Result = Manglings.insert(KV: std::make_pair(x&: MangledName, y&: GD)); |
1993 | return MangledDeclNames[CanonicalGD] = Result.first->first(); |
1994 | } |
1995 | |
1996 | StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, |
1997 | const BlockDecl *BD) { |
1998 | MangleContext &MangleCtx = getCXXABI().getMangleContext(); |
1999 | const Decl *D = GD.getDecl(); |
2000 | |
2001 | SmallString<256> Buffer; |
2002 | llvm::raw_svector_ostream Out(Buffer); |
2003 | if (!D) |
2004 | MangleCtx.mangleGlobalBlock(BD, |
2005 | dyn_cast_or_null<VarDecl>(Val: initializedGlobalDecl.getDecl()), Out); |
2006 | else if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: D)) |
2007 | MangleCtx.mangleCtorBlock(CD, CT: GD.getCtorType(), BD, Out); |
2008 | else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: D)) |
2009 | MangleCtx.mangleDtorBlock(CD: DD, DT: GD.getDtorType(), BD, Out); |
2010 | else |
2011 | MangleCtx.mangleBlock(DC: cast<DeclContext>(Val: D), BD, Out); |
2012 | |
2013 | auto Result = Manglings.insert(KV: std::make_pair(x: Out.str(), y&: BD)); |
2014 | return Result.first->first(); |
2015 | } |
2016 | |
2017 | const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { |
2018 | auto it = MangledDeclNames.begin(); |
2019 | while (it != MangledDeclNames.end()) { |
2020 | if (it->second == Name) |
2021 | return it->first; |
2022 | it++; |
2023 | } |
2024 | return GlobalDecl(); |
2025 | } |
2026 | |
2027 | llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { |
2028 | return getModule().getNamedValue(Name); |
2029 | } |
2030 | |
2031 | /// AddGlobalCtor - Add a function to the list that will be called before |
2032 | /// main() runs. |
2033 | void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, |
2034 | unsigned LexOrder, |
2035 | llvm::Constant *AssociatedData) { |
2036 | // FIXME: Type coercion of void()* types. |
2037 | GlobalCtors.push_back(x: Structor(Priority, LexOrder, Ctor, AssociatedData)); |
2038 | } |
2039 | |
2040 | /// AddGlobalDtor - Add a function to the list that will be called |
2041 | /// when the module is unloaded. |
2042 | void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, |
2043 | bool IsDtorAttrFunc) { |
2044 | if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && |
2045 | (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { |
2046 | DtorsUsingAtExit[Priority].push_back(NewVal: Dtor); |
2047 | return; |
2048 | } |
2049 | |
2050 | // FIXME: Type coercion of void()* types. |
2051 | GlobalDtors.push_back(x: Structor(Priority, ~0U, Dtor, nullptr)); |
2052 | } |
2053 | |
2054 | void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { |
2055 | if (Fns.empty()) return; |
2056 | |
2057 | // Ctor function type is void()*. |
2058 | llvm::FunctionType* CtorFTy = llvm::FunctionType::get(Result: VoidTy, isVarArg: false); |
2059 | llvm::Type *CtorPFTy = llvm::PointerType::get(ElementType: CtorFTy, |
2060 | AddressSpace: TheModule.getDataLayout().getProgramAddressSpace()); |
2061 | |
2062 | // Get the type of a ctor entry, { i32, void ()*, i8* }. |
2063 | llvm::StructType *CtorStructTy = llvm::StructType::get( |
2064 | elt1: Int32Ty, elts: CtorPFTy, elts: VoidPtrTy); |
2065 | |
2066 | // Construct the constructor and destructor arrays. |
2067 | ConstantInitBuilder builder(*this); |
2068 | auto ctors = builder.beginArray(eltTy: CtorStructTy); |
2069 | for (const auto &I : Fns) { |
2070 | auto ctor = ctors.beginStruct(ty: CtorStructTy); |
2071 | ctor.addInt(intTy: Int32Ty, value: I.Priority); |
2072 | ctor.add(value: I.Initializer); |
2073 | if (I.AssociatedData) |
2074 | ctor.add(value: I.AssociatedData); |
2075 | else |
2076 | ctor.addNullPointer(ptrTy: VoidPtrTy); |
2077 | ctor.finishAndAddTo(parent&: ctors); |
2078 | } |
2079 | |
2080 | auto list = |
2081 | ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), |
2082 | /*constant*/ false, |
2083 | llvm::GlobalValue::AppendingLinkage); |
2084 | |
2085 | // The LTO linker doesn't seem to like it when we set an alignment |
2086 | // on appending variables. Take it off as a workaround. |
2087 | list->setAlignment(std::nullopt); |
2088 | |
2089 | Fns.clear(); |
2090 | } |
2091 | |
2092 | llvm::GlobalValue::LinkageTypes |
2093 | CodeGenModule::getFunctionLinkage(GlobalDecl GD) { |
2094 | const auto *D = cast<FunctionDecl>(Val: GD.getDecl()); |
2095 | |
2096 | GVALinkage Linkage = getContext().GetGVALinkageForFunction(FD: D); |
2097 | |
2098 | if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: D)) |
2099 | return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, DT: GD.getDtorType()); |
2100 | |
2101 | return getLLVMLinkageForDeclarator(D, Linkage); |
2102 | } |
2103 | |
2104 | llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { |
2105 | llvm::MDString *MDS = dyn_cast<llvm::MDString>(Val: MD); |
2106 | if (!MDS) return nullptr; |
2107 | |
2108 | return llvm::ConstantInt::get(Ty: Int64Ty, V: llvm::MD5Hash(Str: MDS->getString())); |
2109 | } |
2110 | |
2111 | llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) { |
2112 | if (auto *FnType = T->getAs<FunctionProtoType>()) |
2113 | T = getContext().getFunctionType( |
2114 | ResultTy: FnType->getReturnType(), Args: FnType->getParamTypes(), |
2115 | EPI: FnType->getExtProtoInfo().withExceptionSpec(ESI: EST_None)); |
2116 | |
2117 | std::string OutName; |
2118 | llvm::raw_string_ostream Out(OutName); |
2119 | getCXXABI().getMangleContext().mangleCanonicalTypeName( |
2120 | T, Out, NormalizeIntegers: getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); |
2121 | |
2122 | if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) |
2123 | Out << ".normalized" ; |
2124 | |
2125 | return llvm::ConstantInt::get(Ty: Int32Ty, |
2126 | V: static_cast<uint32_t>(llvm::xxHash64(Data: OutName))); |
2127 | } |
2128 | |
2129 | void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, |
2130 | const CGFunctionInfo &Info, |
2131 | llvm::Function *F, bool IsThunk) { |
2132 | unsigned CallingConv; |
2133 | llvm::AttributeList PAL; |
2134 | ConstructAttributeList(Name: F->getName(), Info, CalleeInfo: GD, Attrs&: PAL, CallingConv, |
2135 | /*AttrOnCallSite=*/false, IsThunk); |
2136 | F->setAttributes(PAL); |
2137 | F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); |
2138 | } |
2139 | |
2140 | static void removeImageAccessQualifier(std::string& TyName) { |
2141 | std::string ReadOnlyQual("__read_only" ); |
2142 | std::string::size_type ReadOnlyPos = TyName.find(str: ReadOnlyQual); |
2143 | if (ReadOnlyPos != std::string::npos) |
2144 | // "+ 1" for the space after access qualifier. |
2145 | TyName.erase(pos: ReadOnlyPos, n: ReadOnlyQual.size() + 1); |
2146 | else { |
2147 | std::string WriteOnlyQual("__write_only" ); |
2148 | std::string::size_type WriteOnlyPos = TyName.find(str: WriteOnlyQual); |
2149 | if (WriteOnlyPos != std::string::npos) |
2150 | TyName.erase(pos: WriteOnlyPos, n: WriteOnlyQual.size() + 1); |
2151 | else { |
2152 | std::string ReadWriteQual("__read_write" ); |
2153 | std::string::size_type ReadWritePos = TyName.find(str: ReadWriteQual); |
2154 | if (ReadWritePos != std::string::npos) |
2155 | TyName.erase(pos: ReadWritePos, n: ReadWriteQual.size() + 1); |
2156 | } |
2157 | } |
2158 | } |
2159 | |
2160 | // Returns the address space id that should be produced to the |
2161 | // kernel_arg_addr_space metadata. This is always fixed to the ids |
2162 | // as specified in the SPIR 2.0 specification in order to differentiate |
2163 | // for example in clGetKernelArgInfo() implementation between the address |
2164 | // spaces with targets without unique mapping to the OpenCL address spaces |
2165 | // (basically all single AS CPUs). |
2166 | static unsigned ArgInfoAddressSpace(LangAS AS) { |
2167 | switch (AS) { |
2168 | case LangAS::opencl_global: |
2169 | return 1; |
2170 | case LangAS::opencl_constant: |
2171 | return 2; |
2172 | case LangAS::opencl_local: |
2173 | return 3; |
2174 | case LangAS::opencl_generic: |
2175 | return 4; // Not in SPIR 2.0 specs. |
2176 | case LangAS::opencl_global_device: |
2177 | return 5; |
2178 | case LangAS::opencl_global_host: |
2179 | return 6; |
2180 | default: |
2181 | return 0; // Assume private. |
2182 | } |
2183 | } |
2184 | |
2185 | void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, |
2186 | const FunctionDecl *FD, |
2187 | CodeGenFunction *CGF) { |
2188 | assert(((FD && CGF) || (!FD && !CGF)) && |
2189 | "Incorrect use - FD and CGF should either be both null or not!" ); |
2190 | // Create MDNodes that represent the kernel arg metadata. |
2191 | // Each MDNode is a list in the form of "key", N number of values which is |
2192 | // the same number of values as their are kernel arguments. |
2193 | |
2194 | const PrintingPolicy &Policy = Context.getPrintingPolicy(); |
2195 | |
2196 | // MDNode for the kernel argument address space qualifiers. |
2197 | SmallVector<llvm::Metadata *, 8> addressQuals; |
2198 | |
2199 | // MDNode for the kernel argument access qualifiers (images only). |
2200 | SmallVector<llvm::Metadata *, 8> accessQuals; |
2201 | |
2202 | // MDNode for the kernel argument type names. |
2203 | SmallVector<llvm::Metadata *, 8> argTypeNames; |
2204 | |
2205 | // MDNode for the kernel argument base type names. |
2206 | SmallVector<llvm::Metadata *, 8> argBaseTypeNames; |
2207 | |
2208 | // MDNode for the kernel argument type qualifiers. |
2209 | SmallVector<llvm::Metadata *, 8> argTypeQuals; |
2210 | |
2211 | // MDNode for the kernel argument names. |
2212 | SmallVector<llvm::Metadata *, 8> argNames; |
2213 | |
2214 | if (FD && CGF) |
2215 | for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { |
2216 | const ParmVarDecl *parm = FD->getParamDecl(i); |
2217 | // Get argument name. |
2218 | argNames.push_back(Elt: llvm::MDString::get(VMContext, parm->getName())); |
2219 | |
2220 | if (!getLangOpts().OpenCL) |
2221 | continue; |
2222 | QualType ty = parm->getType(); |
2223 | std::string typeQuals; |
2224 | |
2225 | // Get image and pipe access qualifier: |
2226 | if (ty->isImageType() || ty->isPipeType()) { |
2227 | const Decl *PDecl = parm; |
2228 | if (const auto *TD = ty->getAs<TypedefType>()) |
2229 | PDecl = TD->getDecl(); |
2230 | const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); |
2231 | if (A && A->isWriteOnly()) |
2232 | accessQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: "write_only" )); |
2233 | else if (A && A->isReadWrite()) |
2234 | accessQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: "read_write" )); |
2235 | else |
2236 | accessQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: "read_only" )); |
2237 | } else |
2238 | accessQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: "none" )); |
2239 | |
2240 | auto getTypeSpelling = [&](QualType Ty) { |
2241 | auto typeName = Ty.getUnqualifiedType().getAsString(Policy); |
2242 | |
2243 | if (Ty.isCanonical()) { |
2244 | StringRef typeNameRef = typeName; |
2245 | // Turn "unsigned type" to "utype" |
2246 | if (typeNameRef.consume_front(Prefix: "unsigned " )) |
2247 | return std::string("u" ) + typeNameRef.str(); |
2248 | if (typeNameRef.consume_front(Prefix: "signed " )) |
2249 | return typeNameRef.str(); |
2250 | } |
2251 | |
2252 | return typeName; |
2253 | }; |
2254 | |
2255 | if (ty->isPointerType()) { |
2256 | QualType pointeeTy = ty->getPointeeType(); |
2257 | |
2258 | // Get address qualifier. |
2259 | addressQuals.push_back( |
2260 | Elt: llvm::ConstantAsMetadata::get(C: CGF->Builder.getInt32( |
2261 | C: ArgInfoAddressSpace(AS: pointeeTy.getAddressSpace())))); |
2262 | |
2263 | // Get argument type name. |
2264 | std::string typeName = getTypeSpelling(pointeeTy) + "*" ; |
2265 | std::string baseTypeName = |
2266 | getTypeSpelling(pointeeTy.getCanonicalType()) + "*" ; |
2267 | argTypeNames.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: typeName)); |
2268 | argBaseTypeNames.push_back( |
2269 | Elt: llvm::MDString::get(Context&: VMContext, Str: baseTypeName)); |
2270 | |
2271 | // Get argument type qualifiers: |
2272 | if (ty.isRestrictQualified()) |
2273 | typeQuals = "restrict" ; |
2274 | if (pointeeTy.isConstQualified() || |
2275 | (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) |
2276 | typeQuals += typeQuals.empty() ? "const" : " const" ; |
2277 | if (pointeeTy.isVolatileQualified()) |
2278 | typeQuals += typeQuals.empty() ? "volatile" : " volatile" ; |
2279 | } else { |
2280 | uint32_t AddrSpc = 0; |
2281 | bool isPipe = ty->isPipeType(); |
2282 | if (ty->isImageType() || isPipe) |
2283 | AddrSpc = ArgInfoAddressSpace(AS: LangAS::opencl_global); |
2284 | |
2285 | addressQuals.push_back( |
2286 | Elt: llvm::ConstantAsMetadata::get(C: CGF->Builder.getInt32(C: AddrSpc))); |
2287 | |
2288 | // Get argument type name. |
2289 | ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; |
2290 | std::string typeName = getTypeSpelling(ty); |
2291 | std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); |
2292 | |
2293 | // Remove access qualifiers on images |
2294 | // (as they are inseparable from type in clang implementation, |
2295 | // but OpenCL spec provides a special query to get access qualifier |
2296 | // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): |
2297 | if (ty->isImageType()) { |
2298 | removeImageAccessQualifier(TyName&: typeName); |
2299 | removeImageAccessQualifier(TyName&: baseTypeName); |
2300 | } |
2301 | |
2302 | argTypeNames.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: typeName)); |
2303 | argBaseTypeNames.push_back( |
2304 | Elt: llvm::MDString::get(Context&: VMContext, Str: baseTypeName)); |
2305 | |
2306 | if (isPipe) |
2307 | typeQuals = "pipe" ; |
2308 | } |
2309 | argTypeQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: typeQuals)); |
2310 | } |
2311 | |
2312 | if (getLangOpts().OpenCL) { |
2313 | Fn->setMetadata(Kind: "kernel_arg_addr_space" , |
2314 | Node: llvm::MDNode::get(Context&: VMContext, MDs: addressQuals)); |
2315 | Fn->setMetadata(Kind: "kernel_arg_access_qual" , |
2316 | Node: llvm::MDNode::get(Context&: VMContext, MDs: accessQuals)); |
2317 | Fn->setMetadata(Kind: "kernel_arg_type" , |
2318 | Node: llvm::MDNode::get(Context&: VMContext, MDs: argTypeNames)); |
2319 | Fn->setMetadata(Kind: "kernel_arg_base_type" , |
2320 | Node: llvm::MDNode::get(Context&: VMContext, MDs: argBaseTypeNames)); |
2321 | Fn->setMetadata(Kind: "kernel_arg_type_qual" , |
2322 | Node: llvm::MDNode::get(Context&: VMContext, MDs: argTypeQuals)); |
2323 | } |
2324 | if (getCodeGenOpts().EmitOpenCLArgMetadata || |
2325 | getCodeGenOpts().HIPSaveKernelArgName) |
2326 | Fn->setMetadata(Kind: "kernel_arg_name" , |
2327 | Node: llvm::MDNode::get(Context&: VMContext, MDs: argNames)); |
2328 | } |
2329 | |
2330 | /// Determines whether the language options require us to model |
2331 | /// unwind exceptions. We treat -fexceptions as mandating this |
2332 | /// except under the fragile ObjC ABI with only ObjC exceptions |
2333 | /// enabled. This means, for example, that C with -fexceptions |
2334 | /// enables this. |
2335 | static bool hasUnwindExceptions(const LangOptions &LangOpts) { |
2336 | // If exceptions are completely disabled, obviously this is false. |
2337 | if (!LangOpts.Exceptions) return false; |
2338 | |
2339 | // If C++ exceptions are enabled, this is true. |
2340 | if (LangOpts.CXXExceptions) return true; |
2341 | |
2342 | // If ObjC exceptions are enabled, this depends on the ABI. |
2343 | if (LangOpts.ObjCExceptions) { |
2344 | return LangOpts.ObjCRuntime.hasUnwindExceptions(); |
2345 | } |
2346 | |
2347 | return true; |
2348 | } |
2349 | |
2350 | static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, |
2351 | const CXXMethodDecl *MD) { |
2352 | // Check that the type metadata can ever actually be used by a call. |
2353 | if (!CGM.getCodeGenOpts().LTOUnit || |
2354 | !CGM.HasHiddenLTOVisibility(RD: MD->getParent())) |
2355 | return false; |
2356 | |
2357 | // Only functions whose address can be taken with a member function pointer |
2358 | // need this sort of type metadata. |
2359 | return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() && |
2360 | !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: MD); |
2361 | } |
2362 | |
2363 | SmallVector<const CXXRecordDecl *, 0> |
2364 | CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { |
2365 | llvm::SetVector<const CXXRecordDecl *> MostBases; |
2366 | |
2367 | std::function<void (const CXXRecordDecl *)> CollectMostBases; |
2368 | CollectMostBases = [&](const CXXRecordDecl *RD) { |
2369 | if (RD->getNumBases() == 0) |
2370 | MostBases.insert(X: RD); |
2371 | for (const CXXBaseSpecifier &B : RD->bases()) |
2372 | CollectMostBases(B.getType()->getAsCXXRecordDecl()); |
2373 | }; |
2374 | CollectMostBases(RD); |
2375 | return MostBases.takeVector(); |
2376 | } |
2377 | |
2378 | void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, |
2379 | llvm::Function *F) { |
2380 | llvm::AttrBuilder B(F->getContext()); |
2381 | |
2382 | if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables) |
2383 | B.addUWTableAttr(Kind: llvm::UWTableKind(CodeGenOpts.UnwindTables)); |
2384 | |
2385 | if (CodeGenOpts.StackClashProtector) |
2386 | B.addAttribute(A: "probe-stack" , V: "inline-asm" ); |
2387 | |
2388 | if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) |
2389 | B.addAttribute(A: "stack-probe-size" , |
2390 | V: std::to_string(val: CodeGenOpts.StackProbeSize)); |
2391 | |
2392 | if (!hasUnwindExceptions(LangOpts)) |
2393 | B.addAttribute(llvm::Attribute::NoUnwind); |
2394 | |
2395 | if (D && D->hasAttr<NoStackProtectorAttr>()) |
2396 | ; // Do nothing. |
2397 | else if (D && D->hasAttr<StrictGuardStackCheckAttr>() && |
2398 | isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) |
2399 | B.addAttribute(llvm::Attribute::StackProtectStrong); |
2400 | else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) |
2401 | B.addAttribute(llvm::Attribute::StackProtect); |
2402 | else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong)) |
2403 | B.addAttribute(llvm::Attribute::StackProtectStrong); |
2404 | else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq)) |
2405 | B.addAttribute(llvm::Attribute::StackProtectReq); |
2406 | |
2407 | if (!D) { |
2408 | // If we don't have a declaration to control inlining, the function isn't |
2409 | // explicitly marked as alwaysinline for semantic reasons, and inlining is |
2410 | // disabled, mark the function as noinline. |
2411 | if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && |
2412 | CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) |
2413 | B.addAttribute(llvm::Attribute::NoInline); |
2414 | |
2415 | F->addFnAttrs(Attrs: B); |
2416 | return; |
2417 | } |
2418 | |
2419 | // Handle SME attributes that apply to function definitions, |
2420 | // rather than to function prototypes. |
2421 | if (D->hasAttr<ArmLocallyStreamingAttr>()) |
2422 | B.addAttribute(A: "aarch64_pstate_sm_body" ); |
2423 | |
2424 | if (auto *Attr = D->getAttr<ArmNewAttr>()) { |
2425 | if (Attr->isNewZA()) |
2426 | B.addAttribute(A: "aarch64_new_za" ); |
2427 | if (Attr->isNewZT0()) |
2428 | B.addAttribute(A: "aarch64_new_zt0" ); |
2429 | } |
2430 | |
2431 | // Track whether we need to add the optnone LLVM attribute, |
2432 | // starting with the default for this optimization level. |
2433 | bool ShouldAddOptNone = |
2434 | !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; |
2435 | // We can't add optnone in the following cases, it won't pass the verifier. |
2436 | ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); |
2437 | ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); |
2438 | |
2439 | // Add optnone, but do so only if the function isn't always_inline. |
2440 | if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && |
2441 | !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { |
2442 | B.addAttribute(llvm::Attribute::OptimizeNone); |
2443 | |
2444 | // OptimizeNone implies noinline; we should not be inlining such functions. |
2445 | B.addAttribute(llvm::Attribute::NoInline); |
2446 | |
2447 | // We still need to handle naked functions even though optnone subsumes |
2448 | // much of their semantics. |
2449 | if (D->hasAttr<NakedAttr>()) |
2450 | B.addAttribute(llvm::Attribute::Naked); |
2451 | |
2452 | // OptimizeNone wins over OptimizeForSize and MinSize. |
2453 | F->removeFnAttr(llvm::Attribute::OptimizeForSize); |
2454 | F->removeFnAttr(llvm::Attribute::MinSize); |
2455 | } else if (D->hasAttr<NakedAttr>()) { |
2456 | // Naked implies noinline: we should not be inlining such functions. |
2457 | B.addAttribute(llvm::Attribute::Naked); |
2458 | B.addAttribute(llvm::Attribute::NoInline); |
2459 | } else if (D->hasAttr<NoDuplicateAttr>()) { |
2460 | B.addAttribute(llvm::Attribute::NoDuplicate); |
2461 | } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { |
2462 | // Add noinline if the function isn't always_inline. |
2463 | B.addAttribute(llvm::Attribute::NoInline); |
2464 | } else if (D->hasAttr<AlwaysInlineAttr>() && |
2465 | !F->hasFnAttribute(llvm::Attribute::NoInline)) { |
2466 | // (noinline wins over always_inline, and we can't specify both in IR) |
2467 | B.addAttribute(llvm::Attribute::AlwaysInline); |
2468 | } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { |
2469 | // If we're not inlining, then force everything that isn't always_inline to |
2470 | // carry an explicit noinline attribute. |
2471 | if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) |
2472 | B.addAttribute(llvm::Attribute::NoInline); |
2473 | } else { |
2474 | // Otherwise, propagate the inline hint attribute and potentially use its |
2475 | // absence to mark things as noinline. |
2476 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
2477 | // Search function and template pattern redeclarations for inline. |
2478 | auto CheckForInline = [](const FunctionDecl *FD) { |
2479 | auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { |
2480 | return Redecl->isInlineSpecified(); |
2481 | }; |
2482 | if (any_of(FD->redecls(), CheckRedeclForInline)) |
2483 | return true; |
2484 | const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); |
2485 | if (!Pattern) |
2486 | return false; |
2487 | return any_of(Pattern->redecls(), CheckRedeclForInline); |
2488 | }; |
2489 | if (CheckForInline(FD)) { |
2490 | B.addAttribute(llvm::Attribute::InlineHint); |
2491 | } else if (CodeGenOpts.getInlining() == |
2492 | CodeGenOptions::OnlyHintInlining && |
2493 | !FD->isInlined() && |
2494 | !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { |
2495 | B.addAttribute(llvm::Attribute::NoInline); |
2496 | } |
2497 | } |
2498 | } |
2499 | |
2500 | // Add other optimization related attributes if we are optimizing this |
2501 | // function. |
2502 | if (!D->hasAttr<OptimizeNoneAttr>()) { |
2503 | if (D->hasAttr<ColdAttr>()) { |
2504 | if (!ShouldAddOptNone) |
2505 | B.addAttribute(llvm::Attribute::OptimizeForSize); |
2506 | B.addAttribute(llvm::Attribute::Cold); |
2507 | } |
2508 | if (D->hasAttr<HotAttr>()) |
2509 | B.addAttribute(llvm::Attribute::Hot); |
2510 | if (D->hasAttr<MinSizeAttr>()) |
2511 | B.addAttribute(llvm::Attribute::MinSize); |
2512 | } |
2513 | |
2514 | F->addFnAttrs(Attrs: B); |
2515 | |
2516 | unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); |
2517 | if (alignment) |
2518 | F->setAlignment(llvm::Align(alignment)); |
2519 | |
2520 | if (!D->hasAttr<AlignedAttr>()) |
2521 | if (LangOpts.FunctionAlignment) |
2522 | F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); |
2523 | |
2524 | // Some C++ ABIs require 2-byte alignment for member functions, in order to |
2525 | // reserve a bit for differentiating between virtual and non-virtual member |
2526 | // functions. If the current target's C++ ABI requires this and this is a |
2527 | // member function, set its alignment accordingly. |
2528 | if (getTarget().getCXXABI().areMemberFunctionsAligned()) { |
2529 | if (isa<CXXMethodDecl>(Val: D) && F->getPointerAlignment(DL: getDataLayout()) < 2) |
2530 | F->setAlignment(std::max(a: llvm::Align(2), b: F->getAlign().valueOrOne())); |
2531 | } |
2532 | |
2533 | // In the cross-dso CFI mode with canonical jump tables, we want !type |
2534 | // attributes on definitions only. |
2535 | if (CodeGenOpts.SanitizeCfiCrossDso && |
2536 | CodeGenOpts.SanitizeCfiCanonicalJumpTables) { |
2537 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
2538 | // Skip available_externally functions. They won't be codegen'ed in the |
2539 | // current module anyway. |
2540 | if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) |
2541 | CreateFunctionTypeMetadataForIcall(FD, F); |
2542 | } |
2543 | } |
2544 | |
2545 | // Emit type metadata on member functions for member function pointer checks. |
2546 | // These are only ever necessary on definitions; we're guaranteed that the |
2547 | // definition will be present in the LTO unit as a result of LTO visibility. |
2548 | auto *MD = dyn_cast<CXXMethodDecl>(Val: D); |
2549 | if (MD && requiresMemberFunctionPointerTypeMetadata(CGM&: *this, MD)) { |
2550 | for (const CXXRecordDecl *Base : getMostBaseClasses(RD: MD->getParent())) { |
2551 | llvm::Metadata *Id = |
2552 | CreateMetadataIdentifierForType(T: Context.getMemberPointerType( |
2553 | T: MD->getType(), Cls: Context.getRecordType(Base).getTypePtr())); |
2554 | F->addTypeMetadata(Offset: 0, TypeID: Id); |
2555 | } |
2556 | } |
2557 | } |
2558 | |
2559 | void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { |
2560 | const Decl *D = GD.getDecl(); |
2561 | if (isa_and_nonnull<NamedDecl>(Val: D)) |
2562 | setGVProperties(GV, GD); |
2563 | else |
2564 | GV->setVisibility(llvm::GlobalValue::DefaultVisibility); |
2565 | |
2566 | if (D && D->hasAttr<UsedAttr>()) |
2567 | addUsedOrCompilerUsedGlobal(GV); |
2568 | |
2569 | if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: D); |
2570 | VD && |
2571 | ((CodeGenOpts.KeepPersistentStorageVariables && |
2572 | (VD->getStorageDuration() == SD_Static || |
2573 | VD->getStorageDuration() == SD_Thread)) || |
2574 | (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && |
2575 | VD->getType().isConstQualified()))) |
2576 | addUsedOrCompilerUsedGlobal(GV); |
2577 | } |
2578 | |
2579 | bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, |
2580 | llvm::AttrBuilder &Attrs, |
2581 | bool SetTargetFeatures) { |
2582 | // Add target-cpu and target-features attributes to functions. If |
2583 | // we have a decl for the function and it has a target attribute then |
2584 | // parse that and add it to the feature set. |
2585 | StringRef TargetCPU = getTarget().getTargetOpts().CPU; |
2586 | StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; |
2587 | std::vector<std::string> Features; |
2588 | const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: GD.getDecl()); |
2589 | FD = FD ? FD->getMostRecentDecl() : FD; |
2590 | const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; |
2591 | const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr; |
2592 | assert((!TD || !TV) && "both target_version and target specified" ); |
2593 | const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; |
2594 | const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; |
2595 | bool AddedAttr = false; |
2596 | if (TD || TV || SD || TC) { |
2597 | llvm::StringMap<bool> FeatureMap; |
2598 | getContext().getFunctionFeatureMap(FeatureMap, GD); |
2599 | |
2600 | // Produce the canonical string for this set of features. |
2601 | for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) |
2602 | Features.push_back(x: (Entry.getValue() ? "+" : "-" ) + Entry.getKey().str()); |
2603 | |
2604 | // Now add the target-cpu and target-features to the function. |
2605 | // While we populated the feature map above, we still need to |
2606 | // get and parse the target attribute so we can get the cpu for |
2607 | // the function. |
2608 | if (TD) { |
2609 | ParsedTargetAttr ParsedAttr = |
2610 | Target.parseTargetAttr(Str: TD->getFeaturesStr()); |
2611 | if (!ParsedAttr.CPU.empty() && |
2612 | getTarget().isValidCPUName(Name: ParsedAttr.CPU)) { |
2613 | TargetCPU = ParsedAttr.CPU; |
2614 | TuneCPU = "" ; // Clear the tune CPU. |
2615 | } |
2616 | if (!ParsedAttr.Tune.empty() && |
2617 | getTarget().isValidCPUName(Name: ParsedAttr.Tune)) |
2618 | TuneCPU = ParsedAttr.Tune; |
2619 | } |
2620 | |
2621 | if (SD) { |
2622 | // Apply the given CPU name as the 'tune-cpu' so that the optimizer can |
2623 | // favor this processor. |
2624 | TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName(); |
2625 | } |
2626 | } else { |
2627 | // Otherwise just add the existing target cpu and target features to the |
2628 | // function. |
2629 | Features = getTarget().getTargetOpts().Features; |
2630 | } |
2631 | |
2632 | if (!TargetCPU.empty()) { |
2633 | Attrs.addAttribute(A: "target-cpu" , V: TargetCPU); |
2634 | AddedAttr = true; |
2635 | } |
2636 | if (!TuneCPU.empty()) { |
2637 | Attrs.addAttribute(A: "tune-cpu" , V: TuneCPU); |
2638 | AddedAttr = true; |
2639 | } |
2640 | if (!Features.empty() && SetTargetFeatures) { |
2641 | llvm::erase_if(C&: Features, P: [&](const std::string& F) { |
2642 | return getTarget().isReadOnlyFeature(Feature: F.substr(pos: 1)); |
2643 | }); |
2644 | llvm::sort(C&: Features); |
2645 | Attrs.addAttribute(A: "target-features" , V: llvm::join(R&: Features, Separator: "," )); |
2646 | AddedAttr = true; |
2647 | } |
2648 | |
2649 | return AddedAttr; |
2650 | } |
2651 | |
2652 | void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, |
2653 | llvm::GlobalObject *GO) { |
2654 | const Decl *D = GD.getDecl(); |
2655 | SetCommonAttributes(GD, GV: GO); |
2656 | |
2657 | if (D) { |
2658 | if (auto *GV = dyn_cast<llvm::GlobalVariable>(Val: GO)) { |
2659 | if (D->hasAttr<RetainAttr>()) |
2660 | addUsedGlobal(GV); |
2661 | if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) |
2662 | GV->addAttribute("bss-section" , SA->getName()); |
2663 | if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) |
2664 | GV->addAttribute("data-section" , SA->getName()); |
2665 | if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) |
2666 | GV->addAttribute("rodata-section" , SA->getName()); |
2667 | if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) |
2668 | GV->addAttribute("relro-section" , SA->getName()); |
2669 | } |
2670 | |
2671 | if (auto *F = dyn_cast<llvm::Function>(Val: GO)) { |
2672 | if (D->hasAttr<RetainAttr>()) |
2673 | addUsedGlobal(GV: F); |
2674 | if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) |
2675 | if (!D->getAttr<SectionAttr>()) |
2676 | F->addFnAttr("implicit-section-name" , SA->getName()); |
2677 | |
2678 | llvm::AttrBuilder Attrs(F->getContext()); |
2679 | if (GetCPUAndFeaturesAttributes(GD, Attrs)) { |
2680 | // We know that GetCPUAndFeaturesAttributes will always have the |
2681 | // newest set, since it has the newest possible FunctionDecl, so the |
2682 | // new ones should replace the old. |
2683 | llvm::AttributeMask RemoveAttrs; |
2684 | RemoveAttrs.addAttribute(A: "target-cpu" ); |
2685 | RemoveAttrs.addAttribute(A: "target-features" ); |
2686 | RemoveAttrs.addAttribute(A: "tune-cpu" ); |
2687 | F->removeFnAttrs(Attrs: RemoveAttrs); |
2688 | F->addFnAttrs(Attrs); |
2689 | } |
2690 | } |
2691 | |
2692 | if (const auto *CSA = D->getAttr<CodeSegAttr>()) |
2693 | GO->setSection(CSA->getName()); |
2694 | else if (const auto *SA = D->getAttr<SectionAttr>()) |
2695 | GO->setSection(SA->getName()); |
2696 | } |
2697 | |
2698 | getTargetCodeGenInfo().setTargetAttributes(D, GV: GO, M&: *this); |
2699 | } |
2700 | |
2701 | void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, |
2702 | llvm::Function *F, |
2703 | const CGFunctionInfo &FI) { |
2704 | const Decl *D = GD.getDecl(); |
2705 | SetLLVMFunctionAttributes(GD, Info: FI, F, /*IsThunk=*/false); |
2706 | SetLLVMFunctionAttributesForDefinition(D, F); |
2707 | |
2708 | F->setLinkage(llvm::Function::InternalLinkage); |
2709 | |
2710 | setNonAliasAttributes(GD, GO: F); |
2711 | } |
2712 | |
2713 | static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { |
2714 | // Set linkage and visibility in case we never see a definition. |
2715 | LinkageInfo LV = ND->getLinkageAndVisibility(); |
2716 | // Don't set internal linkage on declarations. |
2717 | // "extern_weak" is overloaded in LLVM; we probably should have |
2718 | // separate linkage types for this. |
2719 | if (isExternallyVisible(LV.getLinkage()) && |
2720 | (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) |
2721 | GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); |
2722 | } |
2723 | |
2724 | void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, |
2725 | llvm::Function *F) { |
2726 | // Only if we are checking indirect calls. |
2727 | if (!LangOpts.Sanitize.has(K: SanitizerKind::CFIICall)) |
2728 | return; |
2729 | |
2730 | // Non-static class methods are handled via vtable or member function pointer |
2731 | // checks elsewhere. |
2732 | if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) |
2733 | return; |
2734 | |
2735 | llvm::Metadata *MD = CreateMetadataIdentifierForType(T: FD->getType()); |
2736 | F->addTypeMetadata(Offset: 0, TypeID: MD); |
2737 | F->addTypeMetadata(Offset: 0, TypeID: CreateMetadataIdentifierGeneralized(T: FD->getType())); |
2738 | |
2739 | // Emit a hash-based bit set entry for cross-DSO calls. |
2740 | if (CodeGenOpts.SanitizeCfiCrossDso) |
2741 | if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) |
2742 | F->addTypeMetadata(Offset: 0, TypeID: llvm::ConstantAsMetadata::get(C: CrossDsoTypeId)); |
2743 | } |
2744 | |
2745 | void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { |
2746 | llvm::LLVMContext &Ctx = F->getContext(); |
2747 | llvm::MDBuilder MDB(Ctx); |
2748 | F->setMetadata(llvm::LLVMContext::MD_kcfi_type, |
2749 | llvm::MDNode::get( |
2750 | Context&: Ctx, MDs: MDB.createConstant(C: CreateKCFITypeId(T: FD->getType())))); |
2751 | } |
2752 | |
2753 | static bool allowKCFIIdentifier(StringRef Name) { |
2754 | // KCFI type identifier constants are only necessary for external assembly |
2755 | // functions, which means it's safe to skip unusual names. Subset of |
2756 | // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). |
2757 | return llvm::all_of(Range&: Name, P: [](const char &C) { |
2758 | return llvm::isAlnum(C) || C == '_' || C == '.'; |
2759 | }); |
2760 | } |
2761 | |
2762 | void CodeGenModule::finalizeKCFITypes() { |
2763 | llvm::Module &M = getModule(); |
2764 | for (auto &F : M.functions()) { |
2765 | // Remove KCFI type metadata from non-address-taken local functions. |
2766 | bool AddressTaken = F.hasAddressTaken(); |
2767 | if (!AddressTaken && F.hasLocalLinkage()) |
2768 | F.eraseMetadata(KindID: llvm::LLVMContext::MD_kcfi_type); |
2769 | |
2770 | // Generate a constant with the expected KCFI type identifier for all |
2771 | // address-taken function declarations to support annotating indirectly |
2772 | // called assembly functions. |
2773 | if (!AddressTaken || !F.isDeclaration()) |
2774 | continue; |
2775 | |
2776 | const llvm::ConstantInt *Type; |
2777 | if (const llvm::MDNode *MD = F.getMetadata(KindID: llvm::LLVMContext::MD_kcfi_type)) |
2778 | Type = llvm::mdconst::extract<llvm::ConstantInt>(MD: MD->getOperand(I: 0)); |
2779 | else |
2780 | continue; |
2781 | |
2782 | StringRef Name = F.getName(); |
2783 | if (!allowKCFIIdentifier(Name)) |
2784 | continue; |
2785 | |
2786 | std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + |
2787 | Name + ", " + Twine(Type->getZExtValue()) + "\n" ) |
2788 | .str(); |
2789 | M.appendModuleInlineAsm(Asm); |
2790 | } |
2791 | } |
2792 | |
2793 | void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, |
2794 | bool IsIncompleteFunction, |
2795 | bool IsThunk) { |
2796 | |
2797 | if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { |
2798 | // If this is an intrinsic function, set the function's attributes |
2799 | // to the intrinsic's attributes. |
2800 | F->setAttributes(llvm::Intrinsic::getAttributes(C&: getLLVMContext(), id: IID)); |
2801 | return; |
2802 | } |
2803 | |
2804 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
2805 | |
2806 | if (!IsIncompleteFunction) |
2807 | SetLLVMFunctionAttributes(GD, Info: getTypes().arrangeGlobalDeclaration(GD), F, |
2808 | IsThunk); |
2809 | |
2810 | // Add the Returned attribute for "this", except for iOS 5 and earlier |
2811 | // where substantial code, including the libstdc++ dylib, was compiled with |
2812 | // GCC and does not actually return "this". |
2813 | if (!IsThunk && getCXXABI().HasThisReturn(GD) && |
2814 | !(getTriple().isiOS() && getTriple().isOSVersionLT(Major: 6))) { |
2815 | assert(!F->arg_empty() && |
2816 | F->arg_begin()->getType() |
2817 | ->canLosslesslyBitCastTo(F->getReturnType()) && |
2818 | "unexpected this return" ); |
2819 | F->addParamAttr(0, llvm::Attribute::Returned); |
2820 | } |
2821 | |
2822 | // Only a few attributes are set on declarations; these may later be |
2823 | // overridden by a definition. |
2824 | |
2825 | setLinkageForGV(F, FD); |
2826 | setGVProperties(GV: F, GD: FD); |
2827 | |
2828 | // Setup target-specific attributes. |
2829 | if (!IsIncompleteFunction && F->isDeclaration()) |
2830 | getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); |
2831 | |
2832 | if (const auto *CSA = FD->getAttr<CodeSegAttr>()) |
2833 | F->setSection(CSA->getName()); |
2834 | else if (const auto *SA = FD->getAttr<SectionAttr>()) |
2835 | F->setSection(SA->getName()); |
2836 | |
2837 | if (const auto *EA = FD->getAttr<ErrorAttr>()) { |
2838 | if (EA->isError()) |
2839 | F->addFnAttr("dontcall-error" , EA->getUserDiagnostic()); |
2840 | else if (EA->isWarning()) |
2841 | F->addFnAttr("dontcall-warn" , EA->getUserDiagnostic()); |
2842 | } |
2843 | |
2844 | // If we plan on emitting this inline builtin, we can't treat it as a builtin. |
2845 | if (FD->isInlineBuiltinDeclaration()) { |
2846 | const FunctionDecl *FDBody; |
2847 | bool HasBody = FD->hasBody(Definition&: FDBody); |
2848 | (void)HasBody; |
2849 | assert(HasBody && "Inline builtin declarations should always have an " |
2850 | "available body!" ); |
2851 | if (shouldEmitFunction(FDBody)) |
2852 | F->addFnAttr(llvm::Attribute::NoBuiltin); |
2853 | } |
2854 | |
2855 | if (FD->isReplaceableGlobalAllocationFunction()) { |
2856 | // A replaceable global allocation function does not act like a builtin by |
2857 | // default, only if it is invoked by a new-expression or delete-expression. |
2858 | F->addFnAttr(llvm::Attribute::NoBuiltin); |
2859 | } |
2860 | |
2861 | if (isa<CXXConstructorDecl>(Val: FD) || isa<CXXDestructorDecl>(Val: FD)) |
2862 | F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
2863 | else if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) |
2864 | if (MD->isVirtual()) |
2865 | F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
2866 | |
2867 | // Don't emit entries for function declarations in the cross-DSO mode. This |
2868 | // is handled with better precision by the receiving DSO. But if jump tables |
2869 | // are non-canonical then we need type metadata in order to produce the local |
2870 | // jump table. |
2871 | if (!CodeGenOpts.SanitizeCfiCrossDso || |
2872 | !CodeGenOpts.SanitizeCfiCanonicalJumpTables) |
2873 | CreateFunctionTypeMetadataForIcall(FD, F); |
2874 | |
2875 | if (LangOpts.Sanitize.has(K: SanitizerKind::KCFI)) |
2876 | setKCFIType(FD, F); |
2877 | |
2878 | if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) |
2879 | getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn: F); |
2880 | |
2881 | if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) |
2882 | F->addFnAttr(Kind: "inline-max-stacksize" , Val: llvm::utostr(X: CodeGenOpts.InlineMaxStackSize)); |
2883 | |
2884 | if (const auto *CB = FD->getAttr<CallbackAttr>()) { |
2885 | // Annotate the callback behavior as metadata: |
2886 | // - The callback callee (as argument number). |
2887 | // - The callback payloads (as argument numbers). |
2888 | llvm::LLVMContext &Ctx = F->getContext(); |
2889 | llvm::MDBuilder MDB(Ctx); |
2890 | |
2891 | // The payload indices are all but the first one in the encoding. The first |
2892 | // identifies the callback callee. |
2893 | int CalleeIdx = *CB->encoding_begin(); |
2894 | ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); |
2895 | F->addMetadata(KindID: llvm::LLVMContext::MD_callback, |
2896 | MD&: *llvm::MDNode::get(Context&: Ctx, MDs: {MDB.createCallbackEncoding( |
2897 | CalleeArgNo: CalleeIdx, Arguments: PayloadIndices, |
2898 | /* VarArgsArePassed */ false)})); |
2899 | } |
2900 | } |
2901 | |
2902 | void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { |
2903 | assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && |
2904 | "Only globals with definition can force usage." ); |
2905 | LLVMUsed.emplace_back(args&: GV); |
2906 | } |
2907 | |
2908 | void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { |
2909 | assert(!GV->isDeclaration() && |
2910 | "Only globals with definition can force usage." ); |
2911 | LLVMCompilerUsed.emplace_back(args&: GV); |
2912 | } |
2913 | |
2914 | void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { |
2915 | assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && |
2916 | "Only globals with definition can force usage." ); |
2917 | if (getTriple().isOSBinFormatELF()) |
2918 | LLVMCompilerUsed.emplace_back(args&: GV); |
2919 | else |
2920 | LLVMUsed.emplace_back(args&: GV); |
2921 | } |
2922 | |
2923 | static void emitUsed(CodeGenModule &CGM, StringRef Name, |
2924 | std::vector<llvm::WeakTrackingVH> &List) { |
2925 | // Don't create llvm.used if there is no need. |
2926 | if (List.empty()) |
2927 | return; |
2928 | |
2929 | // Convert List to what ConstantArray needs. |
2930 | SmallVector<llvm::Constant*, 8> UsedArray; |
2931 | UsedArray.resize(N: List.size()); |
2932 | for (unsigned i = 0, e = List.size(); i != e; ++i) { |
2933 | UsedArray[i] = |
2934 | llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
2935 | C: cast<llvm::Constant>(Val: &*List[i]), Ty: CGM.Int8PtrTy); |
2936 | } |
2937 | |
2938 | if (UsedArray.empty()) |
2939 | return; |
2940 | llvm::ArrayType *ATy = llvm::ArrayType::get(ElementType: CGM.Int8PtrTy, NumElements: UsedArray.size()); |
2941 | |
2942 | auto *GV = new llvm::GlobalVariable( |
2943 | CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, |
2944 | llvm::ConstantArray::get(T: ATy, V: UsedArray), Name); |
2945 | |
2946 | GV->setSection("llvm.metadata" ); |
2947 | } |
2948 | |
2949 | void CodeGenModule::emitLLVMUsed() { |
2950 | emitUsed(CGM&: *this, Name: "llvm.used" , List&: LLVMUsed); |
2951 | emitUsed(CGM&: *this, Name: "llvm.compiler.used" , List&: LLVMCompilerUsed); |
2952 | } |
2953 | |
2954 | void CodeGenModule::AppendLinkerOptions(StringRef Opts) { |
2955 | auto *MDOpts = llvm::MDString::get(Context&: getLLVMContext(), Str: Opts); |
2956 | LinkerOptionsMetadata.push_back(Elt: llvm::MDNode::get(Context&: getLLVMContext(), MDs: MDOpts)); |
2957 | } |
2958 | |
2959 | void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { |
2960 | llvm::SmallString<32> Opt; |
2961 | getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); |
2962 | if (Opt.empty()) |
2963 | return; |
2964 | auto *MDOpts = llvm::MDString::get(Context&: getLLVMContext(), Str: Opt); |
2965 | LinkerOptionsMetadata.push_back(Elt: llvm::MDNode::get(Context&: getLLVMContext(), MDs: MDOpts)); |
2966 | } |
2967 | |
2968 | void CodeGenModule::AddDependentLib(StringRef Lib) { |
2969 | auto &C = getLLVMContext(); |
2970 | if (getTarget().getTriple().isOSBinFormatELF()) { |
2971 | ELFDependentLibraries.push_back( |
2972 | Elt: llvm::MDNode::get(Context&: C, MDs: llvm::MDString::get(Context&: C, Str: Lib))); |
2973 | return; |
2974 | } |
2975 | |
2976 | llvm::SmallString<24> Opt; |
2977 | getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); |
2978 | auto *MDOpts = llvm::MDString::get(Context&: getLLVMContext(), Str: Opt); |
2979 | LinkerOptionsMetadata.push_back(Elt: llvm::MDNode::get(Context&: C, MDs: MDOpts)); |
2980 | } |
2981 | |
2982 | /// Add link options implied by the given module, including modules |
2983 | /// it depends on, using a postorder walk. |
2984 | static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, |
2985 | SmallVectorImpl<llvm::MDNode *> &Metadata, |
2986 | llvm::SmallPtrSet<Module *, 16> &Visited) { |
2987 | // Import this module's parent. |
2988 | if (Mod->Parent && Visited.insert(Ptr: Mod->Parent).second) { |
2989 | addLinkOptionsPostorder(CGM, Mod: Mod->Parent, Metadata, Visited); |
2990 | } |
2991 | |
2992 | // Import this module's dependencies. |
2993 | for (Module *Import : llvm::reverse(C&: Mod->Imports)) { |
2994 | if (Visited.insert(Ptr: Import).second) |
2995 | addLinkOptionsPostorder(CGM, Mod: Import, Metadata, Visited); |
2996 | } |
2997 | |
2998 | // Add linker options to link against the libraries/frameworks |
2999 | // described by this module. |
3000 | llvm::LLVMContext &Context = CGM.getLLVMContext(); |
3001 | bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); |
3002 | |
3003 | // For modules that use export_as for linking, use that module |
3004 | // name instead. |
3005 | if (Mod->UseExportAsModuleLinkName) |
3006 | return; |
3007 | |
3008 | for (const Module::LinkLibrary &LL : llvm::reverse(C&: Mod->LinkLibraries)) { |
3009 | // Link against a framework. Frameworks are currently Darwin only, so we |
3010 | // don't to ask TargetCodeGenInfo for the spelling of the linker option. |
3011 | if (LL.IsFramework) { |
3012 | llvm::Metadata *Args[2] = {llvm::MDString::get(Context, Str: "-framework" ), |
3013 | llvm::MDString::get(Context, Str: LL.Library)}; |
3014 | |
3015 | Metadata.push_back(Elt: llvm::MDNode::get(Context, MDs: Args)); |
3016 | continue; |
3017 | } |
3018 | |
3019 | // Link against a library. |
3020 | if (IsELF) { |
3021 | llvm::Metadata *Args[2] = { |
3022 | llvm::MDString::get(Context, Str: "lib" ), |
3023 | llvm::MDString::get(Context, Str: LL.Library), |
3024 | }; |
3025 | Metadata.push_back(Elt: llvm::MDNode::get(Context, MDs: Args)); |
3026 | } else { |
3027 | llvm::SmallString<24> Opt; |
3028 | CGM.getTargetCodeGenInfo().getDependentLibraryOption(Lib: LL.Library, Opt); |
3029 | auto *OptString = llvm::MDString::get(Context, Str: Opt); |
3030 | Metadata.push_back(Elt: llvm::MDNode::get(Context, MDs: OptString)); |
3031 | } |
3032 | } |
3033 | } |
3034 | |
3035 | void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) { |
3036 | assert(Primary->isNamedModuleUnit() && |
3037 | "We should only emit module initializers for named modules." ); |
3038 | |
3039 | // Emit the initializers in the order that sub-modules appear in the |
3040 | // source, first Global Module Fragments, if present. |
3041 | if (auto GMF = Primary->getGlobalModuleFragment()) { |
3042 | for (Decl *D : getContext().getModuleInitializers(M: GMF)) { |
3043 | if (isa<ImportDecl>(Val: D)) |
3044 | continue; |
3045 | assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?" ); |
3046 | EmitTopLevelDecl(D); |
3047 | } |
3048 | } |
3049 | // Second any associated with the module, itself. |
3050 | for (Decl *D : getContext().getModuleInitializers(M: Primary)) { |
3051 | // Skip import decls, the inits for those are called explicitly. |
3052 | if (isa<ImportDecl>(Val: D)) |
3053 | continue; |
3054 | EmitTopLevelDecl(D); |
3055 | } |
3056 | // Third any associated with the Privat eMOdule Fragment, if present. |
3057 | if (auto PMF = Primary->getPrivateModuleFragment()) { |
3058 | for (Decl *D : getContext().getModuleInitializers(M: PMF)) { |
3059 | // Skip import decls, the inits for those are called explicitly. |
3060 | if (isa<ImportDecl>(Val: D)) |
3061 | continue; |
3062 | assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?" ); |
3063 | EmitTopLevelDecl(D); |
3064 | } |
3065 | } |
3066 | } |
3067 | |
3068 | void CodeGenModule::EmitModuleLinkOptions() { |
3069 | // Collect the set of all of the modules we want to visit to emit link |
3070 | // options, which is essentially the imported modules and all of their |
3071 | // non-explicit child modules. |
3072 | llvm::SetVector<clang::Module *> LinkModules; |
3073 | llvm::SmallPtrSet<clang::Module *, 16> Visited; |
3074 | SmallVector<clang::Module *, 16> Stack; |
3075 | |
3076 | // Seed the stack with imported modules. |
3077 | for (Module *M : ImportedModules) { |
3078 | // Do not add any link flags when an implementation TU of a module imports |
3079 | // a header of that same module. |
3080 | if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && |
3081 | !getLangOpts().isCompilingModule()) |
3082 | continue; |
3083 | if (Visited.insert(Ptr: M).second) |
3084 | Stack.push_back(Elt: M); |
3085 | } |
3086 | |
3087 | // Find all of the modules to import, making a little effort to prune |
3088 | // non-leaf modules. |
3089 | while (!Stack.empty()) { |
3090 | clang::Module *Mod = Stack.pop_back_val(); |
3091 | |
3092 | bool AnyChildren = false; |
3093 | |
3094 | // Visit the submodules of this module. |
3095 | for (const auto &SM : Mod->submodules()) { |
3096 | // Skip explicit children; they need to be explicitly imported to be |
3097 | // linked against. |
3098 | if (SM->IsExplicit) |
3099 | continue; |
3100 | |
3101 | if (Visited.insert(Ptr: SM).second) { |
3102 | Stack.push_back(Elt: SM); |
3103 | AnyChildren = true; |
3104 | } |
3105 | } |
3106 | |
3107 | // We didn't find any children, so add this module to the list of |
3108 | // modules to link against. |
3109 | if (!AnyChildren) { |
3110 | LinkModules.insert(X: Mod); |
3111 | } |
3112 | } |
3113 | |
3114 | // Add link options for all of the imported modules in reverse topological |
3115 | // order. We don't do anything to try to order import link flags with respect |
3116 | // to linker options inserted by things like #pragma comment(). |
3117 | SmallVector<llvm::MDNode *, 16> MetadataArgs; |
3118 | Visited.clear(); |
3119 | for (Module *M : LinkModules) |
3120 | if (Visited.insert(Ptr: M).second) |
3121 | addLinkOptionsPostorder(CGM&: *this, Mod: M, Metadata&: MetadataArgs, Visited); |
3122 | std::reverse(first: MetadataArgs.begin(), last: MetadataArgs.end()); |
3123 | LinkerOptionsMetadata.append(in_start: MetadataArgs.begin(), in_end: MetadataArgs.end()); |
3124 | |
3125 | // Add the linker options metadata flag. |
3126 | auto *NMD = getModule().getOrInsertNamedMetadata(Name: "llvm.linker.options" ); |
3127 | for (auto *MD : LinkerOptionsMetadata) |
3128 | NMD->addOperand(M: MD); |
3129 | } |
3130 | |
3131 | void CodeGenModule::EmitDeferred() { |
3132 | // Emit deferred declare target declarations. |
3133 | if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) |
3134 | getOpenMPRuntime().emitDeferredTargetDecls(); |
3135 | |
3136 | // Emit code for any potentially referenced deferred decls. Since a |
3137 | // previously unused static decl may become used during the generation of code |
3138 | // for a static function, iterate until no changes are made. |
3139 | |
3140 | if (!DeferredVTables.empty()) { |
3141 | EmitDeferredVTables(); |
3142 | |
3143 | // Emitting a vtable doesn't directly cause more vtables to |
3144 | // become deferred, although it can cause functions to be |
3145 | // emitted that then need those vtables. |
3146 | assert(DeferredVTables.empty()); |
3147 | } |
3148 | |
3149 | // Emit CUDA/HIP static device variables referenced by host code only. |
3150 | // Note we should not clear CUDADeviceVarODRUsedByHost since it is still |
3151 | // needed for further handling. |
3152 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) |
3153 | llvm::append_range(C&: DeferredDeclsToEmit, |
3154 | R&: getContext().CUDADeviceVarODRUsedByHost); |
3155 | |
3156 | // Stop if we're out of both deferred vtables and deferred declarations. |
3157 | if (DeferredDeclsToEmit.empty()) |
3158 | return; |
3159 | |
3160 | // Grab the list of decls to emit. If EmitGlobalDefinition schedules more |
3161 | // work, it will not interfere with this. |
3162 | std::vector<GlobalDecl> CurDeclsToEmit; |
3163 | CurDeclsToEmit.swap(x&: DeferredDeclsToEmit); |
3164 | |
3165 | for (GlobalDecl &D : CurDeclsToEmit) { |
3166 | // We should call GetAddrOfGlobal with IsForDefinition set to true in order |
3167 | // to get GlobalValue with exactly the type we need, not something that |
3168 | // might had been created for another decl with the same mangled name but |
3169 | // different type. |
3170 | llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( |
3171 | Val: GetAddrOfGlobal(GD: D, IsForDefinition: ForDefinition)); |
3172 | |
3173 | // In case of different address spaces, we may still get a cast, even with |
3174 | // IsForDefinition equal to true. Query mangled names table to get |
3175 | // GlobalValue. |
3176 | if (!GV) |
3177 | GV = GetGlobalValue(Name: getMangledName(GD: D)); |
3178 | |
3179 | // Make sure GetGlobalValue returned non-null. |
3180 | assert(GV); |
3181 | |
3182 | // Check to see if we've already emitted this. This is necessary |
3183 | // for a couple of reasons: first, decls can end up in the |
3184 | // deferred-decls queue multiple times, and second, decls can end |
3185 | // up with definitions in unusual ways (e.g. by an extern inline |
3186 | // function acquiring a strong function redefinition). Just |
3187 | // ignore these cases. |
3188 | if (!GV->isDeclaration()) |
3189 | continue; |
3190 | |
3191 | // If this is OpenMP, check if it is legal to emit this global normally. |
3192 | if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD: D)) |
3193 | continue; |
3194 | |
3195 | // Otherwise, emit the definition and move on to the next one. |
3196 | EmitGlobalDefinition(D, GV); |
3197 | |
3198 | // If we found out that we need to emit more decls, do that recursively. |
3199 | // This has the advantage that the decls are emitted in a DFS and related |
3200 | // ones are close together, which is convenient for testing. |
3201 | if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { |
3202 | EmitDeferred(); |
3203 | assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); |
3204 | } |
3205 | } |
3206 | } |
3207 | |
3208 | void CodeGenModule::EmitVTablesOpportunistically() { |
3209 | // Try to emit external vtables as available_externally if they have emitted |
3210 | // all inlined virtual functions. It runs after EmitDeferred() and therefore |
3211 | // is not allowed to create new references to things that need to be emitted |
3212 | // lazily. Note that it also uses fact that we eagerly emitting RTTI. |
3213 | |
3214 | assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) |
3215 | && "Only emit opportunistic vtables with optimizations" ); |
3216 | |
3217 | for (const CXXRecordDecl *RD : OpportunisticVTables) { |
3218 | assert(getVTables().isVTableExternal(RD) && |
3219 | "This queue should only contain external vtables" ); |
3220 | if (getCXXABI().canSpeculativelyEmitVTable(RD)) |
3221 | VTables.GenerateClassData(RD); |
3222 | } |
3223 | OpportunisticVTables.clear(); |
3224 | } |
3225 | |
3226 | void CodeGenModule::EmitGlobalAnnotations() { |
3227 | for (const auto& [MangledName, VD] : DeferredAnnotations) { |
3228 | llvm::GlobalValue *GV = GetGlobalValue(Name: MangledName); |
3229 | if (GV) |
3230 | AddGlobalAnnotations(D: VD, GV); |
3231 | } |
3232 | DeferredAnnotations.clear(); |
3233 | |
3234 | if (Annotations.empty()) |
3235 | return; |
3236 | |
3237 | // Create a new global variable for the ConstantStruct in the Module. |
3238 | llvm::Constant *Array = llvm::ConstantArray::get(T: llvm::ArrayType::get( |
3239 | ElementType: Annotations[0]->getType(), NumElements: Annotations.size()), V: Annotations); |
3240 | auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, |
3241 | llvm::GlobalValue::AppendingLinkage, |
3242 | Array, "llvm.global.annotations" ); |
3243 | gv->setSection(AnnotationSection); |
3244 | } |
3245 | |
3246 | llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { |
3247 | llvm::Constant *&AStr = AnnotationStrings[Str]; |
3248 | if (AStr) |
3249 | return AStr; |
3250 | |
3251 | // Not found yet, create a new global. |
3252 | llvm::Constant *s = llvm::ConstantDataArray::getString(Context&: getLLVMContext(), Initializer: Str); |
3253 | auto *gv = new llvm::GlobalVariable( |
3254 | getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s, |
3255 | ".str" , nullptr, llvm::GlobalValue::NotThreadLocal, |
3256 | ConstGlobalsPtrTy->getAddressSpace()); |
3257 | gv->setSection(AnnotationSection); |
3258 | gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
3259 | AStr = gv; |
3260 | return gv; |
3261 | } |
3262 | |
3263 | llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { |
3264 | SourceManager &SM = getContext().getSourceManager(); |
3265 | PresumedLoc PLoc = SM.getPresumedLoc(Loc); |
3266 | if (PLoc.isValid()) |
3267 | return EmitAnnotationString(Str: PLoc.getFilename()); |
3268 | return EmitAnnotationString(Str: SM.getBufferName(Loc)); |
3269 | } |
3270 | |
3271 | llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { |
3272 | SourceManager &SM = getContext().getSourceManager(); |
3273 | PresumedLoc PLoc = SM.getPresumedLoc(Loc: L); |
3274 | unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : |
3275 | SM.getExpansionLineNumber(Loc: L); |
3276 | return llvm::ConstantInt::get(Ty: Int32Ty, V: LineNo); |
3277 | } |
3278 | |
3279 | llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { |
3280 | ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; |
3281 | if (Exprs.empty()) |
3282 | return llvm::ConstantPointerNull::get(T: ConstGlobalsPtrTy); |
3283 | |
3284 | llvm::FoldingSetNodeID ID; |
3285 | for (Expr *E : Exprs) { |
3286 | ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); |
3287 | } |
3288 | llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; |
3289 | if (Lookup) |
3290 | return Lookup; |
3291 | |
3292 | llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; |
3293 | LLVMArgs.reserve(N: Exprs.size()); |
3294 | ConstantEmitter ConstEmiter(*this); |
3295 | llvm::transform(Range&: Exprs, d_first: std::back_inserter(x&: LLVMArgs), F: [&](const Expr *E) { |
3296 | const auto *CE = cast<clang::ConstantExpr>(Val: E); |
3297 | return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), |
3298 | CE->getType()); |
3299 | }); |
3300 | auto *Struct = llvm::ConstantStruct::getAnon(V: LLVMArgs); |
3301 | auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, |
3302 | llvm::GlobalValue::PrivateLinkage, Struct, |
3303 | ".args" ); |
3304 | GV->setSection(AnnotationSection); |
3305 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
3306 | |
3307 | Lookup = GV; |
3308 | return GV; |
3309 | } |
3310 | |
3311 | llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, |
3312 | const AnnotateAttr *AA, |
3313 | SourceLocation L) { |
3314 | // Get the globals for file name, annotation, and the line number. |
3315 | llvm::Constant *AnnoGV = EmitAnnotationString(Str: AA->getAnnotation()), |
3316 | *UnitGV = EmitAnnotationUnit(Loc: L), |
3317 | *LineNoCst = EmitAnnotationLineNo(L), |
3318 | *Args = EmitAnnotationArgs(Attr: AA); |
3319 | |
3320 | llvm::Constant *GVInGlobalsAS = GV; |
3321 | if (GV->getAddressSpace() != |
3322 | getDataLayout().getDefaultGlobalsAddressSpace()) { |
3323 | GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( |
3324 | C: GV, |
3325 | Ty: llvm::PointerType::get( |
3326 | C&: GV->getContext(), AddressSpace: getDataLayout().getDefaultGlobalsAddressSpace())); |
3327 | } |
3328 | |
3329 | // Create the ConstantStruct for the global annotation. |
3330 | llvm::Constant *Fields[] = { |
3331 | GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args, |
3332 | }; |
3333 | return llvm::ConstantStruct::getAnon(V: Fields); |
3334 | } |
3335 | |
3336 | void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, |
3337 | llvm::GlobalValue *GV) { |
3338 | assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute" ); |
3339 | // Get the struct elements for these annotations. |
3340 | for (const auto *I : D->specific_attrs<AnnotateAttr>()) |
3341 | Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); |
3342 | } |
3343 | |
3344 | bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, |
3345 | SourceLocation Loc) const { |
3346 | const auto &NoSanitizeL = getContext().getNoSanitizeList(); |
3347 | // NoSanitize by function name. |
3348 | if (NoSanitizeL.containsFunction(Mask: Kind, FunctionName: Fn->getName())) |
3349 | return true; |
3350 | // NoSanitize by location. Check "mainfile" prefix. |
3351 | auto &SM = Context.getSourceManager(); |
3352 | FileEntryRef MainFile = *SM.getFileEntryRefForID(FID: SM.getMainFileID()); |
3353 | if (NoSanitizeL.containsMainFile(Mask: Kind, FileName: MainFile.getName())) |
3354 | return true; |
3355 | |
3356 | // Check "src" prefix. |
3357 | if (Loc.isValid()) |
3358 | return NoSanitizeL.containsLocation(Mask: Kind, Loc); |
3359 | // If location is unknown, this may be a compiler-generated function. Assume |
3360 | // it's located in the main file. |
3361 | return NoSanitizeL.containsFile(Mask: Kind, FileName: MainFile.getName()); |
3362 | } |
3363 | |
3364 | bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, |
3365 | llvm::GlobalVariable *GV, |
3366 | SourceLocation Loc, QualType Ty, |
3367 | StringRef Category) const { |
3368 | const auto &NoSanitizeL = getContext().getNoSanitizeList(); |
3369 | if (NoSanitizeL.containsGlobal(Mask: Kind, GlobalName: GV->getName(), Category)) |
3370 | return true; |
3371 | auto &SM = Context.getSourceManager(); |
3372 | if (NoSanitizeL.containsMainFile( |
3373 | Mask: Kind, FileName: SM.getFileEntryRefForID(FID: SM.getMainFileID())->getName(), |
3374 | Category)) |
3375 | return true; |
3376 | if (NoSanitizeL.containsLocation(Mask: Kind, Loc, Category)) |
3377 | return true; |
3378 | |
3379 | // Check global type. |
3380 | if (!Ty.isNull()) { |
3381 | // Drill down the array types: if global variable of a fixed type is |
3382 | // not sanitized, we also don't instrument arrays of them. |
3383 | while (auto AT = dyn_cast<ArrayType>(Val: Ty.getTypePtr())) |
3384 | Ty = AT->getElementType(); |
3385 | Ty = Ty.getCanonicalType().getUnqualifiedType(); |
3386 | // Only record types (classes, structs etc.) are ignored. |
3387 | if (Ty->isRecordType()) { |
3388 | std::string TypeStr = Ty.getAsString(Policy: getContext().getPrintingPolicy()); |
3389 | if (NoSanitizeL.containsType(Mask: Kind, MangledTypeName: TypeStr, Category)) |
3390 | return true; |
3391 | } |
3392 | } |
3393 | return false; |
3394 | } |
3395 | |
3396 | bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, |
3397 | StringRef Category) const { |
3398 | const auto &XRayFilter = getContext().getXRayFilter(); |
3399 | using ImbueAttr = XRayFunctionFilter::ImbueAttribute; |
3400 | auto Attr = ImbueAttr::NONE; |
3401 | if (Loc.isValid()) |
3402 | Attr = XRayFilter.shouldImbueLocation(Loc, Category); |
3403 | if (Attr == ImbueAttr::NONE) |
3404 | Attr = XRayFilter.shouldImbueFunction(FunctionName: Fn->getName()); |
3405 | switch (Attr) { |
3406 | case ImbueAttr::NONE: |
3407 | return false; |
3408 | case ImbueAttr::ALWAYS: |
3409 | Fn->addFnAttr(Kind: "function-instrument" , Val: "xray-always" ); |
3410 | break; |
3411 | case ImbueAttr::ALWAYS_ARG1: |
3412 | Fn->addFnAttr(Kind: "function-instrument" , Val: "xray-always" ); |
3413 | Fn->addFnAttr(Kind: "xray-log-args" , Val: "1" ); |
3414 | break; |
3415 | case ImbueAttr::NEVER: |
3416 | Fn->addFnAttr(Kind: "function-instrument" , Val: "xray-never" ); |
3417 | break; |
3418 | } |
3419 | return true; |
3420 | } |
3421 | |
3422 | ProfileList::ExclusionType |
3423 | CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn, |
3424 | SourceLocation Loc) const { |
3425 | const auto &ProfileList = getContext().getProfileList(); |
3426 | // If the profile list is empty, then instrument everything. |
3427 | if (ProfileList.isEmpty()) |
3428 | return ProfileList::Allow; |
3429 | CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); |
3430 | // First, check the function name. |
3431 | if (auto V = ProfileList.isFunctionExcluded(FunctionName: Fn->getName(), Kind)) |
3432 | return *V; |
3433 | // Next, check the source location. |
3434 | if (Loc.isValid()) |
3435 | if (auto V = ProfileList.isLocationExcluded(Loc, Kind)) |
3436 | return *V; |
3437 | // If location is unknown, this may be a compiler-generated function. Assume |
3438 | // it's located in the main file. |
3439 | auto &SM = Context.getSourceManager(); |
3440 | if (auto MainFile = SM.getFileEntryRefForID(FID: SM.getMainFileID())) |
3441 | if (auto V = ProfileList.isFileExcluded(FileName: MainFile->getName(), Kind)) |
3442 | return *V; |
3443 | return ProfileList.getDefault(Kind); |
3444 | } |
3445 | |
3446 | ProfileList::ExclusionType |
3447 | CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, |
3448 | SourceLocation Loc) const { |
3449 | auto V = isFunctionBlockedByProfileList(Fn, Loc); |
3450 | if (V != ProfileList::Allow) |
3451 | return V; |
3452 | |
3453 | auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups; |
3454 | if (NumGroups > 1) { |
3455 | auto Group = llvm::crc32(Data: arrayRefFromStringRef(Input: Fn->getName())) % NumGroups; |
3456 | if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup) |
3457 | return ProfileList::Skip; |
3458 | } |
3459 | return ProfileList::Allow; |
3460 | } |
3461 | |
3462 | bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { |
3463 | // Never defer when EmitAllDecls is specified. |
3464 | if (LangOpts.EmitAllDecls) |
3465 | return true; |
3466 | |
3467 | const auto *VD = dyn_cast<VarDecl>(Val: Global); |
3468 | if (VD && |
3469 | ((CodeGenOpts.KeepPersistentStorageVariables && |
3470 | (VD->getStorageDuration() == SD_Static || |
3471 | VD->getStorageDuration() == SD_Thread)) || |
3472 | (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && |
3473 | VD->getType().isConstQualified()))) |
3474 | return true; |
3475 | |
3476 | return getContext().DeclMustBeEmitted(Global); |
3477 | } |
3478 | |
3479 | bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { |
3480 | // In OpenMP 5.0 variables and function may be marked as |
3481 | // device_type(host/nohost) and we should not emit them eagerly unless we sure |
3482 | // that they must be emitted on the host/device. To be sure we need to have |
3483 | // seen a declare target with an explicit mentioning of the function, we know |
3484 | // we have if the level of the declare target attribute is -1. Note that we |
3485 | // check somewhere else if we should emit this at all. |
3486 | if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { |
3487 | std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = |
3488 | OMPDeclareTargetDeclAttr::getActiveAttr(Global); |
3489 | if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) |
3490 | return false; |
3491 | } |
3492 | |
3493 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: Global)) { |
3494 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
3495 | // Implicit template instantiations may change linkage if they are later |
3496 | // explicitly instantiated, so they should not be emitted eagerly. |
3497 | return false; |
3498 | } |
3499 | if (const auto *VD = dyn_cast<VarDecl>(Val: Global)) { |
3500 | if (Context.getInlineVariableDefinitionKind(VD) == |
3501 | ASTContext::InlineVariableDefinitionKind::WeakUnknown) |
3502 | // A definition of an inline constexpr static data member may change |
3503 | // linkage later if it's redeclared outside the class. |
3504 | return false; |
3505 | if (CXX20ModuleInits && VD->getOwningModule() && |
3506 | !VD->getOwningModule()->isModuleMapModule()) { |
3507 | // For CXX20, module-owned initializers need to be deferred, since it is |
3508 | // not known at this point if they will be run for the current module or |
3509 | // as part of the initializer for an imported one. |
3510 | return false; |
3511 | } |
3512 | } |
3513 | // If OpenMP is enabled and threadprivates must be generated like TLS, delay |
3514 | // codegen for global variables, because they may be marked as threadprivate. |
3515 | if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && |
3516 | getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && |
3517 | !Global->getType().isConstantStorage(getContext(), false, false) && |
3518 | !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) |
3519 | return false; |
3520 | |
3521 | return true; |
3522 | } |
3523 | |
3524 | ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { |
3525 | StringRef Name = getMangledName(GD); |
3526 | |
3527 | // The UUID descriptor should be pointer aligned. |
3528 | CharUnits Alignment = CharUnits::fromQuantity(Quantity: PointerAlignInBytes); |
3529 | |
3530 | // Look for an existing global. |
3531 | if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) |
3532 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3533 | |
3534 | ConstantEmitter Emitter(*this); |
3535 | llvm::Constant *Init; |
3536 | |
3537 | APValue &V = GD->getAsAPValue(); |
3538 | if (!V.isAbsent()) { |
3539 | // If possible, emit the APValue version of the initializer. In particular, |
3540 | // this gets the type of the constant right. |
3541 | Init = Emitter.emitForInitializer( |
3542 | value: GD->getAsAPValue(), destAddrSpace: GD->getType().getAddressSpace(), destType: GD->getType()); |
3543 | } else { |
3544 | // As a fallback, directly construct the constant. |
3545 | // FIXME: This may get padding wrong under esoteric struct layout rules. |
3546 | // MSVC appears to create a complete type 'struct __s_GUID' that it |
3547 | // presumably uses to represent these constants. |
3548 | MSGuidDecl::Parts Parts = GD->getParts(); |
3549 | llvm::Constant *Fields[4] = { |
3550 | llvm::ConstantInt::get(Ty: Int32Ty, V: Parts.Part1), |
3551 | llvm::ConstantInt::get(Ty: Int16Ty, V: Parts.Part2), |
3552 | llvm::ConstantInt::get(Ty: Int16Ty, V: Parts.Part3), |
3553 | llvm::ConstantDataArray::getRaw( |
3554 | Data: StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), NumElements: 8, |
3555 | ElementTy: Int8Ty)}; |
3556 | Init = llvm::ConstantStruct::getAnon(V: Fields); |
3557 | } |
3558 | |
3559 | auto *GV = new llvm::GlobalVariable( |
3560 | getModule(), Init->getType(), |
3561 | /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); |
3562 | if (supportsCOMDAT()) |
3563 | GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName())); |
3564 | setDSOLocal(GV); |
3565 | |
3566 | if (!V.isAbsent()) { |
3567 | Emitter.finalize(global: GV); |
3568 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3569 | } |
3570 | |
3571 | llvm::Type *Ty = getTypes().ConvertTypeForMem(T: GD->getType()); |
3572 | return ConstantAddress(GV, Ty, Alignment); |
3573 | } |
3574 | |
3575 | ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( |
3576 | const UnnamedGlobalConstantDecl *GCD) { |
3577 | CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType()); |
3578 | |
3579 | llvm::GlobalVariable **Entry = nullptr; |
3580 | Entry = &UnnamedGlobalConstantDeclMap[GCD]; |
3581 | if (*Entry) |
3582 | return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); |
3583 | |
3584 | ConstantEmitter Emitter(*this); |
3585 | llvm::Constant *Init; |
3586 | |
3587 | const APValue &V = GCD->getValue(); |
3588 | |
3589 | assert(!V.isAbsent()); |
3590 | Init = Emitter.emitForInitializer(value: V, destAddrSpace: GCD->getType().getAddressSpace(), |
3591 | destType: GCD->getType()); |
3592 | |
3593 | auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), |
3594 | /*isConstant=*/true, |
3595 | llvm::GlobalValue::PrivateLinkage, Init, |
3596 | ".constant" ); |
3597 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
3598 | GV->setAlignment(Alignment.getAsAlign()); |
3599 | |
3600 | Emitter.finalize(global: GV); |
3601 | |
3602 | *Entry = GV; |
3603 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3604 | } |
3605 | |
3606 | ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( |
3607 | const TemplateParamObjectDecl *TPO) { |
3608 | StringRef Name = getMangledName(TPO); |
3609 | CharUnits Alignment = getNaturalTypeAlignment(T: TPO->getType()); |
3610 | |
3611 | if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) |
3612 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3613 | |
3614 | ConstantEmitter Emitter(*this); |
3615 | llvm::Constant *Init = Emitter.emitForInitializer( |
3616 | value: TPO->getValue(), destAddrSpace: TPO->getType().getAddressSpace(), destType: TPO->getType()); |
3617 | |
3618 | if (!Init) { |
3619 | ErrorUnsupported(TPO, "template parameter object" ); |
3620 | return ConstantAddress::invalid(); |
3621 | } |
3622 | |
3623 | llvm::GlobalValue::LinkageTypes Linkage = |
3624 | isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage()) |
3625 | ? llvm::GlobalValue::LinkOnceODRLinkage |
3626 | : llvm::GlobalValue::InternalLinkage; |
3627 | auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), |
3628 | /*isConstant=*/true, Linkage, Init, Name); |
3629 | setGVProperties(GV, TPO); |
3630 | if (supportsCOMDAT()) |
3631 | GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName())); |
3632 | Emitter.finalize(global: GV); |
3633 | |
3634 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
3635 | } |
3636 | |
3637 | ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { |
3638 | const AliasAttr *AA = VD->getAttr<AliasAttr>(); |
3639 | assert(AA && "No alias?" ); |
3640 | |
3641 | CharUnits Alignment = getContext().getDeclAlign(VD); |
3642 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(T: VD->getType()); |
3643 | |
3644 | // See if there is already something with the target's name in the module. |
3645 | llvm::GlobalValue *Entry = GetGlobalValue(Name: AA->getAliasee()); |
3646 | if (Entry) |
3647 | return ConstantAddress(Entry, DeclTy, Alignment); |
3648 | |
3649 | llvm::Constant *Aliasee; |
3650 | if (isa<llvm::FunctionType>(Val: DeclTy)) |
3651 | Aliasee = GetOrCreateLLVMFunction(MangledName: AA->getAliasee(), Ty: DeclTy, |
3652 | D: GlobalDecl(cast<FunctionDecl>(Val: VD)), |
3653 | /*ForVTable=*/false); |
3654 | else |
3655 | Aliasee = GetOrCreateLLVMGlobal(MangledName: AA->getAliasee(), Ty: DeclTy, AddrSpace: LangAS::Default, |
3656 | D: nullptr); |
3657 | |
3658 | auto *F = cast<llvm::GlobalValue>(Val: Aliasee); |
3659 | F->setLinkage(llvm::Function::ExternalWeakLinkage); |
3660 | WeakRefReferences.insert(Ptr: F); |
3661 | |
3662 | return ConstantAddress(Aliasee, DeclTy, Alignment); |
3663 | } |
3664 | |
3665 | template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) { |
3666 | if (!D) |
3667 | return false; |
3668 | if (auto *A = D->getAttr<AttrT>()) |
3669 | return A->isImplicit(); |
3670 | return D->isImplicit(); |
3671 | } |
3672 | |
3673 | void CodeGenModule::EmitGlobal(GlobalDecl GD) { |
3674 | const auto *Global = cast<ValueDecl>(Val: GD.getDecl()); |
3675 | |
3676 | // Weak references don't produce any output by themselves. |
3677 | if (Global->hasAttr<WeakRefAttr>()) |
3678 | return; |
3679 | |
3680 | // If this is an alias definition (which otherwise looks like a declaration) |
3681 | // emit it now. |
3682 | if (Global->hasAttr<AliasAttr>()) |
3683 | return EmitAliasDefinition(GD); |
3684 | |
3685 | // IFunc like an alias whose value is resolved at runtime by calling resolver. |
3686 | if (Global->hasAttr<IFuncAttr>()) |
3687 | return emitIFuncDefinition(GD); |
3688 | |
3689 | // If this is a cpu_dispatch multiversion function, emit the resolver. |
3690 | if (Global->hasAttr<CPUDispatchAttr>()) |
3691 | return emitCPUDispatchDefinition(GD); |
3692 | |
3693 | // If this is CUDA, be selective about which declarations we emit. |
3694 | // Non-constexpr non-lambda implicit host device functions are not emitted |
3695 | // unless they are used on device side. |
3696 | if (LangOpts.CUDA) { |
3697 | if (LangOpts.CUDAIsDevice) { |
3698 | const auto *FD = dyn_cast<FunctionDecl>(Val: Global); |
3699 | if ((!Global->hasAttr<CUDADeviceAttr>() || |
3700 | (LangOpts.OffloadImplicitHostDeviceTemplates && FD && |
3701 | hasImplicitAttr<CUDAHostAttr>(FD) && |
3702 | hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() && |
3703 | !isLambdaCallOperator(FD) && |
3704 | !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) && |
3705 | !Global->hasAttr<CUDAGlobalAttr>() && |
3706 | !Global->hasAttr<CUDAConstantAttr>() && |
3707 | !Global->hasAttr<CUDASharedAttr>() && |
3708 | !Global->getType()->isCUDADeviceBuiltinSurfaceType() && |
3709 | !Global->getType()->isCUDADeviceBuiltinTextureType() && |
3710 | !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) && |
3711 | !Global->hasAttr<CUDAHostAttr>())) |
3712 | return; |
3713 | } else { |
3714 | // We need to emit host-side 'shadows' for all global |
3715 | // device-side variables because the CUDA runtime needs their |
3716 | // size and host-side address in order to provide access to |
3717 | // their device-side incarnations. |
3718 | |
3719 | // So device-only functions are the only things we skip. |
3720 | if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && |
3721 | Global->hasAttr<CUDADeviceAttr>()) |
3722 | return; |
3723 | |
3724 | assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && |
3725 | "Expected Variable or Function" ); |
3726 | } |
3727 | } |
3728 | |
3729 | if (LangOpts.OpenMP) { |
3730 | // If this is OpenMP, check if it is legal to emit this global normally. |
3731 | if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) |
3732 | return; |
3733 | if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: Global)) { |
3734 | if (MustBeEmitted(Global)) |
3735 | EmitOMPDeclareReduction(D: DRD); |
3736 | return; |
3737 | } |
3738 | if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Val: Global)) { |
3739 | if (MustBeEmitted(Global)) |
3740 | EmitOMPDeclareMapper(D: DMD); |
3741 | return; |
3742 | } |
3743 | } |
3744 | |
3745 | // Ignore declarations, they will be emitted on their first use. |
3746 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: Global)) { |
3747 | // Update deferred annotations with the latest declaration if the function |
3748 | // function was already used or defined. |
3749 | if (FD->hasAttr<AnnotateAttr>()) { |
3750 | StringRef MangledName = getMangledName(GD); |
3751 | if (GetGlobalValue(Name: MangledName)) |
3752 | DeferredAnnotations[MangledName] = FD; |
3753 | } |
3754 | |
3755 | // Forward declarations are emitted lazily on first use. |
3756 | if (!FD->doesThisDeclarationHaveABody()) { |
3757 | if (!FD->doesDeclarationForceExternallyVisibleDefinition()) |
3758 | return; |
3759 | |
3760 | StringRef MangledName = getMangledName(GD); |
3761 | |
3762 | // Compute the function info and LLVM type. |
3763 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
3764 | llvm::Type *Ty = getTypes().GetFunctionType(Info: FI); |
3765 | |
3766 | GetOrCreateLLVMFunction(MangledName, Ty, D: GD, /*ForVTable=*/false, |
3767 | /*DontDefer=*/false); |
3768 | return; |
3769 | } |
3770 | } else { |
3771 | const auto *VD = cast<VarDecl>(Val: Global); |
3772 | assert(VD->isFileVarDecl() && "Cannot emit local var decl as global." ); |
3773 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition && |
3774 | !Context.isMSStaticDataMemberInlineDefinition(VD)) { |
3775 | if (LangOpts.OpenMP) { |
3776 | // Emit declaration of the must-be-emitted declare target variable. |
3777 | if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = |
3778 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { |
3779 | |
3780 | // If this variable has external storage and doesn't require special |
3781 | // link handling we defer to its canonical definition. |
3782 | if (VD->hasExternalStorage() && |
3783 | Res != OMPDeclareTargetDeclAttr::MT_Link) |
3784 | return; |
3785 | |
3786 | bool UnifiedMemoryEnabled = |
3787 | getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); |
3788 | if ((*Res == OMPDeclareTargetDeclAttr::MT_To || |
3789 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && |
3790 | !UnifiedMemoryEnabled) { |
3791 | (void)GetAddrOfGlobalVar(D: VD); |
3792 | } else { |
3793 | assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || |
3794 | ((*Res == OMPDeclareTargetDeclAttr::MT_To || |
3795 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && |
3796 | UnifiedMemoryEnabled)) && |
3797 | "Link clause or to clause with unified memory expected." ); |
3798 | (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); |
3799 | } |
3800 | |
3801 | return; |
3802 | } |
3803 | } |
3804 | // If this declaration may have caused an inline variable definition to |
3805 | // change linkage, make sure that it's emitted. |
3806 | if (Context.getInlineVariableDefinitionKind(VD) == |
3807 | ASTContext::InlineVariableDefinitionKind::Strong) |
3808 | GetAddrOfGlobalVar(D: VD); |
3809 | return; |
3810 | } |
3811 | } |
3812 | |
3813 | // Defer code generation to first use when possible, e.g. if this is an inline |
3814 | // function. If the global must always be emitted, do it eagerly if possible |
3815 | // to benefit from cache locality. |
3816 | if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { |
3817 | // Emit the definition if it can't be deferred. |
3818 | EmitGlobalDefinition(D: GD); |
3819 | addEmittedDeferredDecl(GD); |
3820 | return; |
3821 | } |
3822 | |
3823 | // If we're deferring emission of a C++ variable with an |
3824 | // initializer, remember the order in which it appeared in the file. |
3825 | if (getLangOpts().CPlusPlus && isa<VarDecl>(Val: Global) && |
3826 | cast<VarDecl>(Val: Global)->hasInit()) { |
3827 | DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); |
3828 | CXXGlobalInits.push_back(x: nullptr); |
3829 | } |
3830 | |
3831 | StringRef MangledName = getMangledName(GD); |
3832 | if (GetGlobalValue(Name: MangledName) != nullptr) { |
3833 | // The value has already been used and should therefore be emitted. |
3834 | addDeferredDeclToEmit(GD); |
3835 | } else if (MustBeEmitted(Global)) { |
3836 | // The value must be emitted, but cannot be emitted eagerly. |
3837 | assert(!MayBeEmittedEagerly(Global)); |
3838 | addDeferredDeclToEmit(GD); |
3839 | } else { |
3840 | // Otherwise, remember that we saw a deferred decl with this name. The |
3841 | // first use of the mangled name will cause it to move into |
3842 | // DeferredDeclsToEmit. |
3843 | DeferredDecls[MangledName] = GD; |
3844 | } |
3845 | } |
3846 | |
3847 | // Check if T is a class type with a destructor that's not dllimport. |
3848 | static bool HasNonDllImportDtor(QualType T) { |
3849 | if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) |
3850 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl())) |
3851 | if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) |
3852 | return true; |
3853 | |
3854 | return false; |
3855 | } |
3856 | |
3857 | namespace { |
3858 | struct FunctionIsDirectlyRecursive |
3859 | : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { |
3860 | const StringRef Name; |
3861 | const Builtin::Context &BI; |
3862 | FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) |
3863 | : Name(N), BI(C) {} |
3864 | |
3865 | bool VisitCallExpr(const CallExpr *E) { |
3866 | const FunctionDecl *FD = E->getDirectCallee(); |
3867 | if (!FD) |
3868 | return false; |
3869 | AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); |
3870 | if (Attr && Name == Attr->getLabel()) |
3871 | return true; |
3872 | unsigned BuiltinID = FD->getBuiltinID(); |
3873 | if (!BuiltinID || !BI.isLibFunction(ID: BuiltinID)) |
3874 | return false; |
3875 | StringRef BuiltinName = BI.getName(ID: BuiltinID); |
3876 | if (BuiltinName.starts_with(Prefix: "__builtin_" ) && |
3877 | Name == BuiltinName.slice(Start: strlen(s: "__builtin_" ), End: StringRef::npos)) { |
3878 | return true; |
3879 | } |
3880 | return false; |
3881 | } |
3882 | |
3883 | bool VisitStmt(const Stmt *S) { |
3884 | for (const Stmt *Child : S->children()) |
3885 | if (Child && this->Visit(Child)) |
3886 | return true; |
3887 | return false; |
3888 | } |
3889 | }; |
3890 | |
3891 | // Make sure we're not referencing non-imported vars or functions. |
3892 | struct DLLImportFunctionVisitor |
3893 | : public RecursiveASTVisitor<DLLImportFunctionVisitor> { |
3894 | bool SafeToInline = true; |
3895 | |
3896 | bool shouldVisitImplicitCode() const { return true; } |
3897 | |
3898 | bool VisitVarDecl(VarDecl *VD) { |
3899 | if (VD->getTLSKind()) { |
3900 | // A thread-local variable cannot be imported. |
3901 | SafeToInline = false; |
3902 | return SafeToInline; |
3903 | } |
3904 | |
3905 | // A variable definition might imply a destructor call. |
3906 | if (VD->isThisDeclarationADefinition()) |
3907 | SafeToInline = !HasNonDllImportDtor(VD->getType()); |
3908 | |
3909 | return SafeToInline; |
3910 | } |
3911 | |
3912 | bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { |
3913 | if (const auto *D = E->getTemporary()->getDestructor()) |
3914 | SafeToInline = D->hasAttr<DLLImportAttr>(); |
3915 | return SafeToInline; |
3916 | } |
3917 | |
3918 | bool VisitDeclRefExpr(DeclRefExpr *E) { |
3919 | ValueDecl *VD = E->getDecl(); |
3920 | if (isa<FunctionDecl>(VD)) |
3921 | SafeToInline = VD->hasAttr<DLLImportAttr>(); |
3922 | else if (VarDecl *V = dyn_cast<VarDecl>(VD)) |
3923 | SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); |
3924 | return SafeToInline; |
3925 | } |
3926 | |
3927 | bool VisitCXXConstructExpr(CXXConstructExpr *E) { |
3928 | SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); |
3929 | return SafeToInline; |
3930 | } |
3931 | |
3932 | bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { |
3933 | CXXMethodDecl *M = E->getMethodDecl(); |
3934 | if (!M) { |
3935 | // Call through a pointer to member function. This is safe to inline. |
3936 | SafeToInline = true; |
3937 | } else { |
3938 | SafeToInline = M->hasAttr<DLLImportAttr>(); |
3939 | } |
3940 | return SafeToInline; |
3941 | } |
3942 | |
3943 | bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { |
3944 | SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); |
3945 | return SafeToInline; |
3946 | } |
3947 | |
3948 | bool VisitCXXNewExpr(CXXNewExpr *E) { |
3949 | SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); |
3950 | return SafeToInline; |
3951 | } |
3952 | }; |
3953 | } |
3954 | |
3955 | // isTriviallyRecursive - Check if this function calls another |
3956 | // decl that, because of the asm attribute or the other decl being a builtin, |
3957 | // ends up pointing to itself. |
3958 | bool |
3959 | CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { |
3960 | StringRef Name; |
3961 | if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { |
3962 | // asm labels are a special kind of mangling we have to support. |
3963 | AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); |
3964 | if (!Attr) |
3965 | return false; |
3966 | Name = Attr->getLabel(); |
3967 | } else { |
3968 | Name = FD->getName(); |
3969 | } |
3970 | |
3971 | FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); |
3972 | const Stmt *Body = FD->getBody(); |
3973 | return Body ? Walker.Visit(Body) : false; |
3974 | } |
3975 | |
3976 | bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { |
3977 | if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) |
3978 | return true; |
3979 | |
3980 | const auto *F = cast<FunctionDecl>(Val: GD.getDecl()); |
3981 | if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) |
3982 | return false; |
3983 | |
3984 | // We don't import function bodies from other named module units since that |
3985 | // behavior may break ABI compatibility of the current unit. |
3986 | if (const Module *M = F->getOwningModule(); |
3987 | M && M->getTopLevelModule()->isNamedModule() && |
3988 | getContext().getCurrentNamedModule() != M->getTopLevelModule() && |
3989 | !F->hasAttr<AlwaysInlineAttr>()) |
3990 | return false; |
3991 | |
3992 | if (F->hasAttr<NoInlineAttr>()) |
3993 | return false; |
3994 | |
3995 | if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { |
3996 | // Check whether it would be safe to inline this dllimport function. |
3997 | DLLImportFunctionVisitor Visitor; |
3998 | Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); |
3999 | if (!Visitor.SafeToInline) |
4000 | return false; |
4001 | |
4002 | if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(Val: F)) { |
4003 | // Implicit destructor invocations aren't captured in the AST, so the |
4004 | // check above can't see them. Check for them manually here. |
4005 | for (const Decl *Member : Dtor->getParent()->decls()) |
4006 | if (isa<FieldDecl>(Member)) |
4007 | if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) |
4008 | return false; |
4009 | for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) |
4010 | if (HasNonDllImportDtor(B.getType())) |
4011 | return false; |
4012 | } |
4013 | } |
4014 | |
4015 | // Inline builtins declaration must be emitted. They often are fortified |
4016 | // functions. |
4017 | if (F->isInlineBuiltinDeclaration()) |
4018 | return true; |
4019 | |
4020 | // PR9614. Avoid cases where the source code is lying to us. An available |
4021 | // externally function should have an equivalent function somewhere else, |
4022 | // but a function that calls itself through asm label/`__builtin_` trickery is |
4023 | // clearly not equivalent to the real implementation. |
4024 | // This happens in glibc's btowc and in some configure checks. |
4025 | return !isTriviallyRecursive(FD: F); |
4026 | } |
4027 | |
4028 | bool CodeGenModule::shouldOpportunisticallyEmitVTables() { |
4029 | return CodeGenOpts.OptimizationLevel > 0; |
4030 | } |
4031 | |
4032 | void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, |
4033 | llvm::GlobalValue *GV) { |
4034 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
4035 | |
4036 | if (FD->isCPUSpecificMultiVersion()) { |
4037 | auto *Spec = FD->getAttr<CPUSpecificAttr>(); |
4038 | for (unsigned I = 0; I < Spec->cpus_size(); ++I) |
4039 | EmitGlobalFunctionDefinition(GD: GD.getWithMultiVersionIndex(Index: I), GV: nullptr); |
4040 | } else if (FD->isTargetClonesMultiVersion()) { |
4041 | auto *Clone = FD->getAttr<TargetClonesAttr>(); |
4042 | for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) |
4043 | if (Clone->isFirstOfVersion(I)) |
4044 | EmitGlobalFunctionDefinition(GD: GD.getWithMultiVersionIndex(Index: I), GV: nullptr); |
4045 | // Ensure that the resolver function is also emitted. |
4046 | GetOrCreateMultiVersionResolver(GD); |
4047 | } else if (FD->hasAttr<TargetVersionAttr>()) { |
4048 | GetOrCreateMultiVersionResolver(GD); |
4049 | } else |
4050 | EmitGlobalFunctionDefinition(GD, GV); |
4051 | } |
4052 | |
4053 | void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { |
4054 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
4055 | |
4056 | PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), |
4057 | Context.getSourceManager(), |
4058 | "Generating code for declaration" ); |
4059 | |
4060 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
4061 | // At -O0, don't generate IR for functions with available_externally |
4062 | // linkage. |
4063 | if (!shouldEmitFunction(GD)) |
4064 | return; |
4065 | |
4066 | llvm::TimeTraceScope TimeScope("CodeGen Function" , [&]() { |
4067 | std::string Name; |
4068 | llvm::raw_string_ostream OS(Name); |
4069 | FD->getNameForDiagnostic(OS, Policy: getContext().getPrintingPolicy(), |
4070 | /*Qualified=*/true); |
4071 | return Name; |
4072 | }); |
4073 | |
4074 | if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: D)) { |
4075 | // Make sure to emit the definition(s) before we emit the thunks. |
4076 | // This is necessary for the generation of certain thunks. |
4077 | if (isa<CXXConstructorDecl>(Val: Method) || isa<CXXDestructorDecl>(Val: Method)) |
4078 | ABI->emitCXXStructor(GD); |
4079 | else if (FD->isMultiVersion()) |
4080 | EmitMultiVersionFunctionDefinition(GD, GV); |
4081 | else |
4082 | EmitGlobalFunctionDefinition(GD, GV); |
4083 | |
4084 | if (Method->isVirtual()) |
4085 | getVTables().EmitThunks(GD); |
4086 | |
4087 | return; |
4088 | } |
4089 | |
4090 | if (FD->isMultiVersion()) |
4091 | return EmitMultiVersionFunctionDefinition(GD, GV); |
4092 | return EmitGlobalFunctionDefinition(GD, GV); |
4093 | } |
4094 | |
4095 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
4096 | return EmitGlobalVarDefinition(D: VD, IsTentative: !VD->hasDefinition()); |
4097 | |
4098 | llvm_unreachable("Invalid argument to EmitGlobalDefinition()" ); |
4099 | } |
4100 | |
4101 | static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, |
4102 | llvm::Function *NewFn); |
4103 | |
4104 | static unsigned |
4105 | TargetMVPriority(const TargetInfo &TI, |
4106 | const CodeGenFunction::MultiVersionResolverOption &RO) { |
4107 | unsigned Priority = 0; |
4108 | unsigned NumFeatures = 0; |
4109 | for (StringRef Feat : RO.Conditions.Features) { |
4110 | Priority = std::max(a: Priority, b: TI.multiVersionSortPriority(Name: Feat)); |
4111 | NumFeatures++; |
4112 | } |
4113 | |
4114 | if (!RO.Conditions.Architecture.empty()) |
4115 | Priority = std::max( |
4116 | a: Priority, b: TI.multiVersionSortPriority(Name: RO.Conditions.Architecture)); |
4117 | |
4118 | Priority += TI.multiVersionFeatureCost() * NumFeatures; |
4119 | |
4120 | return Priority; |
4121 | } |
4122 | |
4123 | // Multiversion functions should be at most 'WeakODRLinkage' so that a different |
4124 | // TU can forward declare the function without causing problems. Particularly |
4125 | // in the cases of CPUDispatch, this causes issues. This also makes sure we |
4126 | // work with internal linkage functions, so that the same function name can be |
4127 | // used with internal linkage in multiple TUs. |
4128 | llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, |
4129 | GlobalDecl GD) { |
4130 | const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
4131 | if (FD->getFormalLinkage() == Linkage::Internal) |
4132 | return llvm::GlobalValue::InternalLinkage; |
4133 | return llvm::GlobalValue::WeakODRLinkage; |
4134 | } |
4135 | |
4136 | void CodeGenModule::emitMultiVersionFunctions() { |
4137 | std::vector<GlobalDecl> MVFuncsToEmit; |
4138 | MultiVersionFuncs.swap(x&: MVFuncsToEmit); |
4139 | for (GlobalDecl GD : MVFuncsToEmit) { |
4140 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
4141 | assert(FD && "Expected a FunctionDecl" ); |
4142 | |
4143 | SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; |
4144 | if (FD->isTargetMultiVersion()) { |
4145 | getContext().forEachMultiversionedFunctionVersion( |
4146 | FD, Pred: [this, &GD, &Options](const FunctionDecl *CurFD) { |
4147 | GlobalDecl CurGD{ |
4148 | (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; |
4149 | StringRef MangledName = getMangledName(GD: CurGD); |
4150 | llvm::Constant *Func = GetGlobalValue(Name: MangledName); |
4151 | if (!Func) { |
4152 | if (CurFD->isDefined()) { |
4153 | EmitGlobalFunctionDefinition(GD: CurGD, GV: nullptr); |
4154 | Func = GetGlobalValue(Name: MangledName); |
4155 | } else { |
4156 | const CGFunctionInfo &FI = |
4157 | getTypes().arrangeGlobalDeclaration(GD); |
4158 | llvm::FunctionType *Ty = getTypes().GetFunctionType(Info: FI); |
4159 | Func = GetAddrOfFunction(GD: CurGD, Ty, /*ForVTable=*/false, |
4160 | /*DontDefer=*/false, IsForDefinition: ForDefinition); |
4161 | } |
4162 | assert(Func && "This should have just been created" ); |
4163 | } |
4164 | if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) { |
4165 | const auto *TA = CurFD->getAttr<TargetAttr>(); |
4166 | llvm::SmallVector<StringRef, 8> Feats; |
4167 | TA->getAddedFeatures(Feats); |
4168 | Options.emplace_back(cast<llvm::Function>(Val: Func), |
4169 | TA->getArchitecture(), Feats); |
4170 | } else { |
4171 | const auto *TVA = CurFD->getAttr<TargetVersionAttr>(); |
4172 | llvm::SmallVector<StringRef, 8> Feats; |
4173 | TVA->getFeatures(Feats); |
4174 | Options.emplace_back(Args: cast<llvm::Function>(Val: Func), |
4175 | /*Architecture*/ Args: "" , Args&: Feats); |
4176 | } |
4177 | }); |
4178 | } else if (FD->isTargetClonesMultiVersion()) { |
4179 | const auto *TC = FD->getAttr<TargetClonesAttr>(); |
4180 | for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); |
4181 | ++VersionIndex) { |
4182 | if (!TC->isFirstOfVersion(VersionIndex)) |
4183 | continue; |
4184 | GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD), |
4185 | VersionIndex}; |
4186 | StringRef Version = TC->getFeatureStr(VersionIndex); |
4187 | StringRef MangledName = getMangledName(GD: CurGD); |
4188 | llvm::Constant *Func = GetGlobalValue(Name: MangledName); |
4189 | if (!Func) { |
4190 | if (FD->isDefined()) { |
4191 | EmitGlobalFunctionDefinition(GD: CurGD, GV: nullptr); |
4192 | Func = GetGlobalValue(Name: MangledName); |
4193 | } else { |
4194 | const CGFunctionInfo &FI = |
4195 | getTypes().arrangeGlobalDeclaration(GD: CurGD); |
4196 | llvm::FunctionType *Ty = getTypes().GetFunctionType(Info: FI); |
4197 | Func = GetAddrOfFunction(GD: CurGD, Ty, /*ForVTable=*/false, |
4198 | /*DontDefer=*/false, IsForDefinition: ForDefinition); |
4199 | } |
4200 | assert(Func && "This should have just been created" ); |
4201 | } |
4202 | |
4203 | StringRef Architecture; |
4204 | llvm::SmallVector<StringRef, 1> Feature; |
4205 | |
4206 | if (getTarget().getTriple().isAArch64()) { |
4207 | if (Version != "default" ) { |
4208 | llvm::SmallVector<StringRef, 8> VerFeats; |
4209 | Version.split(A&: VerFeats, Separator: "+" ); |
4210 | for (auto &CurFeat : VerFeats) |
4211 | Feature.push_back(Elt: CurFeat.trim()); |
4212 | } |
4213 | } else { |
4214 | if (Version.starts_with(Prefix: "arch=" )) |
4215 | Architecture = Version.drop_front(N: sizeof("arch=" ) - 1); |
4216 | else if (Version != "default" ) |
4217 | Feature.push_back(Elt: Version); |
4218 | } |
4219 | |
4220 | Options.emplace_back(Args: cast<llvm::Function>(Val: Func), Args&: Architecture, Args&: Feature); |
4221 | } |
4222 | } else { |
4223 | assert(0 && "Expected a target or target_clones multiversion function" ); |
4224 | continue; |
4225 | } |
4226 | |
4227 | llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); |
4228 | if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(Val: ResolverConstant)) { |
4229 | ResolverConstant = IFunc->getResolver(); |
4230 | if (FD->isTargetClonesMultiVersion() || |
4231 | FD->isTargetVersionMultiVersion()) { |
4232 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
4233 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(Info: FI); |
4234 | std::string MangledName = getMangledNameImpl( |
4235 | *this, GD, FD, /*OmitMultiVersionMangling=*/true); |
4236 | // In prior versions of Clang, the mangling for ifuncs incorrectly |
4237 | // included an .ifunc suffix. This alias is generated for backward |
4238 | // compatibility. It is deprecated, and may be removed in the future. |
4239 | auto *Alias = llvm::GlobalAlias::create( |
4240 | Ty: DeclTy, AddressSpace: 0, Linkage: getMultiversionLinkage(CGM&: *this, GD), |
4241 | Name: MangledName + ".ifunc" , Aliasee: IFunc, Parent: &getModule()); |
4242 | SetCommonAttributes(GD: FD, GV: Alias); |
4243 | } |
4244 | } |
4245 | llvm::Function *ResolverFunc = cast<llvm::Function>(Val: ResolverConstant); |
4246 | |
4247 | ResolverFunc->setLinkage(getMultiversionLinkage(CGM&: *this, GD)); |
4248 | |
4249 | if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT()) |
4250 | ResolverFunc->setComdat( |
4251 | getModule().getOrInsertComdat(Name: ResolverFunc->getName())); |
4252 | |
4253 | const TargetInfo &TI = getTarget(); |
4254 | llvm::stable_sort( |
4255 | Range&: Options, C: [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, |
4256 | const CodeGenFunction::MultiVersionResolverOption &RHS) { |
4257 | return TargetMVPriority(TI, RO: LHS) > TargetMVPriority(TI, RO: RHS); |
4258 | }); |
4259 | CodeGenFunction CGF(*this); |
4260 | CGF.EmitMultiVersionResolver(Resolver: ResolverFunc, Options); |
4261 | } |
4262 | |
4263 | // Ensure that any additions to the deferred decls list caused by emitting a |
4264 | // variant are emitted. This can happen when the variant itself is inline and |
4265 | // calls a function without linkage. |
4266 | if (!MVFuncsToEmit.empty()) |
4267 | EmitDeferred(); |
4268 | |
4269 | // Ensure that any additions to the multiversion funcs list from either the |
4270 | // deferred decls or the multiversion functions themselves are emitted. |
4271 | if (!MultiVersionFuncs.empty()) |
4272 | emitMultiVersionFunctions(); |
4273 | } |
4274 | |
4275 | void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { |
4276 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
4277 | assert(FD && "Not a FunctionDecl?" ); |
4278 | assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?" ); |
4279 | const auto *DD = FD->getAttr<CPUDispatchAttr>(); |
4280 | assert(DD && "Not a cpu_dispatch Function?" ); |
4281 | |
4282 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
4283 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(Info: FI); |
4284 | |
4285 | StringRef ResolverName = getMangledName(GD); |
4286 | UpdateMultiVersionNames(GD, FD, CurName&: ResolverName); |
4287 | |
4288 | llvm::Type *ResolverType; |
4289 | GlobalDecl ResolverGD; |
4290 | if (getTarget().supportsIFunc()) { |
4291 | ResolverType = llvm::FunctionType::get( |
4292 | llvm::PointerType::get(DeclTy, |
4293 | getTypes().getTargetAddressSpace(T: FD->getType())), |
4294 | false); |
4295 | } |
4296 | else { |
4297 | ResolverType = DeclTy; |
4298 | ResolverGD = GD; |
4299 | } |
4300 | |
4301 | auto *ResolverFunc = cast<llvm::Function>(Val: GetOrCreateLLVMFunction( |
4302 | MangledName: ResolverName, Ty: ResolverType, D: ResolverGD, /*ForVTable=*/false)); |
4303 | ResolverFunc->setLinkage(getMultiversionLinkage(CGM&: *this, GD)); |
4304 | if (supportsCOMDAT()) |
4305 | ResolverFunc->setComdat( |
4306 | getModule().getOrInsertComdat(Name: ResolverFunc->getName())); |
4307 | |
4308 | SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; |
4309 | const TargetInfo &Target = getTarget(); |
4310 | unsigned Index = 0; |
4311 | for (const IdentifierInfo *II : DD->cpus()) { |
4312 | // Get the name of the target function so we can look it up/create it. |
4313 | std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + |
4314 | getCPUSpecificMangling(*this, II->getName()); |
4315 | |
4316 | llvm::Constant *Func = GetGlobalValue(MangledName); |
4317 | |
4318 | if (!Func) { |
4319 | GlobalDecl ExistingDecl = Manglings.lookup(MangledName); |
4320 | if (ExistingDecl.getDecl() && |
4321 | ExistingDecl.getDecl()->getAsFunction()->isDefined()) { |
4322 | EmitGlobalFunctionDefinition(ExistingDecl, nullptr); |
4323 | Func = GetGlobalValue(MangledName); |
4324 | } else { |
4325 | if (!ExistingDecl.getDecl()) |
4326 | ExistingDecl = GD.getWithMultiVersionIndex(Index); |
4327 | |
4328 | Func = GetOrCreateLLVMFunction( |
4329 | MangledName, DeclTy, ExistingDecl, |
4330 | /*ForVTable=*/false, /*DontDefer=*/true, |
4331 | /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); |
4332 | } |
4333 | } |
4334 | |
4335 | llvm::SmallVector<StringRef, 32> Features; |
4336 | Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); |
4337 | llvm::transform(Features, Features.begin(), |
4338 | [](StringRef Str) { return Str.substr(1); }); |
4339 | llvm::erase_if(Features, [&Target](StringRef Feat) { |
4340 | return !Target.validateCpuSupports(Feat); |
4341 | }); |
4342 | Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); |
4343 | ++Index; |
4344 | } |
4345 | |
4346 | llvm::stable_sort( |
4347 | Range&: Options, C: [](const CodeGenFunction::MultiVersionResolverOption &LHS, |
4348 | const CodeGenFunction::MultiVersionResolverOption &RHS) { |
4349 | return llvm::X86::getCpuSupportsMask(FeatureStrs: LHS.Conditions.Features) > |
4350 | llvm::X86::getCpuSupportsMask(FeatureStrs: RHS.Conditions.Features); |
4351 | }); |
4352 | |
4353 | // If the list contains multiple 'default' versions, such as when it contains |
4354 | // 'pentium' and 'generic', don't emit the call to the generic one (since we |
4355 | // always run on at least a 'pentium'). We do this by deleting the 'least |
4356 | // advanced' (read, lowest mangling letter). |
4357 | while (Options.size() > 1 && |
4358 | llvm::all_of(Range: llvm::X86::getCpuSupportsMask( |
4359 | FeatureStrs: (Options.end() - 2)->Conditions.Features), |
4360 | P: [](auto X) { return X == 0; })) { |
4361 | StringRef LHSName = (Options.end() - 2)->Function->getName(); |
4362 | StringRef RHSName = (Options.end() - 1)->Function->getName(); |
4363 | if (LHSName.compare(RHS: RHSName) < 0) |
4364 | Options.erase(CI: Options.end() - 2); |
4365 | else |
4366 | Options.erase(CI: Options.end() - 1); |
4367 | } |
4368 | |
4369 | CodeGenFunction CGF(*this); |
4370 | CGF.EmitMultiVersionResolver(Resolver: ResolverFunc, Options); |
4371 | |
4372 | if (getTarget().supportsIFunc()) { |
4373 | llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(CGM&: *this, GD); |
4374 | auto *IFunc = cast<llvm::GlobalValue>(Val: GetOrCreateMultiVersionResolver(GD)); |
4375 | |
4376 | // Fix up function declarations that were created for cpu_specific before |
4377 | // cpu_dispatch was known |
4378 | if (!isa<llvm::GlobalIFunc>(Val: IFunc)) { |
4379 | assert(cast<llvm::Function>(IFunc)->isDeclaration()); |
4380 | auto *GI = llvm::GlobalIFunc::create(Ty: DeclTy, AddressSpace: 0, Linkage, Name: "" , Resolver: ResolverFunc, |
4381 | Parent: &getModule()); |
4382 | GI->takeName(V: IFunc); |
4383 | IFunc->replaceAllUsesWith(V: GI); |
4384 | IFunc->eraseFromParent(); |
4385 | IFunc = GI; |
4386 | } |
4387 | |
4388 | std::string AliasName = getMangledNameImpl( |
4389 | *this, GD, FD, /*OmitMultiVersionMangling=*/true); |
4390 | llvm::Constant *AliasFunc = GetGlobalValue(Name: AliasName); |
4391 | if (!AliasFunc) { |
4392 | auto *GA = llvm::GlobalAlias::create(Ty: DeclTy, AddressSpace: 0, Linkage, Name: AliasName, Aliasee: IFunc, |
4393 | Parent: &getModule()); |
4394 | SetCommonAttributes(GD, GV: GA); |
4395 | } |
4396 | } |
4397 | } |
4398 | |
4399 | /// If a dispatcher for the specified mangled name is not in the module, create |
4400 | /// and return an llvm Function with the specified type. |
4401 | llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { |
4402 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
4403 | assert(FD && "Not a FunctionDecl?" ); |
4404 | |
4405 | std::string MangledName = |
4406 | getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); |
4407 | |
4408 | // Holds the name of the resolver, in ifunc mode this is the ifunc (which has |
4409 | // a separate resolver). |
4410 | std::string ResolverName = MangledName; |
4411 | if (getTarget().supportsIFunc()) { |
4412 | switch (FD->getMultiVersionKind()) { |
4413 | case MultiVersionKind::None: |
4414 | llvm_unreachable("unexpected MultiVersionKind::None for resolver" ); |
4415 | case MultiVersionKind::Target: |
4416 | case MultiVersionKind::CPUSpecific: |
4417 | case MultiVersionKind::CPUDispatch: |
4418 | ResolverName += ".ifunc" ; |
4419 | break; |
4420 | case MultiVersionKind::TargetClones: |
4421 | case MultiVersionKind::TargetVersion: |
4422 | break; |
4423 | } |
4424 | } else if (FD->isTargetMultiVersion()) { |
4425 | ResolverName += ".resolver" ; |
4426 | } |
4427 | |
4428 | // If the resolver has already been created, just return it. |
4429 | if (llvm::GlobalValue *ResolverGV = GetGlobalValue(Name: ResolverName)) |
4430 | return ResolverGV; |
4431 | |
4432 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
4433 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(Info: FI); |
4434 | |
4435 | // The resolver needs to be created. For target and target_clones, defer |
4436 | // creation until the end of the TU. |
4437 | if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) |
4438 | MultiVersionFuncs.push_back(x: GD); |
4439 | |
4440 | // For cpu_specific, don't create an ifunc yet because we don't know if the |
4441 | // cpu_dispatch will be emitted in this translation unit. |
4442 | if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) { |
4443 | llvm::Type *ResolverType = llvm::FunctionType::get( |
4444 | llvm::PointerType::get(DeclTy, |
4445 | getTypes().getTargetAddressSpace(T: FD->getType())), |
4446 | false); |
4447 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
4448 | MangledName: MangledName + ".resolver" , Ty: ResolverType, D: GlobalDecl{}, |
4449 | /*ForVTable=*/false); |
4450 | llvm::GlobalIFunc *GIF = |
4451 | llvm::GlobalIFunc::create(Ty: DeclTy, AddressSpace: 0, Linkage: getMultiversionLinkage(CGM&: *this, GD), |
4452 | Name: "" , Resolver, Parent: &getModule()); |
4453 | GIF->setName(ResolverName); |
4454 | SetCommonAttributes(GD: FD, GV: GIF); |
4455 | |
4456 | return GIF; |
4457 | } |
4458 | |
4459 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
4460 | MangledName: ResolverName, Ty: DeclTy, D: GlobalDecl{}, /*ForVTable=*/false); |
4461 | assert(isa<llvm::GlobalValue>(Resolver) && |
4462 | "Resolver should be created for the first time" ); |
4463 | SetCommonAttributes(GD: FD, GV: cast<llvm::GlobalValue>(Val: Resolver)); |
4464 | return Resolver; |
4465 | } |
4466 | |
4467 | /// GetOrCreateLLVMFunction - If the specified mangled name is not in the |
4468 | /// module, create and return an llvm Function with the specified type. If there |
4469 | /// is something in the module with the specified name, return it potentially |
4470 | /// bitcasted to the right type. |
4471 | /// |
4472 | /// If D is non-null, it specifies a decl that correspond to this. This is used |
4473 | /// to set the attributes on the function when it is first created. |
4474 | llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( |
4475 | StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, |
4476 | bool DontDefer, bool IsThunk, llvm::AttributeList , |
4477 | ForDefinition_t IsForDefinition) { |
4478 | const Decl *D = GD.getDecl(); |
4479 | |
4480 | // Any attempts to use a MultiVersion function should result in retrieving |
4481 | // the iFunc instead. Name Mangling will handle the rest of the changes. |
4482 | if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(Val: D)) { |
4483 | // For the device mark the function as one that should be emitted. |
4484 | if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime && |
4485 | !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && |
4486 | !DontDefer && !IsForDefinition) { |
4487 | if (const FunctionDecl *FDDef = FD->getDefinition()) { |
4488 | GlobalDecl GDDef; |
4489 | if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: FDDef)) |
4490 | GDDef = GlobalDecl(CD, GD.getCtorType()); |
4491 | else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: FDDef)) |
4492 | GDDef = GlobalDecl(DD, GD.getDtorType()); |
4493 | else |
4494 | GDDef = GlobalDecl(FDDef); |
4495 | EmitGlobal(GD: GDDef); |
4496 | } |
4497 | } |
4498 | |
4499 | if (FD->isMultiVersion()) { |
4500 | UpdateMultiVersionNames(GD, FD, CurName&: MangledName); |
4501 | if (!IsForDefinition) |
4502 | return GetOrCreateMultiVersionResolver(GD); |
4503 | } |
4504 | } |
4505 | |
4506 | // Lookup the entry, lazily creating it if necessary. |
4507 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
4508 | if (Entry) { |
4509 | if (WeakRefReferences.erase(Ptr: Entry)) { |
4510 | const FunctionDecl *FD = cast_or_null<FunctionDecl>(Val: D); |
4511 | if (FD && !FD->hasAttr<WeakAttr>()) |
4512 | Entry->setLinkage(llvm::Function::ExternalLinkage); |
4513 | } |
4514 | |
4515 | // Handle dropped DLL attributes. |
4516 | if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && |
4517 | !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { |
4518 | Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
4519 | setDSOLocal(Entry); |
4520 | } |
4521 | |
4522 | // If there are two attempts to define the same mangled name, issue an |
4523 | // error. |
4524 | if (IsForDefinition && !Entry->isDeclaration()) { |
4525 | GlobalDecl OtherGD; |
4526 | // Check that GD is not yet in DiagnosedConflictingDefinitions is required |
4527 | // to make sure that we issue an error only once. |
4528 | if (lookupRepresentativeDecl(MangledName, Result&: OtherGD) && |
4529 | (GD.getCanonicalDecl().getDecl() != |
4530 | OtherGD.getCanonicalDecl().getDecl()) && |
4531 | DiagnosedConflictingDefinitions.insert(V: GD).second) { |
4532 | getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) |
4533 | << MangledName; |
4534 | getDiags().Report(OtherGD.getDecl()->getLocation(), |
4535 | diag::note_previous_definition); |
4536 | } |
4537 | } |
4538 | |
4539 | if ((isa<llvm::Function>(Val: Entry) || isa<llvm::GlobalAlias>(Val: Entry)) && |
4540 | (Entry->getValueType() == Ty)) { |
4541 | return Entry; |
4542 | } |
4543 | |
4544 | // Make sure the result is of the correct type. |
4545 | // (If function is requested for a definition, we always need to create a new |
4546 | // function, not just return a bitcast.) |
4547 | if (!IsForDefinition) |
4548 | return Entry; |
4549 | } |
4550 | |
4551 | // This function doesn't have a complete type (for example, the return |
4552 | // type is an incomplete struct). Use a fake type instead, and make |
4553 | // sure not to try to set attributes. |
4554 | bool IsIncompleteFunction = false; |
4555 | |
4556 | llvm::FunctionType *FTy; |
4557 | if (isa<llvm::FunctionType>(Val: Ty)) { |
4558 | FTy = cast<llvm::FunctionType>(Val: Ty); |
4559 | } else { |
4560 | FTy = llvm::FunctionType::get(Result: VoidTy, isVarArg: false); |
4561 | IsIncompleteFunction = true; |
4562 | } |
4563 | |
4564 | llvm::Function *F = |
4565 | llvm::Function::Create(Ty: FTy, Linkage: llvm::Function::ExternalLinkage, |
4566 | N: Entry ? StringRef() : MangledName, M: &getModule()); |
4567 | |
4568 | // Store the declaration associated with this function so it is potentially |
4569 | // updated by further declarations or definitions and emitted at the end. |
4570 | if (D && D->hasAttr<AnnotateAttr>()) |
4571 | DeferredAnnotations[MangledName] = cast<ValueDecl>(Val: D); |
4572 | |
4573 | // If we already created a function with the same mangled name (but different |
4574 | // type) before, take its name and add it to the list of functions to be |
4575 | // replaced with F at the end of CodeGen. |
4576 | // |
4577 | // This happens if there is a prototype for a function (e.g. "int f()") and |
4578 | // then a definition of a different type (e.g. "int f(int x)"). |
4579 | if (Entry) { |
4580 | F->takeName(V: Entry); |
4581 | |
4582 | // This might be an implementation of a function without a prototype, in |
4583 | // which case, try to do special replacement of calls which match the new |
4584 | // prototype. The really key thing here is that we also potentially drop |
4585 | // arguments from the call site so as to make a direct call, which makes the |
4586 | // inliner happier and suppresses a number of optimizer warnings (!) about |
4587 | // dropping arguments. |
4588 | if (!Entry->use_empty()) { |
4589 | ReplaceUsesOfNonProtoTypeWithRealFunction(Old: Entry, NewFn: F); |
4590 | Entry->removeDeadConstantUsers(); |
4591 | } |
4592 | |
4593 | addGlobalValReplacement(GV: Entry, C: F); |
4594 | } |
4595 | |
4596 | assert(F->getName() == MangledName && "name was uniqued!" ); |
4597 | if (D) |
4598 | SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); |
4599 | if (ExtraAttrs.hasFnAttrs()) { |
4600 | llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); |
4601 | F->addFnAttrs(Attrs: B); |
4602 | } |
4603 | |
4604 | if (!DontDefer) { |
4605 | // All MSVC dtors other than the base dtor are linkonce_odr and delegate to |
4606 | // each other bottoming out with the base dtor. Therefore we emit non-base |
4607 | // dtors on usage, even if there is no dtor definition in the TU. |
4608 | if (isa_and_nonnull<CXXDestructorDecl>(Val: D) && |
4609 | getCXXABI().useThunkForDtorVariant(Dtor: cast<CXXDestructorDecl>(Val: D), |
4610 | DT: GD.getDtorType())) |
4611 | addDeferredDeclToEmit(GD); |
4612 | |
4613 | // This is the first use or definition of a mangled name. If there is a |
4614 | // deferred decl with this name, remember that we need to emit it at the end |
4615 | // of the file. |
4616 | auto DDI = DeferredDecls.find(Val: MangledName); |
4617 | if (DDI != DeferredDecls.end()) { |
4618 | // Move the potentially referenced deferred decl to the |
4619 | // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we |
4620 | // don't need it anymore). |
4621 | addDeferredDeclToEmit(GD: DDI->second); |
4622 | DeferredDecls.erase(I: DDI); |
4623 | |
4624 | // Otherwise, there are cases we have to worry about where we're |
4625 | // using a declaration for which we must emit a definition but where |
4626 | // we might not find a top-level definition: |
4627 | // - member functions defined inline in their classes |
4628 | // - friend functions defined inline in some class |
4629 | // - special member functions with implicit definitions |
4630 | // If we ever change our AST traversal to walk into class methods, |
4631 | // this will be unnecessary. |
4632 | // |
4633 | // We also don't emit a definition for a function if it's going to be an |
4634 | // entry in a vtable, unless it's already marked as used. |
4635 | } else if (getLangOpts().CPlusPlus && D) { |
4636 | // Look for a declaration that's lexically in a record. |
4637 | for (const auto *FD = cast<FunctionDecl>(Val: D)->getMostRecentDecl(); FD; |
4638 | FD = FD->getPreviousDecl()) { |
4639 | if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { |
4640 | if (FD->doesThisDeclarationHaveABody()) { |
4641 | addDeferredDeclToEmit(GD: GD.getWithDecl(D: FD)); |
4642 | break; |
4643 | } |
4644 | } |
4645 | } |
4646 | } |
4647 | } |
4648 | |
4649 | // Make sure the result is of the requested type. |
4650 | if (!IsIncompleteFunction) { |
4651 | assert(F->getFunctionType() == Ty); |
4652 | return F; |
4653 | } |
4654 | |
4655 | return F; |
4656 | } |
4657 | |
4658 | /// GetAddrOfFunction - Return the address of the given function. If Ty is |
4659 | /// non-null, then this function will use the specified type if it has to |
4660 | /// create it (this occurs when we see a definition of the function). |
4661 | llvm::Constant * |
4662 | CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable, |
4663 | bool DontDefer, |
4664 | ForDefinition_t IsForDefinition) { |
4665 | // If there was no specific requested type, just convert it now. |
4666 | if (!Ty) { |
4667 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
4668 | Ty = getTypes().ConvertType(T: FD->getType()); |
4669 | } |
4670 | |
4671 | // Devirtualized destructor calls may come through here instead of via |
4672 | // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead |
4673 | // of the complete destructor when necessary. |
4674 | if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: GD.getDecl())) { |
4675 | if (getTarget().getCXXABI().isMicrosoft() && |
4676 | GD.getDtorType() == Dtor_Complete && |
4677 | DD->getParent()->getNumVBases() == 0) |
4678 | GD = GlobalDecl(DD, Dtor_Base); |
4679 | } |
4680 | |
4681 | StringRef MangledName = getMangledName(GD); |
4682 | auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, |
4683 | /*IsThunk=*/false, ExtraAttrs: llvm::AttributeList(), |
4684 | IsForDefinition); |
4685 | // Returns kernel handle for HIP kernel stub function. |
4686 | if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && |
4687 | cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { |
4688 | auto *Handle = getCUDARuntime().getKernelHandle( |
4689 | Stub: cast<llvm::Function>(Val: F->stripPointerCasts()), GD); |
4690 | if (IsForDefinition) |
4691 | return F; |
4692 | return Handle; |
4693 | } |
4694 | return F; |
4695 | } |
4696 | |
4697 | llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { |
4698 | llvm::GlobalValue *F = |
4699 | cast<llvm::GlobalValue>(Val: GetAddrOfFunction(Decl)->stripPointerCasts()); |
4700 | |
4701 | return llvm::NoCFIValue::get(GV: F); |
4702 | } |
4703 | |
4704 | static const FunctionDecl * |
4705 | GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { |
4706 | TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); |
4707 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(D: TUDecl); |
4708 | |
4709 | IdentifierInfo &CII = C.Idents.get(Name); |
4710 | for (const auto *Result : DC->lookup(Name: &CII)) |
4711 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: Result)) |
4712 | return FD; |
4713 | |
4714 | if (!C.getLangOpts().CPlusPlus) |
4715 | return nullptr; |
4716 | |
4717 | // Demangle the premangled name from getTerminateFn() |
4718 | IdentifierInfo &CXXII = |
4719 | (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ" ) |
4720 | ? C.Idents.get(Name: "terminate" ) |
4721 | : C.Idents.get(Name); |
4722 | |
4723 | for (const auto &N : {"__cxxabiv1" , "std" }) { |
4724 | IdentifierInfo &NS = C.Idents.get(Name: N); |
4725 | for (const auto *Result : DC->lookup(Name: &NS)) { |
4726 | const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: Result); |
4727 | if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) |
4728 | for (const auto *Result : LSD->lookup(&NS)) |
4729 | if ((ND = dyn_cast<NamespaceDecl>(Result))) |
4730 | break; |
4731 | |
4732 | if (ND) |
4733 | for (const auto *Result : ND->lookup(&CXXII)) |
4734 | if (const auto *FD = dyn_cast<FunctionDecl>(Result)) |
4735 | return FD; |
4736 | } |
4737 | } |
4738 | |
4739 | return nullptr; |
4740 | } |
4741 | |
4742 | /// CreateRuntimeFunction - Create a new runtime function with the specified |
4743 | /// type and name. |
4744 | llvm::FunctionCallee |
4745 | CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, |
4746 | llvm::AttributeList , bool Local, |
4747 | bool AssumeConvergent) { |
4748 | if (AssumeConvergent) { |
4749 | ExtraAttrs = |
4750 | ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); |
4751 | } |
4752 | |
4753 | llvm::Constant *C = |
4754 | GetOrCreateLLVMFunction(MangledName: Name, Ty: FTy, GD: GlobalDecl(), /*ForVTable=*/false, |
4755 | /*DontDefer=*/false, /*IsThunk=*/false, |
4756 | ExtraAttrs); |
4757 | |
4758 | if (auto *F = dyn_cast<llvm::Function>(Val: C)) { |
4759 | if (F->empty()) { |
4760 | F->setCallingConv(getRuntimeCC()); |
4761 | |
4762 | // In Windows Itanium environments, try to mark runtime functions |
4763 | // dllimport. For Mingw and MSVC, don't. We don't really know if the user |
4764 | // will link their standard library statically or dynamically. Marking |
4765 | // functions imported when they are not imported can cause linker errors |
4766 | // and warnings. |
4767 | if (!Local && getTriple().isWindowsItaniumEnvironment() && |
4768 | !getCodeGenOpts().LTOVisibilityPublicStd) { |
4769 | const FunctionDecl *FD = GetRuntimeFunctionDecl(C&: Context, Name); |
4770 | if (!FD || FD->hasAttr<DLLImportAttr>()) { |
4771 | F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); |
4772 | F->setLinkage(llvm::GlobalValue::ExternalLinkage); |
4773 | } |
4774 | } |
4775 | setDSOLocal(F); |
4776 | } |
4777 | } |
4778 | |
4779 | return {FTy, C}; |
4780 | } |
4781 | |
4782 | /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, |
4783 | /// create and return an llvm GlobalVariable with the specified type and address |
4784 | /// space. If there is something in the module with the specified name, return |
4785 | /// it potentially bitcasted to the right type. |
4786 | /// |
4787 | /// If D is non-null, it specifies a decl that correspond to this. This is used |
4788 | /// to set the attributes on the global when it is first created. |
4789 | /// |
4790 | /// If IsForDefinition is true, it is guaranteed that an actual global with |
4791 | /// type Ty will be returned, not conversion of a variable with the same |
4792 | /// mangled name but some other type. |
4793 | llvm::Constant * |
4794 | CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, |
4795 | LangAS AddrSpace, const VarDecl *D, |
4796 | ForDefinition_t IsForDefinition) { |
4797 | // Lookup the entry, lazily creating it if necessary. |
4798 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
4799 | unsigned TargetAS = getContext().getTargetAddressSpace(AS: AddrSpace); |
4800 | if (Entry) { |
4801 | if (WeakRefReferences.erase(Ptr: Entry)) { |
4802 | if (D && !D->hasAttr<WeakAttr>()) |
4803 | Entry->setLinkage(llvm::Function::ExternalLinkage); |
4804 | } |
4805 | |
4806 | // Handle dropped DLL attributes. |
4807 | if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && |
4808 | !shouldMapVisibilityToDLLExport(D)) |
4809 | Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
4810 | |
4811 | if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) |
4812 | getOpenMPRuntime().registerTargetGlobalVariable(VD: D, Addr: Entry); |
4813 | |
4814 | if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) |
4815 | return Entry; |
4816 | |
4817 | // If there are two attempts to define the same mangled name, issue an |
4818 | // error. |
4819 | if (IsForDefinition && !Entry->isDeclaration()) { |
4820 | GlobalDecl OtherGD; |
4821 | const VarDecl *OtherD; |
4822 | |
4823 | // Check that D is not yet in DiagnosedConflictingDefinitions is required |
4824 | // to make sure that we issue an error only once. |
4825 | if (D && lookupRepresentativeDecl(MangledName, Result&: OtherGD) && |
4826 | (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && |
4827 | (OtherD = dyn_cast<VarDecl>(Val: OtherGD.getDecl())) && |
4828 | OtherD->hasInit() && |
4829 | DiagnosedConflictingDefinitions.insert(V: D).second) { |
4830 | getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) |
4831 | << MangledName; |
4832 | getDiags().Report(OtherGD.getDecl()->getLocation(), |
4833 | diag::note_previous_definition); |
4834 | } |
4835 | } |
4836 | |
4837 | // Make sure the result is of the correct type. |
4838 | if (Entry->getType()->getAddressSpace() != TargetAS) |
4839 | return llvm::ConstantExpr::getAddrSpaceCast( |
4840 | C: Entry, Ty: llvm::PointerType::get(C&: Ty->getContext(), AddressSpace: TargetAS)); |
4841 | |
4842 | // (If global is requested for a definition, we always need to create a new |
4843 | // global, not just return a bitcast.) |
4844 | if (!IsForDefinition) |
4845 | return Entry; |
4846 | } |
4847 | |
4848 | auto DAddrSpace = GetGlobalVarAddressSpace(D); |
4849 | |
4850 | auto *GV = new llvm::GlobalVariable( |
4851 | getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, |
4852 | MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, |
4853 | getContext().getTargetAddressSpace(AS: DAddrSpace)); |
4854 | |
4855 | // If we already created a global with the same mangled name (but different |
4856 | // type) before, take its name and remove it from its parent. |
4857 | if (Entry) { |
4858 | GV->takeName(V: Entry); |
4859 | |
4860 | if (!Entry->use_empty()) { |
4861 | Entry->replaceAllUsesWith(V: GV); |
4862 | } |
4863 | |
4864 | Entry->eraseFromParent(); |
4865 | } |
4866 | |
4867 | // This is the first use or definition of a mangled name. If there is a |
4868 | // deferred decl with this name, remember that we need to emit it at the end |
4869 | // of the file. |
4870 | auto DDI = DeferredDecls.find(Val: MangledName); |
4871 | if (DDI != DeferredDecls.end()) { |
4872 | // Move the potentially referenced deferred decl to the DeferredDeclsToEmit |
4873 | // list, and remove it from DeferredDecls (since we don't need it anymore). |
4874 | addDeferredDeclToEmit(GD: DDI->second); |
4875 | DeferredDecls.erase(I: DDI); |
4876 | } |
4877 | |
4878 | // Handle things which are present even on external declarations. |
4879 | if (D) { |
4880 | if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) |
4881 | getOpenMPRuntime().registerTargetGlobalVariable(VD: D, Addr: GV); |
4882 | |
4883 | // FIXME: This code is overly simple and should be merged with other global |
4884 | // handling. |
4885 | GV->setConstant(D->getType().isConstantStorage(getContext(), false, false)); |
4886 | |
4887 | GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); |
4888 | |
4889 | setLinkageForGV(GV, D); |
4890 | |
4891 | if (D->getTLSKind()) { |
4892 | if (D->getTLSKind() == VarDecl::TLS_Dynamic) |
4893 | CXXThreadLocals.push_back(x: D); |
4894 | setTLSMode(GV, D: *D); |
4895 | } |
4896 | |
4897 | setGVProperties(GV, GD: D); |
4898 | |
4899 | // If required by the ABI, treat declarations of static data members with |
4900 | // inline initializers as definitions. |
4901 | if (getContext().isMSStaticDataMemberInlineDefinition(VD: D)) { |
4902 | EmitGlobalVarDefinition(D); |
4903 | } |
4904 | |
4905 | // Emit section information for extern variables. |
4906 | if (D->hasExternalStorage()) { |
4907 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) |
4908 | GV->setSection(SA->getName()); |
4909 | } |
4910 | |
4911 | // Handle XCore specific ABI requirements. |
4912 | if (getTriple().getArch() == llvm::Triple::xcore && |
4913 | D->getLanguageLinkage() == CLanguageLinkage && |
4914 | D->getType().isConstant(Context) && |
4915 | isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) |
4916 | GV->setSection(".cp.rodata" ); |
4917 | |
4918 | // Handle code model attribute |
4919 | if (const auto *CMA = D->getAttr<CodeModelAttr>()) |
4920 | GV->setCodeModel(CMA->getModel()); |
4921 | |
4922 | // Check if we a have a const declaration with an initializer, we may be |
4923 | // able to emit it as available_externally to expose it's value to the |
4924 | // optimizer. |
4925 | if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && |
4926 | D->getType().isConstQualified() && !GV->hasInitializer() && |
4927 | !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { |
4928 | const auto *Record = |
4929 | Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); |
4930 | bool HasMutableFields = Record && Record->hasMutableFields(); |
4931 | if (!HasMutableFields) { |
4932 | const VarDecl *InitDecl; |
4933 | const Expr *InitExpr = D->getAnyInitializer(D&: InitDecl); |
4934 | if (InitExpr) { |
4935 | ConstantEmitter emitter(*this); |
4936 | llvm::Constant *Init = emitter.tryEmitForInitializer(D: *InitDecl); |
4937 | if (Init) { |
4938 | auto *InitType = Init->getType(); |
4939 | if (GV->getValueType() != InitType) { |
4940 | // The type of the initializer does not match the definition. |
4941 | // This happens when an initializer has a different type from |
4942 | // the type of the global (because of padding at the end of a |
4943 | // structure for instance). |
4944 | GV->setName(StringRef()); |
4945 | // Make a new global with the correct type, this is now guaranteed |
4946 | // to work. |
4947 | auto *NewGV = cast<llvm::GlobalVariable>( |
4948 | Val: GetAddrOfGlobalVar(D, Ty: InitType, IsForDefinition) |
4949 | ->stripPointerCasts()); |
4950 | |
4951 | // Erase the old global, since it is no longer used. |
4952 | GV->eraseFromParent(); |
4953 | GV = NewGV; |
4954 | } else { |
4955 | GV->setInitializer(Init); |
4956 | GV->setConstant(true); |
4957 | GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); |
4958 | } |
4959 | emitter.finalize(global: GV); |
4960 | } |
4961 | } |
4962 | } |
4963 | } |
4964 | } |
4965 | |
4966 | if (D && |
4967 | D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) { |
4968 | getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); |
4969 | // External HIP managed variables needed to be recorded for transformation |
4970 | // in both device and host compilations. |
4971 | if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && |
4972 | D->hasExternalStorage()) |
4973 | getCUDARuntime().handleVarRegistration(VD: D, Var&: *GV); |
4974 | } |
4975 | |
4976 | if (D) |
4977 | SanitizerMD->reportGlobal(GV, D: *D); |
4978 | |
4979 | LangAS ExpectedAS = |
4980 | D ? D->getType().getAddressSpace() |
4981 | : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); |
4982 | assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); |
4983 | if (DAddrSpace != ExpectedAS) { |
4984 | return getTargetCodeGenInfo().performAddrSpaceCast( |
4985 | CGM&: *this, V: GV, SrcAddr: DAddrSpace, DestAddr: ExpectedAS, |
4986 | DestTy: llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: TargetAS)); |
4987 | } |
4988 | |
4989 | return GV; |
4990 | } |
4991 | |
4992 | llvm::Constant * |
4993 | CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { |
4994 | const Decl *D = GD.getDecl(); |
4995 | |
4996 | if (isa<CXXConstructorDecl>(Val: D) || isa<CXXDestructorDecl>(Val: D)) |
4997 | return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, |
4998 | /*DontDefer=*/false, IsForDefinition); |
4999 | |
5000 | if (isa<CXXMethodDecl>(Val: D)) { |
5001 | auto FInfo = |
5002 | &getTypes().arrangeCXXMethodDeclaration(MD: cast<CXXMethodDecl>(Val: D)); |
5003 | auto Ty = getTypes().GetFunctionType(Info: *FInfo); |
5004 | return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, |
5005 | IsForDefinition); |
5006 | } |
5007 | |
5008 | if (isa<FunctionDecl>(Val: D)) { |
5009 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
5010 | llvm::FunctionType *Ty = getTypes().GetFunctionType(Info: FI); |
5011 | return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, |
5012 | IsForDefinition); |
5013 | } |
5014 | |
5015 | return GetAddrOfGlobalVar(D: cast<VarDecl>(Val: D), /*Ty=*/nullptr, IsForDefinition); |
5016 | } |
5017 | |
5018 | llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( |
5019 | StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, |
5020 | llvm::Align Alignment) { |
5021 | llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); |
5022 | llvm::GlobalVariable *OldGV = nullptr; |
5023 | |
5024 | if (GV) { |
5025 | // Check if the variable has the right type. |
5026 | if (GV->getValueType() == Ty) |
5027 | return GV; |
5028 | |
5029 | // Because C++ name mangling, the only way we can end up with an already |
5030 | // existing global with the same name is if it has been declared extern "C". |
5031 | assert(GV->isDeclaration() && "Declaration has wrong type!" ); |
5032 | OldGV = GV; |
5033 | } |
5034 | |
5035 | // Create a new variable. |
5036 | GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, |
5037 | Linkage, nullptr, Name); |
5038 | |
5039 | if (OldGV) { |
5040 | // Replace occurrences of the old variable if needed. |
5041 | GV->takeName(V: OldGV); |
5042 | |
5043 | if (!OldGV->use_empty()) { |
5044 | OldGV->replaceAllUsesWith(V: GV); |
5045 | } |
5046 | |
5047 | OldGV->eraseFromParent(); |
5048 | } |
5049 | |
5050 | if (supportsCOMDAT() && GV->isWeakForLinker() && |
5051 | !GV->hasAvailableExternallyLinkage()) |
5052 | GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName())); |
5053 | |
5054 | GV->setAlignment(Alignment); |
5055 | |
5056 | return GV; |
5057 | } |
5058 | |
5059 | /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the |
5060 | /// given global variable. If Ty is non-null and if the global doesn't exist, |
5061 | /// then it will be created with the specified type instead of whatever the |
5062 | /// normal requested type would be. If IsForDefinition is true, it is guaranteed |
5063 | /// that an actual global with type Ty will be returned, not conversion of a |
5064 | /// variable with the same mangled name but some other type. |
5065 | llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, |
5066 | llvm::Type *Ty, |
5067 | ForDefinition_t IsForDefinition) { |
5068 | assert(D->hasGlobalStorage() && "Not a global variable" ); |
5069 | QualType ASTTy = D->getType(); |
5070 | if (!Ty) |
5071 | Ty = getTypes().ConvertTypeForMem(T: ASTTy); |
5072 | |
5073 | StringRef MangledName = getMangledName(GD: D); |
5074 | return GetOrCreateLLVMGlobal(MangledName, Ty, AddrSpace: ASTTy.getAddressSpace(), D, |
5075 | IsForDefinition); |
5076 | } |
5077 | |
5078 | /// CreateRuntimeVariable - Create a new runtime global variable with the |
5079 | /// specified type and name. |
5080 | llvm::Constant * |
5081 | CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, |
5082 | StringRef Name) { |
5083 | LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global |
5084 | : LangAS::Default; |
5085 | auto *Ret = GetOrCreateLLVMGlobal(MangledName: Name, Ty, AddrSpace, D: nullptr); |
5086 | setDSOLocal(cast<llvm::GlobalValue>(Val: Ret->stripPointerCasts())); |
5087 | return Ret; |
5088 | } |
5089 | |
5090 | void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { |
5091 | assert(!D->getInit() && "Cannot emit definite definitions here!" ); |
5092 | |
5093 | StringRef MangledName = getMangledName(GD: D); |
5094 | llvm::GlobalValue *GV = GetGlobalValue(Name: MangledName); |
5095 | |
5096 | // We already have a definition, not declaration, with the same mangled name. |
5097 | // Emitting of declaration is not required (and actually overwrites emitted |
5098 | // definition). |
5099 | if (GV && !GV->isDeclaration()) |
5100 | return; |
5101 | |
5102 | // If we have not seen a reference to this variable yet, place it into the |
5103 | // deferred declarations table to be emitted if needed later. |
5104 | if (!MustBeEmitted(D) && !GV) { |
5105 | DeferredDecls[MangledName] = D; |
5106 | return; |
5107 | } |
5108 | |
5109 | // The tentative definition is the only definition. |
5110 | EmitGlobalVarDefinition(D); |
5111 | } |
5112 | |
5113 | void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { |
5114 | EmitExternalVarDeclaration(D); |
5115 | } |
5116 | |
5117 | CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { |
5118 | return Context.toCharUnitsFromBits( |
5119 | BitSize: getDataLayout().getTypeStoreSizeInBits(Ty)); |
5120 | } |
5121 | |
5122 | LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { |
5123 | if (LangOpts.OpenCL) { |
5124 | LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; |
5125 | assert(AS == LangAS::opencl_global || |
5126 | AS == LangAS::opencl_global_device || |
5127 | AS == LangAS::opencl_global_host || |
5128 | AS == LangAS::opencl_constant || |
5129 | AS == LangAS::opencl_local || |
5130 | AS >= LangAS::FirstTargetAddressSpace); |
5131 | return AS; |
5132 | } |
5133 | |
5134 | if (LangOpts.SYCLIsDevice && |
5135 | (!D || D->getType().getAddressSpace() == LangAS::Default)) |
5136 | return LangAS::sycl_global; |
5137 | |
5138 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { |
5139 | if (D) { |
5140 | if (D->hasAttr<CUDAConstantAttr>()) |
5141 | return LangAS::cuda_constant; |
5142 | if (D->hasAttr<CUDASharedAttr>()) |
5143 | return LangAS::cuda_shared; |
5144 | if (D->hasAttr<CUDADeviceAttr>()) |
5145 | return LangAS::cuda_device; |
5146 | if (D->getType().isConstQualified()) |
5147 | return LangAS::cuda_constant; |
5148 | } |
5149 | return LangAS::cuda_device; |
5150 | } |
5151 | |
5152 | if (LangOpts.OpenMP) { |
5153 | LangAS AS; |
5154 | if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(VD: D, AS)) |
5155 | return AS; |
5156 | } |
5157 | return getTargetCodeGenInfo().getGlobalVarAddressSpace(CGM&: *this, D); |
5158 | } |
5159 | |
5160 | LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { |
5161 | // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. |
5162 | if (LangOpts.OpenCL) |
5163 | return LangAS::opencl_constant; |
5164 | if (LangOpts.SYCLIsDevice) |
5165 | return LangAS::sycl_global; |
5166 | if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) |
5167 | // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) |
5168 | // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up |
5169 | // with OpVariable instructions with Generic storage class which is not |
5170 | // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V |
5171 | // UniformConstant storage class is not viable as pointers to it may not be |
5172 | // casted to Generic pointers which are used to model HIP's "flat" pointers. |
5173 | return LangAS::cuda_device; |
5174 | if (auto AS = getTarget().getConstantAddressSpace()) |
5175 | return *AS; |
5176 | return LangAS::Default; |
5177 | } |
5178 | |
5179 | // In address space agnostic languages, string literals are in default address |
5180 | // space in AST. However, certain targets (e.g. amdgcn) request them to be |
5181 | // emitted in constant address space in LLVM IR. To be consistent with other |
5182 | // parts of AST, string literal global variables in constant address space |
5183 | // need to be casted to default address space before being put into address |
5184 | // map and referenced by other part of CodeGen. |
5185 | // In OpenCL, string literals are in constant address space in AST, therefore |
5186 | // they should not be casted to default address space. |
5187 | static llvm::Constant * |
5188 | castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, |
5189 | llvm::GlobalVariable *GV) { |
5190 | llvm::Constant *Cast = GV; |
5191 | if (!CGM.getLangOpts().OpenCL) { |
5192 | auto AS = CGM.GetGlobalConstantAddressSpace(); |
5193 | if (AS != LangAS::Default) |
5194 | Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( |
5195 | CGM, V: GV, SrcAddr: AS, DestAddr: LangAS::Default, |
5196 | DestTy: llvm::PointerType::get( |
5197 | C&: CGM.getLLVMContext(), |
5198 | AddressSpace: CGM.getContext().getTargetAddressSpace(AS: LangAS::Default))); |
5199 | } |
5200 | return Cast; |
5201 | } |
5202 | |
5203 | template<typename SomeDecl> |
5204 | void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, |
5205 | llvm::GlobalValue *GV) { |
5206 | if (!getLangOpts().CPlusPlus) |
5207 | return; |
5208 | |
5209 | // Must have 'used' attribute, or else inline assembly can't rely on |
5210 | // the name existing. |
5211 | if (!D->template hasAttr<UsedAttr>()) |
5212 | return; |
5213 | |
5214 | // Must have internal linkage and an ordinary name. |
5215 | if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal) |
5216 | return; |
5217 | |
5218 | // Must be in an extern "C" context. Entities declared directly within |
5219 | // a record are not extern "C" even if the record is in such a context. |
5220 | const SomeDecl *First = D->getFirstDecl(); |
5221 | if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) |
5222 | return; |
5223 | |
5224 | // OK, this is an internal linkage entity inside an extern "C" linkage |
5225 | // specification. Make a note of that so we can give it the "expected" |
5226 | // mangled name if nothing else is using that name. |
5227 | std::pair<StaticExternCMap::iterator, bool> R = |
5228 | StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); |
5229 | |
5230 | // If we have multiple internal linkage entities with the same name |
5231 | // in extern "C" regions, none of them gets that name. |
5232 | if (!R.second) |
5233 | R.first->second = nullptr; |
5234 | } |
5235 | |
5236 | static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { |
5237 | if (!CGM.supportsCOMDAT()) |
5238 | return false; |
5239 | |
5240 | if (D.hasAttr<SelectAnyAttr>()) |
5241 | return true; |
5242 | |
5243 | GVALinkage Linkage; |
5244 | if (auto *VD = dyn_cast<VarDecl>(Val: &D)) |
5245 | Linkage = CGM.getContext().GetGVALinkageForVariable(VD); |
5246 | else |
5247 | Linkage = CGM.getContext().GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: &D)); |
5248 | |
5249 | switch (Linkage) { |
5250 | case GVA_Internal: |
5251 | case GVA_AvailableExternally: |
5252 | case GVA_StrongExternal: |
5253 | return false; |
5254 | case GVA_DiscardableODR: |
5255 | case GVA_StrongODR: |
5256 | return true; |
5257 | } |
5258 | llvm_unreachable("No such linkage" ); |
5259 | } |
5260 | |
5261 | bool CodeGenModule::supportsCOMDAT() const { |
5262 | return getTriple().supportsCOMDAT(); |
5263 | } |
5264 | |
5265 | void CodeGenModule::maybeSetTrivialComdat(const Decl &D, |
5266 | llvm::GlobalObject &GO) { |
5267 | if (!shouldBeInCOMDAT(CGM&: *this, D)) |
5268 | return; |
5269 | GO.setComdat(TheModule.getOrInsertComdat(Name: GO.getName())); |
5270 | } |
5271 | |
5272 | /// Pass IsTentative as true if you want to create a tentative definition. |
5273 | void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, |
5274 | bool IsTentative) { |
5275 | // OpenCL global variables of sampler type are translated to function calls, |
5276 | // therefore no need to be translated. |
5277 | QualType ASTTy = D->getType(); |
5278 | if (getLangOpts().OpenCL && ASTTy->isSamplerT()) |
5279 | return; |
5280 | |
5281 | // If this is OpenMP device, check if it is legal to emit this global |
5282 | // normally. |
5283 | if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime && |
5284 | OpenMPRuntime->emitTargetGlobalVariable(GD: D)) |
5285 | return; |
5286 | |
5287 | llvm::TrackingVH<llvm::Constant> Init; |
5288 | bool NeedsGlobalCtor = false; |
5289 | // Whether the definition of the variable is available externally. |
5290 | // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable |
5291 | // since this is the job for its original source. |
5292 | bool IsDefinitionAvailableExternally = |
5293 | getContext().GetGVALinkageForVariable(VD: D) == GVA_AvailableExternally; |
5294 | bool NeedsGlobalDtor = |
5295 | !IsDefinitionAvailableExternally && |
5296 | D->needsDestruction(Ctx: getContext()) == QualType::DK_cxx_destructor; |
5297 | |
5298 | const VarDecl *InitDecl; |
5299 | const Expr *InitExpr = D->getAnyInitializer(D&: InitDecl); |
5300 | |
5301 | std::optional<ConstantEmitter> emitter; |
5302 | |
5303 | // CUDA E.2.4.1 "__shared__ variables cannot have an initialization |
5304 | // as part of their declaration." Sema has already checked for |
5305 | // error cases, so we just need to set Init to UndefValue. |
5306 | bool IsCUDASharedVar = |
5307 | getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); |
5308 | // Shadows of initialized device-side global variables are also left |
5309 | // undefined. |
5310 | // Managed Variables should be initialized on both host side and device side. |
5311 | bool IsCUDAShadowVar = |
5312 | !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && |
5313 | (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || |
5314 | D->hasAttr<CUDASharedAttr>()); |
5315 | bool IsCUDADeviceShadowVar = |
5316 | getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && |
5317 | (D->getType()->isCUDADeviceBuiltinSurfaceType() || |
5318 | D->getType()->isCUDADeviceBuiltinTextureType()); |
5319 | if (getLangOpts().CUDA && |
5320 | (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) |
5321 | Init = llvm::UndefValue::get(T: getTypes().ConvertTypeForMem(T: ASTTy)); |
5322 | else if (D->hasAttr<LoaderUninitializedAttr>()) |
5323 | Init = llvm::UndefValue::get(T: getTypes().ConvertTypeForMem(T: ASTTy)); |
5324 | else if (!InitExpr) { |
5325 | // This is a tentative definition; tentative definitions are |
5326 | // implicitly initialized with { 0 }. |
5327 | // |
5328 | // Note that tentative definitions are only emitted at the end of |
5329 | // a translation unit, so they should never have incomplete |
5330 | // type. In addition, EmitTentativeDefinition makes sure that we |
5331 | // never attempt to emit a tentative definition if a real one |
5332 | // exists. A use may still exists, however, so we still may need |
5333 | // to do a RAUW. |
5334 | assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type" ); |
5335 | Init = EmitNullConstant(T: D->getType()); |
5336 | } else { |
5337 | initializedGlobalDecl = GlobalDecl(D); |
5338 | emitter.emplace(args&: *this); |
5339 | llvm::Constant *Initializer = emitter->tryEmitForInitializer(D: *InitDecl); |
5340 | if (!Initializer) { |
5341 | QualType T = InitExpr->getType(); |
5342 | if (D->getType()->isReferenceType()) |
5343 | T = D->getType(); |
5344 | |
5345 | if (getLangOpts().CPlusPlus) { |
5346 | if (InitDecl->hasFlexibleArrayInit(Ctx: getContext())) |
5347 | ErrorUnsupported(D, "flexible array initializer" ); |
5348 | Init = EmitNullConstant(T); |
5349 | |
5350 | if (!IsDefinitionAvailableExternally) |
5351 | NeedsGlobalCtor = true; |
5352 | } else { |
5353 | ErrorUnsupported(D, "static initializer" ); |
5354 | Init = llvm::UndefValue::get(T: getTypes().ConvertType(T)); |
5355 | } |
5356 | } else { |
5357 | Init = Initializer; |
5358 | // We don't need an initializer, so remove the entry for the delayed |
5359 | // initializer position (just in case this entry was delayed) if we |
5360 | // also don't need to register a destructor. |
5361 | if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) |
5362 | DelayedCXXInitPosition.erase(D); |
5363 | |
5364 | #ifndef NDEBUG |
5365 | CharUnits VarSize = getContext().getTypeSizeInChars(T: ASTTy) + |
5366 | InitDecl->getFlexibleArrayInitChars(Ctx: getContext()); |
5367 | CharUnits CstSize = CharUnits::fromQuantity( |
5368 | Quantity: getDataLayout().getTypeAllocSize(Ty: Init->getType())); |
5369 | assert(VarSize == CstSize && "Emitted constant has unexpected size" ); |
5370 | #endif |
5371 | } |
5372 | } |
5373 | |
5374 | llvm::Type* InitType = Init->getType(); |
5375 | llvm::Constant *Entry = |
5376 | GetAddrOfGlobalVar(D, Ty: InitType, IsForDefinition: ForDefinition_t(!IsTentative)); |
5377 | |
5378 | // Strip off pointer casts if we got them. |
5379 | Entry = Entry->stripPointerCasts(); |
5380 | |
5381 | // Entry is now either a Function or GlobalVariable. |
5382 | auto *GV = dyn_cast<llvm::GlobalVariable>(Val: Entry); |
5383 | |
5384 | // We have a definition after a declaration with the wrong type. |
5385 | // We must make a new GlobalVariable* and update everything that used OldGV |
5386 | // (a declaration or tentative definition) with the new GlobalVariable* |
5387 | // (which will be a definition). |
5388 | // |
5389 | // This happens if there is a prototype for a global (e.g. |
5390 | // "extern int x[];") and then a definition of a different type (e.g. |
5391 | // "int x[10];"). This also happens when an initializer has a different type |
5392 | // from the type of the global (this happens with unions). |
5393 | if (!GV || GV->getValueType() != InitType || |
5394 | GV->getType()->getAddressSpace() != |
5395 | getContext().getTargetAddressSpace(AS: GetGlobalVarAddressSpace(D))) { |
5396 | |
5397 | // Move the old entry aside so that we'll create a new one. |
5398 | Entry->setName(StringRef()); |
5399 | |
5400 | // Make a new global with the correct type, this is now guaranteed to work. |
5401 | GV = cast<llvm::GlobalVariable>( |
5402 | Val: GetAddrOfGlobalVar(D, Ty: InitType, IsForDefinition: ForDefinition_t(!IsTentative)) |
5403 | ->stripPointerCasts()); |
5404 | |
5405 | // Replace all uses of the old global with the new global |
5406 | llvm::Constant *NewPtrForOldDecl = |
5407 | llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(C: GV, |
5408 | Ty: Entry->getType()); |
5409 | Entry->replaceAllUsesWith(V: NewPtrForOldDecl); |
5410 | |
5411 | // Erase the old global, since it is no longer used. |
5412 | cast<llvm::GlobalValue>(Val: Entry)->eraseFromParent(); |
5413 | } |
5414 | |
5415 | MaybeHandleStaticInExternC(D, GV); |
5416 | |
5417 | if (D->hasAttr<AnnotateAttr>()) |
5418 | AddGlobalAnnotations(D, GV); |
5419 | |
5420 | // Set the llvm linkage type as appropriate. |
5421 | llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD: D); |
5422 | |
5423 | // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on |
5424 | // the device. [...]" |
5425 | // CUDA B.2.2 "The __constant__ qualifier, optionally used together with |
5426 | // __device__, declares a variable that: [...] |
5427 | // Is accessible from all the threads within the grid and from the host |
5428 | // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() |
5429 | // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." |
5430 | if (LangOpts.CUDA) { |
5431 | if (LangOpts.CUDAIsDevice) { |
5432 | if (Linkage != llvm::GlobalValue::InternalLinkage && |
5433 | (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || |
5434 | D->getType()->isCUDADeviceBuiltinSurfaceType() || |
5435 | D->getType()->isCUDADeviceBuiltinTextureType())) |
5436 | GV->setExternallyInitialized(true); |
5437 | } else { |
5438 | getCUDARuntime().internalizeDeviceSideVar(D, Linkage); |
5439 | } |
5440 | getCUDARuntime().handleVarRegistration(VD: D, Var&: *GV); |
5441 | } |
5442 | |
5443 | GV->setInitializer(Init); |
5444 | if (emitter) |
5445 | emitter->finalize(global: GV); |
5446 | |
5447 | // If it is safe to mark the global 'constant', do so now. |
5448 | GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && |
5449 | D->getType().isConstantStorage(getContext(), true, true)); |
5450 | |
5451 | // If it is in a read-only section, mark it 'constant'. |
5452 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { |
5453 | const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; |
5454 | if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) |
5455 | GV->setConstant(true); |
5456 | } |
5457 | |
5458 | CharUnits AlignVal = getContext().getDeclAlign(D); |
5459 | // Check for alignment specifed in an 'omp allocate' directive. |
5460 | if (std::optional<CharUnits> AlignValFromAllocate = |
5461 | getOMPAllocateAlignment(VD: D)) |
5462 | AlignVal = *AlignValFromAllocate; |
5463 | GV->setAlignment(AlignVal.getAsAlign()); |
5464 | |
5465 | // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper |
5466 | // function is only defined alongside the variable, not also alongside |
5467 | // callers. Normally, all accesses to a thread_local go through the |
5468 | // thread-wrapper in order to ensure initialization has occurred, underlying |
5469 | // variable will never be used other than the thread-wrapper, so it can be |
5470 | // converted to internal linkage. |
5471 | // |
5472 | // However, if the variable has the 'constinit' attribute, it _can_ be |
5473 | // referenced directly, without calling the thread-wrapper, so the linkage |
5474 | // must not be changed. |
5475 | // |
5476 | // Additionally, if the variable isn't plain external linkage, e.g. if it's |
5477 | // weak or linkonce, the de-duplication semantics are important to preserve, |
5478 | // so we don't change the linkage. |
5479 | if (D->getTLSKind() == VarDecl::TLS_Dynamic && |
5480 | Linkage == llvm::GlobalValue::ExternalLinkage && |
5481 | Context.getTargetInfo().getTriple().isOSDarwin() && |
5482 | !D->hasAttr<ConstInitAttr>()) |
5483 | Linkage = llvm::GlobalValue::InternalLinkage; |
5484 | |
5485 | GV->setLinkage(Linkage); |
5486 | if (D->hasAttr<DLLImportAttr>()) |
5487 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); |
5488 | else if (D->hasAttr<DLLExportAttr>()) |
5489 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); |
5490 | else |
5491 | GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); |
5492 | |
5493 | if (Linkage == llvm::GlobalVariable::CommonLinkage) { |
5494 | // common vars aren't constant even if declared const. |
5495 | GV->setConstant(false); |
5496 | // Tentative definition of global variables may be initialized with |
5497 | // non-zero null pointers. In this case they should have weak linkage |
5498 | // since common linkage must have zero initializer and must not have |
5499 | // explicit section therefore cannot have non-zero initial value. |
5500 | if (!GV->getInitializer()->isNullValue()) |
5501 | GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); |
5502 | } |
5503 | |
5504 | setNonAliasAttributes(GD: D, GO: GV); |
5505 | |
5506 | if (D->getTLSKind() && !GV->isThreadLocal()) { |
5507 | if (D->getTLSKind() == VarDecl::TLS_Dynamic) |
5508 | CXXThreadLocals.push_back(x: D); |
5509 | setTLSMode(GV, D: *D); |
5510 | } |
5511 | |
5512 | maybeSetTrivialComdat(*D, *GV); |
5513 | |
5514 | // Emit the initializer function if necessary. |
5515 | if (NeedsGlobalCtor || NeedsGlobalDtor) |
5516 | EmitCXXGlobalVarDeclInitFunc(D, Addr: GV, PerformInit: NeedsGlobalCtor); |
5517 | |
5518 | SanitizerMD->reportGlobal(GV, D: *D, IsDynInit: NeedsGlobalCtor); |
5519 | |
5520 | // Emit global variable debug information. |
5521 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
5522 | if (getCodeGenOpts().hasReducedDebugInfo()) |
5523 | DI->EmitGlobalVariable(GV, Decl: D); |
5524 | } |
5525 | |
5526 | void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { |
5527 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
5528 | if (getCodeGenOpts().hasReducedDebugInfo()) { |
5529 | QualType ASTTy = D->getType(); |
5530 | llvm::Type *Ty = getTypes().ConvertTypeForMem(T: D->getType()); |
5531 | llvm::Constant *GV = |
5532 | GetOrCreateLLVMGlobal(MangledName: D->getName(), Ty, AddrSpace: ASTTy.getAddressSpace(), D); |
5533 | DI->EmitExternalVariable( |
5534 | GV: cast<llvm::GlobalVariable>(Val: GV->stripPointerCasts()), Decl: D); |
5535 | } |
5536 | } |
5537 | |
5538 | static bool isVarDeclStrongDefinition(const ASTContext &Context, |
5539 | CodeGenModule &CGM, const VarDecl *D, |
5540 | bool NoCommon) { |
5541 | // Don't give variables common linkage if -fno-common was specified unless it |
5542 | // was overridden by a NoCommon attribute. |
5543 | if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) |
5544 | return true; |
5545 | |
5546 | // C11 6.9.2/2: |
5547 | // A declaration of an identifier for an object that has file scope without |
5548 | // an initializer, and without a storage-class specifier or with the |
5549 | // storage-class specifier static, constitutes a tentative definition. |
5550 | if (D->getInit() || D->hasExternalStorage()) |
5551 | return true; |
5552 | |
5553 | // A variable cannot be both common and exist in a section. |
5554 | if (D->hasAttr<SectionAttr>()) |
5555 | return true; |
5556 | |
5557 | // A variable cannot be both common and exist in a section. |
5558 | // We don't try to determine which is the right section in the front-end. |
5559 | // If no specialized section name is applicable, it will resort to default. |
5560 | if (D->hasAttr<PragmaClangBSSSectionAttr>() || |
5561 | D->hasAttr<PragmaClangDataSectionAttr>() || |
5562 | D->hasAttr<PragmaClangRelroSectionAttr>() || |
5563 | D->hasAttr<PragmaClangRodataSectionAttr>()) |
5564 | return true; |
5565 | |
5566 | // Thread local vars aren't considered common linkage. |
5567 | if (D->getTLSKind()) |
5568 | return true; |
5569 | |
5570 | // Tentative definitions marked with WeakImportAttr are true definitions. |
5571 | if (D->hasAttr<WeakImportAttr>()) |
5572 | return true; |
5573 | |
5574 | // A variable cannot be both common and exist in a comdat. |
5575 | if (shouldBeInCOMDAT(CGM, *D)) |
5576 | return true; |
5577 | |
5578 | // Declarations with a required alignment do not have common linkage in MSVC |
5579 | // mode. |
5580 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
5581 | if (D->hasAttr<AlignedAttr>()) |
5582 | return true; |
5583 | QualType VarType = D->getType(); |
5584 | if (Context.isAlignmentRequired(T: VarType)) |
5585 | return true; |
5586 | |
5587 | if (const auto *RT = VarType->getAs<RecordType>()) { |
5588 | const RecordDecl *RD = RT->getDecl(); |
5589 | for (const FieldDecl *FD : RD->fields()) { |
5590 | if (FD->isBitField()) |
5591 | continue; |
5592 | if (FD->hasAttr<AlignedAttr>()) |
5593 | return true; |
5594 | if (Context.isAlignmentRequired(FD->getType())) |
5595 | return true; |
5596 | } |
5597 | } |
5598 | } |
5599 | |
5600 | // Microsoft's link.exe doesn't support alignments greater than 32 bytes for |
5601 | // common symbols, so symbols with greater alignment requirements cannot be |
5602 | // common. |
5603 | // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two |
5604 | // alignments for common symbols via the aligncomm directive, so this |
5605 | // restriction only applies to MSVC environments. |
5606 | if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && |
5607 | Context.getTypeAlignIfKnown(T: D->getType()) > |
5608 | Context.toBits(CharSize: CharUnits::fromQuantity(Quantity: 32))) |
5609 | return true; |
5610 | |
5611 | return false; |
5612 | } |
5613 | |
5614 | llvm::GlobalValue::LinkageTypes |
5615 | CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D, |
5616 | GVALinkage Linkage) { |
5617 | if (Linkage == GVA_Internal) |
5618 | return llvm::Function::InternalLinkage; |
5619 | |
5620 | if (D->hasAttr<WeakAttr>()) |
5621 | return llvm::GlobalVariable::WeakAnyLinkage; |
5622 | |
5623 | if (const auto *FD = D->getAsFunction()) |
5624 | if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) |
5625 | return llvm::GlobalVariable::LinkOnceAnyLinkage; |
5626 | |
5627 | // We are guaranteed to have a strong definition somewhere else, |
5628 | // so we can use available_externally linkage. |
5629 | if (Linkage == GVA_AvailableExternally) |
5630 | return llvm::GlobalValue::AvailableExternallyLinkage; |
5631 | |
5632 | // Note that Apple's kernel linker doesn't support symbol |
5633 | // coalescing, so we need to avoid linkonce and weak linkages there. |
5634 | // Normally, this means we just map to internal, but for explicit |
5635 | // instantiations we'll map to external. |
5636 | |
5637 | // In C++, the compiler has to emit a definition in every translation unit |
5638 | // that references the function. We should use linkonce_odr because |
5639 | // a) if all references in this translation unit are optimized away, we |
5640 | // don't need to codegen it. b) if the function persists, it needs to be |
5641 | // merged with other definitions. c) C++ has the ODR, so we know the |
5642 | // definition is dependable. |
5643 | if (Linkage == GVA_DiscardableODR) |
5644 | return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage |
5645 | : llvm::Function::InternalLinkage; |
5646 | |
5647 | // An explicit instantiation of a template has weak linkage, since |
5648 | // explicit instantiations can occur in multiple translation units |
5649 | // and must all be equivalent. However, we are not allowed to |
5650 | // throw away these explicit instantiations. |
5651 | // |
5652 | // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, |
5653 | // so say that CUDA templates are either external (for kernels) or internal. |
5654 | // This lets llvm perform aggressive inter-procedural optimizations. For |
5655 | // -fgpu-rdc case, device function calls across multiple TU's are allowed, |
5656 | // therefore we need to follow the normal linkage paradigm. |
5657 | if (Linkage == GVA_StrongODR) { |
5658 | if (getLangOpts().AppleKext) |
5659 | return llvm::Function::ExternalLinkage; |
5660 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && |
5661 | !getLangOpts().GPURelocatableDeviceCode) |
5662 | return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage |
5663 | : llvm::Function::InternalLinkage; |
5664 | return llvm::Function::WeakODRLinkage; |
5665 | } |
5666 | |
5667 | // C++ doesn't have tentative definitions and thus cannot have common |
5668 | // linkage. |
5669 | if (!getLangOpts().CPlusPlus && isa<VarDecl>(Val: D) && |
5670 | !isVarDeclStrongDefinition(Context, CGM&: *this, D: cast<VarDecl>(Val: D), |
5671 | NoCommon: CodeGenOpts.NoCommon)) |
5672 | return llvm::GlobalVariable::CommonLinkage; |
5673 | |
5674 | // selectany symbols are externally visible, so use weak instead of |
5675 | // linkonce. MSVC optimizes away references to const selectany globals, so |
5676 | // all definitions should be the same and ODR linkage should be used. |
5677 | // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx |
5678 | if (D->hasAttr<SelectAnyAttr>()) |
5679 | return llvm::GlobalVariable::WeakODRLinkage; |
5680 | |
5681 | // Otherwise, we have strong external linkage. |
5682 | assert(Linkage == GVA_StrongExternal); |
5683 | return llvm::GlobalVariable::ExternalLinkage; |
5684 | } |
5685 | |
5686 | llvm::GlobalValue::LinkageTypes |
5687 | CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) { |
5688 | GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); |
5689 | return getLLVMLinkageForDeclarator(VD, Linkage); |
5690 | } |
5691 | |
5692 | /// Replace the uses of a function that was declared with a non-proto type. |
5693 | /// We want to silently drop extra arguments from call sites |
5694 | static void replaceUsesOfNonProtoConstant(llvm::Constant *old, |
5695 | llvm::Function *newFn) { |
5696 | // Fast path. |
5697 | if (old->use_empty()) return; |
5698 | |
5699 | llvm::Type *newRetTy = newFn->getReturnType(); |
5700 | SmallVector<llvm::Value*, 4> newArgs; |
5701 | |
5702 | for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); |
5703 | ui != ue; ) { |
5704 | llvm::Value::use_iterator use = ui++; // Increment before the use is erased. |
5705 | llvm::User *user = use->getUser(); |
5706 | |
5707 | // Recognize and replace uses of bitcasts. Most calls to |
5708 | // unprototyped functions will use bitcasts. |
5709 | if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(Val: user)) { |
5710 | if (bitcast->getOpcode() == llvm::Instruction::BitCast) |
5711 | replaceUsesOfNonProtoConstant(old: bitcast, newFn); |
5712 | continue; |
5713 | } |
5714 | |
5715 | // Recognize calls to the function. |
5716 | llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(Val: user); |
5717 | if (!callSite) continue; |
5718 | if (!callSite->isCallee(U: &*use)) |
5719 | continue; |
5720 | |
5721 | // If the return types don't match exactly, then we can't |
5722 | // transform this call unless it's dead. |
5723 | if (callSite->getType() != newRetTy && !callSite->use_empty()) |
5724 | continue; |
5725 | |
5726 | // Get the call site's attribute list. |
5727 | SmallVector<llvm::AttributeSet, 8> newArgAttrs; |
5728 | llvm::AttributeList oldAttrs = callSite->getAttributes(); |
5729 | |
5730 | // If the function was passed too few arguments, don't transform. |
5731 | unsigned newNumArgs = newFn->arg_size(); |
5732 | if (callSite->arg_size() < newNumArgs) |
5733 | continue; |
5734 | |
5735 | // If extra arguments were passed, we silently drop them. |
5736 | // If any of the types mismatch, we don't transform. |
5737 | unsigned argNo = 0; |
5738 | bool dontTransform = false; |
5739 | for (llvm::Argument &A : newFn->args()) { |
5740 | if (callSite->getArgOperand(i: argNo)->getType() != A.getType()) { |
5741 | dontTransform = true; |
5742 | break; |
5743 | } |
5744 | |
5745 | // Add any parameter attributes. |
5746 | newArgAttrs.push_back(Elt: oldAttrs.getParamAttrs(ArgNo: argNo)); |
5747 | argNo++; |
5748 | } |
5749 | if (dontTransform) |
5750 | continue; |
5751 | |
5752 | // Okay, we can transform this. Create the new call instruction and copy |
5753 | // over the required information. |
5754 | newArgs.append(in_start: callSite->arg_begin(), in_end: callSite->arg_begin() + argNo); |
5755 | |
5756 | // Copy over any operand bundles. |
5757 | SmallVector<llvm::OperandBundleDef, 1> newBundles; |
5758 | callSite->getOperandBundlesAsDefs(Defs&: newBundles); |
5759 | |
5760 | llvm::CallBase *newCall; |
5761 | if (isa<llvm::CallInst>(Val: callSite)) { |
5762 | newCall = |
5763 | llvm::CallInst::Create(Func: newFn, Args: newArgs, Bundles: newBundles, NameStr: "" , InsertBefore: callSite); |
5764 | } else { |
5765 | auto *oldInvoke = cast<llvm::InvokeInst>(Val: callSite); |
5766 | newCall = llvm::InvokeInst::Create(Func: newFn, IfNormal: oldInvoke->getNormalDest(), |
5767 | IfException: oldInvoke->getUnwindDest(), Args: newArgs, |
5768 | Bundles: newBundles, NameStr: "" , InsertBefore: callSite); |
5769 | } |
5770 | newArgs.clear(); // for the next iteration |
5771 | |
5772 | if (!newCall->getType()->isVoidTy()) |
5773 | newCall->takeName(V: callSite); |
5774 | newCall->setAttributes( |
5775 | llvm::AttributeList::get(C&: newFn->getContext(), FnAttrs: oldAttrs.getFnAttrs(), |
5776 | RetAttrs: oldAttrs.getRetAttrs(), ArgAttrs: newArgAttrs)); |
5777 | newCall->setCallingConv(callSite->getCallingConv()); |
5778 | |
5779 | // Finally, remove the old call, replacing any uses with the new one. |
5780 | if (!callSite->use_empty()) |
5781 | callSite->replaceAllUsesWith(V: newCall); |
5782 | |
5783 | // Copy debug location attached to CI. |
5784 | if (callSite->getDebugLoc()) |
5785 | newCall->setDebugLoc(callSite->getDebugLoc()); |
5786 | |
5787 | callSite->eraseFromParent(); |
5788 | } |
5789 | } |
5790 | |
5791 | /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we |
5792 | /// implement a function with no prototype, e.g. "int foo() {}". If there are |
5793 | /// existing call uses of the old function in the module, this adjusts them to |
5794 | /// call the new function directly. |
5795 | /// |
5796 | /// This is not just a cleanup: the always_inline pass requires direct calls to |
5797 | /// functions to be able to inline them. If there is a bitcast in the way, it |
5798 | /// won't inline them. Instcombine normally deletes these calls, but it isn't |
5799 | /// run at -O0. |
5800 | static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, |
5801 | llvm::Function *NewFn) { |
5802 | // If we're redefining a global as a function, don't transform it. |
5803 | if (!isa<llvm::Function>(Val: Old)) return; |
5804 | |
5805 | replaceUsesOfNonProtoConstant(old: Old, newFn: NewFn); |
5806 | } |
5807 | |
5808 | void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { |
5809 | auto DK = VD->isThisDeclarationADefinition(); |
5810 | if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) |
5811 | return; |
5812 | |
5813 | TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); |
5814 | // If we have a definition, this might be a deferred decl. If the |
5815 | // instantiation is explicit, make sure we emit it at the end. |
5816 | if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) |
5817 | GetAddrOfGlobalVar(D: VD); |
5818 | |
5819 | EmitTopLevelDecl(VD); |
5820 | } |
5821 | |
5822 | void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, |
5823 | llvm::GlobalValue *GV) { |
5824 | const auto *D = cast<FunctionDecl>(Val: GD.getDecl()); |
5825 | |
5826 | // Compute the function info and LLVM type. |
5827 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
5828 | llvm::FunctionType *Ty = getTypes().GetFunctionType(Info: FI); |
5829 | |
5830 | // Get or create the prototype for the function. |
5831 | if (!GV || (GV->getValueType() != Ty)) |
5832 | GV = cast<llvm::GlobalValue>(Val: GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, |
5833 | /*DontDefer=*/true, |
5834 | IsForDefinition: ForDefinition)); |
5835 | |
5836 | // Already emitted. |
5837 | if (!GV->isDeclaration()) |
5838 | return; |
5839 | |
5840 | // We need to set linkage and visibility on the function before |
5841 | // generating code for it because various parts of IR generation |
5842 | // want to propagate this information down (e.g. to local static |
5843 | // declarations). |
5844 | auto *Fn = cast<llvm::Function>(Val: GV); |
5845 | setFunctionLinkage(GD, F: Fn); |
5846 | |
5847 | // FIXME: this is redundant with part of setFunctionDefinitionAttributes |
5848 | setGVProperties(GV: Fn, GD); |
5849 | |
5850 | MaybeHandleStaticInExternC(D, GV: Fn); |
5851 | |
5852 | maybeSetTrivialComdat(*D, *Fn); |
5853 | |
5854 | CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo: FI); |
5855 | |
5856 | setNonAliasAttributes(GD, GO: Fn); |
5857 | SetLLVMFunctionAttributesForDefinition(D, Fn); |
5858 | |
5859 | if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) |
5860 | AddGlobalCtor(Ctor: Fn, Priority: CA->getPriority()); |
5861 | if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) |
5862 | AddGlobalDtor(Dtor: Fn, Priority: DA->getPriority(), IsDtorAttrFunc: true); |
5863 | if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>()) |
5864 | getOpenMPRuntime().emitDeclareTargetFunction(FD: D, GV); |
5865 | } |
5866 | |
5867 | void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { |
5868 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
5869 | const AliasAttr *AA = D->getAttr<AliasAttr>(); |
5870 | assert(AA && "Not an alias?" ); |
5871 | |
5872 | StringRef MangledName = getMangledName(GD); |
5873 | |
5874 | if (AA->getAliasee() == MangledName) { |
5875 | Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; |
5876 | return; |
5877 | } |
5878 | |
5879 | // If there is a definition in the module, then it wins over the alias. |
5880 | // This is dubious, but allow it to be safe. Just ignore the alias. |
5881 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
5882 | if (Entry && !Entry->isDeclaration()) |
5883 | return; |
5884 | |
5885 | Aliases.push_back(x: GD); |
5886 | |
5887 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(T: D->getType()); |
5888 | |
5889 | // Create a reference to the named value. This ensures that it is emitted |
5890 | // if a deferred decl. |
5891 | llvm::Constant *Aliasee; |
5892 | llvm::GlobalValue::LinkageTypes LT; |
5893 | if (isa<llvm::FunctionType>(Val: DeclTy)) { |
5894 | Aliasee = GetOrCreateLLVMFunction(MangledName: AA->getAliasee(), Ty: DeclTy, GD, |
5895 | /*ForVTable=*/false); |
5896 | LT = getFunctionLinkage(GD); |
5897 | } else { |
5898 | Aliasee = GetOrCreateLLVMGlobal(MangledName: AA->getAliasee(), Ty: DeclTy, AddrSpace: LangAS::Default, |
5899 | /*D=*/nullptr); |
5900 | if (const auto *VD = dyn_cast<VarDecl>(Val: GD.getDecl())) |
5901 | LT = getLLVMLinkageVarDefinition(VD); |
5902 | else |
5903 | LT = getFunctionLinkage(GD); |
5904 | } |
5905 | |
5906 | // Create the new alias itself, but don't set a name yet. |
5907 | unsigned AS = Aliasee->getType()->getPointerAddressSpace(); |
5908 | auto *GA = |
5909 | llvm::GlobalAlias::create(Ty: DeclTy, AddressSpace: AS, Linkage: LT, Name: "" , Aliasee, Parent: &getModule()); |
5910 | |
5911 | if (Entry) { |
5912 | if (GA->getAliasee() == Entry) { |
5913 | Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; |
5914 | return; |
5915 | } |
5916 | |
5917 | assert(Entry->isDeclaration()); |
5918 | |
5919 | // If there is a declaration in the module, then we had an extern followed |
5920 | // by the alias, as in: |
5921 | // extern int test6(); |
5922 | // ... |
5923 | // int test6() __attribute__((alias("test7"))); |
5924 | // |
5925 | // Remove it and replace uses of it with the alias. |
5926 | GA->takeName(V: Entry); |
5927 | |
5928 | Entry->replaceAllUsesWith(V: GA); |
5929 | Entry->eraseFromParent(); |
5930 | } else { |
5931 | GA->setName(MangledName); |
5932 | } |
5933 | |
5934 | // Set attributes which are particular to an alias; this is a |
5935 | // specialization of the attributes which may be set on a global |
5936 | // variable/function. |
5937 | if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || |
5938 | D->isWeakImported()) { |
5939 | GA->setLinkage(llvm::Function::WeakAnyLinkage); |
5940 | } |
5941 | |
5942 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
5943 | if (VD->getTLSKind()) |
5944 | setTLSMode(GV: GA, D: *VD); |
5945 | |
5946 | SetCommonAttributes(GD, GV: GA); |
5947 | |
5948 | // Emit global alias debug information. |
5949 | if (isa<VarDecl>(Val: D)) |
5950 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
5951 | DI->EmitGlobalAlias(GV: cast<llvm::GlobalValue>(Val: GA->getAliasee()->stripPointerCasts()), Decl: GD); |
5952 | } |
5953 | |
5954 | void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { |
5955 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
5956 | const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); |
5957 | assert(IFA && "Not an ifunc?" ); |
5958 | |
5959 | StringRef MangledName = getMangledName(GD); |
5960 | |
5961 | if (IFA->getResolver() == MangledName) { |
5962 | Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; |
5963 | return; |
5964 | } |
5965 | |
5966 | // Report an error if some definition overrides ifunc. |
5967 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
5968 | if (Entry && !Entry->isDeclaration()) { |
5969 | GlobalDecl OtherGD; |
5970 | if (lookupRepresentativeDecl(MangledName, Result&: OtherGD) && |
5971 | DiagnosedConflictingDefinitions.insert(V: GD).second) { |
5972 | Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) |
5973 | << MangledName; |
5974 | Diags.Report(OtherGD.getDecl()->getLocation(), |
5975 | diag::note_previous_definition); |
5976 | } |
5977 | return; |
5978 | } |
5979 | |
5980 | Aliases.push_back(x: GD); |
5981 | |
5982 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(T: D->getType()); |
5983 | llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(IFuncValTy: DeclTy); |
5984 | llvm::Constant *Resolver = |
5985 | GetOrCreateLLVMFunction(MangledName: IFA->getResolver(), Ty: ResolverTy, GD: {}, |
5986 | /*ForVTable=*/false); |
5987 | llvm::GlobalIFunc *GIF = |
5988 | llvm::GlobalIFunc::create(Ty: DeclTy, AddressSpace: 0, Linkage: llvm::Function::ExternalLinkage, |
5989 | Name: "" , Resolver, Parent: &getModule()); |
5990 | if (Entry) { |
5991 | if (GIF->getResolver() == Entry) { |
5992 | Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; |
5993 | return; |
5994 | } |
5995 | assert(Entry->isDeclaration()); |
5996 | |
5997 | // If there is a declaration in the module, then we had an extern followed |
5998 | // by the ifunc, as in: |
5999 | // extern int test(); |
6000 | // ... |
6001 | // int test() __attribute__((ifunc("resolver"))); |
6002 | // |
6003 | // Remove it and replace uses of it with the ifunc. |
6004 | GIF->takeName(V: Entry); |
6005 | |
6006 | Entry->replaceAllUsesWith(V: GIF); |
6007 | Entry->eraseFromParent(); |
6008 | } else |
6009 | GIF->setName(MangledName); |
6010 | if (auto *F = dyn_cast<llvm::Function>(Resolver)) { |
6011 | F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation); |
6012 | } |
6013 | SetCommonAttributes(GD, GV: GIF); |
6014 | } |
6015 | |
6016 | llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, |
6017 | ArrayRef<llvm::Type*> Tys) { |
6018 | return llvm::Intrinsic::getDeclaration(M: &getModule(), id: (llvm::Intrinsic::ID)IID, |
6019 | Tys); |
6020 | } |
6021 | |
6022 | static llvm::StringMapEntry<llvm::GlobalVariable *> & |
6023 | GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, |
6024 | const StringLiteral *Literal, bool TargetIsLSB, |
6025 | bool &IsUTF16, unsigned &StringLength) { |
6026 | StringRef String = Literal->getString(); |
6027 | unsigned NumBytes = String.size(); |
6028 | |
6029 | // Check for simple case. |
6030 | if (!Literal->containsNonAsciiOrNull()) { |
6031 | StringLength = NumBytes; |
6032 | return *Map.insert(KV: std::make_pair(x&: String, y: nullptr)).first; |
6033 | } |
6034 | |
6035 | // Otherwise, convert the UTF8 literals into a string of shorts. |
6036 | IsUTF16 = true; |
6037 | |
6038 | SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. |
6039 | const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); |
6040 | llvm::UTF16 *ToPtr = &ToBuf[0]; |
6041 | |
6042 | (void)llvm::ConvertUTF8toUTF16(sourceStart: &FromPtr, sourceEnd: FromPtr + NumBytes, targetStart: &ToPtr, |
6043 | targetEnd: ToPtr + NumBytes, flags: llvm::strictConversion); |
6044 | |
6045 | // ConvertUTF8toUTF16 returns the length in ToPtr. |
6046 | StringLength = ToPtr - &ToBuf[0]; |
6047 | |
6048 | // Add an explicit null. |
6049 | *ToPtr = 0; |
6050 | return *Map.insert(KV: std::make_pair( |
6051 | x: StringRef(reinterpret_cast<const char *>(ToBuf.data()), |
6052 | (StringLength + 1) * 2), |
6053 | y: nullptr)).first; |
6054 | } |
6055 | |
6056 | ConstantAddress |
6057 | CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { |
6058 | unsigned StringLength = 0; |
6059 | bool isUTF16 = false; |
6060 | llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = |
6061 | GetConstantCFStringEntry(Map&: CFConstantStringMap, Literal, |
6062 | TargetIsLSB: getDataLayout().isLittleEndian(), IsUTF16&: isUTF16, |
6063 | StringLength); |
6064 | |
6065 | if (auto *C = Entry.second) |
6066 | return ConstantAddress( |
6067 | C, C->getValueType(), CharUnits::fromQuantity(Quantity: C->getAlignment())); |
6068 | |
6069 | llvm::Constant *Zero = llvm::Constant::getNullValue(Ty: Int32Ty); |
6070 | llvm::Constant *Zeros[] = { Zero, Zero }; |
6071 | |
6072 | const ASTContext &Context = getContext(); |
6073 | const llvm::Triple &Triple = getTriple(); |
6074 | |
6075 | const auto CFRuntime = getLangOpts().CFRuntime; |
6076 | const bool IsSwiftABI = |
6077 | static_cast<unsigned>(CFRuntime) >= |
6078 | static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); |
6079 | const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; |
6080 | |
6081 | // If we don't already have it, get __CFConstantStringClassReference. |
6082 | if (!CFConstantStringClassRef) { |
6083 | const char *CFConstantStringClassName = "__CFConstantStringClassReference" ; |
6084 | llvm::Type *Ty = getTypes().ConvertType(T: getContext().IntTy); |
6085 | Ty = llvm::ArrayType::get(ElementType: Ty, NumElements: 0); |
6086 | |
6087 | switch (CFRuntime) { |
6088 | default: break; |
6089 | case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; |
6090 | case LangOptions::CoreFoundationABI::Swift5_0: |
6091 | CFConstantStringClassName = |
6092 | Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" |
6093 | : "$s10Foundation19_NSCFConstantStringCN" ; |
6094 | Ty = IntPtrTy; |
6095 | break; |
6096 | case LangOptions::CoreFoundationABI::Swift4_2: |
6097 | CFConstantStringClassName = |
6098 | Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" |
6099 | : "$S10Foundation19_NSCFConstantStringCN" ; |
6100 | Ty = IntPtrTy; |
6101 | break; |
6102 | case LangOptions::CoreFoundationABI::Swift4_1: |
6103 | CFConstantStringClassName = |
6104 | Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" |
6105 | : "__T010Foundation19_NSCFConstantStringCN" ; |
6106 | Ty = IntPtrTy; |
6107 | break; |
6108 | } |
6109 | |
6110 | llvm::Constant *C = CreateRuntimeVariable(Ty, Name: CFConstantStringClassName); |
6111 | |
6112 | if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { |
6113 | llvm::GlobalValue *GV = nullptr; |
6114 | |
6115 | if ((GV = dyn_cast<llvm::GlobalValue>(Val: C))) { |
6116 | IdentifierInfo &II = Context.Idents.get(Name: GV->getName()); |
6117 | TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); |
6118 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(D: TUDecl); |
6119 | |
6120 | const VarDecl *VD = nullptr; |
6121 | for (const auto *Result : DC->lookup(Name: &II)) |
6122 | if ((VD = dyn_cast<VarDecl>(Val: Result))) |
6123 | break; |
6124 | |
6125 | if (Triple.isOSBinFormatELF()) { |
6126 | if (!VD) |
6127 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); |
6128 | } else { |
6129 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); |
6130 | if (!VD || !VD->hasAttr<DLLExportAttr>()) |
6131 | GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); |
6132 | else |
6133 | GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); |
6134 | } |
6135 | |
6136 | setDSOLocal(GV); |
6137 | } |
6138 | } |
6139 | |
6140 | // Decay array -> ptr |
6141 | CFConstantStringClassRef = |
6142 | IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) |
6143 | : llvm::ConstantExpr::getGetElementPtr(Ty, C, IdxList: Zeros); |
6144 | } |
6145 | |
6146 | QualType CFTy = Context.getCFConstantStringType(); |
6147 | |
6148 | auto *STy = cast<llvm::StructType>(Val: getTypes().ConvertType(T: CFTy)); |
6149 | |
6150 | ConstantInitBuilder Builder(*this); |
6151 | auto Fields = Builder.beginStruct(structTy: STy); |
6152 | |
6153 | // Class pointer. |
6154 | Fields.add(value: cast<llvm::Constant>(Val&: CFConstantStringClassRef)); |
6155 | |
6156 | // Flags. |
6157 | if (IsSwiftABI) { |
6158 | Fields.addInt(intTy: IntPtrTy, value: IsSwift4_1 ? 0x05 : 0x01); |
6159 | Fields.addInt(intTy: Int64Ty, value: isUTF16 ? 0x07d0 : 0x07c8); |
6160 | } else { |
6161 | Fields.addInt(intTy: IntTy, value: isUTF16 ? 0x07d0 : 0x07C8); |
6162 | } |
6163 | |
6164 | // String pointer. |
6165 | llvm::Constant *C = nullptr; |
6166 | if (isUTF16) { |
6167 | auto Arr = llvm::ArrayRef( |
6168 | reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), |
6169 | Entry.first().size() / 2); |
6170 | C = llvm::ConstantDataArray::get(Context&: VMContext, Elts: Arr); |
6171 | } else { |
6172 | C = llvm::ConstantDataArray::getString(Context&: VMContext, Initializer: Entry.first()); |
6173 | } |
6174 | |
6175 | // Note: -fwritable-strings doesn't make the backing store strings of |
6176 | // CFStrings writable. |
6177 | auto *GV = |
6178 | new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, |
6179 | llvm::GlobalValue::PrivateLinkage, C, ".str" ); |
6180 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
6181 | // Don't enforce the target's minimum global alignment, since the only use |
6182 | // of the string is via this class initializer. |
6183 | CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) |
6184 | : Context.getTypeAlignInChars(Context.CharTy); |
6185 | GV->setAlignment(Align.getAsAlign()); |
6186 | |
6187 | // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. |
6188 | // Without it LLVM can merge the string with a non unnamed_addr one during |
6189 | // LTO. Doing that changes the section it ends in, which surprises ld64. |
6190 | if (Triple.isOSBinFormatMachO()) |
6191 | GV->setSection(isUTF16 ? "__TEXT,__ustring" |
6192 | : "__TEXT,__cstring,cstring_literals" ); |
6193 | // Make sure the literal ends up in .rodata to allow for safe ICF and for |
6194 | // the static linker to adjust permissions to read-only later on. |
6195 | else if (Triple.isOSBinFormatELF()) |
6196 | GV->setSection(".rodata" ); |
6197 | |
6198 | // String. |
6199 | llvm::Constant *Str = |
6200 | llvm::ConstantExpr::getGetElementPtr(Ty: GV->getValueType(), C: GV, IdxList: Zeros); |
6201 | |
6202 | Fields.add(value: Str); |
6203 | |
6204 | // String length. |
6205 | llvm::IntegerType *LengthTy = |
6206 | llvm::IntegerType::get(C&: getModule().getContext(), |
6207 | NumBits: Context.getTargetInfo().getLongWidth()); |
6208 | if (IsSwiftABI) { |
6209 | if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || |
6210 | CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) |
6211 | LengthTy = Int32Ty; |
6212 | else |
6213 | LengthTy = IntPtrTy; |
6214 | } |
6215 | Fields.addInt(intTy: LengthTy, value: StringLength); |
6216 | |
6217 | // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is |
6218 | // properly aligned on 32-bit platforms. |
6219 | CharUnits Alignment = |
6220 | IsSwiftABI ? Context.toCharUnitsFromBits(BitSize: 64) : getPointerAlign(); |
6221 | |
6222 | // The struct. |
6223 | GV = Fields.finishAndCreateGlobal(args: "_unnamed_cfstring_" , args&: Alignment, |
6224 | /*isConstant=*/args: false, |
6225 | args: llvm::GlobalVariable::PrivateLinkage); |
6226 | GV->addAttribute(Kind: "objc_arc_inert" ); |
6227 | switch (Triple.getObjectFormat()) { |
6228 | case llvm::Triple::UnknownObjectFormat: |
6229 | llvm_unreachable("unknown file format" ); |
6230 | case llvm::Triple::DXContainer: |
6231 | case llvm::Triple::GOFF: |
6232 | case llvm::Triple::SPIRV: |
6233 | case llvm::Triple::XCOFF: |
6234 | llvm_unreachable("unimplemented" ); |
6235 | case llvm::Triple::COFF: |
6236 | case llvm::Triple::ELF: |
6237 | case llvm::Triple::Wasm: |
6238 | GV->setSection("cfstring" ); |
6239 | break; |
6240 | case llvm::Triple::MachO: |
6241 | GV->setSection("__DATA,__cfstring" ); |
6242 | break; |
6243 | } |
6244 | Entry.second = GV; |
6245 | |
6246 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
6247 | } |
6248 | |
6249 | bool CodeGenModule::getExpressionLocationsEnabled() const { |
6250 | return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; |
6251 | } |
6252 | |
6253 | QualType CodeGenModule::getObjCFastEnumerationStateType() { |
6254 | if (ObjCFastEnumerationStateType.isNull()) { |
6255 | RecordDecl *D = Context.buildImplicitRecord(Name: "__objcFastEnumerationState" ); |
6256 | D->startDefinition(); |
6257 | |
6258 | QualType FieldTypes[] = { |
6259 | Context.UnsignedLongTy, Context.getPointerType(T: Context.getObjCIdType()), |
6260 | Context.getPointerType(Context.UnsignedLongTy), |
6261 | Context.getConstantArrayType(EltTy: Context.UnsignedLongTy, ArySize: llvm::APInt(32, 5), |
6262 | SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0)}; |
6263 | |
6264 | for (size_t i = 0; i < 4; ++i) { |
6265 | FieldDecl *Field = FieldDecl::Create(C: Context, |
6266 | DC: D, |
6267 | StartLoc: SourceLocation(), |
6268 | IdLoc: SourceLocation(), Id: nullptr, |
6269 | T: FieldTypes[i], /*TInfo=*/nullptr, |
6270 | /*BitWidth=*/BW: nullptr, |
6271 | /*Mutable=*/false, |
6272 | InitStyle: ICIS_NoInit); |
6273 | Field->setAccess(AS_public); |
6274 | D->addDecl(Field); |
6275 | } |
6276 | |
6277 | D->completeDefinition(); |
6278 | ObjCFastEnumerationStateType = Context.getTagDeclType(D); |
6279 | } |
6280 | |
6281 | return ObjCFastEnumerationStateType; |
6282 | } |
6283 | |
6284 | llvm::Constant * |
6285 | CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { |
6286 | assert(!E->getType()->isPointerType() && "Strings are always arrays" ); |
6287 | |
6288 | // Don't emit it as the address of the string, emit the string data itself |
6289 | // as an inline array. |
6290 | if (E->getCharByteWidth() == 1) { |
6291 | SmallString<64> Str(E->getString()); |
6292 | |
6293 | // Resize the string to the right size, which is indicated by its type. |
6294 | const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: E->getType()); |
6295 | assert(CAT && "String literal not of constant array type!" ); |
6296 | Str.resize(N: CAT->getSize().getZExtValue()); |
6297 | return llvm::ConstantDataArray::getString(Context&: VMContext, Initializer: Str, AddNull: false); |
6298 | } |
6299 | |
6300 | auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(T: E->getType())); |
6301 | llvm::Type *ElemTy = AType->getElementType(); |
6302 | unsigned NumElements = AType->getNumElements(); |
6303 | |
6304 | // Wide strings have either 2-byte or 4-byte elements. |
6305 | if (ElemTy->getPrimitiveSizeInBits() == 16) { |
6306 | SmallVector<uint16_t, 32> Elements; |
6307 | Elements.reserve(N: NumElements); |
6308 | |
6309 | for(unsigned i = 0, e = E->getLength(); i != e; ++i) |
6310 | Elements.push_back(Elt: E->getCodeUnit(i)); |
6311 | Elements.resize(N: NumElements); |
6312 | return llvm::ConstantDataArray::get(Context&: VMContext, Elts&: Elements); |
6313 | } |
6314 | |
6315 | assert(ElemTy->getPrimitiveSizeInBits() == 32); |
6316 | SmallVector<uint32_t, 32> Elements; |
6317 | Elements.reserve(N: NumElements); |
6318 | |
6319 | for(unsigned i = 0, e = E->getLength(); i != e; ++i) |
6320 | Elements.push_back(Elt: E->getCodeUnit(i)); |
6321 | Elements.resize(N: NumElements); |
6322 | return llvm::ConstantDataArray::get(Context&: VMContext, Elts&: Elements); |
6323 | } |
6324 | |
6325 | static llvm::GlobalVariable * |
6326 | GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, |
6327 | CodeGenModule &CGM, StringRef GlobalName, |
6328 | CharUnits Alignment) { |
6329 | unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( |
6330 | AS: CGM.GetGlobalConstantAddressSpace()); |
6331 | |
6332 | llvm::Module &M = CGM.getModule(); |
6333 | // Create a global variable for this string |
6334 | auto *GV = new llvm::GlobalVariable( |
6335 | M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, |
6336 | nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); |
6337 | GV->setAlignment(Alignment.getAsAlign()); |
6338 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
6339 | if (GV->isWeakForLinker()) { |
6340 | assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals" ); |
6341 | GV->setComdat(M.getOrInsertComdat(Name: GV->getName())); |
6342 | } |
6343 | CGM.setDSOLocal(GV); |
6344 | |
6345 | return GV; |
6346 | } |
6347 | |
6348 | /// GetAddrOfConstantStringFromLiteral - Return a pointer to a |
6349 | /// constant array for the given string literal. |
6350 | ConstantAddress |
6351 | CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, |
6352 | StringRef Name) { |
6353 | CharUnits Alignment = |
6354 | getContext().getAlignOfGlobalVarInChars(T: S->getType(), /*VD=*/nullptr); |
6355 | |
6356 | llvm::Constant *C = GetConstantArrayFromStringLiteral(E: S); |
6357 | llvm::GlobalVariable **Entry = nullptr; |
6358 | if (!LangOpts.WritableStrings) { |
6359 | Entry = &ConstantStringMap[C]; |
6360 | if (auto GV = *Entry) { |
6361 | if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) |
6362 | GV->setAlignment(Alignment.getAsAlign()); |
6363 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(CGM&: *this, GV), |
6364 | GV->getValueType(), Alignment); |
6365 | } |
6366 | } |
6367 | |
6368 | SmallString<256> MangledNameBuffer; |
6369 | StringRef GlobalVariableName; |
6370 | llvm::GlobalValue::LinkageTypes LT; |
6371 | |
6372 | // Mangle the string literal if that's how the ABI merges duplicate strings. |
6373 | // Don't do it if they are writable, since we don't want writes in one TU to |
6374 | // affect strings in another. |
6375 | if (getCXXABI().getMangleContext().shouldMangleStringLiteral(SL: S) && |
6376 | !LangOpts.WritableStrings) { |
6377 | llvm::raw_svector_ostream Out(MangledNameBuffer); |
6378 | getCXXABI().getMangleContext().mangleStringLiteral(SL: S, Out); |
6379 | LT = llvm::GlobalValue::LinkOnceODRLinkage; |
6380 | GlobalVariableName = MangledNameBuffer; |
6381 | } else { |
6382 | LT = llvm::GlobalValue::PrivateLinkage; |
6383 | GlobalVariableName = Name; |
6384 | } |
6385 | |
6386 | auto GV = GenerateStringLiteral(C, LT, CGM&: *this, GlobalName: GlobalVariableName, Alignment); |
6387 | |
6388 | CGDebugInfo *DI = getModuleDebugInfo(); |
6389 | if (DI && getCodeGenOpts().hasReducedDebugInfo()) |
6390 | DI->AddStringLiteralDebugInfo(GV: GV, S); |
6391 | |
6392 | if (Entry) |
6393 | *Entry = GV; |
6394 | |
6395 | SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(TokNum: 0), "<string literal>" ); |
6396 | |
6397 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), |
6398 | GV->getValueType(), Alignment); |
6399 | } |
6400 | |
6401 | /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant |
6402 | /// array for the given ObjCEncodeExpr node. |
6403 | ConstantAddress |
6404 | CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { |
6405 | std::string Str; |
6406 | getContext().getObjCEncodingForType(T: E->getEncodedType(), S&: Str); |
6407 | |
6408 | return GetAddrOfConstantCString(Str); |
6409 | } |
6410 | |
6411 | /// GetAddrOfConstantCString - Returns a pointer to a character array containing |
6412 | /// the literal and a terminating '\0' character. |
6413 | /// The result has pointer to array type. |
6414 | ConstantAddress CodeGenModule::GetAddrOfConstantCString( |
6415 | const std::string &Str, const char *GlobalName) { |
6416 | StringRef StrWithNull(Str.c_str(), Str.size() + 1); |
6417 | CharUnits Alignment = getContext().getAlignOfGlobalVarInChars( |
6418 | T: getContext().CharTy, /*VD=*/nullptr); |
6419 | |
6420 | llvm::Constant *C = |
6421 | llvm::ConstantDataArray::getString(Context&: getLLVMContext(), Initializer: StrWithNull, AddNull: false); |
6422 | |
6423 | // Don't share any string literals if strings aren't constant. |
6424 | llvm::GlobalVariable **Entry = nullptr; |
6425 | if (!LangOpts.WritableStrings) { |
6426 | Entry = &ConstantStringMap[C]; |
6427 | if (auto GV = *Entry) { |
6428 | if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) |
6429 | GV->setAlignment(Alignment.getAsAlign()); |
6430 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(CGM&: *this, GV), |
6431 | GV->getValueType(), Alignment); |
6432 | } |
6433 | } |
6434 | |
6435 | // Get the default prefix if a name wasn't specified. |
6436 | if (!GlobalName) |
6437 | GlobalName = ".str" ; |
6438 | // Create a global variable for this. |
6439 | auto GV = GenerateStringLiteral(C, LT: llvm::GlobalValue::PrivateLinkage, CGM&: *this, |
6440 | GlobalName, Alignment); |
6441 | if (Entry) |
6442 | *Entry = GV; |
6443 | |
6444 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), |
6445 | GV->getValueType(), Alignment); |
6446 | } |
6447 | |
6448 | ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( |
6449 | const MaterializeTemporaryExpr *E, const Expr *Init) { |
6450 | assert((E->getStorageDuration() == SD_Static || |
6451 | E->getStorageDuration() == SD_Thread) && "not a global temporary" ); |
6452 | const auto *VD = cast<VarDecl>(Val: E->getExtendingDecl()); |
6453 | |
6454 | // If we're not materializing a subobject of the temporary, keep the |
6455 | // cv-qualifiers from the type of the MaterializeTemporaryExpr. |
6456 | QualType MaterializedType = Init->getType(); |
6457 | if (Init == E->getSubExpr()) |
6458 | MaterializedType = E->getType(); |
6459 | |
6460 | CharUnits Align = getContext().getTypeAlignInChars(T: MaterializedType); |
6461 | |
6462 | auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); |
6463 | if (!InsertResult.second) { |
6464 | // We've seen this before: either we already created it or we're in the |
6465 | // process of doing so. |
6466 | if (!InsertResult.first->second) { |
6467 | // We recursively re-entered this function, probably during emission of |
6468 | // the initializer. Create a placeholder. We'll clean this up in the |
6469 | // outer call, at the end of this function. |
6470 | llvm::Type *Type = getTypes().ConvertTypeForMem(T: MaterializedType); |
6471 | InsertResult.first->second = new llvm::GlobalVariable( |
6472 | getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, |
6473 | nullptr); |
6474 | } |
6475 | return ConstantAddress(InsertResult.first->second, |
6476 | llvm::cast<llvm::GlobalVariable>( |
6477 | InsertResult.first->second->stripPointerCasts()) |
6478 | ->getValueType(), |
6479 | Align); |
6480 | } |
6481 | |
6482 | // FIXME: If an externally-visible declaration extends multiple temporaries, |
6483 | // we need to give each temporary the same name in every translation unit (and |
6484 | // we also need to make the temporaries externally-visible). |
6485 | SmallString<256> Name; |
6486 | llvm::raw_svector_ostream Out(Name); |
6487 | getCXXABI().getMangleContext().mangleReferenceTemporary( |
6488 | D: VD, ManglingNumber: E->getManglingNumber(), Out); |
6489 | |
6490 | APValue *Value = nullptr; |
6491 | if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) { |
6492 | // If the initializer of the extending declaration is a constant |
6493 | // initializer, we should have a cached constant initializer for this |
6494 | // temporary. Note that this might have a different value from the value |
6495 | // computed by evaluating the initializer if the surrounding constant |
6496 | // expression modifies the temporary. |
6497 | Value = E->getOrCreateValue(MayCreate: false); |
6498 | } |
6499 | |
6500 | // Try evaluating it now, it might have a constant initializer. |
6501 | Expr::EvalResult EvalResult; |
6502 | if (!Value && Init->EvaluateAsRValue(Result&: EvalResult, Ctx: getContext()) && |
6503 | !EvalResult.hasSideEffects()) |
6504 | Value = &EvalResult.Val; |
6505 | |
6506 | LangAS AddrSpace = GetGlobalVarAddressSpace(D: VD); |
6507 | |
6508 | std::optional<ConstantEmitter> emitter; |
6509 | llvm::Constant *InitialValue = nullptr; |
6510 | bool Constant = false; |
6511 | llvm::Type *Type; |
6512 | if (Value) { |
6513 | // The temporary has a constant initializer, use it. |
6514 | emitter.emplace(args&: *this); |
6515 | InitialValue = emitter->emitForInitializer(value: *Value, destAddrSpace: AddrSpace, |
6516 | destType: MaterializedType); |
6517 | Constant = |
6518 | MaterializedType.isConstantStorage(Ctx: getContext(), /*ExcludeCtor*/ Value, |
6519 | /*ExcludeDtor*/ false); |
6520 | Type = InitialValue->getType(); |
6521 | } else { |
6522 | // No initializer, the initialization will be provided when we |
6523 | // initialize the declaration which performed lifetime extension. |
6524 | Type = getTypes().ConvertTypeForMem(T: MaterializedType); |
6525 | } |
6526 | |
6527 | // Create a global variable for this lifetime-extended temporary. |
6528 | llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD); |
6529 | if (Linkage == llvm::GlobalVariable::ExternalLinkage) { |
6530 | const VarDecl *InitVD; |
6531 | if (VD->isStaticDataMember() && VD->getAnyInitializer(D&: InitVD) && |
6532 | isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { |
6533 | // Temporaries defined inside a class get linkonce_odr linkage because the |
6534 | // class can be defined in multiple translation units. |
6535 | Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; |
6536 | } else { |
6537 | // There is no need for this temporary to have external linkage if the |
6538 | // VarDecl has external linkage. |
6539 | Linkage = llvm::GlobalVariable::InternalLinkage; |
6540 | } |
6541 | } |
6542 | auto TargetAS = getContext().getTargetAddressSpace(AS: AddrSpace); |
6543 | auto *GV = new llvm::GlobalVariable( |
6544 | getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), |
6545 | /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); |
6546 | if (emitter) emitter->finalize(global: GV); |
6547 | // Don't assign dllimport or dllexport to local linkage globals. |
6548 | if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { |
6549 | setGVProperties(GV, GD: VD); |
6550 | if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) |
6551 | // The reference temporary should never be dllexport. |
6552 | GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); |
6553 | } |
6554 | GV->setAlignment(Align.getAsAlign()); |
6555 | if (supportsCOMDAT() && GV->isWeakForLinker()) |
6556 | GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName())); |
6557 | if (VD->getTLSKind()) |
6558 | setTLSMode(GV, D: *VD); |
6559 | llvm::Constant *CV = GV; |
6560 | if (AddrSpace != LangAS::Default) |
6561 | CV = getTargetCodeGenInfo().performAddrSpaceCast( |
6562 | CGM&: *this, V: GV, SrcAddr: AddrSpace, DestAddr: LangAS::Default, |
6563 | DestTy: llvm::PointerType::get( |
6564 | C&: getLLVMContext(), |
6565 | AddressSpace: getContext().getTargetAddressSpace(AS: LangAS::Default))); |
6566 | |
6567 | // Update the map with the new temporary. If we created a placeholder above, |
6568 | // replace it with the new global now. |
6569 | llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; |
6570 | if (Entry) { |
6571 | Entry->replaceAllUsesWith(V: CV); |
6572 | llvm::cast<llvm::GlobalVariable>(Val: Entry)->eraseFromParent(); |
6573 | } |
6574 | Entry = CV; |
6575 | |
6576 | return ConstantAddress(CV, Type, Align); |
6577 | } |
6578 | |
6579 | /// EmitObjCPropertyImplementations - Emit information for synthesized |
6580 | /// properties for an implementation. |
6581 | void CodeGenModule::EmitObjCPropertyImplementations(const |
6582 | ObjCImplementationDecl *D) { |
6583 | for (const auto *PID : D->property_impls()) { |
6584 | // Dynamic is just for type-checking. |
6585 | if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { |
6586 | ObjCPropertyDecl *PD = PID->getPropertyDecl(); |
6587 | |
6588 | // Determine which methods need to be implemented, some may have |
6589 | // been overridden. Note that ::isPropertyAccessor is not the method |
6590 | // we want, that just indicates if the decl came from a |
6591 | // property. What we want to know is if the method is defined in |
6592 | // this implementation. |
6593 | auto *Getter = PID->getGetterMethodDecl(); |
6594 | if (!Getter || Getter->isSynthesizedAccessorStub()) |
6595 | CodeGenFunction(*this).GenerateObjCGetter( |
6596 | const_cast<ObjCImplementationDecl *>(D), PID); |
6597 | auto *Setter = PID->getSetterMethodDecl(); |
6598 | if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) |
6599 | CodeGenFunction(*this).GenerateObjCSetter( |
6600 | const_cast<ObjCImplementationDecl *>(D), PID); |
6601 | } |
6602 | } |
6603 | } |
6604 | |
6605 | static bool needsDestructMethod(ObjCImplementationDecl *impl) { |
6606 | const ObjCInterfaceDecl *iface = impl->getClassInterface(); |
6607 | for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); |
6608 | ivar; ivar = ivar->getNextIvar()) |
6609 | if (ivar->getType().isDestructedType()) |
6610 | return true; |
6611 | |
6612 | return false; |
6613 | } |
6614 | |
6615 | static bool AllTrivialInitializers(CodeGenModule &CGM, |
6616 | ObjCImplementationDecl *D) { |
6617 | CodeGenFunction CGF(CGM); |
6618 | for (ObjCImplementationDecl::init_iterator B = D->init_begin(), |
6619 | E = D->init_end(); B != E; ++B) { |
6620 | CXXCtorInitializer *CtorInitExp = *B; |
6621 | Expr *Init = CtorInitExp->getInit(); |
6622 | if (!CGF.isTrivialInitializer(Init)) |
6623 | return false; |
6624 | } |
6625 | return true; |
6626 | } |
6627 | |
6628 | /// EmitObjCIvarInitializations - Emit information for ivar initialization |
6629 | /// for an implementation. |
6630 | void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { |
6631 | // We might need a .cxx_destruct even if we don't have any ivar initializers. |
6632 | if (needsDestructMethod(impl: D)) { |
6633 | IdentifierInfo *II = &getContext().Idents.get(Name: ".cxx_destruct" ); |
6634 | Selector cxxSelector = getContext().Selectors.getSelector(NumArgs: 0, IIV: &II); |
6635 | ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( |
6636 | C&: getContext(), beginLoc: D->getLocation(), endLoc: D->getLocation(), SelInfo: cxxSelector, |
6637 | T: getContext().VoidTy, ReturnTInfo: nullptr, contextDecl: D, |
6638 | /*isInstance=*/true, /*isVariadic=*/false, |
6639 | /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, |
6640 | /*isImplicitlyDeclared=*/true, |
6641 | /*isDefined=*/false, impControl: ObjCImplementationControl::Required); |
6642 | D->addInstanceMethod(DTORMethod); |
6643 | CodeGenFunction(*this).GenerateObjCCtorDtorMethod(IMP: D, MD: DTORMethod, ctor: false); |
6644 | D->setHasDestructors(true); |
6645 | } |
6646 | |
6647 | // If the implementation doesn't have any ivar initializers, we don't need |
6648 | // a .cxx_construct. |
6649 | if (D->getNumIvarInitializers() == 0 || |
6650 | AllTrivialInitializers(CGM&: *this, D)) |
6651 | return; |
6652 | |
6653 | IdentifierInfo *II = &getContext().Idents.get(Name: ".cxx_construct" ); |
6654 | Selector cxxSelector = getContext().Selectors.getSelector(NumArgs: 0, IIV: &II); |
6655 | // The constructor returns 'self'. |
6656 | ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( |
6657 | C&: getContext(), beginLoc: D->getLocation(), endLoc: D->getLocation(), SelInfo: cxxSelector, |
6658 | T: getContext().getObjCIdType(), ReturnTInfo: nullptr, contextDecl: D, /*isInstance=*/true, |
6659 | /*isVariadic=*/false, |
6660 | /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, |
6661 | /*isImplicitlyDeclared=*/true, |
6662 | /*isDefined=*/false, impControl: ObjCImplementationControl::Required); |
6663 | D->addInstanceMethod(CTORMethod); |
6664 | CodeGenFunction(*this).GenerateObjCCtorDtorMethod(IMP: D, MD: CTORMethod, ctor: true); |
6665 | D->setHasNonZeroConstructors(true); |
6666 | } |
6667 | |
6668 | // EmitLinkageSpec - Emit all declarations in a linkage spec. |
6669 | void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { |
6670 | if (LSD->getLanguage() != LinkageSpecLanguageIDs::C && |
6671 | LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) { |
6672 | ErrorUnsupported(LSD, "linkage spec" ); |
6673 | return; |
6674 | } |
6675 | |
6676 | EmitDeclContext(LSD); |
6677 | } |
6678 | |
6679 | void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { |
6680 | // Device code should not be at top level. |
6681 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) |
6682 | return; |
6683 | |
6684 | std::unique_ptr<CodeGenFunction> &CurCGF = |
6685 | GlobalTopLevelStmtBlockInFlight.first; |
6686 | |
6687 | // We emitted a top-level stmt but after it there is initialization. |
6688 | // Stop squashing the top-level stmts into a single function. |
6689 | if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { |
6690 | CurCGF->FinishFunction(EndLoc: D->getEndLoc()); |
6691 | CurCGF = nullptr; |
6692 | } |
6693 | |
6694 | if (!CurCGF) { |
6695 | // void __stmts__N(void) |
6696 | // FIXME: Ask the ABI name mangler to pick a name. |
6697 | std::string Name = "__stmts__" + llvm::utostr(X: CXXGlobalInits.size()); |
6698 | FunctionArgList Args; |
6699 | QualType RetTy = getContext().VoidTy; |
6700 | const CGFunctionInfo &FnInfo = |
6701 | getTypes().arrangeBuiltinFunctionDeclaration(resultType: RetTy, args: Args); |
6702 | llvm::FunctionType *FnTy = getTypes().GetFunctionType(Info: FnInfo); |
6703 | llvm::Function *Fn = llvm::Function::Create( |
6704 | Ty: FnTy, Linkage: llvm::GlobalValue::InternalLinkage, N: Name, M: &getModule()); |
6705 | |
6706 | CurCGF.reset(p: new CodeGenFunction(*this)); |
6707 | GlobalTopLevelStmtBlockInFlight.second = D; |
6708 | CurCGF->StartFunction(GD: GlobalDecl(), RetTy, Fn, FnInfo, Args, |
6709 | Loc: D->getBeginLoc(), StartLoc: D->getBeginLoc()); |
6710 | CXXGlobalInits.push_back(x: Fn); |
6711 | } |
6712 | |
6713 | CurCGF->EmitStmt(S: D->getStmt()); |
6714 | } |
6715 | |
6716 | void CodeGenModule::EmitDeclContext(const DeclContext *DC) { |
6717 | for (auto *I : DC->decls()) { |
6718 | // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope |
6719 | // are themselves considered "top-level", so EmitTopLevelDecl on an |
6720 | // ObjCImplDecl does not recursively visit them. We need to do that in |
6721 | // case they're nested inside another construct (LinkageSpecDecl / |
6722 | // ExportDecl) that does stop them from being considered "top-level". |
6723 | if (auto *OID = dyn_cast<ObjCImplDecl>(Val: I)) { |
6724 | for (auto *M : OID->methods()) |
6725 | EmitTopLevelDecl(M); |
6726 | } |
6727 | |
6728 | EmitTopLevelDecl(D: I); |
6729 | } |
6730 | } |
6731 | |
6732 | /// EmitTopLevelDecl - Emit code for a single top level declaration. |
6733 | void CodeGenModule::EmitTopLevelDecl(Decl *D) { |
6734 | // Ignore dependent declarations. |
6735 | if (D->isTemplated()) |
6736 | return; |
6737 | |
6738 | // Consteval function shouldn't be emitted. |
6739 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D); FD && FD->isImmediateFunction()) |
6740 | return; |
6741 | |
6742 | switch (D->getKind()) { |
6743 | case Decl::CXXConversion: |
6744 | case Decl::CXXMethod: |
6745 | case Decl::Function: |
6746 | EmitGlobal(GD: cast<FunctionDecl>(Val: D)); |
6747 | // Always provide some coverage mapping |
6748 | // even for the functions that aren't emitted. |
6749 | AddDeferredUnusedCoverageMapping(D); |
6750 | break; |
6751 | |
6752 | case Decl::CXXDeductionGuide: |
6753 | // Function-like, but does not result in code emission. |
6754 | break; |
6755 | |
6756 | case Decl::Var: |
6757 | case Decl::Decomposition: |
6758 | case Decl::VarTemplateSpecialization: |
6759 | EmitGlobal(GD: cast<VarDecl>(Val: D)); |
6760 | if (auto *DD = dyn_cast<DecompositionDecl>(Val: D)) |
6761 | for (auto *B : DD->bindings()) |
6762 | if (auto *HD = B->getHoldingVar()) |
6763 | EmitGlobal(GD: HD); |
6764 | break; |
6765 | |
6766 | // Indirect fields from global anonymous structs and unions can be |
6767 | // ignored; only the actual variable requires IR gen support. |
6768 | case Decl::IndirectField: |
6769 | break; |
6770 | |
6771 | // C++ Decls |
6772 | case Decl::Namespace: |
6773 | EmitDeclContext(cast<NamespaceDecl>(Val: D)); |
6774 | break; |
6775 | case Decl::ClassTemplateSpecialization: { |
6776 | const auto *Spec = cast<ClassTemplateSpecializationDecl>(Val: D); |
6777 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6778 | if (Spec->getSpecializationKind() == |
6779 | TSK_ExplicitInstantiationDefinition && |
6780 | Spec->hasDefinition()) |
6781 | DI->completeTemplateDefinition(SD: *Spec); |
6782 | } [[fallthrough]]; |
6783 | case Decl::CXXRecord: { |
6784 | CXXRecordDecl *CRD = cast<CXXRecordDecl>(Val: D); |
6785 | if (CGDebugInfo *DI = getModuleDebugInfo()) { |
6786 | if (CRD->hasDefinition()) |
6787 | DI->EmitAndRetainType(Ty: getContext().getRecordType(Decl: cast<RecordDecl>(Val: D))); |
6788 | if (auto *ES = D->getASTContext().getExternalSource()) |
6789 | if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) |
6790 | DI->completeUnusedClass(D: *CRD); |
6791 | } |
6792 | // Emit any static data members, they may be definitions. |
6793 | for (auto *I : CRD->decls()) |
6794 | if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) |
6795 | EmitTopLevelDecl(I); |
6796 | break; |
6797 | } |
6798 | // No code generation needed. |
6799 | case Decl::UsingShadow: |
6800 | case Decl::ClassTemplate: |
6801 | case Decl::VarTemplate: |
6802 | case Decl::Concept: |
6803 | case Decl::VarTemplatePartialSpecialization: |
6804 | case Decl::FunctionTemplate: |
6805 | case Decl::TypeAliasTemplate: |
6806 | case Decl::Block: |
6807 | case Decl::Empty: |
6808 | case Decl::Binding: |
6809 | break; |
6810 | case Decl::Using: // using X; [C++] |
6811 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6812 | DI->EmitUsingDecl(UD: cast<UsingDecl>(Val&: *D)); |
6813 | break; |
6814 | case Decl::UsingEnum: // using enum X; [C++] |
6815 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6816 | DI->EmitUsingEnumDecl(UD: cast<UsingEnumDecl>(Val&: *D)); |
6817 | break; |
6818 | case Decl::NamespaceAlias: |
6819 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6820 | DI->EmitNamespaceAlias(NA: cast<NamespaceAliasDecl>(Val&: *D)); |
6821 | break; |
6822 | case Decl::UsingDirective: // using namespace X; [C++] |
6823 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6824 | DI->EmitUsingDirective(UD: cast<UsingDirectiveDecl>(Val&: *D)); |
6825 | break; |
6826 | case Decl::CXXConstructor: |
6827 | getCXXABI().EmitCXXConstructors(D: cast<CXXConstructorDecl>(Val: D)); |
6828 | break; |
6829 | case Decl::CXXDestructor: |
6830 | getCXXABI().EmitCXXDestructors(D: cast<CXXDestructorDecl>(Val: D)); |
6831 | break; |
6832 | |
6833 | case Decl::StaticAssert: |
6834 | // Nothing to do. |
6835 | break; |
6836 | |
6837 | // Objective-C Decls |
6838 | |
6839 | // Forward declarations, no (immediate) code generation. |
6840 | case Decl::ObjCInterface: |
6841 | case Decl::ObjCCategory: |
6842 | break; |
6843 | |
6844 | case Decl::ObjCProtocol: { |
6845 | auto *Proto = cast<ObjCProtocolDecl>(Val: D); |
6846 | if (Proto->isThisDeclarationADefinition()) |
6847 | ObjCRuntime->GenerateProtocol(OPD: Proto); |
6848 | break; |
6849 | } |
6850 | |
6851 | case Decl::ObjCCategoryImpl: |
6852 | // Categories have properties but don't support synthesize so we |
6853 | // can ignore them here. |
6854 | ObjCRuntime->GenerateCategory(OCD: cast<ObjCCategoryImplDecl>(Val: D)); |
6855 | break; |
6856 | |
6857 | case Decl::ObjCImplementation: { |
6858 | auto *OMD = cast<ObjCImplementationDecl>(Val: D); |
6859 | EmitObjCPropertyImplementations(D: OMD); |
6860 | EmitObjCIvarInitializations(D: OMD); |
6861 | ObjCRuntime->GenerateClass(OID: OMD); |
6862 | // Emit global variable debug information. |
6863 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6864 | if (getCodeGenOpts().hasReducedDebugInfo()) |
6865 | DI->getOrCreateInterfaceType(Ty: getContext().getObjCInterfaceType( |
6866 | Decl: OMD->getClassInterface()), Loc: OMD->getLocation()); |
6867 | break; |
6868 | } |
6869 | case Decl::ObjCMethod: { |
6870 | auto *OMD = cast<ObjCMethodDecl>(Val: D); |
6871 | // If this is not a prototype, emit the body. |
6872 | if (OMD->getBody()) |
6873 | CodeGenFunction(*this).GenerateObjCMethod(OMD); |
6874 | break; |
6875 | } |
6876 | case Decl::ObjCCompatibleAlias: |
6877 | ObjCRuntime->RegisterAlias(OAD: cast<ObjCCompatibleAliasDecl>(Val: D)); |
6878 | break; |
6879 | |
6880 | case Decl::PragmaComment: { |
6881 | const auto *PCD = cast<PragmaCommentDecl>(Val: D); |
6882 | switch (PCD->getCommentKind()) { |
6883 | case PCK_Unknown: |
6884 | llvm_unreachable("unexpected pragma comment kind" ); |
6885 | case PCK_Linker: |
6886 | AppendLinkerOptions(Opts: PCD->getArg()); |
6887 | break; |
6888 | case PCK_Lib: |
6889 | AddDependentLib(Lib: PCD->getArg()); |
6890 | break; |
6891 | case PCK_Compiler: |
6892 | case PCK_ExeStr: |
6893 | case PCK_User: |
6894 | break; // We ignore all of these. |
6895 | } |
6896 | break; |
6897 | } |
6898 | |
6899 | case Decl::PragmaDetectMismatch: { |
6900 | const auto *PDMD = cast<PragmaDetectMismatchDecl>(Val: D); |
6901 | AddDetectMismatch(Name: PDMD->getName(), Value: PDMD->getValue()); |
6902 | break; |
6903 | } |
6904 | |
6905 | case Decl::LinkageSpec: |
6906 | EmitLinkageSpec(LSD: cast<LinkageSpecDecl>(Val: D)); |
6907 | break; |
6908 | |
6909 | case Decl::FileScopeAsm: { |
6910 | // File-scope asm is ignored during device-side CUDA compilation. |
6911 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) |
6912 | break; |
6913 | // File-scope asm is ignored during device-side OpenMP compilation. |
6914 | if (LangOpts.OpenMPIsTargetDevice) |
6915 | break; |
6916 | // File-scope asm is ignored during device-side SYCL compilation. |
6917 | if (LangOpts.SYCLIsDevice) |
6918 | break; |
6919 | auto *AD = cast<FileScopeAsmDecl>(Val: D); |
6920 | getModule().appendModuleInlineAsm(Asm: AD->getAsmString()->getString()); |
6921 | break; |
6922 | } |
6923 | |
6924 | case Decl::TopLevelStmt: |
6925 | EmitTopLevelStmt(D: cast<TopLevelStmtDecl>(Val: D)); |
6926 | break; |
6927 | |
6928 | case Decl::Import: { |
6929 | auto *Import = cast<ImportDecl>(Val: D); |
6930 | |
6931 | // If we've already imported this module, we're done. |
6932 | if (!ImportedModules.insert(X: Import->getImportedModule())) |
6933 | break; |
6934 | |
6935 | // Emit debug information for direct imports. |
6936 | if (!Import->getImportedOwningModule()) { |
6937 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
6938 | DI->EmitImportDecl(ID: *Import); |
6939 | } |
6940 | |
6941 | // For C++ standard modules we are done - we will call the module |
6942 | // initializer for imported modules, and that will likewise call those for |
6943 | // any imports it has. |
6944 | if (CXX20ModuleInits && Import->getImportedOwningModule() && |
6945 | !Import->getImportedOwningModule()->isModuleMapModule()) |
6946 | break; |
6947 | |
6948 | // For clang C++ module map modules the initializers for sub-modules are |
6949 | // emitted here. |
6950 | |
6951 | // Find all of the submodules and emit the module initializers. |
6952 | llvm::SmallPtrSet<clang::Module *, 16> Visited; |
6953 | SmallVector<clang::Module *, 16> Stack; |
6954 | Visited.insert(Ptr: Import->getImportedModule()); |
6955 | Stack.push_back(Elt: Import->getImportedModule()); |
6956 | |
6957 | while (!Stack.empty()) { |
6958 | clang::Module *Mod = Stack.pop_back_val(); |
6959 | if (!EmittedModuleInitializers.insert(Ptr: Mod).second) |
6960 | continue; |
6961 | |
6962 | for (auto *D : Context.getModuleInitializers(M: Mod)) |
6963 | EmitTopLevelDecl(D); |
6964 | |
6965 | // Visit the submodules of this module. |
6966 | for (auto *Submodule : Mod->submodules()) { |
6967 | // Skip explicit children; they need to be explicitly imported to emit |
6968 | // the initializers. |
6969 | if (Submodule->IsExplicit) |
6970 | continue; |
6971 | |
6972 | if (Visited.insert(Ptr: Submodule).second) |
6973 | Stack.push_back(Elt: Submodule); |
6974 | } |
6975 | } |
6976 | break; |
6977 | } |
6978 | |
6979 | case Decl::Export: |
6980 | EmitDeclContext(cast<ExportDecl>(Val: D)); |
6981 | break; |
6982 | |
6983 | case Decl::OMPThreadPrivate: |
6984 | EmitOMPThreadPrivateDecl(D: cast<OMPThreadPrivateDecl>(Val: D)); |
6985 | break; |
6986 | |
6987 | case Decl::OMPAllocate: |
6988 | EmitOMPAllocateDecl(D: cast<OMPAllocateDecl>(Val: D)); |
6989 | break; |
6990 | |
6991 | case Decl::OMPDeclareReduction: |
6992 | EmitOMPDeclareReduction(D: cast<OMPDeclareReductionDecl>(Val: D)); |
6993 | break; |
6994 | |
6995 | case Decl::OMPDeclareMapper: |
6996 | EmitOMPDeclareMapper(D: cast<OMPDeclareMapperDecl>(Val: D)); |
6997 | break; |
6998 | |
6999 | case Decl::OMPRequires: |
7000 | EmitOMPRequiresDecl(D: cast<OMPRequiresDecl>(Val: D)); |
7001 | break; |
7002 | |
7003 | case Decl::Typedef: |
7004 | case Decl::TypeAlias: // using foo = bar; [C++11] |
7005 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
7006 | DI->EmitAndRetainType( |
7007 | Ty: getContext().getTypedefType(Decl: cast<TypedefNameDecl>(Val: D))); |
7008 | break; |
7009 | |
7010 | case Decl::Record: |
7011 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
7012 | if (cast<RecordDecl>(Val: D)->getDefinition()) |
7013 | DI->EmitAndRetainType(Ty: getContext().getRecordType(Decl: cast<RecordDecl>(Val: D))); |
7014 | break; |
7015 | |
7016 | case Decl::Enum: |
7017 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
7018 | if (cast<EnumDecl>(Val: D)->getDefinition()) |
7019 | DI->EmitAndRetainType(Ty: getContext().getEnumType(Decl: cast<EnumDecl>(Val: D))); |
7020 | break; |
7021 | |
7022 | case Decl::HLSLBuffer: |
7023 | getHLSLRuntime().addBuffer(D: cast<HLSLBufferDecl>(Val: D)); |
7024 | break; |
7025 | |
7026 | default: |
7027 | // Make sure we handled everything we should, every other kind is a |
7028 | // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind |
7029 | // function. Need to recode Decl::Kind to do that easily. |
7030 | assert(isa<TypeDecl>(D) && "Unsupported decl kind" ); |
7031 | break; |
7032 | } |
7033 | } |
7034 | |
7035 | void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { |
7036 | // Do we need to generate coverage mapping? |
7037 | if (!CodeGenOpts.CoverageMapping) |
7038 | return; |
7039 | switch (D->getKind()) { |
7040 | case Decl::CXXConversion: |
7041 | case Decl::CXXMethod: |
7042 | case Decl::Function: |
7043 | case Decl::ObjCMethod: |
7044 | case Decl::CXXConstructor: |
7045 | case Decl::CXXDestructor: { |
7046 | if (!cast<FunctionDecl>(Val: D)->doesThisDeclarationHaveABody()) |
7047 | break; |
7048 | SourceManager &SM = getContext().getSourceManager(); |
7049 | if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(SpellingLoc: D->getBeginLoc())) |
7050 | break; |
7051 | DeferredEmptyCoverageMappingDecls.try_emplace(Key: D, Args: true); |
7052 | break; |
7053 | } |
7054 | default: |
7055 | break; |
7056 | }; |
7057 | } |
7058 | |
7059 | void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { |
7060 | // Do we need to generate coverage mapping? |
7061 | if (!CodeGenOpts.CoverageMapping) |
7062 | return; |
7063 | if (const auto *Fn = dyn_cast<FunctionDecl>(Val: D)) { |
7064 | if (Fn->isTemplateInstantiation()) |
7065 | ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); |
7066 | } |
7067 | DeferredEmptyCoverageMappingDecls.insert_or_assign(Key: D, Val: false); |
7068 | } |
7069 | |
7070 | void CodeGenModule::EmitDeferredUnusedCoverageMappings() { |
7071 | // We call takeVector() here to avoid use-after-free. |
7072 | // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because |
7073 | // we deserialize function bodies to emit coverage info for them, and that |
7074 | // deserializes more declarations. How should we handle that case? |
7075 | for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { |
7076 | if (!Entry.second) |
7077 | continue; |
7078 | const Decl *D = Entry.first; |
7079 | switch (D->getKind()) { |
7080 | case Decl::CXXConversion: |
7081 | case Decl::CXXMethod: |
7082 | case Decl::Function: |
7083 | case Decl::ObjCMethod: { |
7084 | CodeGenPGO PGO(*this); |
7085 | GlobalDecl GD(cast<FunctionDecl>(Val: D)); |
7086 | PGO.emitEmptyCounterMapping(D, FuncName: getMangledName(GD), |
7087 | Linkage: getFunctionLinkage(GD)); |
7088 | break; |
7089 | } |
7090 | case Decl::CXXConstructor: { |
7091 | CodeGenPGO PGO(*this); |
7092 | GlobalDecl GD(cast<CXXConstructorDecl>(Val: D), Ctor_Base); |
7093 | PGO.emitEmptyCounterMapping(D, FuncName: getMangledName(GD), |
7094 | Linkage: getFunctionLinkage(GD)); |
7095 | break; |
7096 | } |
7097 | case Decl::CXXDestructor: { |
7098 | CodeGenPGO PGO(*this); |
7099 | GlobalDecl GD(cast<CXXDestructorDecl>(Val: D), Dtor_Base); |
7100 | PGO.emitEmptyCounterMapping(D, FuncName: getMangledName(GD), |
7101 | Linkage: getFunctionLinkage(GD)); |
7102 | break; |
7103 | } |
7104 | default: |
7105 | break; |
7106 | }; |
7107 | } |
7108 | } |
7109 | |
7110 | void CodeGenModule::EmitMainVoidAlias() { |
7111 | // In order to transition away from "__original_main" gracefully, emit an |
7112 | // alias for "main" in the no-argument case so that libc can detect when |
7113 | // new-style no-argument main is in used. |
7114 | if (llvm::Function *F = getModule().getFunction(Name: "main" )) { |
7115 | if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && |
7116 | F->getReturnType()->isIntegerTy(Bitwidth: Context.getTargetInfo().getIntWidth())) { |
7117 | auto *GA = llvm::GlobalAlias::create(Name: "__main_void" , Aliasee: F); |
7118 | GA->setVisibility(llvm::GlobalValue::HiddenVisibility); |
7119 | } |
7120 | } |
7121 | } |
7122 | |
7123 | /// Turns the given pointer into a constant. |
7124 | static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, |
7125 | const void *Ptr) { |
7126 | uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); |
7127 | llvm::Type *i64 = llvm::Type::getInt64Ty(C&: Context); |
7128 | return llvm::ConstantInt::get(Ty: i64, V: PtrInt); |
7129 | } |
7130 | |
7131 | static void EmitGlobalDeclMetadata(CodeGenModule &CGM, |
7132 | llvm::NamedMDNode *&GlobalMetadata, |
7133 | GlobalDecl D, |
7134 | llvm::GlobalValue *Addr) { |
7135 | if (!GlobalMetadata) |
7136 | GlobalMetadata = |
7137 | CGM.getModule().getOrInsertNamedMetadata(Name: "clang.global.decl.ptrs" ); |
7138 | |
7139 | // TODO: should we report variant information for ctors/dtors? |
7140 | llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(C: Addr), |
7141 | llvm::ConstantAsMetadata::get(C: GetPointerConstant( |
7142 | Context&: CGM.getLLVMContext(), Ptr: D.getDecl()))}; |
7143 | GlobalMetadata->addOperand(M: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Ops)); |
7144 | } |
7145 | |
7146 | bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, |
7147 | llvm::GlobalValue *CppFunc) { |
7148 | // Store the list of ifuncs we need to replace uses in. |
7149 | llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; |
7150 | // List of ConstantExprs that we should be able to delete when we're done |
7151 | // here. |
7152 | llvm::SmallVector<llvm::ConstantExpr *> CEs; |
7153 | |
7154 | // It isn't valid to replace the extern-C ifuncs if all we find is itself! |
7155 | if (Elem == CppFunc) |
7156 | return false; |
7157 | |
7158 | // First make sure that all users of this are ifuncs (or ifuncs via a |
7159 | // bitcast), and collect the list of ifuncs and CEs so we can work on them |
7160 | // later. |
7161 | for (llvm::User *User : Elem->users()) { |
7162 | // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an |
7163 | // ifunc directly. In any other case, just give up, as we don't know what we |
7164 | // could break by changing those. |
7165 | if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(Val: User)) { |
7166 | if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) |
7167 | return false; |
7168 | |
7169 | for (llvm::User *CEUser : ConstExpr->users()) { |
7170 | if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(Val: CEUser)) { |
7171 | IFuncs.push_back(Elt: IFunc); |
7172 | } else { |
7173 | return false; |
7174 | } |
7175 | } |
7176 | CEs.push_back(Elt: ConstExpr); |
7177 | } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(Val: User)) { |
7178 | IFuncs.push_back(Elt: IFunc); |
7179 | } else { |
7180 | // This user is one we don't know how to handle, so fail redirection. This |
7181 | // will result in an ifunc retaining a resolver name that will ultimately |
7182 | // fail to be resolved to a defined function. |
7183 | return false; |
7184 | } |
7185 | } |
7186 | |
7187 | // Now we know this is a valid case where we can do this alias replacement, we |
7188 | // need to remove all of the references to Elem (and the bitcasts!) so we can |
7189 | // delete it. |
7190 | for (llvm::GlobalIFunc *IFunc : IFuncs) |
7191 | IFunc->setResolver(nullptr); |
7192 | for (llvm::ConstantExpr *ConstExpr : CEs) |
7193 | ConstExpr->destroyConstant(); |
7194 | |
7195 | // We should now be out of uses for the 'old' version of this function, so we |
7196 | // can erase it as well. |
7197 | Elem->eraseFromParent(); |
7198 | |
7199 | for (llvm::GlobalIFunc *IFunc : IFuncs) { |
7200 | // The type of the resolver is always just a function-type that returns the |
7201 | // type of the IFunc, so create that here. If the type of the actual |
7202 | // resolver doesn't match, it just gets bitcast to the right thing. |
7203 | auto *ResolverTy = |
7204 | llvm::FunctionType::get(Result: IFunc->getType(), /*isVarArg*/ false); |
7205 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
7206 | MangledName: CppFunc->getName(), Ty: ResolverTy, GD: {}, /*ForVTable*/ false); |
7207 | IFunc->setResolver(Resolver); |
7208 | } |
7209 | return true; |
7210 | } |
7211 | |
7212 | /// For each function which is declared within an extern "C" region and marked |
7213 | /// as 'used', but has internal linkage, create an alias from the unmangled |
7214 | /// name to the mangled name if possible. People expect to be able to refer |
7215 | /// to such functions with an unmangled name from inline assembly within the |
7216 | /// same translation unit. |
7217 | void CodeGenModule::EmitStaticExternCAliases() { |
7218 | if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) |
7219 | return; |
7220 | for (auto &I : StaticExternCValues) { |
7221 | IdentifierInfo *Name = I.first; |
7222 | llvm::GlobalValue *Val = I.second; |
7223 | |
7224 | // If Val is null, that implies there were multiple declarations that each |
7225 | // had a claim to the unmangled name. In this case, generation of the alias |
7226 | // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. |
7227 | if (!Val) |
7228 | break; |
7229 | |
7230 | llvm::GlobalValue *ExistingElem = |
7231 | getModule().getNamedValue(Name: Name->getName()); |
7232 | |
7233 | // If there is either not something already by this name, or we were able to |
7234 | // replace all uses from IFuncs, create the alias. |
7235 | if (!ExistingElem || CheckAndReplaceExternCIFuncs(Elem: ExistingElem, CppFunc: Val)) |
7236 | addCompilerUsedGlobal(GV: llvm::GlobalAlias::create(Name: Name->getName(), Aliasee: Val)); |
7237 | } |
7238 | } |
7239 | |
7240 | bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, |
7241 | GlobalDecl &Result) const { |
7242 | auto Res = Manglings.find(Key: MangledName); |
7243 | if (Res == Manglings.end()) |
7244 | return false; |
7245 | Result = Res->getValue(); |
7246 | return true; |
7247 | } |
7248 | |
7249 | /// Emits metadata nodes associating all the global values in the |
7250 | /// current module with the Decls they came from. This is useful for |
7251 | /// projects using IR gen as a subroutine. |
7252 | /// |
7253 | /// Since there's currently no way to associate an MDNode directly |
7254 | /// with an llvm::GlobalValue, we create a global named metadata |
7255 | /// with the name 'clang.global.decl.ptrs'. |
7256 | void CodeGenModule::EmitDeclMetadata() { |
7257 | llvm::NamedMDNode *GlobalMetadata = nullptr; |
7258 | |
7259 | for (auto &I : MangledDeclNames) { |
7260 | llvm::GlobalValue *Addr = getModule().getNamedValue(Name: I.second); |
7261 | // Some mangled names don't necessarily have an associated GlobalValue |
7262 | // in this module, e.g. if we mangled it for DebugInfo. |
7263 | if (Addr) |
7264 | EmitGlobalDeclMetadata(CGM&: *this, GlobalMetadata, D: I.first, Addr); |
7265 | } |
7266 | } |
7267 | |
7268 | /// Emits metadata nodes for all the local variables in the current |
7269 | /// function. |
7270 | void CodeGenFunction::EmitDeclMetadata() { |
7271 | if (LocalDeclMap.empty()) return; |
7272 | |
7273 | llvm::LLVMContext &Context = getLLVMContext(); |
7274 | |
7275 | // Find the unique metadata ID for this name. |
7276 | unsigned DeclPtrKind = Context.getMDKindID(Name: "clang.decl.ptr" ); |
7277 | |
7278 | llvm::NamedMDNode *GlobalMetadata = nullptr; |
7279 | |
7280 | for (auto &I : LocalDeclMap) { |
7281 | const Decl *D = I.first; |
7282 | llvm::Value *Addr = I.second.getPointer(); |
7283 | if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Val: Addr)) { |
7284 | llvm::Value *DAddr = GetPointerConstant(Context&: getLLVMContext(), Ptr: D); |
7285 | Alloca->setMetadata( |
7286 | KindID: DeclPtrKind, Node: llvm::MDNode::get( |
7287 | Context, MDs: llvm::ValueAsMetadata::getConstant(C: DAddr))); |
7288 | } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Val: Addr)) { |
7289 | GlobalDecl GD = GlobalDecl(cast<VarDecl>(Val: D)); |
7290 | EmitGlobalDeclMetadata(CGM, GlobalMetadata, D: GD, Addr: GV); |
7291 | } |
7292 | } |
7293 | } |
7294 | |
7295 | void CodeGenModule::EmitVersionIdentMetadata() { |
7296 | llvm::NamedMDNode *IdentMetadata = |
7297 | TheModule.getOrInsertNamedMetadata(Name: "llvm.ident" ); |
7298 | std::string Version = getClangFullVersion(); |
7299 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
7300 | |
7301 | llvm::Metadata *IdentNode[] = {llvm::MDString::get(Context&: Ctx, Str: Version)}; |
7302 | IdentMetadata->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: IdentNode)); |
7303 | } |
7304 | |
7305 | void CodeGenModule::EmitCommandLineMetadata() { |
7306 | llvm::NamedMDNode *CommandLineMetadata = |
7307 | TheModule.getOrInsertNamedMetadata(Name: "llvm.commandline" ); |
7308 | std::string CommandLine = getCodeGenOpts().RecordCommandLine; |
7309 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
7310 | |
7311 | llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Context&: Ctx, Str: CommandLine)}; |
7312 | CommandLineMetadata->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: CommandLineNode)); |
7313 | } |
7314 | |
7315 | void CodeGenModule::EmitCoverageFile() { |
7316 | llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(Name: "llvm.dbg.cu" ); |
7317 | if (!CUNode) |
7318 | return; |
7319 | |
7320 | llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(Name: "llvm.gcov" ); |
7321 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
7322 | auto *CoverageDataFile = |
7323 | llvm::MDString::get(Context&: Ctx, Str: getCodeGenOpts().CoverageDataFile); |
7324 | auto *CoverageNotesFile = |
7325 | llvm::MDString::get(Context&: Ctx, Str: getCodeGenOpts().CoverageNotesFile); |
7326 | for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { |
7327 | llvm::MDNode *CU = CUNode->getOperand(i); |
7328 | llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; |
7329 | GCov->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: Elts)); |
7330 | } |
7331 | } |
7332 | |
7333 | llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, |
7334 | bool ForEH) { |
7335 | // Return a bogus pointer if RTTI is disabled, unless it's for EH. |
7336 | // FIXME: should we even be calling this method if RTTI is disabled |
7337 | // and it's not for EH? |
7338 | if (!shouldEmitRTTI(ForEH)) |
7339 | return llvm::Constant::getNullValue(Ty: GlobalsInt8PtrTy); |
7340 | |
7341 | if (ForEH && Ty->isObjCObjectPointerType() && |
7342 | LangOpts.ObjCRuntime.isGNUFamily()) |
7343 | return ObjCRuntime->GetEHType(T: Ty); |
7344 | |
7345 | return getCXXABI().getAddrOfRTTIDescriptor(Ty); |
7346 | } |
7347 | |
7348 | void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { |
7349 | // Do not emit threadprivates in simd-only mode. |
7350 | if (LangOpts.OpenMP && LangOpts.OpenMPSimd) |
7351 | return; |
7352 | for (auto RefExpr : D->varlists()) { |
7353 | auto *VD = cast<VarDecl>(Val: cast<DeclRefExpr>(Val: RefExpr)->getDecl()); |
7354 | bool PerformInit = |
7355 | VD->getAnyInitializer() && |
7356 | !VD->getAnyInitializer()->isConstantInitializer(Ctx&: getContext(), |
7357 | /*ForRef=*/false); |
7358 | |
7359 | Address Addr(GetAddrOfGlobalVar(D: VD), |
7360 | getTypes().ConvertTypeForMem(T: VD->getType()), |
7361 | getContext().getDeclAlign(VD)); |
7362 | if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( |
7363 | VD, Addr, RefExpr->getBeginLoc(), PerformInit)) |
7364 | CXXGlobalInits.push_back(InitFunction); |
7365 | } |
7366 | } |
7367 | |
7368 | llvm::Metadata * |
7369 | CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, |
7370 | StringRef Suffix) { |
7371 | if (auto *FnType = T->getAs<FunctionProtoType>()) |
7372 | T = getContext().getFunctionType( |
7373 | ResultTy: FnType->getReturnType(), Args: FnType->getParamTypes(), |
7374 | EPI: FnType->getExtProtoInfo().withExceptionSpec(ESI: EST_None)); |
7375 | |
7376 | llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; |
7377 | if (InternalId) |
7378 | return InternalId; |
7379 | |
7380 | if (isExternallyVisible(L: T->getLinkage())) { |
7381 | std::string OutName; |
7382 | llvm::raw_string_ostream Out(OutName); |
7383 | getCXXABI().getMangleContext().mangleCanonicalTypeName( |
7384 | T, Out, NormalizeIntegers: getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); |
7385 | |
7386 | if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) |
7387 | Out << ".normalized" ; |
7388 | |
7389 | Out << Suffix; |
7390 | |
7391 | InternalId = llvm::MDString::get(Context&: getLLVMContext(), Str: Out.str()); |
7392 | } else { |
7393 | InternalId = llvm::MDNode::getDistinct(Context&: getLLVMContext(), |
7394 | MDs: llvm::ArrayRef<llvm::Metadata *>()); |
7395 | } |
7396 | |
7397 | return InternalId; |
7398 | } |
7399 | |
7400 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { |
7401 | return CreateMetadataIdentifierImpl(T, Map&: MetadataIdMap, Suffix: "" ); |
7402 | } |
7403 | |
7404 | llvm::Metadata * |
7405 | CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { |
7406 | return CreateMetadataIdentifierImpl(T, Map&: VirtualMetadataIdMap, Suffix: ".virtual" ); |
7407 | } |
7408 | |
7409 | // Generalize pointer types to a void pointer with the qualifiers of the |
7410 | // originally pointed-to type, e.g. 'const char *' and 'char * const *' |
7411 | // generalize to 'const void *' while 'char *' and 'const char **' generalize to |
7412 | // 'void *'. |
7413 | static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { |
7414 | if (!Ty->isPointerType()) |
7415 | return Ty; |
7416 | |
7417 | return Ctx.getPointerType( |
7418 | T: QualType(Ctx.VoidTy).withCVRQualifiers( |
7419 | CVR: Ty->getPointeeType().getCVRQualifiers())); |
7420 | } |
7421 | |
7422 | // Apply type generalization to a FunctionType's return and argument types |
7423 | static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { |
7424 | if (auto *FnType = Ty->getAs<FunctionProtoType>()) { |
7425 | SmallVector<QualType, 8> GeneralizedParams; |
7426 | for (auto &Param : FnType->param_types()) |
7427 | GeneralizedParams.push_back(Elt: GeneralizeType(Ctx, Ty: Param)); |
7428 | |
7429 | return Ctx.getFunctionType( |
7430 | ResultTy: GeneralizeType(Ctx, FnType->getReturnType()), |
7431 | Args: GeneralizedParams, EPI: FnType->getExtProtoInfo()); |
7432 | } |
7433 | |
7434 | if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) |
7435 | return Ctx.getFunctionNoProtoType( |
7436 | GeneralizeType(Ctx, FnType->getReturnType())); |
7437 | |
7438 | llvm_unreachable("Encountered unknown FunctionType" ); |
7439 | } |
7440 | |
7441 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { |
7442 | return CreateMetadataIdentifierImpl(T: GeneralizeFunctionType(Ctx&: getContext(), Ty: T), |
7443 | Map&: GeneralizedMetadataIdMap, Suffix: ".generalized" ); |
7444 | } |
7445 | |
7446 | /// Returns whether this module needs the "all-vtables" type identifier. |
7447 | bool CodeGenModule::NeedAllVtablesTypeId() const { |
7448 | // Returns true if at least one of vtable-based CFI checkers is enabled and |
7449 | // is not in the trapping mode. |
7450 | return ((LangOpts.Sanitize.has(K: SanitizerKind::CFIVCall) && |
7451 | !CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::CFIVCall)) || |
7452 | (LangOpts.Sanitize.has(K: SanitizerKind::CFINVCall) && |
7453 | !CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::CFINVCall)) || |
7454 | (LangOpts.Sanitize.has(K: SanitizerKind::CFIDerivedCast) && |
7455 | !CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::CFIDerivedCast)) || |
7456 | (LangOpts.Sanitize.has(K: SanitizerKind::CFIUnrelatedCast) && |
7457 | !CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::CFIUnrelatedCast))); |
7458 | } |
7459 | |
7460 | void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, |
7461 | CharUnits Offset, |
7462 | const CXXRecordDecl *RD) { |
7463 | llvm::Metadata *MD = |
7464 | CreateMetadataIdentifierForType(T: QualType(RD->getTypeForDecl(), 0)); |
7465 | VTable->addTypeMetadata(Offset: Offset.getQuantity(), TypeID: MD); |
7466 | |
7467 | if (CodeGenOpts.SanitizeCfiCrossDso) |
7468 | if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) |
7469 | VTable->addTypeMetadata(Offset: Offset.getQuantity(), |
7470 | TypeID: llvm::ConstantAsMetadata::get(C: CrossDsoTypeId)); |
7471 | |
7472 | if (NeedAllVtablesTypeId()) { |
7473 | llvm::Metadata *MD = llvm::MDString::get(Context&: getLLVMContext(), Str: "all-vtables" ); |
7474 | VTable->addTypeMetadata(Offset: Offset.getQuantity(), TypeID: MD); |
7475 | } |
7476 | } |
7477 | |
7478 | llvm::SanitizerStatReport &CodeGenModule::getSanStats() { |
7479 | if (!SanStats) |
7480 | SanStats = std::make_unique<llvm::SanitizerStatReport>(args: &getModule()); |
7481 | |
7482 | return *SanStats; |
7483 | } |
7484 | |
7485 | llvm::Value * |
7486 | CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, |
7487 | CodeGenFunction &CGF) { |
7488 | llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, T: E->getType()); |
7489 | auto *SamplerT = getOpenCLRuntime().getSamplerType(T: E->getType().getTypePtr()); |
7490 | auto *FTy = llvm::FunctionType::get(Result: SamplerT, Params: {C->getType()}, isVarArg: false); |
7491 | auto *Call = CGF.EmitRuntimeCall( |
7492 | callee: CreateRuntimeFunction(FTy, Name: "__translate_sampler_initializer" ), args: {C}); |
7493 | return Call; |
7494 | } |
7495 | |
7496 | CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( |
7497 | QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { |
7498 | return getNaturalTypeAlignment(T: T->getPointeeType(), BaseInfo, TBAAInfo, |
7499 | /* forPointeeType= */ true); |
7500 | } |
7501 | |
7502 | CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, |
7503 | LValueBaseInfo *BaseInfo, |
7504 | TBAAAccessInfo *TBAAInfo, |
7505 | bool forPointeeType) { |
7506 | if (TBAAInfo) |
7507 | *TBAAInfo = getTBAAAccessInfo(AccessType: T); |
7508 | |
7509 | // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But |
7510 | // that doesn't return the information we need to compute BaseInfo. |
7511 | |
7512 | // Honor alignment typedef attributes even on incomplete types. |
7513 | // We also honor them straight for C++ class types, even as pointees; |
7514 | // there's an expressivity gap here. |
7515 | if (auto TT = T->getAs<TypedefType>()) { |
7516 | if (auto Align = TT->getDecl()->getMaxAlignment()) { |
7517 | if (BaseInfo) |
7518 | *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); |
7519 | return getContext().toCharUnitsFromBits(BitSize: Align); |
7520 | } |
7521 | } |
7522 | |
7523 | bool AlignForArray = T->isArrayType(); |
7524 | |
7525 | // Analyze the base element type, so we don't get confused by incomplete |
7526 | // array types. |
7527 | T = getContext().getBaseElementType(QT: T); |
7528 | |
7529 | if (T->isIncompleteType()) { |
7530 | // We could try to replicate the logic from |
7531 | // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the |
7532 | // type is incomplete, so it's impossible to test. We could try to reuse |
7533 | // getTypeAlignIfKnown, but that doesn't return the information we need |
7534 | // to set BaseInfo. So just ignore the possibility that the alignment is |
7535 | // greater than one. |
7536 | if (BaseInfo) |
7537 | *BaseInfo = LValueBaseInfo(AlignmentSource::Type); |
7538 | return CharUnits::One(); |
7539 | } |
7540 | |
7541 | if (BaseInfo) |
7542 | *BaseInfo = LValueBaseInfo(AlignmentSource::Type); |
7543 | |
7544 | CharUnits Alignment; |
7545 | const CXXRecordDecl *RD; |
7546 | if (T.getQualifiers().hasUnaligned()) { |
7547 | Alignment = CharUnits::One(); |
7548 | } else if (forPointeeType && !AlignForArray && |
7549 | (RD = T->getAsCXXRecordDecl())) { |
7550 | // For C++ class pointees, we don't know whether we're pointing at a |
7551 | // base or a complete object, so we generally need to use the |
7552 | // non-virtual alignment. |
7553 | Alignment = getClassPointerAlignment(CD: RD); |
7554 | } else { |
7555 | Alignment = getContext().getTypeAlignInChars(T); |
7556 | } |
7557 | |
7558 | // Cap to the global maximum type alignment unless the alignment |
7559 | // was somehow explicit on the type. |
7560 | if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { |
7561 | if (Alignment.getQuantity() > MaxAlign && |
7562 | !getContext().isAlignmentRequired(T)) |
7563 | Alignment = CharUnits::fromQuantity(Quantity: MaxAlign); |
7564 | } |
7565 | return Alignment; |
7566 | } |
7567 | |
7568 | bool CodeGenModule::stopAutoInit() { |
7569 | unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; |
7570 | if (StopAfter) { |
7571 | // This number is positive only when -ftrivial-auto-var-init-stop-after=* is |
7572 | // used |
7573 | if (NumAutoVarInit >= StopAfter) { |
7574 | return true; |
7575 | } |
7576 | if (!NumAutoVarInit) { |
7577 | unsigned DiagID = getDiags().getCustomDiagID( |
7578 | L: DiagnosticsEngine::Warning, |
7579 | FormatString: "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " |
7580 | "number of times ftrivial-auto-var-init=%1 gets applied." ); |
7581 | getDiags().Report(DiagID) |
7582 | << StopAfter |
7583 | << (getContext().getLangOpts().getTrivialAutoVarInit() == |
7584 | LangOptions::TrivialAutoVarInitKind::Zero |
7585 | ? "zero" |
7586 | : "pattern" ); |
7587 | } |
7588 | ++NumAutoVarInit; |
7589 | } |
7590 | return false; |
7591 | } |
7592 | |
7593 | void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, |
7594 | const Decl *D) const { |
7595 | // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers |
7596 | // postfix beginning with '.' since the symbol name can be demangled. |
7597 | if (LangOpts.HIP) |
7598 | OS << (isa<VarDecl>(Val: D) ? ".static." : ".intern." ); |
7599 | else |
7600 | OS << (isa<VarDecl>(Val: D) ? "__static__" : "__intern__" ); |
7601 | |
7602 | // If the CUID is not specified we try to generate a unique postfix. |
7603 | if (getLangOpts().CUID.empty()) { |
7604 | SourceManager &SM = getContext().getSourceManager(); |
7605 | PresumedLoc PLoc = SM.getPresumedLoc(Loc: D->getLocation()); |
7606 | assert(PLoc.isValid() && "Source location is expected to be valid." ); |
7607 | |
7608 | // Get the hash of the user defined macros. |
7609 | llvm::MD5 Hash; |
7610 | llvm::MD5::MD5Result Result; |
7611 | for (const auto &Arg : PreprocessorOpts.Macros) |
7612 | Hash.update(Str: Arg.first); |
7613 | Hash.final(Result); |
7614 | |
7615 | // Get the UniqueID for the file containing the decl. |
7616 | llvm::sys::fs::UniqueID ID; |
7617 | if (llvm::sys::fs::getUniqueID(Path: PLoc.getFilename(), Result&: ID)) { |
7618 | PLoc = SM.getPresumedLoc(Loc: D->getLocation(), /*UseLineDirectives=*/false); |
7619 | assert(PLoc.isValid() && "Source location is expected to be valid." ); |
7620 | if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) |
7621 | SM.getDiagnostics().Report(diag::err_cannot_open_file) |
7622 | << PLoc.getFilename() << EC.message(); |
7623 | } |
7624 | OS << llvm::format(Fmt: "%x" , Vals: ID.getFile()) << llvm::format(Fmt: "%x" , Vals: ID.getDevice()) |
7625 | << "_" << llvm::utohexstr(X: Result.low(), /*LowerCase=*/true, /*Width=*/8); |
7626 | } else { |
7627 | OS << getContext().getCUIDHash(); |
7628 | } |
7629 | } |
7630 | |
7631 | void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { |
7632 | assert(DeferredDeclsToEmit.empty() && |
7633 | "Should have emitted all decls deferred to emit." ); |
7634 | assert(NewBuilder->DeferredDecls.empty() && |
7635 | "Newly created module should not have deferred decls" ); |
7636 | NewBuilder->DeferredDecls = std::move(DeferredDecls); |
7637 | assert(EmittedDeferredDecls.empty() && |
7638 | "Still have (unmerged) EmittedDeferredDecls deferred decls" ); |
7639 | |
7640 | assert(NewBuilder->DeferredVTables.empty() && |
7641 | "Newly created module should not have deferred vtables" ); |
7642 | NewBuilder->DeferredVTables = std::move(DeferredVTables); |
7643 | |
7644 | assert(NewBuilder->MangledDeclNames.empty() && |
7645 | "Newly created module should not have mangled decl names" ); |
7646 | assert(NewBuilder->Manglings.empty() && |
7647 | "Newly created module should not have manglings" ); |
7648 | NewBuilder->Manglings = std::move(Manglings); |
7649 | |
7650 | NewBuilder->WeakRefReferences = std::move(WeakRefReferences); |
7651 | |
7652 | NewBuilder->TBAA = std::move(TBAA); |
7653 | |
7654 | NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); |
7655 | } |
7656 | |