xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 5deeebd8c6ca991269e72902a7a62cada57947f6)
10b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This coordinates the per-module state used while generating code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CodeGenModule.h"
14fcaf7f86SDimitry Andric #include "ABIInfo.h"
150b57cec5SDimitry Andric #include "CGBlocks.h"
160b57cec5SDimitry Andric #include "CGCUDARuntime.h"
170b57cec5SDimitry Andric #include "CGCXXABI.h"
180b57cec5SDimitry Andric #include "CGCall.h"
190b57cec5SDimitry Andric #include "CGDebugInfo.h"
2081ad6265SDimitry Andric #include "CGHLSLRuntime.h"
210b57cec5SDimitry Andric #include "CGObjCRuntime.h"
220b57cec5SDimitry Andric #include "CGOpenCLRuntime.h"
230b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
24349cc55cSDimitry Andric #include "CGOpenMPRuntimeGPU.h"
250b57cec5SDimitry Andric #include "CodeGenFunction.h"
260b57cec5SDimitry Andric #include "CodeGenPGO.h"
270b57cec5SDimitry Andric #include "ConstantEmitter.h"
280b57cec5SDimitry Andric #include "CoverageMappingGen.h"
290b57cec5SDimitry Andric #include "TargetInfo.h"
300b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
315f757f3fSDimitry Andric #include "clang/AST/ASTLambda.h"
320b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
330fca6ea1SDimitry Andric #include "clang/AST/Decl.h"
340b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
350b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
360b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
370b57cec5SDimitry Andric #include "clang/AST/Mangle.h"
380b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
390b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
400b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
410b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
420b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
430b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
445ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
450b57cec5SDimitry Andric #include "clang/Basic/Module.h"
460b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
470b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
480b57cec5SDimitry Andric #include "clang/Basic/Version.h"
4981ad6265SDimitry Andric #include "clang/CodeGen/BackendUtil.h"
500b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
510b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
52bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h"
53bdd1243dSDimitry Andric #include "llvm/ADT/StringExtras.h"
540b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
550b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
560fca6ea1SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
57480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
5806c3fb27SDimitry Andric #include "llvm/IR/AttributeMask.h"
590b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
600b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
610b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
620b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
630b57cec5SDimitry Andric #include "llvm/IR/Module.h"
640b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h"
650b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
66bdd1243dSDimitry Andric #include "llvm/ProfileData/SampleProf.h"
67fcaf7f86SDimitry Andric #include "llvm/Support/CRC.h"
680b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
69480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
700b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
710b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
720b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
73bdd1243dSDimitry Andric #include "llvm/Support/xxhash.h"
740fca6ea1SDimitry Andric #include "llvm/TargetParser/RISCVISAInfo.h"
7506c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
7606c3fb27SDimitry Andric #include "llvm/TargetParser/X86TargetParser.h"
770fca6ea1SDimitry Andric #include "llvm/Transforms/Utils/BuildLibCalls.h"
78bdd1243dSDimitry Andric #include <optional>
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric using namespace clang;
810b57cec5SDimitry Andric using namespace CodeGen;
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
8481ad6265SDimitry Andric     "limited-coverage-experimental", llvm::cl::Hidden,
8581ad6265SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
90fe6060f1SDimitry Andric   switch (CGM.getContext().getCXXABIKind()) {
91e8d8bef9SDimitry Andric   case TargetCXXABI::AppleARM64:
92480093f4SDimitry Andric   case TargetCXXABI::Fuchsia:
930b57cec5SDimitry Andric   case TargetCXXABI::GenericAArch64:
940b57cec5SDimitry Andric   case TargetCXXABI::GenericARM:
950b57cec5SDimitry Andric   case TargetCXXABI::iOS:
960b57cec5SDimitry Andric   case TargetCXXABI::WatchOS:
970b57cec5SDimitry Andric   case TargetCXXABI::GenericMIPS:
980b57cec5SDimitry Andric   case TargetCXXABI::GenericItanium:
990b57cec5SDimitry Andric   case TargetCXXABI::WebAssembly:
1005ffd83dbSDimitry Andric   case TargetCXXABI::XL:
1010b57cec5SDimitry Andric     return CreateItaniumCXXABI(CGM);
1020b57cec5SDimitry Andric   case TargetCXXABI::Microsoft:
1030b57cec5SDimitry Andric     return CreateMicrosoftCXXABI(CGM);
1040b57cec5SDimitry Andric   }
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
1070b57cec5SDimitry Andric }
1080b57cec5SDimitry Andric 
10906c3fb27SDimitry Andric static std::unique_ptr<TargetCodeGenInfo>
11006c3fb27SDimitry Andric createTargetCodeGenInfo(CodeGenModule &CGM) {
11106c3fb27SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
11206c3fb27SDimitry Andric   const llvm::Triple &Triple = Target.getTriple();
11306c3fb27SDimitry Andric   const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
11406c3fb27SDimitry Andric 
11506c3fb27SDimitry Andric   switch (Triple.getArch()) {
11606c3fb27SDimitry Andric   default:
11706c3fb27SDimitry Andric     return createDefaultTargetCodeGenInfo(CGM);
11806c3fb27SDimitry Andric 
11906c3fb27SDimitry Andric   case llvm::Triple::le32:
12006c3fb27SDimitry Andric     return createPNaClTargetCodeGenInfo(CGM);
12106c3fb27SDimitry Andric   case llvm::Triple::m68k:
12206c3fb27SDimitry Andric     return createM68kTargetCodeGenInfo(CGM);
12306c3fb27SDimitry Andric   case llvm::Triple::mips:
12406c3fb27SDimitry Andric   case llvm::Triple::mipsel:
12506c3fb27SDimitry Andric     if (Triple.getOS() == llvm::Triple::NaCl)
12606c3fb27SDimitry Andric       return createPNaClTargetCodeGenInfo(CGM);
12706c3fb27SDimitry Andric     return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
12806c3fb27SDimitry Andric 
12906c3fb27SDimitry Andric   case llvm::Triple::mips64:
13006c3fb27SDimitry Andric   case llvm::Triple::mips64el:
13106c3fb27SDimitry Andric     return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false);
13206c3fb27SDimitry Andric 
13306c3fb27SDimitry Andric   case llvm::Triple::avr: {
13406c3fb27SDimitry Andric     // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
13506c3fb27SDimitry Andric     // on avrtiny. For passing return value, R18~R25 are used on avr, and
13606c3fb27SDimitry Andric     // R22~R25 are used on avrtiny.
13706c3fb27SDimitry Andric     unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18;
13806c3fb27SDimitry Andric     unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8;
13906c3fb27SDimitry Andric     return createAVRTargetCodeGenInfo(CGM, NPR, NRR);
14006c3fb27SDimitry Andric   }
14106c3fb27SDimitry Andric 
14206c3fb27SDimitry Andric   case llvm::Triple::aarch64:
14306c3fb27SDimitry Andric   case llvm::Triple::aarch64_32:
14406c3fb27SDimitry Andric   case llvm::Triple::aarch64_be: {
14506c3fb27SDimitry Andric     AArch64ABIKind Kind = AArch64ABIKind::AAPCS;
14606c3fb27SDimitry Andric     if (Target.getABI() == "darwinpcs")
14706c3fb27SDimitry Andric       Kind = AArch64ABIKind::DarwinPCS;
14806c3fb27SDimitry Andric     else if (Triple.isOSWindows())
14906c3fb27SDimitry Andric       return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64);
1500fca6ea1SDimitry Andric     else if (Target.getABI() == "aapcs-soft")
1510fca6ea1SDimitry Andric       Kind = AArch64ABIKind::AAPCSSoft;
1520fca6ea1SDimitry Andric     else if (Target.getABI() == "pauthtest")
1530fca6ea1SDimitry Andric       Kind = AArch64ABIKind::PAuthTest;
15406c3fb27SDimitry Andric 
15506c3fb27SDimitry Andric     return createAArch64TargetCodeGenInfo(CGM, Kind);
15606c3fb27SDimitry Andric   }
15706c3fb27SDimitry Andric 
15806c3fb27SDimitry Andric   case llvm::Triple::wasm32:
15906c3fb27SDimitry Andric   case llvm::Triple::wasm64: {
16006c3fb27SDimitry Andric     WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP;
16106c3fb27SDimitry Andric     if (Target.getABI() == "experimental-mv")
16206c3fb27SDimitry Andric       Kind = WebAssemblyABIKind::ExperimentalMV;
16306c3fb27SDimitry Andric     return createWebAssemblyTargetCodeGenInfo(CGM, Kind);
16406c3fb27SDimitry Andric   }
16506c3fb27SDimitry Andric 
16606c3fb27SDimitry Andric   case llvm::Triple::arm:
16706c3fb27SDimitry Andric   case llvm::Triple::armeb:
16806c3fb27SDimitry Andric   case llvm::Triple::thumb:
16906c3fb27SDimitry Andric   case llvm::Triple::thumbeb: {
17006c3fb27SDimitry Andric     if (Triple.getOS() == llvm::Triple::Win32)
17106c3fb27SDimitry Andric       return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP);
17206c3fb27SDimitry Andric 
17306c3fb27SDimitry Andric     ARMABIKind Kind = ARMABIKind::AAPCS;
17406c3fb27SDimitry Andric     StringRef ABIStr = Target.getABI();
17506c3fb27SDimitry Andric     if (ABIStr == "apcs-gnu")
17606c3fb27SDimitry Andric       Kind = ARMABIKind::APCS;
17706c3fb27SDimitry Andric     else if (ABIStr == "aapcs16")
17806c3fb27SDimitry Andric       Kind = ARMABIKind::AAPCS16_VFP;
17906c3fb27SDimitry Andric     else if (CodeGenOpts.FloatABI == "hard" ||
18006c3fb27SDimitry Andric              (CodeGenOpts.FloatABI != "soft" &&
18106c3fb27SDimitry Andric               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
18206c3fb27SDimitry Andric                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
18306c3fb27SDimitry Andric                Triple.getEnvironment() == llvm::Triple::EABIHF)))
18406c3fb27SDimitry Andric       Kind = ARMABIKind::AAPCS_VFP;
18506c3fb27SDimitry Andric 
18606c3fb27SDimitry Andric     return createARMTargetCodeGenInfo(CGM, Kind);
18706c3fb27SDimitry Andric   }
18806c3fb27SDimitry Andric 
18906c3fb27SDimitry Andric   case llvm::Triple::ppc: {
19006c3fb27SDimitry Andric     if (Triple.isOSAIX())
19106c3fb27SDimitry Andric       return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false);
19206c3fb27SDimitry Andric 
19306c3fb27SDimitry Andric     bool IsSoftFloat =
19406c3fb27SDimitry Andric         CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
19506c3fb27SDimitry Andric     return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
19606c3fb27SDimitry Andric   }
19706c3fb27SDimitry Andric   case llvm::Triple::ppcle: {
19806c3fb27SDimitry Andric     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
19906c3fb27SDimitry Andric     return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
20006c3fb27SDimitry Andric   }
20106c3fb27SDimitry Andric   case llvm::Triple::ppc64:
20206c3fb27SDimitry Andric     if (Triple.isOSAIX())
20306c3fb27SDimitry Andric       return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true);
20406c3fb27SDimitry Andric 
20506c3fb27SDimitry Andric     if (Triple.isOSBinFormatELF()) {
20606c3fb27SDimitry Andric       PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1;
20706c3fb27SDimitry Andric       if (Target.getABI() == "elfv2")
20806c3fb27SDimitry Andric         Kind = PPC64_SVR4_ABIKind::ELFv2;
20906c3fb27SDimitry Andric       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
21006c3fb27SDimitry Andric 
21106c3fb27SDimitry Andric       return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
21206c3fb27SDimitry Andric     }
21306c3fb27SDimitry Andric     return createPPC64TargetCodeGenInfo(CGM);
21406c3fb27SDimitry Andric   case llvm::Triple::ppc64le: {
21506c3fb27SDimitry Andric     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
21606c3fb27SDimitry Andric     PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2;
21706c3fb27SDimitry Andric     if (Target.getABI() == "elfv1")
21806c3fb27SDimitry Andric       Kind = PPC64_SVR4_ABIKind::ELFv1;
21906c3fb27SDimitry Andric     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
22006c3fb27SDimitry Andric 
22106c3fb27SDimitry Andric     return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
22206c3fb27SDimitry Andric   }
22306c3fb27SDimitry Andric 
22406c3fb27SDimitry Andric   case llvm::Triple::nvptx:
22506c3fb27SDimitry Andric   case llvm::Triple::nvptx64:
22606c3fb27SDimitry Andric     return createNVPTXTargetCodeGenInfo(CGM);
22706c3fb27SDimitry Andric 
22806c3fb27SDimitry Andric   case llvm::Triple::msp430:
22906c3fb27SDimitry Andric     return createMSP430TargetCodeGenInfo(CGM);
23006c3fb27SDimitry Andric 
23106c3fb27SDimitry Andric   case llvm::Triple::riscv32:
23206c3fb27SDimitry Andric   case llvm::Triple::riscv64: {
23306c3fb27SDimitry Andric     StringRef ABIStr = Target.getABI();
23406c3fb27SDimitry Andric     unsigned XLen = Target.getPointerWidth(LangAS::Default);
23506c3fb27SDimitry Andric     unsigned ABIFLen = 0;
2365f757f3fSDimitry Andric     if (ABIStr.ends_with("f"))
23706c3fb27SDimitry Andric       ABIFLen = 32;
2385f757f3fSDimitry Andric     else if (ABIStr.ends_with("d"))
23906c3fb27SDimitry Andric       ABIFLen = 64;
2407a6dacacSDimitry Andric     bool EABI = ABIStr.ends_with("e");
2417a6dacacSDimitry Andric     return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI);
24206c3fb27SDimitry Andric   }
24306c3fb27SDimitry Andric 
24406c3fb27SDimitry Andric   case llvm::Triple::systemz: {
24506c3fb27SDimitry Andric     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
24606c3fb27SDimitry Andric     bool HasVector = !SoftFloat && Target.getABI() == "vector";
24706c3fb27SDimitry Andric     return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
24806c3fb27SDimitry Andric   }
24906c3fb27SDimitry Andric 
25006c3fb27SDimitry Andric   case llvm::Triple::tce:
25106c3fb27SDimitry Andric   case llvm::Triple::tcele:
25206c3fb27SDimitry Andric     return createTCETargetCodeGenInfo(CGM);
25306c3fb27SDimitry Andric 
25406c3fb27SDimitry Andric   case llvm::Triple::x86: {
25506c3fb27SDimitry Andric     bool IsDarwinVectorABI = Triple.isOSDarwin();
25606c3fb27SDimitry Andric     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
25706c3fb27SDimitry Andric 
25806c3fb27SDimitry Andric     if (Triple.getOS() == llvm::Triple::Win32) {
25906c3fb27SDimitry Andric       return createWinX86_32TargetCodeGenInfo(
26006c3fb27SDimitry Andric           CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
26106c3fb27SDimitry Andric           CodeGenOpts.NumRegisterParameters);
26206c3fb27SDimitry Andric     }
26306c3fb27SDimitry Andric     return createX86_32TargetCodeGenInfo(
26406c3fb27SDimitry Andric         CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
26506c3fb27SDimitry Andric         CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft");
26606c3fb27SDimitry Andric   }
26706c3fb27SDimitry Andric 
26806c3fb27SDimitry Andric   case llvm::Triple::x86_64: {
26906c3fb27SDimitry Andric     StringRef ABI = Target.getABI();
27006c3fb27SDimitry Andric     X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512
27106c3fb27SDimitry Andric                                : ABI == "avx"  ? X86AVXABILevel::AVX
27206c3fb27SDimitry Andric                                                : X86AVXABILevel::None);
27306c3fb27SDimitry Andric 
27406c3fb27SDimitry Andric     switch (Triple.getOS()) {
27506c3fb27SDimitry Andric     case llvm::Triple::Win32:
27606c3fb27SDimitry Andric       return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel);
27706c3fb27SDimitry Andric     default:
27806c3fb27SDimitry Andric       return createX86_64TargetCodeGenInfo(CGM, AVXLevel);
27906c3fb27SDimitry Andric     }
28006c3fb27SDimitry Andric   }
28106c3fb27SDimitry Andric   case llvm::Triple::hexagon:
28206c3fb27SDimitry Andric     return createHexagonTargetCodeGenInfo(CGM);
28306c3fb27SDimitry Andric   case llvm::Triple::lanai:
28406c3fb27SDimitry Andric     return createLanaiTargetCodeGenInfo(CGM);
28506c3fb27SDimitry Andric   case llvm::Triple::r600:
28606c3fb27SDimitry Andric     return createAMDGPUTargetCodeGenInfo(CGM);
28706c3fb27SDimitry Andric   case llvm::Triple::amdgcn:
28806c3fb27SDimitry Andric     return createAMDGPUTargetCodeGenInfo(CGM);
28906c3fb27SDimitry Andric   case llvm::Triple::sparc:
29006c3fb27SDimitry Andric     return createSparcV8TargetCodeGenInfo(CGM);
29106c3fb27SDimitry Andric   case llvm::Triple::sparcv9:
29206c3fb27SDimitry Andric     return createSparcV9TargetCodeGenInfo(CGM);
29306c3fb27SDimitry Andric   case llvm::Triple::xcore:
29406c3fb27SDimitry Andric     return createXCoreTargetCodeGenInfo(CGM);
29506c3fb27SDimitry Andric   case llvm::Triple::arc:
29606c3fb27SDimitry Andric     return createARCTargetCodeGenInfo(CGM);
29706c3fb27SDimitry Andric   case llvm::Triple::spir:
29806c3fb27SDimitry Andric   case llvm::Triple::spir64:
29906c3fb27SDimitry Andric     return createCommonSPIRTargetCodeGenInfo(CGM);
30006c3fb27SDimitry Andric   case llvm::Triple::spirv32:
30106c3fb27SDimitry Andric   case llvm::Triple::spirv64:
30206c3fb27SDimitry Andric     return createSPIRVTargetCodeGenInfo(CGM);
30306c3fb27SDimitry Andric   case llvm::Triple::ve:
30406c3fb27SDimitry Andric     return createVETargetCodeGenInfo(CGM);
30506c3fb27SDimitry Andric   case llvm::Triple::csky: {
30606c3fb27SDimitry Andric     bool IsSoftFloat = !Target.hasFeature("hard-float-abi");
30706c3fb27SDimitry Andric     bool hasFP64 =
30806c3fb27SDimitry Andric         Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df");
30906c3fb27SDimitry Andric     return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0
31006c3fb27SDimitry Andric                                             : hasFP64   ? 64
31106c3fb27SDimitry Andric                                                         : 32);
31206c3fb27SDimitry Andric   }
31306c3fb27SDimitry Andric   case llvm::Triple::bpfeb:
31406c3fb27SDimitry Andric   case llvm::Triple::bpfel:
31506c3fb27SDimitry Andric     return createBPFTargetCodeGenInfo(CGM);
31606c3fb27SDimitry Andric   case llvm::Triple::loongarch32:
31706c3fb27SDimitry Andric   case llvm::Triple::loongarch64: {
31806c3fb27SDimitry Andric     StringRef ABIStr = Target.getABI();
31906c3fb27SDimitry Andric     unsigned ABIFRLen = 0;
3205f757f3fSDimitry Andric     if (ABIStr.ends_with("f"))
32106c3fb27SDimitry Andric       ABIFRLen = 32;
3225f757f3fSDimitry Andric     else if (ABIStr.ends_with("d"))
32306c3fb27SDimitry Andric       ABIFRLen = 64;
32406c3fb27SDimitry Andric     return createLoongArchTargetCodeGenInfo(
32506c3fb27SDimitry Andric         CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen);
32606c3fb27SDimitry Andric   }
32706c3fb27SDimitry Andric   }
32806c3fb27SDimitry Andric }
32906c3fb27SDimitry Andric 
33006c3fb27SDimitry Andric const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
33106c3fb27SDimitry Andric   if (!TheTargetCodeGenInfo)
33206c3fb27SDimitry Andric     TheTargetCodeGenInfo = createTargetCodeGenInfo(*this);
33306c3fb27SDimitry Andric   return *TheTargetCodeGenInfo;
33406c3fb27SDimitry Andric }
33506c3fb27SDimitry Andric 
336972a253aSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C,
337972a253aSDimitry Andric                              IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
338972a253aSDimitry Andric                              const HeaderSearchOptions &HSO,
3390b57cec5SDimitry Andric                              const PreprocessorOptions &PPO,
3400b57cec5SDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
3410b57cec5SDimitry Andric                              DiagnosticsEngine &diags,
3420b57cec5SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
34306c3fb27SDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
34406c3fb27SDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
34506c3fb27SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
346*5deeebd8SDimitry Andric       VMContext(M.getContext()), VTables(*this),
34706c3fb27SDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   // Initialize the type cache.
350*5deeebd8SDimitry Andric   Types.reset(new CodeGenTypes(*this));
3510b57cec5SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
3520b57cec5SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
3530b57cec5SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
3540b57cec5SDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
3550b57cec5SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
3560b57cec5SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
3570b57cec5SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
3585ffd83dbSDimitry Andric   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
3590b57cec5SDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
3600b57cec5SDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
361bdd1243dSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
3620b57cec5SDimitry Andric   PointerAlignInBytes =
363bdd1243dSDimitry Andric       C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
364bdd1243dSDimitry Andric           .getQuantity();
3650b57cec5SDimitry Andric   SizeSizeInBytes =
3660b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
3670b57cec5SDimitry Andric   IntAlignInBytes =
3680b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
369e8d8bef9SDimitry Andric   CharTy =
370e8d8bef9SDimitry Andric     llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
3710b57cec5SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
3720b57cec5SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
3730b57cec5SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
3740fca6ea1SDimitry Andric   Int8PtrTy = llvm::PointerType::get(LLVMContext,
3750fca6ea1SDimitry Andric                                      C.getTargetAddressSpace(LangAS::Default));
376349cc55cSDimitry Andric   const llvm::DataLayout &DL = M.getDataLayout();
3775f757f3fSDimitry Andric   AllocaInt8PtrTy =
3785f757f3fSDimitry Andric       llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
3795f757f3fSDimitry Andric   GlobalsInt8PtrTy =
3805f757f3fSDimitry Andric       llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
3815f757f3fSDimitry Andric   ConstGlobalsPtrTy = llvm::PointerType::get(
3825f757f3fSDimitry Andric       LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
3830b57cec5SDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
3840b57cec5SDimitry Andric 
385fcaf7f86SDimitry Andric   // Build C++20 Module initializers.
386fcaf7f86SDimitry Andric   // TODO: Add Microsoft here once we know the mangling required for the
387fcaf7f86SDimitry Andric   // initializers.
388fcaf7f86SDimitry Andric   CXX20ModuleInits =
389fcaf7f86SDimitry Andric       LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
390fcaf7f86SDimitry Andric                                        ItaniumMangleContext::MK_Itanium;
391fcaf7f86SDimitry Andric 
3920b57cec5SDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   if (LangOpts.ObjC)
3950b57cec5SDimitry Andric     createObjCRuntime();
3960b57cec5SDimitry Andric   if (LangOpts.OpenCL)
3970b57cec5SDimitry Andric     createOpenCLRuntime();
3980b57cec5SDimitry Andric   if (LangOpts.OpenMP)
3990b57cec5SDimitry Andric     createOpenMPRuntime();
4000b57cec5SDimitry Andric   if (LangOpts.CUDA)
4010b57cec5SDimitry Andric     createCUDARuntime();
40281ad6265SDimitry Andric   if (LangOpts.HLSL)
40381ad6265SDimitry Andric     createHLSLRuntime();
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
4060b57cec5SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
4070b57cec5SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
4080fca6ea1SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, getTypes(), TheModule, CodeGenOpts,
409*5deeebd8SDimitry Andric                                getLangOpts()));
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
4120b57cec5SDimitry Andric   // object.
41306c3fb27SDimitry Andric   if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
41406c3fb27SDimitry Andric       CodeGenOpts.CoverageNotesFile.size() ||
41506c3fb27SDimitry Andric       CodeGenOpts.CoverageDataFile.size())
4160b57cec5SDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   Block.GlobalUniqueCount = 0;
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   if (C.getLangOpts().ObjC)
4210b57cec5SDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
4240b57cec5SDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
42506c3fb27SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, *FS,
42606c3fb27SDimitry Andric         CodeGenOpts.ProfileRemappingFile);
427bdd1243dSDimitry Andric     // We're checking for profile read errors in CompilerInvocation, so if
428bdd1243dSDimitry Andric     // there was an error it should've already been caught. If it hasn't been
429bdd1243dSDimitry Andric     // somehow, trip an assertion.
430bdd1243dSDimitry Andric     assert(ReaderOrErr);
4310b57cec5SDimitry Andric     PGOReader = std::move(ReaderOrErr.get());
4320b57cec5SDimitry Andric   }
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   // If coverage mapping generation is enabled, create the
4350b57cec5SDimitry Andric   // CoverageMappingModuleGen object.
4360b57cec5SDimitry Andric   if (CodeGenOpts.CoverageMapping)
4370b57cec5SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
438fe6060f1SDimitry Andric 
439fe6060f1SDimitry Andric   // Generate the module name hash here if needed.
440fe6060f1SDimitry Andric   if (CodeGenOpts.UniqueInternalLinkageNames &&
441fe6060f1SDimitry Andric       !getModule().getSourceFileName().empty()) {
442fe6060f1SDimitry Andric     std::string Path = getModule().getSourceFileName();
443fe6060f1SDimitry Andric     // Check if a path substitution is needed from the MacroPrefixMap.
4446e75b2fbSDimitry Andric     for (const auto &Entry : LangOpts.MacroPrefixMap)
445fe6060f1SDimitry Andric       if (Path.rfind(Entry.first, 0) != std::string::npos) {
446fe6060f1SDimitry Andric         Path = Entry.second + Path.substr(Entry.first.size());
447fe6060f1SDimitry Andric         break;
448fe6060f1SDimitry Andric       }
449bdd1243dSDimitry Andric     ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
450fe6060f1SDimitry Andric   }
4510fca6ea1SDimitry Andric 
4520fca6ea1SDimitry Andric   // Record mregparm value now so it is visible through all of codegen.
4530fca6ea1SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4540fca6ea1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
4550fca6ea1SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
4560b57cec5SDimitry Andric }
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {}
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() {
4610b57cec5SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
4620b57cec5SDimitry Andric   // new ABIs to decide how best to do this.
4630b57cec5SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
4640b57cec5SDimitry Andric   case ObjCRuntime::GNUstep:
4650b57cec5SDimitry Andric   case ObjCRuntime::GCC:
4660b57cec5SDimitry Andric   case ObjCRuntime::ObjFW:
4670b57cec5SDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
4680b57cec5SDimitry Andric     return;
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   case ObjCRuntime::FragileMacOSX:
4710b57cec5SDimitry Andric   case ObjCRuntime::MacOSX:
4720b57cec5SDimitry Andric   case ObjCRuntime::iOS:
4730b57cec5SDimitry Andric   case ObjCRuntime::WatchOS:
4740b57cec5SDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
4750b57cec5SDimitry Andric     return;
4760b57cec5SDimitry Andric   }
4770b57cec5SDimitry Andric   llvm_unreachable("bad runtime kind");
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
4810b57cec5SDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
4820b57cec5SDimitry Andric }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() {
4850b57cec5SDimitry Andric   // Select a specialized code generation class based on the target, if any.
4860b57cec5SDimitry Andric   // If it does not exist use the default implementation.
4870b57cec5SDimitry Andric   switch (getTriple().getArch()) {
4880b57cec5SDimitry Andric   case llvm::Triple::nvptx:
4890b57cec5SDimitry Andric   case llvm::Triple::nvptx64:
490e8d8bef9SDimitry Andric   case llvm::Triple::amdgcn:
49106c3fb27SDimitry Andric     assert(getLangOpts().OpenMPIsTargetDevice &&
492349cc55cSDimitry Andric            "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
493349cc55cSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
494e8d8bef9SDimitry Andric     break;
4950b57cec5SDimitry Andric   default:
4960b57cec5SDimitry Andric     if (LangOpts.OpenMPSimd)
4970b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
4980b57cec5SDimitry Andric     else
4990b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
5000b57cec5SDimitry Andric     break;
5010b57cec5SDimitry Andric   }
5020b57cec5SDimitry Andric }
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() {
5050b57cec5SDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
5060b57cec5SDimitry Andric }
5070b57cec5SDimitry Andric 
50881ad6265SDimitry Andric void CodeGenModule::createHLSLRuntime() {
50981ad6265SDimitry Andric   HLSLRuntime.reset(new CGHLSLRuntime(*this));
51081ad6265SDimitry Andric }
51181ad6265SDimitry Andric 
5120b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
5130b57cec5SDimitry Andric   Replacements[Name] = C;
5140b57cec5SDimitry Andric }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric void CodeGenModule::applyReplacements() {
5170b57cec5SDimitry Andric   for (auto &I : Replacements) {
51806c3fb27SDimitry Andric     StringRef MangledName = I.first;
5190b57cec5SDimitry Andric     llvm::Constant *Replacement = I.second;
5200b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5210b57cec5SDimitry Andric     if (!Entry)
5220b57cec5SDimitry Andric       continue;
5230b57cec5SDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
5240b57cec5SDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
5250b57cec5SDimitry Andric     if (!NewF) {
5260b57cec5SDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
5270b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
5280b57cec5SDimitry Andric       } else {
5290b57cec5SDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
5300b57cec5SDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
5310b57cec5SDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
5320b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
5330b57cec5SDimitry Andric       }
5340b57cec5SDimitry Andric     }
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric     // Replace old with new, but keep the old order.
5370b57cec5SDimitry Andric     OldF->replaceAllUsesWith(Replacement);
5380b57cec5SDimitry Andric     if (NewF) {
5390b57cec5SDimitry Andric       NewF->removeFromParent();
5400b57cec5SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
5410b57cec5SDimitry Andric                                                        NewF);
5420b57cec5SDimitry Andric     }
5430b57cec5SDimitry Andric     OldF->eraseFromParent();
5440b57cec5SDimitry Andric   }
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
5480b57cec5SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
5490b57cec5SDimitry Andric }
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
5520b57cec5SDimitry Andric   for (auto &I : GlobalValReplacements) {
5530b57cec5SDimitry Andric     llvm::GlobalValue *GV = I.first;
5540b57cec5SDimitry Andric     llvm::Constant *C = I.second;
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric     GV->replaceAllUsesWith(C);
5570b57cec5SDimitry Andric     GV->eraseFromParent();
5580b57cec5SDimitry Andric   }
5590b57cec5SDimitry Andric }
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a
5620b57cec5SDimitry Andric // linear structure.
563349cc55cSDimitry Andric static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
564349cc55cSDimitry Andric   const llvm::Constant *C;
565349cc55cSDimitry Andric   if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
566349cc55cSDimitry Andric     C = GA->getAliasee();
567349cc55cSDimitry Andric   else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
568349cc55cSDimitry Andric     C = GI->getResolver();
569349cc55cSDimitry Andric   else
570349cc55cSDimitry Andric     return GV;
571349cc55cSDimitry Andric 
572349cc55cSDimitry Andric   const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
573349cc55cSDimitry Andric   if (!AliaseeGV)
5740b57cec5SDimitry Andric     return nullptr;
575349cc55cSDimitry Andric 
576349cc55cSDimitry Andric   const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
577349cc55cSDimitry Andric   if (FinalGV == GV)
5780b57cec5SDimitry Andric     return nullptr;
579349cc55cSDimitry Andric 
580349cc55cSDimitry Andric   return FinalGV;
5810b57cec5SDimitry Andric }
582349cc55cSDimitry Andric 
58306c3fb27SDimitry Andric static bool checkAliasedGlobal(
5845f757f3fSDimitry Andric     const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location,
5855f757f3fSDimitry Andric     bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
58606c3fb27SDimitry Andric     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
58706c3fb27SDimitry Andric     SourceRange AliasRange) {
588349cc55cSDimitry Andric   GV = getAliasedGlobal(Alias);
589349cc55cSDimitry Andric   if (!GV) {
590349cc55cSDimitry Andric     Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
591349cc55cSDimitry Andric     return false;
592349cc55cSDimitry Andric   }
593349cc55cSDimitry Andric 
5945f757f3fSDimitry Andric   if (GV->hasCommonLinkage()) {
5955f757f3fSDimitry Andric     const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
5965f757f3fSDimitry Andric     if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
5975f757f3fSDimitry Andric       Diags.Report(Location, diag::err_alias_to_common);
5985f757f3fSDimitry Andric       return false;
5995f757f3fSDimitry Andric     }
6005f757f3fSDimitry Andric   }
6015f757f3fSDimitry Andric 
602349cc55cSDimitry Andric   if (GV->isDeclaration()) {
603349cc55cSDimitry Andric     Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
60406c3fb27SDimitry Andric     Diags.Report(Location, diag::note_alias_requires_mangled_name)
60506c3fb27SDimitry Andric         << IsIFunc << IsIFunc;
60606c3fb27SDimitry Andric     // Provide a note if the given function is not found and exists as a
60706c3fb27SDimitry Andric     // mangled name.
60806c3fb27SDimitry Andric     for (const auto &[Decl, Name] : MangledDeclNames) {
60906c3fb27SDimitry Andric       if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) {
61006c3fb27SDimitry Andric         if (ND->getName() == GV->getName()) {
61106c3fb27SDimitry Andric           Diags.Report(Location, diag::note_alias_mangled_name_alternative)
61206c3fb27SDimitry Andric               << Name
61306c3fb27SDimitry Andric               << FixItHint::CreateReplacement(
61406c3fb27SDimitry Andric                      AliasRange,
61506c3fb27SDimitry Andric                      (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")")
61606c3fb27SDimitry Andric                          .str());
61706c3fb27SDimitry Andric         }
61806c3fb27SDimitry Andric       }
61906c3fb27SDimitry Andric     }
620349cc55cSDimitry Andric     return false;
621349cc55cSDimitry Andric   }
622349cc55cSDimitry Andric 
623349cc55cSDimitry Andric   if (IsIFunc) {
624349cc55cSDimitry Andric     // Check resolver function type.
625349cc55cSDimitry Andric     const auto *F = dyn_cast<llvm::Function>(GV);
626349cc55cSDimitry Andric     if (!F) {
627349cc55cSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
628349cc55cSDimitry Andric           << IsIFunc << IsIFunc;
629349cc55cSDimitry Andric       return false;
630349cc55cSDimitry Andric     }
631349cc55cSDimitry Andric 
632349cc55cSDimitry Andric     llvm::FunctionType *FTy = F->getFunctionType();
633349cc55cSDimitry Andric     if (!FTy->getReturnType()->isPointerTy()) {
634349cc55cSDimitry Andric       Diags.Report(Location, diag::err_ifunc_resolver_return);
635349cc55cSDimitry Andric       return false;
636349cc55cSDimitry Andric     }
637349cc55cSDimitry Andric   }
638349cc55cSDimitry Andric 
639349cc55cSDimitry Andric   return true;
6400b57cec5SDimitry Andric }
6410b57cec5SDimitry Andric 
6420fca6ea1SDimitry Andric // Emit a warning if toc-data attribute is requested for global variables that
6430fca6ea1SDimitry Andric // have aliases and remove the toc-data attribute.
6440fca6ea1SDimitry Andric static void checkAliasForTocData(llvm::GlobalVariable *GVar,
6450fca6ea1SDimitry Andric                                  const CodeGenOptions &CodeGenOpts,
6460fca6ea1SDimitry Andric                                  DiagnosticsEngine &Diags,
6470fca6ea1SDimitry Andric                                  SourceLocation Location) {
6480fca6ea1SDimitry Andric   if (GVar->hasAttribute("toc-data")) {
6490fca6ea1SDimitry Andric     auto GVId = GVar->getName();
6500fca6ea1SDimitry Andric     // Is this a global variable specified by the user as local?
6510fca6ea1SDimitry Andric     if ((llvm::binary_search(CodeGenOpts.TocDataVarsUserSpecified, GVId))) {
6520fca6ea1SDimitry Andric       Diags.Report(Location, diag::warn_toc_unsupported_type)
6530fca6ea1SDimitry Andric           << GVId << "the variable has an alias";
6540fca6ea1SDimitry Andric     }
6550fca6ea1SDimitry Andric     llvm::AttributeSet CurrAttributes = GVar->getAttributes();
6560fca6ea1SDimitry Andric     llvm::AttributeSet NewAttributes =
6570fca6ea1SDimitry Andric         CurrAttributes.removeAttribute(GVar->getContext(), "toc-data");
6580fca6ea1SDimitry Andric     GVar->setAttributes(NewAttributes);
6590fca6ea1SDimitry Andric   }
6600fca6ea1SDimitry Andric }
6610fca6ea1SDimitry Andric 
6620b57cec5SDimitry Andric void CodeGenModule::checkAliases() {
6630b57cec5SDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
6640b57cec5SDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
6650b57cec5SDimitry Andric   // and aliases during codegen.
6660b57cec5SDimitry Andric   bool Error = false;
6670b57cec5SDimitry Andric   DiagnosticsEngine &Diags = getDiags();
6680b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
6690b57cec5SDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
6700b57cec5SDimitry Andric     SourceLocation Location;
67106c3fb27SDimitry Andric     SourceRange Range;
6720b57cec5SDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
67306c3fb27SDimitry Andric     if (const Attr *A = D->getDefiningAttr()) {
6740b57cec5SDimitry Andric       Location = A->getLocation();
67506c3fb27SDimitry Andric       Range = A->getRange();
67606c3fb27SDimitry Andric     } else
6770b57cec5SDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
678349cc55cSDimitry Andric 
6790b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
680349cc55cSDimitry Andric     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
681349cc55cSDimitry Andric     const llvm::GlobalValue *GV = nullptr;
6825f757f3fSDimitry Andric     if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV,
68306c3fb27SDimitry Andric                             MangledDeclNames, Range)) {
6840b57cec5SDimitry Andric       Error = true;
685349cc55cSDimitry Andric       continue;
6860b57cec5SDimitry Andric     }
6870b57cec5SDimitry Andric 
6880fca6ea1SDimitry Andric     if (getContext().getTargetInfo().getTriple().isOSAIX())
6890fca6ea1SDimitry Andric       if (const llvm::GlobalVariable *GVar =
6900fca6ea1SDimitry Andric               dyn_cast<const llvm::GlobalVariable>(GV))
6910fca6ea1SDimitry Andric         checkAliasForTocData(const_cast<llvm::GlobalVariable *>(GVar),
6920fca6ea1SDimitry Andric                              getCodeGenOpts(), Diags, Location);
6930fca6ea1SDimitry Andric 
694349cc55cSDimitry Andric     llvm::Constant *Aliasee =
695349cc55cSDimitry Andric         IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
696349cc55cSDimitry Andric                 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
697349cc55cSDimitry Andric 
6980b57cec5SDimitry Andric     llvm::GlobalValue *AliaseeGV;
6990b57cec5SDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
7000b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
7010b57cec5SDimitry Andric     else
7020b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
7050b57cec5SDimitry Andric       StringRef AliasSection = SA->getName();
7060b57cec5SDimitry Andric       if (AliasSection != AliaseeGV->getSection())
7070b57cec5SDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
7080b57cec5SDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
7090b57cec5SDimitry Andric     }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
7120b57cec5SDimitry Andric     // this since the object semantics would not match the IL one. For
7130b57cec5SDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
7140b57cec5SDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
7150b57cec5SDimitry Andric     // expecting the link to be weak.
716349cc55cSDimitry Andric     if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
7170b57cec5SDimitry Andric       if (GA->isInterposable()) {
7180b57cec5SDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
7190b57cec5SDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
7200b57cec5SDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
721349cc55cSDimitry Andric             GA->getAliasee(), Alias->getType());
722349cc55cSDimitry Andric 
723349cc55cSDimitry Andric         if (IsIFunc)
724349cc55cSDimitry Andric           cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
725349cc55cSDimitry Andric         else
726349cc55cSDimitry Andric           cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
7270b57cec5SDimitry Andric       }
7280b57cec5SDimitry Andric     }
7290fca6ea1SDimitry Andric     // ifunc resolvers are usually implemented to run before sanitizer
7300fca6ea1SDimitry Andric     // initialization. Disable instrumentation to prevent the ordering issue.
7310fca6ea1SDimitry Andric     if (IsIFunc)
7320fca6ea1SDimitry Andric       cast<llvm::Function>(Aliasee)->addFnAttr(
7330fca6ea1SDimitry Andric           llvm::Attribute::DisableSanitizerInstrumentation);
7340b57cec5SDimitry Andric   }
7350b57cec5SDimitry Andric   if (!Error)
7360b57cec5SDimitry Andric     return;
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
7390b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
740349cc55cSDimitry Andric     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
7410b57cec5SDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
7420b57cec5SDimitry Andric     Alias->eraseFromParent();
7430b57cec5SDimitry Andric   }
7440b57cec5SDimitry Andric }
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric void CodeGenModule::clear() {
7470b57cec5SDimitry Andric   DeferredDeclsToEmit.clear();
748753f127fSDimitry Andric   EmittedDeferredDecls.clear();
7495f757f3fSDimitry Andric   DeferredAnnotations.clear();
7500b57cec5SDimitry Andric   if (OpenMPRuntime)
7510b57cec5SDimitry Andric     OpenMPRuntime->clear();
7520b57cec5SDimitry Andric }
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
7550b57cec5SDimitry Andric                                        StringRef MainFile) {
7560b57cec5SDimitry Andric   if (!hasDiagnostics())
7570b57cec5SDimitry Andric     return;
7580b57cec5SDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
7590b57cec5SDimitry Andric     if (MainFile.empty())
7600b57cec5SDimitry Andric       MainFile = "<stdin>";
7610b57cec5SDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
7620b57cec5SDimitry Andric   } else {
7630b57cec5SDimitry Andric     if (Mismatched > 0)
7640b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric     if (Missing > 0)
7670b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
7680b57cec5SDimitry Andric   }
7690b57cec5SDimitry Andric }
7700b57cec5SDimitry Andric 
7717a6dacacSDimitry Andric static std::optional<llvm::GlobalValue::VisibilityTypes>
7727a6dacacSDimitry Andric getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) {
7737a6dacacSDimitry Andric   // Map to LLVM visibility.
7747a6dacacSDimitry Andric   switch (K) {
7757a6dacacSDimitry Andric   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep:
7767a6dacacSDimitry Andric     return std::nullopt;
7777a6dacacSDimitry Andric   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default:
7787a6dacacSDimitry Andric     return llvm::GlobalValue::DefaultVisibility;
7797a6dacacSDimitry Andric   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden:
7807a6dacacSDimitry Andric     return llvm::GlobalValue::HiddenVisibility;
7817a6dacacSDimitry Andric   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected:
7827a6dacacSDimitry Andric     return llvm::GlobalValue::ProtectedVisibility;
7837a6dacacSDimitry Andric   }
7847a6dacacSDimitry Andric   llvm_unreachable("unknown option value!");
7857a6dacacSDimitry Andric }
7867a6dacacSDimitry Andric 
7877a6dacacSDimitry Andric void setLLVMVisibility(llvm::GlobalValue &GV,
7887a6dacacSDimitry Andric                        std::optional<llvm::GlobalValue::VisibilityTypes> V) {
7897a6dacacSDimitry Andric   if (!V)
790e8d8bef9SDimitry Andric     return;
791e8d8bef9SDimitry Andric 
792e8d8bef9SDimitry Andric   // Reset DSO locality before setting the visibility. This removes
793e8d8bef9SDimitry Andric   // any effects that visibility options and annotations may have
794e8d8bef9SDimitry Andric   // had on the DSO locality. Setting the visibility will implicitly set
795e8d8bef9SDimitry Andric   // appropriate globals to DSO Local; however, this will be pessimistic
796e8d8bef9SDimitry Andric   // w.r.t. to the normal compiler IRGen.
797e8d8bef9SDimitry Andric   GV.setDSOLocal(false);
7987a6dacacSDimitry Andric   GV.setVisibility(*V);
7997a6dacacSDimitry Andric }
800e8d8bef9SDimitry Andric 
8017a6dacacSDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
8027a6dacacSDimitry Andric                                              llvm::Module &M) {
8037a6dacacSDimitry Andric   if (!LO.VisibilityFromDLLStorageClass)
8047a6dacacSDimitry Andric     return;
8057a6dacacSDimitry Andric 
8067a6dacacSDimitry Andric   std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
8077a6dacacSDimitry Andric       getLLVMVisibility(LO.getDLLExportVisibility());
8087a6dacacSDimitry Andric 
8097a6dacacSDimitry Andric   std::optional<llvm::GlobalValue::VisibilityTypes>
8107a6dacacSDimitry Andric       NoDLLStorageClassVisibility =
8117a6dacacSDimitry Andric           getLLVMVisibility(LO.getNoDLLStorageClassVisibility());
8127a6dacacSDimitry Andric 
8137a6dacacSDimitry Andric   std::optional<llvm::GlobalValue::VisibilityTypes>
8147a6dacacSDimitry Andric       ExternDeclDLLImportVisibility =
8157a6dacacSDimitry Andric           getLLVMVisibility(LO.getExternDeclDLLImportVisibility());
8167a6dacacSDimitry Andric 
8177a6dacacSDimitry Andric   std::optional<llvm::GlobalValue::VisibilityTypes>
8187a6dacacSDimitry Andric       ExternDeclNoDLLStorageClassVisibility =
8197a6dacacSDimitry Andric           getLLVMVisibility(LO.getExternDeclNoDLLStorageClassVisibility());
8207a6dacacSDimitry Andric 
8217a6dacacSDimitry Andric   for (llvm::GlobalValue &GV : M.global_values()) {
8227a6dacacSDimitry Andric     if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
8237a6dacacSDimitry Andric       continue;
8247a6dacacSDimitry Andric 
8257a6dacacSDimitry Andric     if (GV.isDeclarationForLinker())
8267a6dacacSDimitry Andric       setLLVMVisibility(GV, GV.getDLLStorageClass() ==
827e8d8bef9SDimitry Andric                                     llvm::GlobalValue::DLLImportStorageClass
828e8d8bef9SDimitry Andric                                 ? ExternDeclDLLImportVisibility
829e8d8bef9SDimitry Andric                                 : ExternDeclNoDLLStorageClassVisibility);
8307a6dacacSDimitry Andric     else
8317a6dacacSDimitry Andric       setLLVMVisibility(GV, GV.getDLLStorageClass() ==
832e8d8bef9SDimitry Andric                                     llvm::GlobalValue::DLLExportStorageClass
833e8d8bef9SDimitry Andric                                 ? DLLExportVisibility
834e8d8bef9SDimitry Andric                                 : NoDLLStorageClassVisibility);
835e8d8bef9SDimitry Andric 
836e8d8bef9SDimitry Andric     GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
837e8d8bef9SDimitry Andric   }
838e8d8bef9SDimitry Andric }
839e8d8bef9SDimitry Andric 
8405f757f3fSDimitry Andric static bool isStackProtectorOn(const LangOptions &LangOpts,
8415f757f3fSDimitry Andric                                const llvm::Triple &Triple,
8425f757f3fSDimitry Andric                                clang::LangOptions::StackProtectorMode Mode) {
8435f757f3fSDimitry Andric   if (Triple.isAMDGPU() || Triple.isNVPTX())
8445f757f3fSDimitry Andric     return false;
8455f757f3fSDimitry Andric   return LangOpts.getStackProtector() == Mode;
8465f757f3fSDimitry Andric }
8475f757f3fSDimitry Andric 
8480b57cec5SDimitry Andric void CodeGenModule::Release() {
84906c3fb27SDimitry Andric   Module *Primary = getContext().getCurrentNamedModule();
85061cfbce3SDimitry Andric   if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
851fcaf7f86SDimitry Andric     EmitModuleInitializers(Primary);
8520b57cec5SDimitry Andric   EmitDeferred();
853753f127fSDimitry Andric   DeferredDecls.insert(EmittedDeferredDecls.begin(),
854753f127fSDimitry Andric                        EmittedDeferredDecls.end());
855753f127fSDimitry Andric   EmittedDeferredDecls.clear();
8560b57cec5SDimitry Andric   EmitVTablesOpportunistically();
8570b57cec5SDimitry Andric   applyGlobalValReplacements();
8580b57cec5SDimitry Andric   applyReplacements();
8590b57cec5SDimitry Andric   emitMultiVersionFunctions();
860bdd1243dSDimitry Andric 
861bdd1243dSDimitry Andric   if (Context.getLangOpts().IncrementalExtensions &&
862bdd1243dSDimitry Andric       GlobalTopLevelStmtBlockInFlight.first) {
863bdd1243dSDimitry Andric     const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
864bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
865bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
866bdd1243dSDimitry Andric   }
867bdd1243dSDimitry Andric 
86806c3fb27SDimitry Andric   // Module implementations are initialized the same way as a regular TU that
86906c3fb27SDimitry Andric   // imports one or more modules.
870fcaf7f86SDimitry Andric   if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
871fcaf7f86SDimitry Andric     EmitCXXModuleInitFunc(Primary);
872fcaf7f86SDimitry Andric   else
8730b57cec5SDimitry Andric     EmitCXXGlobalInitFunc();
8745ffd83dbSDimitry Andric   EmitCXXGlobalCleanUpFunc();
8750b57cec5SDimitry Andric   registerGlobalDtorsWithAtExit();
8760b57cec5SDimitry Andric   EmitCXXThreadLocalInitFunc();
8770b57cec5SDimitry Andric   if (ObjCRuntime)
8780b57cec5SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
8790b57cec5SDimitry Andric       AddGlobalCtor(ObjCInitFunction);
880fe6060f1SDimitry Andric   if (Context.getLangOpts().CUDA && CUDARuntime) {
881fe6060f1SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
8820b57cec5SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
8830b57cec5SDimitry Andric   }
8840b57cec5SDimitry Andric   if (OpenMPRuntime) {
885a7dea167SDimitry Andric     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
8860b57cec5SDimitry Andric     OpenMPRuntime->clear();
8870b57cec5SDimitry Andric   }
8880b57cec5SDimitry Andric   if (PGOReader) {
8890b57cec5SDimitry Andric     getModule().setProfileSummary(
8900b57cec5SDimitry Andric         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
8910b57cec5SDimitry Andric         llvm::ProfileSummary::PSK_Instr);
8920b57cec5SDimitry Andric     if (PGOStats.hasDiagnostics())
8930b57cec5SDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
8940b57cec5SDimitry Andric   }
895bdd1243dSDimitry Andric   llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
896bdd1243dSDimitry Andric     return L.LexOrder < R.LexOrder;
897bdd1243dSDimitry Andric   });
8980b57cec5SDimitry Andric   EmitCtorList(GlobalCtors, "llvm.global_ctors");
8990b57cec5SDimitry Andric   EmitCtorList(GlobalDtors, "llvm.global_dtors");
9000b57cec5SDimitry Andric   EmitGlobalAnnotations();
9010b57cec5SDimitry Andric   EmitStaticExternCAliases();
90281ad6265SDimitry Andric   checkAliases();
9030b57cec5SDimitry Andric   EmitDeferredUnusedCoverageMappings();
904fe6060f1SDimitry Andric   CodeGenPGO(*this).setValueProfilingFlag(getModule());
9050fca6ea1SDimitry Andric   CodeGenPGO(*this).setProfileVersion(getModule());
9060b57cec5SDimitry Andric   if (CoverageMapping)
9070b57cec5SDimitry Andric     CoverageMapping->emit();
9080b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
9090b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
9100b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
9110b57cec5SDimitry Andric   }
912bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
913bdd1243dSDimitry Andric     finalizeKCFITypes();
9140b57cec5SDimitry Andric   emitAtAvailableLinkGuard();
91581ad6265SDimitry Andric   if (Context.getTargetInfo().getTriple().isWasm())
9165ffd83dbSDimitry Andric     EmitMainVoidAlias();
917fe6060f1SDimitry Andric 
9180fca6ea1SDimitry Andric   if (getTriple().isAMDGPU() ||
9190fca6ea1SDimitry Andric       (getTriple().isSPIRV() && getTriple().getVendor() == llvm::Triple::AMD)) {
9200fca6ea1SDimitry Andric     // Emit amdhsa_code_object_version module flag, which is code object version
92181ad6265SDimitry Andric     // times 100.
922bdd1243dSDimitry Andric     if (getTarget().getTargetOpts().CodeObjectVersion !=
9235f757f3fSDimitry Andric         llvm::CodeObjectVersionKind::COV_None) {
92481ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Error,
9250fca6ea1SDimitry Andric                                 "amdhsa_code_object_version",
92681ad6265SDimitry Andric                                 getTarget().getTargetOpts().CodeObjectVersion);
92781ad6265SDimitry Andric     }
92806c3fb27SDimitry Andric 
92906c3fb27SDimitry Andric     // Currently, "-mprintf-kind" option is only supported for HIP
93006c3fb27SDimitry Andric     if (LangOpts.HIP) {
93106c3fb27SDimitry Andric       auto *MDStr = llvm::MDString::get(
93206c3fb27SDimitry Andric           getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal ==
93306c3fb27SDimitry Andric                              TargetOptions::AMDGPUPrintfKind::Hostcall)
93406c3fb27SDimitry Andric                                 ? "hostcall"
93506c3fb27SDimitry Andric                                 : "buffered");
93606c3fb27SDimitry Andric       getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
93706c3fb27SDimitry Andric                                 MDStr);
93806c3fb27SDimitry Andric     }
93981ad6265SDimitry Andric   }
94081ad6265SDimitry Andric 
94181ad6265SDimitry Andric   // Emit a global array containing all external kernels or device variables
94281ad6265SDimitry Andric   // used by host functions and mark it as used for CUDA/HIP. This is necessary
94381ad6265SDimitry Andric   // to get kernels or device variables in archives linked in even if these
94481ad6265SDimitry Andric   // kernels or device variables are only used in host functions.
94581ad6265SDimitry Andric   if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
94681ad6265SDimitry Andric     SmallVector<llvm::Constant *, 8> UsedArray;
94781ad6265SDimitry Andric     for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
94881ad6265SDimitry Andric       GlobalDecl GD;
94981ad6265SDimitry Andric       if (auto *FD = dyn_cast<FunctionDecl>(D))
95081ad6265SDimitry Andric         GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
95181ad6265SDimitry Andric       else
95281ad6265SDimitry Andric         GD = GlobalDecl(D);
95381ad6265SDimitry Andric       UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
95481ad6265SDimitry Andric           GetAddrOfGlobal(GD), Int8PtrTy));
95581ad6265SDimitry Andric     }
95681ad6265SDimitry Andric 
95781ad6265SDimitry Andric     llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
95881ad6265SDimitry Andric 
95981ad6265SDimitry Andric     auto *GV = new llvm::GlobalVariable(
96081ad6265SDimitry Andric         getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
96181ad6265SDimitry Andric         llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
96281ad6265SDimitry Andric     addCompilerUsedGlobal(GV);
96304eeddc0SDimitry Andric   }
9640fca6ea1SDimitry Andric   if (LangOpts.HIP && !getLangOpts().OffloadingNewDriver) {
9650fca6ea1SDimitry Andric     // Emit a unique ID so that host and device binaries from the same
9660fca6ea1SDimitry Andric     // compilation unit can be associated.
9670fca6ea1SDimitry Andric     auto *GV = new llvm::GlobalVariable(
9680fca6ea1SDimitry Andric         getModule(), Int8Ty, false, llvm::GlobalValue::ExternalLinkage,
9690fca6ea1SDimitry Andric         llvm::Constant::getNullValue(Int8Ty),
9700fca6ea1SDimitry Andric         "__hip_cuid_" + getContext().getCUIDHash());
9710fca6ea1SDimitry Andric     addCompilerUsedGlobal(GV);
9720fca6ea1SDimitry Andric   }
9730b57cec5SDimitry Andric   emitLLVMUsed();
9740b57cec5SDimitry Andric   if (SanStats)
9750b57cec5SDimitry Andric     SanStats->finish();
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric   if (CodeGenOpts.Autolink &&
9780b57cec5SDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
9790b57cec5SDimitry Andric     EmitModuleLinkOptions();
9800b57cec5SDimitry Andric   }
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric   // On ELF we pass the dependent library specifiers directly to the linker
9830b57cec5SDimitry Andric   // without manipulating them. This is in contrast to other platforms where
9840b57cec5SDimitry Andric   // they are mapped to a specific linker option by the compiler. This
9850b57cec5SDimitry Andric   // difference is a result of the greater variety of ELF linkers and the fact
9860b57cec5SDimitry Andric   // that ELF linkers tend to handle libraries in a more complicated fashion
9870b57cec5SDimitry Andric   // than on other platforms. This forces us to defer handling the dependent
9880b57cec5SDimitry Andric   // libs to the linker.
9890b57cec5SDimitry Andric   //
9900b57cec5SDimitry Andric   // CUDA/HIP device and host libraries are different. Currently there is no
9910b57cec5SDimitry Andric   // way to differentiate dependent libraries for host or device. Existing
9920b57cec5SDimitry Andric   // usage of #pragma comment(lib, *) is intended for host libraries on
9930b57cec5SDimitry Andric   // Windows. Therefore emit llvm.dependent-libraries only for host.
9940b57cec5SDimitry Andric   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
9950b57cec5SDimitry Andric     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
9960b57cec5SDimitry Andric     for (auto *MD : ELFDependentLibraries)
9970b57cec5SDimitry Andric       NMD->addOperand(MD);
9980b57cec5SDimitry Andric   }
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
1001480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
10020b57cec5SDimitry Andric                               CodeGenOpts.DwarfVersion);
10030b57cec5SDimitry Andric   }
10045ffd83dbSDimitry Andric 
1005fe6060f1SDimitry Andric   if (CodeGenOpts.Dwarf64)
1006fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
1007fe6060f1SDimitry Andric 
10085ffd83dbSDimitry Andric   if (Context.getLangOpts().SemanticInterposition)
10095ffd83dbSDimitry Andric     // Require various optimization to respect semantic interposition.
101004eeddc0SDimitry Andric     getModule().setSemanticInterposition(true);
10115ffd83dbSDimitry Andric 
10120b57cec5SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
10130b57cec5SDimitry Andric     // Indicate that we want CodeView in the metadata.
10140b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
10150b57cec5SDimitry Andric   }
10160b57cec5SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
10170b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
10180b57cec5SDimitry Andric   }
10190b57cec5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
1020480093f4SDimitry Andric     // Function ID tables and checks for Control Flow Guard (cfguard=2).
1021480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
1022480093f4SDimitry Andric   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1023480093f4SDimitry Andric     // Function ID tables for Control Flow Guard (cfguard=1).
1024480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
10250b57cec5SDimitry Andric   }
1026fe6060f1SDimitry Andric   if (CodeGenOpts.EHContGuard) {
1027fe6060f1SDimitry Andric     // Function ID tables for EH Continuation Guard.
1028fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
1029fe6060f1SDimitry Andric   }
1030bdd1243dSDimitry Andric   if (Context.getLangOpts().Kernel) {
1031bdd1243dSDimitry Andric     // Note if we are compiling with /kernel.
1032bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
1033bdd1243dSDimitry Andric   }
10340b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
10350b57cec5SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
10360b57cec5SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
10370b57cec5SDimitry Andric     // by StrictVTablePointers.
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric     llvm::Metadata *Ops[2] = {
10420b57cec5SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
10430b57cec5SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
10440b57cec5SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
10470b57cec5SDimitry Andric                               "StrictVTablePointersRequirement",
10480b57cec5SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
10490b57cec5SDimitry Andric   }
10505ffd83dbSDimitry Andric   if (getModuleDebugInfo())
10510b57cec5SDimitry Andric     // We support a single version in the linked module. The LLVM
10520b57cec5SDimitry Andric     // parser will drop debug info with a different version number
10530b57cec5SDimitry Andric     // (and warn about it, too).
10540b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
10550b57cec5SDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
10580b57cec5SDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
10590b57cec5SDimitry Andric   // TargetLibraryInfo.
10600b57cec5SDimitry Andric   uint64_t WCharWidth =
10610b57cec5SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
10620b57cec5SDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
10630b57cec5SDimitry Andric 
10645f757f3fSDimitry Andric   if (getTriple().isOSzOS()) {
10655f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning,
10665f757f3fSDimitry Andric                               "zos_product_major_version",
10675f757f3fSDimitry Andric                               uint32_t(CLANG_VERSION_MAJOR));
10685f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning,
10695f757f3fSDimitry Andric                               "zos_product_minor_version",
10705f757f3fSDimitry Andric                               uint32_t(CLANG_VERSION_MINOR));
10715f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel",
10725f757f3fSDimitry Andric                               uint32_t(CLANG_VERSION_PATCHLEVEL));
1073cb14a3feSDimitry Andric     std::string ProductId = getClangVendor() + "clang";
10745f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "zos_product_id",
10755f757f3fSDimitry Andric                               llvm::MDString::get(VMContext, ProductId));
10765f757f3fSDimitry Andric 
10775f757f3fSDimitry Andric     // Record the language because we need it for the PPA2.
10785f757f3fSDimitry Andric     StringRef lang_str = languageToString(
10795f757f3fSDimitry Andric         LangStandard::getLangStandardForKind(LangOpts.LangStd).Language);
10805f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language",
10815f757f3fSDimitry Andric                               llvm::MDString::get(VMContext, lang_str));
10825f757f3fSDimitry Andric 
10835f757f3fSDimitry Andric     time_t TT = PreprocessorOpts.SourceDateEpoch
10845f757f3fSDimitry Andric                     ? *PreprocessorOpts.SourceDateEpoch
10855f757f3fSDimitry Andric                     : std::time(nullptr);
10865f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time",
10875f757f3fSDimitry Andric                               static_cast<uint64_t>(TT));
10885f757f3fSDimitry Andric 
10895f757f3fSDimitry Andric     // Multiple modes will be supported here.
10905f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode",
10915f757f3fSDimitry Andric                               llvm::MDString::get(VMContext, "ascii"));
10925f757f3fSDimitry Andric   }
10935f757f3fSDimitry Andric 
10940fca6ea1SDimitry Andric   llvm::Triple T = Context.getTargetInfo().getTriple();
10950fca6ea1SDimitry Andric   if (T.isARM() || T.isThumb()) {
10960b57cec5SDimitry Andric     // The minimum width of an enum in bytes
10970b57cec5SDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
10980b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
10990b57cec5SDimitry Andric   }
11000b57cec5SDimitry Andric 
11010fca6ea1SDimitry Andric   if (T.isRISCV()) {
110213138422SDimitry Andric     StringRef ABIStr = Target.getABI();
110313138422SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
110413138422SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
110513138422SDimitry Andric                               llvm::MDString::get(Ctx, ABIStr));
11063a079333SDimitry Andric 
11073a079333SDimitry Andric     // Add the canonical ISA string as metadata so the backend can set the ELF
11083a079333SDimitry Andric     // attributes correctly. We use AppendUnique so LTO will keep all of the
11093a079333SDimitry Andric     // unique ISA strings that were linked together.
11103a079333SDimitry Andric     const std::vector<std::string> &Features =
11113a079333SDimitry Andric         getTarget().getTargetOpts().Features;
11120fca6ea1SDimitry Andric     auto ParseResult =
11130fca6ea1SDimitry Andric         llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
11143a079333SDimitry Andric     if (!errorToBool(ParseResult.takeError()))
11153a079333SDimitry Andric       getModule().addModuleFlag(
11163a079333SDimitry Andric           llvm::Module::AppendUnique, "riscv-isa",
11173a079333SDimitry Andric           llvm::MDNode::get(
11183a079333SDimitry Andric               Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
111913138422SDimitry Andric   }
112013138422SDimitry Andric 
11210b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
11220b57cec5SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
11230b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
11240b57cec5SDimitry Andric   }
11250b57cec5SDimitry Andric 
11265ffd83dbSDimitry Andric   if (CodeGenOpts.WholeProgramVTables) {
11275ffd83dbSDimitry Andric     // Indicate whether VFE was enabled for this module, so that the
11285ffd83dbSDimitry Andric     // vcall_visibility metadata added under whole program vtables is handled
11295ffd83dbSDimitry Andric     // appropriately in the optimizer.
11305ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
11315ffd83dbSDimitry Andric                               CodeGenOpts.VirtualFunctionElimination);
11325ffd83dbSDimitry Andric   }
11335ffd83dbSDimitry Andric 
1134a7dea167SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1135a7dea167SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
1136a7dea167SDimitry Andric                               "CFI Canonical Jump Tables",
1137a7dea167SDimitry Andric                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1138a7dea167SDimitry Andric   }
1139a7dea167SDimitry Andric 
1140bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1141bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
1142bdd1243dSDimitry Andric     // KCFI assumes patchable-function-prefix is the same for all indirectly
1143bdd1243dSDimitry Andric     // called functions. Store the expected offset for code generation.
1144bdd1243dSDimitry Andric     if (CodeGenOpts.PatchableFunctionEntryOffset)
1145bdd1243dSDimitry Andric       getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
1146bdd1243dSDimitry Andric                                 CodeGenOpts.PatchableFunctionEntryOffset);
1147bdd1243dSDimitry Andric   }
1148bdd1243dSDimitry Andric 
11490b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
11500b57cec5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
11510b57cec5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
1152fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
11530b57cec5SDimitry Andric                               1);
11540b57cec5SDimitry Andric   }
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
11570b57cec5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
11580b57cec5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
1159fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
11600b57cec5SDimitry Andric                               1);
11610b57cec5SDimitry Andric   }
11620b57cec5SDimitry Andric 
1163fcaf7f86SDimitry Andric   if (CodeGenOpts.FunctionReturnThunks)
1164fcaf7f86SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
116504eeddc0SDimitry Andric 
1166bdd1243dSDimitry Andric   if (CodeGenOpts.IndirectBranchCSPrefix)
1167bdd1243dSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
1168bdd1243dSDimitry Andric 
11694824e7fdSDimitry Andric   // Add module metadata for return address signing (ignoring
11704824e7fdSDimitry Andric   // non-leaf/all) and stack tagging. These are actually turned on by function
11714824e7fdSDimitry Andric   // attributes, but we use module metadata to emit build attributes. This is
11724824e7fdSDimitry Andric   // needed for LTO, where the function attributes are inside bitcode
11734824e7fdSDimitry Andric   // serialised into a global variable by the time build attributes are
117481ad6265SDimitry Andric   // emitted, so we can't access them. LTO objects could be compiled with
117581ad6265SDimitry Andric   // different flags therefore module flags are set to "Min" behavior to achieve
117681ad6265SDimitry Andric   // the same end result of the normal build where e.g BTI is off if any object
117781ad6265SDimitry Andric   // doesn't support it.
11784824e7fdSDimitry Andric   if (Context.getTargetInfo().hasFeature("ptrauth") &&
11794824e7fdSDimitry Andric       LangOpts.getSignReturnAddressScope() !=
11804824e7fdSDimitry Andric           LangOptions::SignReturnAddressScopeKind::None)
11814824e7fdSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
11824824e7fdSDimitry Andric                               "sign-return-address-buildattr", 1);
118381ad6265SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
11844824e7fdSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
11854824e7fdSDimitry Andric                               "tag-stack-memory-buildattr", 1);
11864824e7fdSDimitry Andric 
11870fca6ea1SDimitry Andric   if (T.isARM() || T.isThumb() || T.isAArch64()) {
1188972a253aSDimitry Andric     if (LangOpts.BranchTargetEnforcement)
118981ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
1190972a253aSDimitry Andric                                 1);
1191cb14a3feSDimitry Andric     if (LangOpts.BranchProtectionPAuthLR)
1192cb14a3feSDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr",
1193cb14a3feSDimitry Andric                                 1);
1194297eecfbSDimitry Andric     if (LangOpts.GuardedControlStack)
1195297eecfbSDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 1);
1196972a253aSDimitry Andric     if (LangOpts.hasSignReturnAddress())
1197972a253aSDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
1198972a253aSDimitry Andric     if (LangOpts.isSignReturnAddressScopeAll())
119981ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
1200972a253aSDimitry Andric                                 1);
1201972a253aSDimitry Andric     if (!LangOpts.isSignReturnAddressWithAKey())
120281ad6265SDimitry Andric       getModule().addModuleFlag(llvm::Module::Min,
1203972a253aSDimitry Andric                                 "sign-return-address-with-bkey", 1);
12040fca6ea1SDimitry Andric 
12050fca6ea1SDimitry Andric     if (getTriple().isOSLinux()) {
12060fca6ea1SDimitry Andric       assert(getTriple().isOSBinFormatELF());
12070fca6ea1SDimitry Andric       using namespace llvm::ELF;
12080fca6ea1SDimitry Andric       uint64_t PAuthABIVersion =
12090fca6ea1SDimitry Andric           (LangOpts.PointerAuthIntrinsics
12100fca6ea1SDimitry Andric            << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
12110fca6ea1SDimitry Andric           (LangOpts.PointerAuthCalls
12120fca6ea1SDimitry Andric            << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
12130fca6ea1SDimitry Andric           (LangOpts.PointerAuthReturns
12140fca6ea1SDimitry Andric            << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
12150fca6ea1SDimitry Andric           (LangOpts.PointerAuthAuthTraps
12160fca6ea1SDimitry Andric            << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
12170fca6ea1SDimitry Andric           (LangOpts.PointerAuthVTPtrAddressDiscrimination
12180fca6ea1SDimitry Andric            << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
12190fca6ea1SDimitry Andric           (LangOpts.PointerAuthVTPtrTypeDiscrimination
12200fca6ea1SDimitry Andric            << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
12210fca6ea1SDimitry Andric           (LangOpts.PointerAuthInitFini
12220fca6ea1SDimitry Andric            << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI);
12230fca6ea1SDimitry Andric       static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI ==
12240fca6ea1SDimitry Andric                         AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
12250fca6ea1SDimitry Andric                     "Update when new enum items are defined");
12260fca6ea1SDimitry Andric       if (PAuthABIVersion != 0) {
12270fca6ea1SDimitry Andric         getModule().addModuleFlag(llvm::Module::Error,
12280fca6ea1SDimitry Andric                                   "aarch64-elf-pauthabi-platform",
12290fca6ea1SDimitry Andric                                   AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
12300fca6ea1SDimitry Andric         getModule().addModuleFlag(llvm::Module::Error,
12310fca6ea1SDimitry Andric                                   "aarch64-elf-pauthabi-version",
12320fca6ea1SDimitry Andric                                   PAuthABIVersion);
12330fca6ea1SDimitry Andric       }
12340fca6ea1SDimitry Andric     }
1235e8d8bef9SDimitry Andric   }
1236e8d8bef9SDimitry Andric 
12375f757f3fSDimitry Andric   if (CodeGenOpts.StackClashProtector)
12385f757f3fSDimitry Andric     getModule().addModuleFlag(
12395f757f3fSDimitry Andric         llvm::Module::Override, "probe-stack",
12405f757f3fSDimitry Andric         llvm::MDString::get(TheModule.getContext(), "inline-asm"));
12415f757f3fSDimitry Andric 
12425f757f3fSDimitry Andric   if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
12435f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size",
12445f757f3fSDimitry Andric                               CodeGenOpts.StackProbeSize);
12455f757f3fSDimitry Andric 
1246e8d8bef9SDimitry Andric   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1247e8d8bef9SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
1248e8d8bef9SDimitry Andric     getModule().addModuleFlag(
1249e8d8bef9SDimitry Andric         llvm::Module::Error, "MemProfProfileFilename",
1250e8d8bef9SDimitry Andric         llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1251e8d8bef9SDimitry Andric   }
1252e8d8bef9SDimitry Andric 
12530b57cec5SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
12540b57cec5SDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
12550b57cec5SDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
12560b57cec5SDimitry Andric     // property.)
12570b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
12585ffd83dbSDimitry Andric                               CodeGenOpts.FP32DenormalMode.Output !=
12595ffd83dbSDimitry Andric                                   llvm::DenormalMode::IEEE);
12600b57cec5SDimitry Andric   }
12610b57cec5SDimitry Andric 
1262fe6060f1SDimitry Andric   if (LangOpts.EHAsynch)
1263fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
1264fe6060f1SDimitry Andric 
1265fe6060f1SDimitry Andric   // Indicate whether this Module was compiled with -fopenmp
1266fe6060f1SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1267fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
126806c3fb27SDimitry Andric   if (getLangOpts().OpenMPIsTargetDevice)
1269fe6060f1SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
1270fe6060f1SDimitry Andric                               LangOpts.OpenMP);
1271fe6060f1SDimitry Andric 
12720b57cec5SDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
127381ad6265SDimitry Andric   if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
12740b57cec5SDimitry Andric     EmitOpenCLMetadata();
12750b57cec5SDimitry Andric     // Emit SPIR version.
12760b57cec5SDimitry Andric     if (getTriple().isSPIR()) {
12770b57cec5SDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
12780b57cec5SDimitry Andric       // opencl.spir.version named metadata.
1279349cc55cSDimitry Andric       // C++ for OpenCL has a distinct mapping for version compatibility with
1280349cc55cSDimitry Andric       // OpenCL.
1281349cc55cSDimitry Andric       auto Version = LangOpts.getOpenCLCompatibleVersion();
12820b57cec5SDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
12830b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
12840b57cec5SDimitry Andric               Int32Ty, Version / 100)),
12850b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
12860b57cec5SDimitry Andric               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
12870b57cec5SDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
12880b57cec5SDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
12890b57cec5SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
12900b57cec5SDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
12910b57cec5SDimitry Andric     }
12920b57cec5SDimitry Andric   }
12930b57cec5SDimitry Andric 
129481ad6265SDimitry Andric   // HLSL related end of code gen work items.
129581ad6265SDimitry Andric   if (LangOpts.HLSL)
129681ad6265SDimitry Andric     getHLSLRuntime().finishCodeGen();
129781ad6265SDimitry Andric 
12980b57cec5SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
12990b57cec5SDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
13000b57cec5SDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
13010b57cec5SDimitry Andric     if (Context.getLangOpts().PIE)
13020b57cec5SDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
13030b57cec5SDimitry Andric   }
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
13060b57cec5SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
13070b57cec5SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
13080b57cec5SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
13090b57cec5SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
13100b57cec5SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
13110b57cec5SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
13120b57cec5SDimitry Andric                   .Default(~0u);
13130b57cec5SDimitry Andric     if (CM != ~0u) {
13140b57cec5SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
13150b57cec5SDimitry Andric       getModule().setCodeModel(codeModel);
13165f757f3fSDimitry Andric 
13177a6dacacSDimitry Andric       if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
13185f757f3fSDimitry Andric           Context.getTargetInfo().getTriple().getArch() ==
13195f757f3fSDimitry Andric               llvm::Triple::x86_64) {
13205f757f3fSDimitry Andric         getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold);
13215f757f3fSDimitry Andric       }
13220b57cec5SDimitry Andric     }
13230b57cec5SDimitry Andric   }
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   if (CodeGenOpts.NoPLT)
13260b57cec5SDimitry Andric     getModule().setRtLibUseGOT();
132706c3fb27SDimitry Andric   if (getTriple().isOSBinFormatELF() &&
132806c3fb27SDimitry Andric       CodeGenOpts.DirectAccessExternalData !=
132906c3fb27SDimitry Andric           getModule().getDirectAccessExternalData()) {
133006c3fb27SDimitry Andric     getModule().setDirectAccessExternalData(
133106c3fb27SDimitry Andric         CodeGenOpts.DirectAccessExternalData);
133206c3fb27SDimitry Andric   }
1333fe6060f1SDimitry Andric   if (CodeGenOpts.UnwindTables)
133481ad6265SDimitry Andric     getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1335fe6060f1SDimitry Andric 
1336fe6060f1SDimitry Andric   switch (CodeGenOpts.getFramePointer()) {
1337fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::None:
1338fe6060f1SDimitry Andric     // 0 ("none") is the default.
1339fe6060f1SDimitry Andric     break;
13400fca6ea1SDimitry Andric   case CodeGenOptions::FramePointerKind::Reserved:
13410fca6ea1SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::Reserved);
13420fca6ea1SDimitry Andric     break;
1343fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::NonLeaf:
1344fe6060f1SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1345fe6060f1SDimitry Andric     break;
1346fe6060f1SDimitry Andric   case CodeGenOptions::FramePointerKind::All:
1347fe6060f1SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::All);
1348fe6060f1SDimitry Andric     break;
1349fe6060f1SDimitry Andric   }
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric   SimplifyPersonality();
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric   if (getCodeGenOpts().EmitDeclMetadata)
13540b57cec5SDimitry Andric     EmitDeclMetadata();
13550b57cec5SDimitry Andric 
135606c3fb27SDimitry Andric   if (getCodeGenOpts().CoverageNotesFile.size() ||
135706c3fb27SDimitry Andric       getCodeGenOpts().CoverageDataFile.size())
13580b57cec5SDimitry Andric     EmitCoverageFile();
13590b57cec5SDimitry Andric 
13605ffd83dbSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
13615ffd83dbSDimitry Andric     DI->finalize();
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
13640b57cec5SDimitry Andric     EmitVersionIdentMetadata();
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
13670b57cec5SDimitry Andric     EmitCommandLineMetadata();
13680b57cec5SDimitry Andric 
1369fe6060f1SDimitry Andric   if (!getCodeGenOpts().StackProtectorGuard.empty())
1370fe6060f1SDimitry Andric     getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1371fe6060f1SDimitry Andric   if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1372fe6060f1SDimitry Andric     getModule().setStackProtectorGuardReg(
1373fe6060f1SDimitry Andric         getCodeGenOpts().StackProtectorGuardReg);
1374753f127fSDimitry Andric   if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1375753f127fSDimitry Andric     getModule().setStackProtectorGuardSymbol(
1376753f127fSDimitry Andric         getCodeGenOpts().StackProtectorGuardSymbol);
1377fe6060f1SDimitry Andric   if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1378fe6060f1SDimitry Andric     getModule().setStackProtectorGuardOffset(
1379fe6060f1SDimitry Andric         getCodeGenOpts().StackProtectorGuardOffset);
1380fe6060f1SDimitry Andric   if (getCodeGenOpts().StackAlignment)
1381fe6060f1SDimitry Andric     getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1382349cc55cSDimitry Andric   if (getCodeGenOpts().SkipRaxSetup)
1383349cc55cSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
13845f757f3fSDimitry Andric   if (getLangOpts().RegCall4)
13855f757f3fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1);
1386fe6060f1SDimitry Andric 
138706c3fb27SDimitry Andric   if (getContext().getTargetInfo().getMaxTLSAlign())
138806c3fb27SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
138906c3fb27SDimitry Andric                               getContext().getTargetInfo().getMaxTLSAlign());
139006c3fb27SDimitry Andric 
13915f757f3fSDimitry Andric   getTargetCodeGenInfo().emitTargetGlobals(*this);
13925f757f3fSDimitry Andric 
13935ffd83dbSDimitry Andric   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
13945ffd83dbSDimitry Andric 
13955ffd83dbSDimitry Andric   EmitBackendOptionsMetadata(getCodeGenOpts());
1396e8d8bef9SDimitry Andric 
139781ad6265SDimitry Andric   // If there is device offloading code embed it in the host now.
139881ad6265SDimitry Andric   EmbedObject(&getModule(), CodeGenOpts, getDiags());
139981ad6265SDimitry Andric 
1400e8d8bef9SDimitry Andric   // Set visibility from DLL storage class
1401e8d8bef9SDimitry Andric   // We do this at the end of LLVM IR generation; after any operation
1402e8d8bef9SDimitry Andric   // that might affect the DLL storage class or the visibility, and
1403e8d8bef9SDimitry Andric   // before anything that might act on these.
1404e8d8bef9SDimitry Andric   setVisibilityFromDLLStorageClass(LangOpts, getModule());
14050fca6ea1SDimitry Andric 
14060fca6ea1SDimitry Andric   // Check the tail call symbols are truly undefined.
14070fca6ea1SDimitry Andric   if (getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
14080fca6ea1SDimitry Andric     for (auto &I : MustTailCallUndefinedGlobals) {
14090fca6ea1SDimitry Andric       if (!I.first->isDefined())
14100fca6ea1SDimitry Andric         getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
14110fca6ea1SDimitry Andric       else {
14120fca6ea1SDimitry Andric         StringRef MangledName = getMangledName(GlobalDecl(I.first));
14130fca6ea1SDimitry Andric         llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
14140fca6ea1SDimitry Andric         if (!Entry || Entry->isWeakForLinker() ||
14150fca6ea1SDimitry Andric             Entry->isDeclarationForLinker())
14160fca6ea1SDimitry Andric           getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
14170fca6ea1SDimitry Andric       }
14180fca6ea1SDimitry Andric     }
14190fca6ea1SDimitry Andric   }
14200b57cec5SDimitry Andric }
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
14230b57cec5SDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
14240b57cec5SDimitry Andric   // opencl.ocl.version named metadata node.
14250fca6ea1SDimitry Andric   // C++ for OpenCL has a distinct mapping for versions compatible with OpenCL.
14260fca6ea1SDimitry Andric   auto CLVersion = LangOpts.getOpenCLCompatibleVersion();
14270fca6ea1SDimitry Andric 
14280fca6ea1SDimitry Andric   auto EmitVersion = [this](StringRef MDName, int Version) {
14290b57cec5SDimitry Andric     llvm::Metadata *OCLVerElts[] = {
14300fca6ea1SDimitry Andric         llvm::ConstantAsMetadata::get(
14310fca6ea1SDimitry Andric             llvm::ConstantInt::get(Int32Ty, Version / 100)),
14320fca6ea1SDimitry Andric         llvm::ConstantAsMetadata::get(
14330fca6ea1SDimitry Andric             llvm::ConstantInt::get(Int32Ty, (Version % 100) / 10))};
14340fca6ea1SDimitry Andric     llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
14350b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
14360b57cec5SDimitry Andric     OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
14370fca6ea1SDimitry Andric   };
14380fca6ea1SDimitry Andric 
14390fca6ea1SDimitry Andric   EmitVersion("opencl.ocl.version", CLVersion);
14400fca6ea1SDimitry Andric   if (LangOpts.OpenCLCPlusPlus) {
14410fca6ea1SDimitry Andric     // In addition to the OpenCL compatible version, emit the C++ version.
14420fca6ea1SDimitry Andric     EmitVersion("opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
14430fca6ea1SDimitry Andric   }
14440b57cec5SDimitry Andric }
14450b57cec5SDimitry Andric 
14465ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata(
144706c3fb27SDimitry Andric     const CodeGenOptions &CodeGenOpts) {
1448bdd1243dSDimitry Andric   if (getTriple().isRISCV()) {
144906c3fb27SDimitry Andric     getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
14505ffd83dbSDimitry Andric                               CodeGenOpts.SmallDataLimit);
14515ffd83dbSDimitry Andric   }
14525ffd83dbSDimitry Andric }
14535ffd83dbSDimitry Andric 
14540b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
14550b57cec5SDimitry Andric   // Make sure that this type is translated.
1456*5deeebd8SDimitry Andric   getTypes().UpdateCompletedType(TD);
14570b57cec5SDimitry Andric }
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
14600b57cec5SDimitry Andric   // Make sure that this type is translated.
1461*5deeebd8SDimitry Andric   getTypes().RefreshTypeCacheForClass(RD);
14620b57cec5SDimitry Andric }
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
14650b57cec5SDimitry Andric   if (!TBAA)
14660b57cec5SDimitry Andric     return nullptr;
14670b57cec5SDimitry Andric   return TBAA->getTypeInfo(QTy);
14680b57cec5SDimitry Andric }
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
14710b57cec5SDimitry Andric   if (!TBAA)
14720b57cec5SDimitry Andric     return TBAAAccessInfo();
14735ffd83dbSDimitry Andric   if (getLangOpts().CUDAIsDevice) {
14745ffd83dbSDimitry Andric     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
14755ffd83dbSDimitry Andric     // access info.
14765ffd83dbSDimitry Andric     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
14775ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
14785ffd83dbSDimitry Andric           nullptr)
14795ffd83dbSDimitry Andric         return TBAAAccessInfo();
14805ffd83dbSDimitry Andric     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
14815ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
14825ffd83dbSDimitry Andric           nullptr)
14835ffd83dbSDimitry Andric         return TBAAAccessInfo();
14845ffd83dbSDimitry Andric     }
14855ffd83dbSDimitry Andric   }
14860b57cec5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
14870b57cec5SDimitry Andric }
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric TBAAAccessInfo
14900b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
14910b57cec5SDimitry Andric   if (!TBAA)
14920b57cec5SDimitry Andric     return TBAAAccessInfo();
14930b57cec5SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
14940b57cec5SDimitry Andric }
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
14970b57cec5SDimitry Andric   if (!TBAA)
14980b57cec5SDimitry Andric     return nullptr;
14990b57cec5SDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
15000b57cec5SDimitry Andric }
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
15030b57cec5SDimitry Andric   if (!TBAA)
15040b57cec5SDimitry Andric     return nullptr;
15050b57cec5SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
15060b57cec5SDimitry Andric }
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
15090b57cec5SDimitry Andric   if (!TBAA)
15100b57cec5SDimitry Andric     return nullptr;
15110b57cec5SDimitry Andric   return TBAA->getAccessTagInfo(Info);
15120b57cec5SDimitry Andric }
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
15150b57cec5SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
15160b57cec5SDimitry Andric   if (!TBAA)
15170b57cec5SDimitry Andric     return TBAAAccessInfo();
15180b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
15190b57cec5SDimitry Andric }
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric TBAAAccessInfo
15220b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
15230b57cec5SDimitry Andric                                                    TBAAAccessInfo InfoB) {
15240b57cec5SDimitry Andric   if (!TBAA)
15250b57cec5SDimitry Andric     return TBAAAccessInfo();
15260b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
15270b57cec5SDimitry Andric }
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric TBAAAccessInfo
15300b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
15310b57cec5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
15320b57cec5SDimitry Andric   if (!TBAA)
15330b57cec5SDimitry Andric     return TBAAAccessInfo();
15340b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
15350b57cec5SDimitry Andric }
15360b57cec5SDimitry Andric 
15370b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
15380b57cec5SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
15390b57cec5SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
15400b57cec5SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
15410b57cec5SDimitry Andric }
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
15440b57cec5SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
15450b57cec5SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
15460b57cec5SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
15470b57cec5SDimitry Andric }
15480b57cec5SDimitry Andric 
15490b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
15500b57cec5SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
15510b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
15520b57cec5SDimitry Andric }
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
15550b57cec5SDimitry Andric /// specified stmt yet.
15560b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
15570b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
15580b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
15590b57cec5SDimitry Andric   std::string Msg = Type;
15600b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
15610b57cec5SDimitry Andric       << Msg << S->getSourceRange();
15620b57cec5SDimitry Andric }
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
15650b57cec5SDimitry Andric /// specified decl yet.
15660b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
15670b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
15680b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
15690b57cec5SDimitry Andric   std::string Msg = Type;
15700b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
15710b57cec5SDimitry Andric }
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
15740b57cec5SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
15750b57cec5SDimitry Andric }
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
15780b57cec5SDimitry Andric                                         const NamedDecl *D) const {
15790b57cec5SDimitry Andric   // Internal definitions always have default visibility.
15800b57cec5SDimitry Andric   if (GV->hasLocalLinkage()) {
15810b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
15820b57cec5SDimitry Andric     return;
15830b57cec5SDimitry Andric   }
15840b57cec5SDimitry Andric   if (!D)
15850b57cec5SDimitry Andric     return;
15865f757f3fSDimitry Andric 
15870b57cec5SDimitry Andric   // Set visibility for definitions, and for declarations if requested globally
15880b57cec5SDimitry Andric   // or set explicitly.
15890b57cec5SDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
15905f757f3fSDimitry Andric 
15915f757f3fSDimitry Andric   // OpenMP declare target variables must be visible to the host so they can
15925f757f3fSDimitry Andric   // be registered. We require protected visibility unless the variable has
15935f757f3fSDimitry Andric   // the DT_nohost modifier and does not need to be registered.
15945f757f3fSDimitry Andric   if (Context.getLangOpts().OpenMP &&
15955f757f3fSDimitry Andric       Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) &&
15965f757f3fSDimitry Andric       D->hasAttr<OMPDeclareTargetDeclAttr>() &&
15975f757f3fSDimitry Andric       D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
15985f757f3fSDimitry Andric           OMPDeclareTargetDeclAttr::DT_NoHost &&
15995f757f3fSDimitry Andric       LV.getVisibility() == HiddenVisibility) {
16005f757f3fSDimitry Andric     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
16015f757f3fSDimitry Andric     return;
16025f757f3fSDimitry Andric   }
16035f757f3fSDimitry Andric 
1604bdd1243dSDimitry Andric   if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1605bdd1243dSDimitry Andric     // Reject incompatible dlllstorage and visibility annotations.
1606bdd1243dSDimitry Andric     if (!LV.isVisibilityExplicit())
1607bdd1243dSDimitry Andric       return;
1608bdd1243dSDimitry Andric     if (GV->hasDLLExportStorageClass()) {
1609bdd1243dSDimitry Andric       if (LV.getVisibility() == HiddenVisibility)
1610bdd1243dSDimitry Andric         getDiags().Report(D->getLocation(),
1611bdd1243dSDimitry Andric                           diag::err_hidden_visibility_dllexport);
1612bdd1243dSDimitry Andric     } else if (LV.getVisibility() != DefaultVisibility) {
1613bdd1243dSDimitry Andric       getDiags().Report(D->getLocation(),
1614bdd1243dSDimitry Andric                         diag::err_non_default_visibility_dllimport);
1615bdd1243dSDimitry Andric     }
1616bdd1243dSDimitry Andric     return;
1617bdd1243dSDimitry Andric   }
1618bdd1243dSDimitry Andric 
16190b57cec5SDimitry Andric   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
16200b57cec5SDimitry Andric       !GV->isDeclarationForLinker())
16210b57cec5SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
16220b57cec5SDimitry Andric }
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
16250b57cec5SDimitry Andric                                  llvm::GlobalValue *GV) {
16260b57cec5SDimitry Andric   if (GV->hasLocalLinkage())
16270b57cec5SDimitry Andric     return true;
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
16300b57cec5SDimitry Andric     return true;
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric   // DLLImport explicitly marks the GV as external.
16330b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
16340b57cec5SDimitry Andric     return false;
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
16375f757f3fSDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
16380b57cec5SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
16390b57cec5SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
16400b57cec5SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
16410b57cec5SDimitry Andric     // potentially could come from another DLL as DSO local.
1642fe6060f1SDimitry Andric 
1643fe6060f1SDimitry Andric     // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1644fe6060f1SDimitry Andric     // (and this actually happens in the public interface of libstdc++), so
1645fe6060f1SDimitry Andric     // such variables can't be marked as DSO local. (Native TLS variables
1646fe6060f1SDimitry Andric     // can't be dllimported at all, though.)
16470b57cec5SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
16485f757f3fSDimitry Andric         (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) &&
16495f757f3fSDimitry Andric         CGOpts.AutoImport)
16500b57cec5SDimitry Andric       return false;
16510b57cec5SDimitry Andric   }
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
16540b57cec5SDimitry Andric   // remain unresolved in the link, they can be resolved to zero, which is
16550b57cec5SDimitry Andric   // outside the current DSO.
16560b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
16570b57cec5SDimitry Andric     return false;
16580b57cec5SDimitry Andric 
16590b57cec5SDimitry Andric   // Every other GV is local on COFF.
16600b57cec5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
16610b57cec5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
16620b57cec5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
16630b57cec5SDimitry Andric   // FIXME: even thread local variables?
16640b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
16650b57cec5SDimitry Andric     return true;
16660b57cec5SDimitry Andric 
16670b57cec5SDimitry Andric   // Only handle COFF and ELF for now.
16680b57cec5SDimitry Andric   if (!TT.isOSBinFormatELF())
16690b57cec5SDimitry Andric     return false;
16700b57cec5SDimitry Andric 
1671fe6060f1SDimitry Andric   // If this is not an executable, don't assume anything is local.
1672fe6060f1SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
1673fe6060f1SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
1674e8d8bef9SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1675e8d8bef9SDimitry Andric     // On ELF, if -fno-semantic-interposition is specified and the target
1676e8d8bef9SDimitry Andric     // supports local aliases, there will be neither CC1
1677e8d8bef9SDimitry Andric     // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1678fe6060f1SDimitry Andric     // dso_local on the function if using a local alias is preferable (can avoid
1679fe6060f1SDimitry Andric     // PLT indirection).
1680fe6060f1SDimitry Andric     if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
16810b57cec5SDimitry Andric       return false;
1682e8d8bef9SDimitry Andric     return !(CGM.getLangOpts().SemanticInterposition ||
1683e8d8bef9SDimitry Andric              CGM.getLangOpts().HalfNoSemanticInterposition);
1684e8d8bef9SDimitry Andric   }
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   // A definition cannot be preempted from an executable.
16870b57cec5SDimitry Andric   if (!GV->isDeclarationForLinker())
16880b57cec5SDimitry Andric     return true;
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
16910b57cec5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
16920b57cec5SDimitry Andric   // depended, it seems worth it to handle it here.
16930b57cec5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
16940b57cec5SDimitry Andric     return false;
16950b57cec5SDimitry Andric 
1696e8d8bef9SDimitry Andric   // PowerPC64 prefers TOC indirection to avoid copy relocations.
1697e8d8bef9SDimitry Andric   if (TT.isPPC64())
16980b57cec5SDimitry Andric     return false;
16990b57cec5SDimitry Andric 
1700e8d8bef9SDimitry Andric   if (CGOpts.DirectAccessExternalData) {
1701e8d8bef9SDimitry Andric     // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1702e8d8bef9SDimitry Andric     // for non-thread-local variables. If the symbol is not defined in the
1703e8d8bef9SDimitry Andric     // executable, a copy relocation will be needed at link time. dso_local is
1704e8d8bef9SDimitry Andric     // excluded for thread-local variables because they generally don't support
1705e8d8bef9SDimitry Andric     // copy relocations.
17060b57cec5SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1707e8d8bef9SDimitry Andric       if (!Var->isThreadLocal())
17080b57cec5SDimitry Andric         return true;
17090b57cec5SDimitry Andric 
1710e8d8bef9SDimitry Andric     // -fno-pic sets dso_local on a function declaration to allow direct
1711e8d8bef9SDimitry Andric     // accesses when taking its address (similar to a data symbol). If the
1712e8d8bef9SDimitry Andric     // function is not defined in the executable, a canonical PLT entry will be
1713e8d8bef9SDimitry Andric     // needed at link time. -fno-direct-access-external-data can avoid the
1714e8d8bef9SDimitry Andric     // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1715e8d8bef9SDimitry Andric     // it could just cause trouble without providing perceptible benefits.
17160b57cec5SDimitry Andric     if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
17170b57cec5SDimitry Andric       return true;
1718e8d8bef9SDimitry Andric   }
1719e8d8bef9SDimitry Andric 
1720e8d8bef9SDimitry Andric   // If we can use copy relocations we can assume it is local.
17210b57cec5SDimitry Andric 
17225ffd83dbSDimitry Andric   // Otherwise don't assume it is local.
17230b57cec5SDimitry Andric   return false;
17240b57cec5SDimitry Andric }
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
17270b57cec5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
17280b57cec5SDimitry Andric }
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
17310b57cec5SDimitry Andric                                           GlobalDecl GD) const {
17320b57cec5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
17330b57cec5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
17340b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
17350b57cec5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
17360b57cec5SDimitry Andric     return;
17370b57cec5SDimitry Andric   }
17380b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
17390b57cec5SDimitry Andric }
17400b57cec5SDimitry Andric 
17410b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
17420b57cec5SDimitry Andric                                           const NamedDecl *D) const {
17430b57cec5SDimitry Andric   if (D && D->isExternallyVisible()) {
17440b57cec5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
17450b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
174681ad6265SDimitry Andric     else if ((D->hasAttr<DLLExportAttr>() ||
174781ad6265SDimitry Andric               shouldMapVisibilityToDLLExport(D)) &&
174881ad6265SDimitry Andric              !GV->isDeclarationForLinker())
17490b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
17500b57cec5SDimitry Andric   }
17510b57cec5SDimitry Andric }
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
17540b57cec5SDimitry Andric                                     GlobalDecl GD) const {
17550b57cec5SDimitry Andric   setDLLImportDLLExport(GV, GD);
17560b57cec5SDimitry Andric   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
17570b57cec5SDimitry Andric }
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
17600b57cec5SDimitry Andric                                     const NamedDecl *D) const {
17610b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
17620b57cec5SDimitry Andric   setGVPropertiesAux(GV, D);
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
17660b57cec5SDimitry Andric                                        const NamedDecl *D) const {
17670b57cec5SDimitry Andric   setGlobalVisibility(GV, D);
17680b57cec5SDimitry Andric   setDSOLocal(GV);
17690b57cec5SDimitry Andric   GV->setPartition(CodeGenOpts.SymbolPartition);
17700b57cec5SDimitry Andric }
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
17730b57cec5SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
17740b57cec5SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
17750b57cec5SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
17760b57cec5SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
17770b57cec5SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
17780b57cec5SDimitry Andric }
17790b57cec5SDimitry Andric 
17805ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode
17815ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const {
17825ffd83dbSDimitry Andric   switch (CodeGenOpts.getDefaultTLSModel()) {
17830b57cec5SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
17840b57cec5SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
17850b57cec5SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
17860b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
17870b57cec5SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
17880b57cec5SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
17890b57cec5SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
17900b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
17910b57cec5SDimitry Andric   }
17920b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model!");
17930b57cec5SDimitry Andric }
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
17960b57cec5SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
17995ffd83dbSDimitry Andric   TLM = GetDefaultLLVMTLSModel();
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric   // Override the TLS model if it is explicitly specified.
18020b57cec5SDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
18030b57cec5SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
18040b57cec5SDimitry Andric   }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   GV->setThreadLocalMode(TLM);
18070b57cec5SDimitry Andric }
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
18100b57cec5SDimitry Andric                                           StringRef Name) {
18110b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
18120b57cec5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
18130b57cec5SDimitry Andric }
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
18160b57cec5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
18170b57cec5SDimitry Andric                                                  unsigned CPUIndex,
18180b57cec5SDimitry Andric                                                  raw_ostream &Out) {
18190b57cec5SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
18200b57cec5SDimitry Andric   // supported.
18210b57cec5SDimitry Andric   if (Attr)
18220b57cec5SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
18230b57cec5SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
18240b57cec5SDimitry Andric     Out << ".resolver";
18250b57cec5SDimitry Andric }
18260b57cec5SDimitry Andric 
1827fe6060f1SDimitry Andric // Returns true if GD is a function decl with internal linkage and
1828fe6060f1SDimitry Andric // needs a unique suffix after the mangled name.
1829fe6060f1SDimitry Andric static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1830fe6060f1SDimitry Andric                                         CodeGenModule &CGM) {
1831fe6060f1SDimitry Andric   const Decl *D = GD.getDecl();
1832fe6060f1SDimitry Andric   return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1833fe6060f1SDimitry Andric          (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1834fe6060f1SDimitry Andric }
1835fe6060f1SDimitry Andric 
1836fe6060f1SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
18370b57cec5SDimitry Andric                                       const NamedDecl *ND,
18380b57cec5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
18390b57cec5SDimitry Andric   SmallString<256> Buffer;
18400b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
18410b57cec5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
1842fe6060f1SDimitry Andric   if (!CGM.getModuleNameHash().empty())
1843fe6060f1SDimitry Andric     MC.needsUniqueInternalLinkageNames();
1844fe6060f1SDimitry Andric   bool ShouldMangle = MC.shouldMangleDeclName(ND);
1845fe6060f1SDimitry Andric   if (ShouldMangle)
18465ffd83dbSDimitry Andric     MC.mangleName(GD.getWithDecl(ND), Out);
18475ffd83dbSDimitry Andric   else {
18480b57cec5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
18490b57cec5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
18500b57cec5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
18510b57cec5SDimitry Andric 
18520b57cec5SDimitry Andric     if (FD &&
18530b57cec5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
18545f757f3fSDimitry Andric       if (CGM.getLangOpts().RegCall4)
18555f757f3fSDimitry Andric         Out << "__regcall4__" << II->getName();
18565f757f3fSDimitry Andric       else
18570b57cec5SDimitry Andric         Out << "__regcall3__" << II->getName();
18585ffd83dbSDimitry Andric     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
18595ffd83dbSDimitry Andric                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
18605ffd83dbSDimitry Andric       Out << "__device_stub__" << II->getName();
18610b57cec5SDimitry Andric     } else {
18620b57cec5SDimitry Andric       Out << II->getName();
18630b57cec5SDimitry Andric     }
18640b57cec5SDimitry Andric   }
18650b57cec5SDimitry Andric 
1866fe6060f1SDimitry Andric   // Check if the module name hash should be appended for internal linkage
1867fe6060f1SDimitry Andric   // symbols.   This should come before multi-version target suffixes are
1868fe6060f1SDimitry Andric   // appended. This is to keep the name and module hash suffix of the
1869fe6060f1SDimitry Andric   // internal linkage function together.  The unique suffix should only be
1870fe6060f1SDimitry Andric   // added when name mangling is done to make sure that the final name can
1871fe6060f1SDimitry Andric   // be properly demangled.  For example, for C functions without prototypes,
1872fe6060f1SDimitry Andric   // name mangling is not done and the unique suffix should not be appeneded
1873fe6060f1SDimitry Andric   // then.
1874fe6060f1SDimitry Andric   if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1875fe6060f1SDimitry Andric     assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1876fe6060f1SDimitry Andric            "Hash computed when not explicitly requested");
1877fe6060f1SDimitry Andric     Out << CGM.getModuleNameHash();
1878fe6060f1SDimitry Andric   }
1879fe6060f1SDimitry Andric 
18800b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
18810b57cec5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
18820b57cec5SDimitry Andric       switch (FD->getMultiVersionKind()) {
18830b57cec5SDimitry Andric       case MultiVersionKind::CPUDispatch:
18840b57cec5SDimitry Andric       case MultiVersionKind::CPUSpecific:
18850b57cec5SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
18860b57cec5SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
18870b57cec5SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
18880b57cec5SDimitry Andric         break;
18890fca6ea1SDimitry Andric       case MultiVersionKind::Target: {
18900fca6ea1SDimitry Andric         auto *Attr = FD->getAttr<TargetAttr>();
18910fca6ea1SDimitry Andric         assert(Attr && "Expected TargetAttr to be present "
18920fca6ea1SDimitry Andric                        "for attribute mangling");
18930fca6ea1SDimitry Andric         const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
18940fca6ea1SDimitry Andric         Info.appendAttributeMangling(Attr, Out);
18950b57cec5SDimitry Andric         break;
18960fca6ea1SDimitry Andric       }
18970fca6ea1SDimitry Andric       case MultiVersionKind::TargetVersion: {
18980fca6ea1SDimitry Andric         auto *Attr = FD->getAttr<TargetVersionAttr>();
18990fca6ea1SDimitry Andric         assert(Attr && "Expected TargetVersionAttr to be present "
19000fca6ea1SDimitry Andric                        "for attribute mangling");
19010fca6ea1SDimitry Andric         const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
19020fca6ea1SDimitry Andric         Info.appendAttributeMangling(Attr, Out);
1903bdd1243dSDimitry Andric         break;
19040fca6ea1SDimitry Andric       }
19050fca6ea1SDimitry Andric       case MultiVersionKind::TargetClones: {
19060fca6ea1SDimitry Andric         auto *Attr = FD->getAttr<TargetClonesAttr>();
19070fca6ea1SDimitry Andric         assert(Attr && "Expected TargetClonesAttr to be present "
19080fca6ea1SDimitry Andric                        "for attribute mangling");
19090fca6ea1SDimitry Andric         unsigned Index = GD.getMultiVersionIndex();
19100fca6ea1SDimitry Andric         const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
19110fca6ea1SDimitry Andric         Info.appendAttributeMangling(Attr, Index, Out);
19124824e7fdSDimitry Andric         break;
19130fca6ea1SDimitry Andric       }
19140b57cec5SDimitry Andric       case MultiVersionKind::None:
19150b57cec5SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
19160b57cec5SDimitry Andric       }
19170b57cec5SDimitry Andric     }
19180b57cec5SDimitry Andric 
1919fe6060f1SDimitry Andric   // Make unique name for device side static file-scope variable for HIP.
192081ad6265SDimitry Andric   if (CGM.getContext().shouldExternalize(ND) &&
1921fe6060f1SDimitry Andric       CGM.getLangOpts().GPURelocatableDeviceCode &&
192281ad6265SDimitry Andric       CGM.getLangOpts().CUDAIsDevice)
19232a66634dSDimitry Andric     CGM.printPostfixForExternalizedDecl(Out, ND);
192481ad6265SDimitry Andric 
19255ffd83dbSDimitry Andric   return std::string(Out.str());
19260b57cec5SDimitry Andric }
19270b57cec5SDimitry Andric 
19280b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
192904eeddc0SDimitry Andric                                             const FunctionDecl *FD,
193004eeddc0SDimitry Andric                                             StringRef &CurName) {
19310b57cec5SDimitry Andric   if (!FD->isMultiVersion())
19320b57cec5SDimitry Andric     return;
19330b57cec5SDimitry Andric 
19340b57cec5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
19350b57cec5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
19360b57cec5SDimitry Andric   // multiversion function.
19370b57cec5SDimitry Andric   std::string NonTargetName =
19380b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
19390b57cec5SDimitry Andric   GlobalDecl OtherGD;
19400b57cec5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
19410b57cec5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
19420b57cec5SDimitry Andric                .getDecl()
19430b57cec5SDimitry Andric                ->getAsFunction()
19440b57cec5SDimitry Andric                ->isMultiVersion() &&
19450b57cec5SDimitry Andric            "Other GD should now be a multiversioned function");
19460b57cec5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
19470b57cec5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
19480b57cec5SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
19490b57cec5SDimitry Andric                                       .getDecl()
19500b57cec5SDimitry Andric                                       ->getAsFunction()
19510b57cec5SDimitry Andric                                       ->getMostRecentDecl();
19520b57cec5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
19530b57cec5SDimitry Andric     // This is so that if the initial version was already the 'default'
19540b57cec5SDimitry Andric     // version, we don't try to update it.
19550b57cec5SDimitry Andric     if (OtherName != NonTargetName) {
19560b57cec5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
19570b57cec5SDimitry Andric       // to this.
19580b57cec5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
19590b57cec5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
19600b57cec5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
19610b57cec5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
196204eeddc0SDimitry Andric       StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
196304eeddc0SDimitry Andric           Result.first->first();
196404eeddc0SDimitry Andric       // If this is the current decl is being created, make sure we update the name.
196504eeddc0SDimitry Andric       if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
196604eeddc0SDimitry Andric         CurName = OtherNameRef;
19670b57cec5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
19680b57cec5SDimitry Andric         Entry->setName(OtherName);
19690b57cec5SDimitry Andric     }
19700b57cec5SDimitry Andric   }
19710b57cec5SDimitry Andric }
19720b57cec5SDimitry Andric 
19730b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
19740b57cec5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
19750b57cec5SDimitry Andric 
19760b57cec5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
19770b57cec5SDimitry Andric   // complete constructors get mangled the same.
19780b57cec5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
19790b57cec5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
19800b57cec5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
19810b57cec5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
19820b57cec5SDimitry Andric       if (OrigCtorType == Ctor_Base)
19830b57cec5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
19840b57cec5SDimitry Andric     }
19850b57cec5SDimitry Andric   }
19860b57cec5SDimitry Andric 
1987fe6060f1SDimitry Andric   // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1988fe6060f1SDimitry Andric   // static device variable depends on whether the variable is referenced by
1989fe6060f1SDimitry Andric   // a host or device host function. Therefore the mangled name cannot be
1990fe6060f1SDimitry Andric   // cached.
199181ad6265SDimitry Andric   if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
19920b57cec5SDimitry Andric     auto FoundName = MangledDeclNames.find(CanonicalGD);
19930b57cec5SDimitry Andric     if (FoundName != MangledDeclNames.end())
19940b57cec5SDimitry Andric       return FoundName->second;
1995fe6060f1SDimitry Andric   }
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric   // Keep the first result in the case of a mangling collision.
19980b57cec5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
19990b57cec5SDimitry Andric   std::string MangledName = getMangledNameImpl(*this, GD, ND);
20000b57cec5SDimitry Andric 
20015ffd83dbSDimitry Andric   // Ensure either we have different ABIs between host and device compilations,
20025ffd83dbSDimitry Andric   // says host compilation following MSVC ABI but device compilation follows
20035ffd83dbSDimitry Andric   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
20045ffd83dbSDimitry Andric   // mangling should be the same after name stubbing. The later checking is
20055ffd83dbSDimitry Andric   // very important as the device kernel name being mangled in host-compilation
20065ffd83dbSDimitry Andric   // is used to resolve the device binaries to be executed. Inconsistent naming
20075ffd83dbSDimitry Andric   // result in undefined behavior. Even though we cannot check that naming
20085ffd83dbSDimitry Andric   // directly between host- and device-compilations, the host- and
20095ffd83dbSDimitry Andric   // device-mangling in host compilation could help catching certain ones.
20105ffd83dbSDimitry Andric   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
201181ad6265SDimitry Andric          getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
20125ffd83dbSDimitry Andric          (getContext().getAuxTargetInfo() &&
20135ffd83dbSDimitry Andric           (getContext().getAuxTargetInfo()->getCXXABI() !=
20145ffd83dbSDimitry Andric            getContext().getTargetInfo().getCXXABI())) ||
20155ffd83dbSDimitry Andric          getCUDARuntime().getDeviceSideName(ND) ==
20165ffd83dbSDimitry Andric              getMangledNameImpl(
20175ffd83dbSDimitry Andric                  *this,
20185ffd83dbSDimitry Andric                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
20195ffd83dbSDimitry Andric                  ND));
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
20220b57cec5SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
20230b57cec5SDimitry Andric }
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
20260b57cec5SDimitry Andric                                              const BlockDecl *BD) {
20270b57cec5SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
20280b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric   SmallString<256> Buffer;
20310b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
20320b57cec5SDimitry Andric   if (!D)
20330b57cec5SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
20340b57cec5SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
20350b57cec5SDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
20360b57cec5SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
20370b57cec5SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
20380b57cec5SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
20390b57cec5SDimitry Andric   else
20400b57cec5SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
20430b57cec5SDimitry Andric   return Result.first->first();
20440b57cec5SDimitry Andric }
20450b57cec5SDimitry Andric 
204681ad6265SDimitry Andric const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
204781ad6265SDimitry Andric   auto it = MangledDeclNames.begin();
204881ad6265SDimitry Andric   while (it != MangledDeclNames.end()) {
204981ad6265SDimitry Andric     if (it->second == Name)
205081ad6265SDimitry Andric       return it->first;
205181ad6265SDimitry Andric     it++;
205281ad6265SDimitry Andric   }
205381ad6265SDimitry Andric   return GlobalDecl();
205481ad6265SDimitry Andric }
205581ad6265SDimitry Andric 
20560b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
20570b57cec5SDimitry Andric   return getModule().getNamedValue(Name);
20580b57cec5SDimitry Andric }
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before
20610b57cec5SDimitry Andric /// main() runs.
20620b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
2063bdd1243dSDimitry Andric                                   unsigned LexOrder,
20640b57cec5SDimitry Andric                                   llvm::Constant *AssociatedData) {
20650b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
2066bdd1243dSDimitry Andric   GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
20670b57cec5SDimitry Andric }
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called
20700b57cec5SDimitry Andric /// when the module is unloaded.
2071e8d8bef9SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
2072e8d8bef9SDimitry Andric                                   bool IsDtorAttrFunc) {
2073e8d8bef9SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2074e8d8bef9SDimitry Andric       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
20750b57cec5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
20760b57cec5SDimitry Andric     return;
20770b57cec5SDimitry Andric   }
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
2080bdd1243dSDimitry Andric   GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
20810b57cec5SDimitry Andric }
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
20840b57cec5SDimitry Andric   if (Fns.empty()) return;
20850b57cec5SDimitry Andric 
20860b57cec5SDimitry Andric   // Ctor function type is void()*.
20870b57cec5SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
20880b57cec5SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
20890b57cec5SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
20900b57cec5SDimitry Andric 
20910b57cec5SDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
20920b57cec5SDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
20930b57cec5SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric   // Construct the constructor and destructor arrays.
20960b57cec5SDimitry Andric   ConstantInitBuilder builder(*this);
20970b57cec5SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
20980b57cec5SDimitry Andric   for (const auto &I : Fns) {
20990b57cec5SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
21000b57cec5SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
21015f757f3fSDimitry Andric     ctor.add(I.Initializer);
21020b57cec5SDimitry Andric     if (I.AssociatedData)
21035f757f3fSDimitry Andric       ctor.add(I.AssociatedData);
21040b57cec5SDimitry Andric     else
21050b57cec5SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
21060b57cec5SDimitry Andric     ctor.finishAndAddTo(ctors);
21070b57cec5SDimitry Andric   }
21080b57cec5SDimitry Andric 
21090b57cec5SDimitry Andric   auto list =
21100b57cec5SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
21110b57cec5SDimitry Andric                                 /*constant*/ false,
21120b57cec5SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
21150b57cec5SDimitry Andric   // on appending variables.  Take it off as a workaround.
2116bdd1243dSDimitry Andric   list->setAlignment(std::nullopt);
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric   Fns.clear();
21190b57cec5SDimitry Andric }
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes
21220b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
21230b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
21280b57cec5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
21290b57cec5SDimitry Andric 
21308a4dda33SDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage);
21310b57cec5SDimitry Andric }
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
21340b57cec5SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
21350b57cec5SDimitry Andric   if (!MDS) return nullptr;
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
21380b57cec5SDimitry Andric }
21390b57cec5SDimitry Andric 
2140bdd1243dSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
2141bdd1243dSDimitry Andric   if (auto *FnType = T->getAs<FunctionProtoType>())
2142bdd1243dSDimitry Andric     T = getContext().getFunctionType(
2143bdd1243dSDimitry Andric         FnType->getReturnType(), FnType->getParamTypes(),
2144bdd1243dSDimitry Andric         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
2145bdd1243dSDimitry Andric 
2146bdd1243dSDimitry Andric   std::string OutName;
2147bdd1243dSDimitry Andric   llvm::raw_string_ostream Out(OutName);
21485f757f3fSDimitry Andric   getCXXABI().getMangleContext().mangleCanonicalTypeName(
214906c3fb27SDimitry Andric       T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
215006c3fb27SDimitry Andric 
215106c3fb27SDimitry Andric   if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
215206c3fb27SDimitry Andric     Out << ".normalized";
2153bdd1243dSDimitry Andric 
2154bdd1243dSDimitry Andric   return llvm::ConstantInt::get(Int32Ty,
2155bdd1243dSDimitry Andric                                 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2156bdd1243dSDimitry Andric }
2157bdd1243dSDimitry Andric 
21580b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
21590b57cec5SDimitry Andric                                               const CGFunctionInfo &Info,
2160fe6060f1SDimitry Andric                                               llvm::Function *F, bool IsThunk) {
21610b57cec5SDimitry Andric   unsigned CallingConv;
21620b57cec5SDimitry Andric   llvm::AttributeList PAL;
2163fe6060f1SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2164fe6060f1SDimitry Andric                          /*AttrOnCallSite=*/false, IsThunk);
21650fca6ea1SDimitry Andric   if (CallingConv == llvm::CallingConv::X86_VectorCall &&
21660fca6ea1SDimitry Andric       getTarget().getTriple().isWindowsArm64EC()) {
21670fca6ea1SDimitry Andric     SourceLocation Loc;
21680fca6ea1SDimitry Andric     if (const Decl *D = GD.getDecl())
21690fca6ea1SDimitry Andric       Loc = D->getLocation();
21700fca6ea1SDimitry Andric 
21710fca6ea1SDimitry Andric     Error(Loc, "__vectorcall calling convention is not currently supported");
21720fca6ea1SDimitry Andric   }
21730b57cec5SDimitry Andric   F->setAttributes(PAL);
21740b57cec5SDimitry Andric   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
21750b57cec5SDimitry Andric }
21760b57cec5SDimitry Andric 
21770b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
21780b57cec5SDimitry Andric   std::string ReadOnlyQual("__read_only");
21790b57cec5SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
21800b57cec5SDimitry Andric   if (ReadOnlyPos != std::string::npos)
21810b57cec5SDimitry Andric     // "+ 1" for the space after access qualifier.
21820b57cec5SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
21830b57cec5SDimitry Andric   else {
21840b57cec5SDimitry Andric     std::string WriteOnlyQual("__write_only");
21850b57cec5SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
21860b57cec5SDimitry Andric     if (WriteOnlyPos != std::string::npos)
21870b57cec5SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
21880b57cec5SDimitry Andric     else {
21890b57cec5SDimitry Andric       std::string ReadWriteQual("__read_write");
21900b57cec5SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
21910b57cec5SDimitry Andric       if (ReadWritePos != std::string::npos)
21920b57cec5SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
21930b57cec5SDimitry Andric     }
21940b57cec5SDimitry Andric   }
21950b57cec5SDimitry Andric }
21960b57cec5SDimitry Andric 
21970b57cec5SDimitry Andric // Returns the address space id that should be produced to the
21980b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
21990b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
22000b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
22010b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
22020b57cec5SDimitry Andric // (basically all single AS CPUs).
22030b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
22040b57cec5SDimitry Andric   switch (AS) {
2205e8d8bef9SDimitry Andric   case LangAS::opencl_global:
2206e8d8bef9SDimitry Andric     return 1;
2207e8d8bef9SDimitry Andric   case LangAS::opencl_constant:
2208e8d8bef9SDimitry Andric     return 2;
2209e8d8bef9SDimitry Andric   case LangAS::opencl_local:
2210e8d8bef9SDimitry Andric     return 3;
2211e8d8bef9SDimitry Andric   case LangAS::opencl_generic:
2212e8d8bef9SDimitry Andric     return 4; // Not in SPIR 2.0 specs.
2213e8d8bef9SDimitry Andric   case LangAS::opencl_global_device:
2214e8d8bef9SDimitry Andric     return 5;
2215e8d8bef9SDimitry Andric   case LangAS::opencl_global_host:
2216e8d8bef9SDimitry Andric     return 6;
22170b57cec5SDimitry Andric   default:
22180b57cec5SDimitry Andric     return 0; // Assume private.
22190b57cec5SDimitry Andric   }
22200b57cec5SDimitry Andric }
22210b57cec5SDimitry Andric 
222281ad6265SDimitry Andric void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
22230b57cec5SDimitry Andric                                          const FunctionDecl *FD,
22240b57cec5SDimitry Andric                                          CodeGenFunction *CGF) {
22250b57cec5SDimitry Andric   assert(((FD && CGF) || (!FD && !CGF)) &&
22260b57cec5SDimitry Andric          "Incorrect use - FD and CGF should either be both null or not!");
22270b57cec5SDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
22280b57cec5SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
22290b57cec5SDimitry Andric   // the same number of values as their are kernel arguments.
22300b57cec5SDimitry Andric 
22310b57cec5SDimitry Andric   const PrintingPolicy &Policy = Context.getPrintingPolicy();
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   // MDNode for the kernel argument address space qualifiers.
22340b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
22350b57cec5SDimitry Andric 
22360b57cec5SDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
22370b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric   // MDNode for the kernel argument type names.
22400b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric   // MDNode for the kernel argument base type names.
22430b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
22440b57cec5SDimitry Andric 
22450b57cec5SDimitry Andric   // MDNode for the kernel argument type qualifiers.
22460b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
22470b57cec5SDimitry Andric 
22480b57cec5SDimitry Andric   // MDNode for the kernel argument names.
22490b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric   if (FD && CGF)
22520b57cec5SDimitry Andric     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
22530b57cec5SDimitry Andric       const ParmVarDecl *parm = FD->getParamDecl(i);
225481ad6265SDimitry Andric       // Get argument name.
225581ad6265SDimitry Andric       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
225681ad6265SDimitry Andric 
225781ad6265SDimitry Andric       if (!getLangOpts().OpenCL)
225881ad6265SDimitry Andric         continue;
22590b57cec5SDimitry Andric       QualType ty = parm->getType();
22600b57cec5SDimitry Andric       std::string typeQuals;
22610b57cec5SDimitry Andric 
2262fe6060f1SDimitry Andric       // Get image and pipe access qualifier:
2263fe6060f1SDimitry Andric       if (ty->isImageType() || ty->isPipeType()) {
2264fe6060f1SDimitry Andric         const Decl *PDecl = parm;
2265bdd1243dSDimitry Andric         if (const auto *TD = ty->getAs<TypedefType>())
2266fe6060f1SDimitry Andric           PDecl = TD->getDecl();
2267fe6060f1SDimitry Andric         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2268fe6060f1SDimitry Andric         if (A && A->isWriteOnly())
2269fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2270fe6060f1SDimitry Andric         else if (A && A->isReadWrite())
2271fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2272fe6060f1SDimitry Andric         else
2273fe6060f1SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2274fe6060f1SDimitry Andric       } else
2275fe6060f1SDimitry Andric         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2276fe6060f1SDimitry Andric 
2277fe6060f1SDimitry Andric       auto getTypeSpelling = [&](QualType Ty) {
2278fe6060f1SDimitry Andric         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2279fe6060f1SDimitry Andric 
2280fe6060f1SDimitry Andric         if (Ty.isCanonical()) {
2281fe6060f1SDimitry Andric           StringRef typeNameRef = typeName;
2282fe6060f1SDimitry Andric           // Turn "unsigned type" to "utype"
2283fe6060f1SDimitry Andric           if (typeNameRef.consume_front("unsigned "))
2284fe6060f1SDimitry Andric             return std::string("u") + typeNameRef.str();
2285fe6060f1SDimitry Andric           if (typeNameRef.consume_front("signed "))
2286fe6060f1SDimitry Andric             return typeNameRef.str();
2287fe6060f1SDimitry Andric         }
2288fe6060f1SDimitry Andric 
2289fe6060f1SDimitry Andric         return typeName;
2290fe6060f1SDimitry Andric       };
2291fe6060f1SDimitry Andric 
22920b57cec5SDimitry Andric       if (ty->isPointerType()) {
22930b57cec5SDimitry Andric         QualType pointeeTy = ty->getPointeeType();
22940b57cec5SDimitry Andric 
22950b57cec5SDimitry Andric         // Get address qualifier.
22960b57cec5SDimitry Andric         addressQuals.push_back(
22970b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
22980b57cec5SDimitry Andric                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric         // Get argument type name.
2301fe6060f1SDimitry Andric         std::string typeName = getTypeSpelling(pointeeTy) + "*";
23020b57cec5SDimitry Andric         std::string baseTypeName =
2303fe6060f1SDimitry Andric             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2304fe6060f1SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
23050b57cec5SDimitry Andric         argBaseTypeNames.push_back(
23060b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric         // Get argument type qualifiers:
23090b57cec5SDimitry Andric         if (ty.isRestrictQualified())
23100b57cec5SDimitry Andric           typeQuals = "restrict";
23110b57cec5SDimitry Andric         if (pointeeTy.isConstQualified() ||
23120b57cec5SDimitry Andric             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
23130b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "const" : " const";
23140b57cec5SDimitry Andric         if (pointeeTy.isVolatileQualified())
23150b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
23160b57cec5SDimitry Andric       } else {
23170b57cec5SDimitry Andric         uint32_t AddrSpc = 0;
23180b57cec5SDimitry Andric         bool isPipe = ty->isPipeType();
23190b57cec5SDimitry Andric         if (ty->isImageType() || isPipe)
23200b57cec5SDimitry Andric           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric         addressQuals.push_back(
23230b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric         // Get argument type name.
2326fe6060f1SDimitry Andric         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2327fe6060f1SDimitry Andric         std::string typeName = getTypeSpelling(ty);
2328fe6060f1SDimitry Andric         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
23290b57cec5SDimitry Andric 
23300b57cec5SDimitry Andric         // Remove access qualifiers on images
23310b57cec5SDimitry Andric         // (as they are inseparable from type in clang implementation,
23320b57cec5SDimitry Andric         // but OpenCL spec provides a special query to get access qualifier
23330b57cec5SDimitry Andric         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
23340b57cec5SDimitry Andric         if (ty->isImageType()) {
23350b57cec5SDimitry Andric           removeImageAccessQualifier(typeName);
23360b57cec5SDimitry Andric           removeImageAccessQualifier(baseTypeName);
23370b57cec5SDimitry Andric         }
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
23400b57cec5SDimitry Andric         argBaseTypeNames.push_back(
23410b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric         if (isPipe)
23440b57cec5SDimitry Andric           typeQuals = "pipe";
23450b57cec5SDimitry Andric       }
23460b57cec5SDimitry Andric       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
23470b57cec5SDimitry Andric     }
23480b57cec5SDimitry Andric 
234981ad6265SDimitry Andric   if (getLangOpts().OpenCL) {
23500b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_addr_space",
23510b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, addressQuals));
23520b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_access_qual",
23530b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, accessQuals));
23540b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_type",
23550b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argTypeNames));
23560b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_base_type",
23570b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argBaseTypeNames));
23580b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_type_qual",
23590b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argTypeQuals));
236081ad6265SDimitry Andric   }
236181ad6265SDimitry Andric   if (getCodeGenOpts().EmitOpenCLArgMetadata ||
236281ad6265SDimitry Andric       getCodeGenOpts().HIPSaveKernelArgName)
23630b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_name",
23640b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argNames));
23650b57cec5SDimitry Andric }
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric /// Determines whether the language options require us to model
23680b57cec5SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
23690b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
23700b57cec5SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
23710b57cec5SDimitry Andric /// enables this.
23720b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
23730b57cec5SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
23740b57cec5SDimitry Andric   if (!LangOpts.Exceptions) return false;
23750b57cec5SDimitry Andric 
23760b57cec5SDimitry Andric   // If C++ exceptions are enabled, this is true.
23770b57cec5SDimitry Andric   if (LangOpts.CXXExceptions) return true;
23780b57cec5SDimitry Andric 
23790b57cec5SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
23800b57cec5SDimitry Andric   if (LangOpts.ObjCExceptions) {
23810b57cec5SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
23820b57cec5SDimitry Andric   }
23830b57cec5SDimitry Andric 
23840b57cec5SDimitry Andric   return true;
23850b57cec5SDimitry Andric }
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
23880b57cec5SDimitry Andric                                                       const CXXMethodDecl *MD) {
23890b57cec5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
23900b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
23910b57cec5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
23920b57cec5SDimitry Andric     return false;
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
23950b57cec5SDimitry Andric   // need this sort of type metadata.
23965f757f3fSDimitry Andric   return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
23975f757f3fSDimitry Andric          !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
23980b57cec5SDimitry Andric }
23990b57cec5SDimitry Andric 
24005f757f3fSDimitry Andric SmallVector<const CXXRecordDecl *, 0>
24010b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
24020b57cec5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
24030b57cec5SDimitry Andric 
24040b57cec5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
24050b57cec5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
24060b57cec5SDimitry Andric     if (RD->getNumBases() == 0)
24070b57cec5SDimitry Andric       MostBases.insert(RD);
24080b57cec5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
24090b57cec5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
24100b57cec5SDimitry Andric   };
24110b57cec5SDimitry Andric   CollectMostBases(RD);
24120b57cec5SDimitry Andric   return MostBases.takeVector();
24130b57cec5SDimitry Andric }
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
24160b57cec5SDimitry Andric                                                            llvm::Function *F) {
241704eeddc0SDimitry Andric   llvm::AttrBuilder B(F->getContext());
24180b57cec5SDimitry Andric 
2419bdd1243dSDimitry Andric   if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
242081ad6265SDimitry Andric     B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
24210b57cec5SDimitry Andric 
24225ffd83dbSDimitry Andric   if (CodeGenOpts.StackClashProtector)
24235ffd83dbSDimitry Andric     B.addAttribute("probe-stack", "inline-asm");
24245ffd83dbSDimitry Andric 
24255f757f3fSDimitry Andric   if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
24265f757f3fSDimitry Andric     B.addAttribute("stack-probe-size",
24275f757f3fSDimitry Andric                    std::to_string(CodeGenOpts.StackProbeSize));
24285f757f3fSDimitry Andric 
24290b57cec5SDimitry Andric   if (!hasUnwindExceptions(LangOpts))
24300b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
24310b57cec5SDimitry Andric 
2432bdd1243dSDimitry Andric   if (D && D->hasAttr<NoStackProtectorAttr>())
2433bdd1243dSDimitry Andric     ; // Do nothing.
2434bdd1243dSDimitry Andric   else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
24355f757f3fSDimitry Andric            isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2436bdd1243dSDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
24375f757f3fSDimitry Andric   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
24380b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
24395f757f3fSDimitry Andric   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong))
24400b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
24415f757f3fSDimitry Andric   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq))
24420b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric   if (!D) {
24450b57cec5SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
24460b57cec5SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
24470b57cec5SDimitry Andric     // disabled, mark the function as noinline.
24480b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
24490b57cec5SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
24500b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
24510b57cec5SDimitry Andric 
2452349cc55cSDimitry Andric     F->addFnAttrs(B);
24530b57cec5SDimitry Andric     return;
24540b57cec5SDimitry Andric   }
24550b57cec5SDimitry Andric 
24565f757f3fSDimitry Andric   // Handle SME attributes that apply to function definitions,
24575f757f3fSDimitry Andric   // rather than to function prototypes.
24585f757f3fSDimitry Andric   if (D->hasAttr<ArmLocallyStreamingAttr>())
24595f757f3fSDimitry Andric     B.addAttribute("aarch64_pstate_sm_body");
24605f757f3fSDimitry Andric 
24617a6dacacSDimitry Andric   if (auto *Attr = D->getAttr<ArmNewAttr>()) {
24627a6dacacSDimitry Andric     if (Attr->isNewZA())
24630fca6ea1SDimitry Andric       B.addAttribute("aarch64_new_za");
24647a6dacacSDimitry Andric     if (Attr->isNewZT0())
24657a6dacacSDimitry Andric       B.addAttribute("aarch64_new_zt0");
24667a6dacacSDimitry Andric   }
24675f757f3fSDimitry Andric 
24680b57cec5SDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
24690b57cec5SDimitry Andric   // starting with the default for this optimization level.
24700b57cec5SDimitry Andric   bool ShouldAddOptNone =
24710b57cec5SDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
24720b57cec5SDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
24730b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
24740b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
24750b57cec5SDimitry Andric 
2476480093f4SDimitry Andric   // Add optnone, but do so only if the function isn't always_inline.
2477480093f4SDimitry Andric   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2478480093f4SDimitry Andric       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
24790b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
24820b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
24830b57cec5SDimitry Andric 
24840b57cec5SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
24850b57cec5SDimitry Andric     // much of their semantics.
24860b57cec5SDimitry Andric     if (D->hasAttr<NakedAttr>())
24870b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
24900b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
24910b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
24920b57cec5SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
24930b57cec5SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
24940b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
24950b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
24960b57cec5SDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
24970b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
2498480093f4SDimitry Andric   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2499480093f4SDimitry Andric     // Add noinline if the function isn't always_inline.
25000b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
25010b57cec5SDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
25020b57cec5SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
25030b57cec5SDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
25040b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
25050b57cec5SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
25060b57cec5SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
25070b57cec5SDimitry Andric     // carry an explicit noinline attribute.
25080b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
25090b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
25100b57cec5SDimitry Andric   } else {
25110b57cec5SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
25120b57cec5SDimitry Andric     // absence to mark things as noinline.
25130b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
25140b57cec5SDimitry Andric       // Search function and template pattern redeclarations for inline.
25150b57cec5SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
25160b57cec5SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
25170b57cec5SDimitry Andric           return Redecl->isInlineSpecified();
25180b57cec5SDimitry Andric         };
25190b57cec5SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
25200b57cec5SDimitry Andric           return true;
25210b57cec5SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
25220b57cec5SDimitry Andric         if (!Pattern)
25230b57cec5SDimitry Andric           return false;
25240b57cec5SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
25250b57cec5SDimitry Andric       };
25260b57cec5SDimitry Andric       if (CheckForInline(FD)) {
25270b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
25280b57cec5SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
25290b57cec5SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
25300b57cec5SDimitry Andric                  !FD->isInlined() &&
25310b57cec5SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
25320b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
25330b57cec5SDimitry Andric       }
25340b57cec5SDimitry Andric     }
25350b57cec5SDimitry Andric   }
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric   // Add other optimization related attributes if we are optimizing this
25380b57cec5SDimitry Andric   // function.
25390b57cec5SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
25400b57cec5SDimitry Andric     if (D->hasAttr<ColdAttr>()) {
25410b57cec5SDimitry Andric       if (!ShouldAddOptNone)
25420b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
25430b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
25440b57cec5SDimitry Andric     }
2545e8d8bef9SDimitry Andric     if (D->hasAttr<HotAttr>())
2546e8d8bef9SDimitry Andric       B.addAttribute(llvm::Attribute::Hot);
25470b57cec5SDimitry Andric     if (D->hasAttr<MinSizeAttr>())
25480b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
25490b57cec5SDimitry Andric   }
25500b57cec5SDimitry Andric 
2551349cc55cSDimitry Andric   F->addFnAttrs(B);
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
25540b57cec5SDimitry Andric   if (alignment)
2555a7dea167SDimitry Andric     F->setAlignment(llvm::Align(alignment));
25560b57cec5SDimitry Andric 
25570b57cec5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
25580b57cec5SDimitry Andric     if (LangOpts.FunctionAlignment)
2559a7dea167SDimitry Andric       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
25620b57cec5SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
25630b57cec5SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
25640b57cec5SDimitry Andric   // member function, set its alignment accordingly.
25650b57cec5SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
25668a4dda33SDimitry Andric     if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
256706c3fb27SDimitry Andric       F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
25680b57cec5SDimitry Andric   }
25690b57cec5SDimitry Andric 
2570a7dea167SDimitry Andric   // In the cross-dso CFI mode with canonical jump tables, we want !type
2571a7dea167SDimitry Andric   // attributes on definitions only.
2572a7dea167SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso &&
2573a7dea167SDimitry Andric       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2574a7dea167SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2575a7dea167SDimitry Andric       // Skip available_externally functions. They won't be codegen'ed in the
2576a7dea167SDimitry Andric       // current module anyway.
2577a7dea167SDimitry Andric       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
25780b57cec5SDimitry Andric         CreateFunctionTypeMetadataForIcall(FD, F);
2579a7dea167SDimitry Andric     }
2580a7dea167SDimitry Andric   }
25810b57cec5SDimitry Andric 
25820b57cec5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
25830b57cec5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
25840b57cec5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
25850b57cec5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
25860b57cec5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
25870b57cec5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
25880b57cec5SDimitry Andric       llvm::Metadata *Id =
25890b57cec5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
25900b57cec5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
25910b57cec5SDimitry Andric       F->addTypeMetadata(0, Id);
25920b57cec5SDimitry Andric     }
25930b57cec5SDimitry Andric   }
25940b57cec5SDimitry Andric }
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
25970b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
2598349cc55cSDimitry Andric   if (isa_and_nonnull<NamedDecl>(D))
25990b57cec5SDimitry Andric     setGVProperties(GV, GD);
26000b57cec5SDimitry Andric   else
26010b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
26020b57cec5SDimitry Andric 
26030b57cec5SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
2604fe6060f1SDimitry Andric     addUsedOrCompilerUsedGlobal(GV);
26050b57cec5SDimitry Andric 
260606c3fb27SDimitry Andric   if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
260706c3fb27SDimitry Andric       VD &&
260806c3fb27SDimitry Andric       ((CodeGenOpts.KeepPersistentStorageVariables &&
260906c3fb27SDimitry Andric         (VD->getStorageDuration() == SD_Static ||
261006c3fb27SDimitry Andric          VD->getStorageDuration() == SD_Thread)) ||
261106c3fb27SDimitry Andric        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
261206c3fb27SDimitry Andric         VD->getType().isConstQualified())))
2613fe6060f1SDimitry Andric     addUsedOrCompilerUsedGlobal(GV);
26140b57cec5SDimitry Andric }
26150b57cec5SDimitry Andric 
26160b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
261706c3fb27SDimitry Andric                                                 llvm::AttrBuilder &Attrs,
261806c3fb27SDimitry Andric                                                 bool SetTargetFeatures) {
26190b57cec5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
26200b57cec5SDimitry Andric   // we have a decl for the function and it has a target attribute then
26210b57cec5SDimitry Andric   // parse that and add it to the feature set.
26220b57cec5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2623e8d8bef9SDimitry Andric   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
26240b57cec5SDimitry Andric   std::vector<std::string> Features;
26250b57cec5SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
26260b57cec5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
26270b57cec5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2628bdd1243dSDimitry Andric   const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2629bdd1243dSDimitry Andric   assert((!TD || !TV) && "both target_version and target specified");
26300b57cec5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
26314824e7fdSDimitry Andric   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
26320b57cec5SDimitry Andric   bool AddedAttr = false;
2633bdd1243dSDimitry Andric   if (TD || TV || SD || TC) {
26340b57cec5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
2635480093f4SDimitry Andric     getContext().getFunctionFeatureMap(FeatureMap, GD);
26360b57cec5SDimitry Andric 
26370b57cec5SDimitry Andric     // Produce the canonical string for this set of features.
26380b57cec5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
26390b57cec5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
26400b57cec5SDimitry Andric 
26410b57cec5SDimitry Andric     // Now add the target-cpu and target-features to the function.
26420b57cec5SDimitry Andric     // While we populated the feature map above, we still need to
26430b57cec5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
26440b57cec5SDimitry Andric     // the function.
26450b57cec5SDimitry Andric     if (TD) {
2646bdd1243dSDimitry Andric       ParsedTargetAttr ParsedAttr =
2647bdd1243dSDimitry Andric           Target.parseTargetAttr(TD->getFeaturesStr());
2648bdd1243dSDimitry Andric       if (!ParsedAttr.CPU.empty() &&
2649bdd1243dSDimitry Andric           getTarget().isValidCPUName(ParsedAttr.CPU)) {
2650bdd1243dSDimitry Andric         TargetCPU = ParsedAttr.CPU;
2651e8d8bef9SDimitry Andric         TuneCPU = ""; // Clear the tune CPU.
2652e8d8bef9SDimitry Andric       }
2653e8d8bef9SDimitry Andric       if (!ParsedAttr.Tune.empty() &&
2654e8d8bef9SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Tune))
2655e8d8bef9SDimitry Andric         TuneCPU = ParsedAttr.Tune;
26560b57cec5SDimitry Andric     }
265781ad6265SDimitry Andric 
265881ad6265SDimitry Andric     if (SD) {
265981ad6265SDimitry Andric       // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
266081ad6265SDimitry Andric       // favor this processor.
266106c3fb27SDimitry Andric       TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
266281ad6265SDimitry Andric     }
26630b57cec5SDimitry Andric   } else {
26640b57cec5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
26650b57cec5SDimitry Andric     // function.
26660b57cec5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
26670b57cec5SDimitry Andric   }
26680b57cec5SDimitry Andric 
2669e8d8bef9SDimitry Andric   if (!TargetCPU.empty()) {
26700b57cec5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
26710b57cec5SDimitry Andric     AddedAttr = true;
26720b57cec5SDimitry Andric   }
2673e8d8bef9SDimitry Andric   if (!TuneCPU.empty()) {
2674e8d8bef9SDimitry Andric     Attrs.addAttribute("tune-cpu", TuneCPU);
2675e8d8bef9SDimitry Andric     AddedAttr = true;
2676e8d8bef9SDimitry Andric   }
267706c3fb27SDimitry Andric   if (!Features.empty() && SetTargetFeatures) {
267806c3fb27SDimitry Andric     llvm::erase_if(Features, [&](const std::string& F) {
267906c3fb27SDimitry Andric        return getTarget().isReadOnlyFeature(F.substr(1));
268006c3fb27SDimitry Andric     });
26810b57cec5SDimitry Andric     llvm::sort(Features);
26820b57cec5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
26830b57cec5SDimitry Andric     AddedAttr = true;
26840b57cec5SDimitry Andric   }
26850b57cec5SDimitry Andric 
26860b57cec5SDimitry Andric   return AddedAttr;
26870b57cec5SDimitry Andric }
26880b57cec5SDimitry Andric 
26890b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
26900b57cec5SDimitry Andric                                           llvm::GlobalObject *GO) {
26910b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
26920b57cec5SDimitry Andric   SetCommonAttributes(GD, GO);
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric   if (D) {
26950b57cec5SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2696fe6060f1SDimitry Andric       if (D->hasAttr<RetainAttr>())
2697fe6060f1SDimitry Andric         addUsedGlobal(GV);
26980b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
26990b57cec5SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
27000b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
27010b57cec5SDimitry Andric         GV->addAttribute("data-section", SA->getName());
27020b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
27030b57cec5SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
2704a7dea167SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2705a7dea167SDimitry Andric         GV->addAttribute("relro-section", SA->getName());
27060b57cec5SDimitry Andric     }
27070b57cec5SDimitry Andric 
27080b57cec5SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
2709fe6060f1SDimitry Andric       if (D->hasAttr<RetainAttr>())
2710fe6060f1SDimitry Andric         addUsedGlobal(F);
27110b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
27120b57cec5SDimitry Andric         if (!D->getAttr<SectionAttr>())
27130fca6ea1SDimitry Andric           F->setSection(SA->getName());
27140b57cec5SDimitry Andric 
271504eeddc0SDimitry Andric       llvm::AttrBuilder Attrs(F->getContext());
27160b57cec5SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
27170b57cec5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
27180b57cec5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
27190b57cec5SDimitry Andric         // new ones should replace the old.
272004eeddc0SDimitry Andric         llvm::AttributeMask RemoveAttrs;
2721e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("target-cpu");
2722e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("target-features");
2723e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("tune-cpu");
2724349cc55cSDimitry Andric         F->removeFnAttrs(RemoveAttrs);
2725349cc55cSDimitry Andric         F->addFnAttrs(Attrs);
27260b57cec5SDimitry Andric       }
27270b57cec5SDimitry Andric     }
27280b57cec5SDimitry Andric 
27290b57cec5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
27300b57cec5SDimitry Andric       GO->setSection(CSA->getName());
27310b57cec5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
27320b57cec5SDimitry Andric       GO->setSection(SA->getName());
27330b57cec5SDimitry Andric   }
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
27360b57cec5SDimitry Andric }
27370b57cec5SDimitry Andric 
27380b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
27390b57cec5SDimitry Andric                                                   llvm::Function *F,
27400b57cec5SDimitry Andric                                                   const CGFunctionInfo &FI) {
27410b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
2742fe6060f1SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
27430b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, F);
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric   F->setLinkage(llvm::Function::InternalLinkage);
27460b57cec5SDimitry Andric 
27470b57cec5SDimitry Andric   setNonAliasAttributes(GD, F);
27480b57cec5SDimitry Andric }
27490b57cec5SDimitry Andric 
27500b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
27510b57cec5SDimitry Andric   // Set linkage and visibility in case we never see a definition.
27520b57cec5SDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
27530b57cec5SDimitry Andric   // Don't set internal linkage on declarations.
27540b57cec5SDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
27550b57cec5SDimitry Andric   // separate linkage types for this.
27560b57cec5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
27570b57cec5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
27580b57cec5SDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
27590b57cec5SDimitry Andric }
27600b57cec5SDimitry Andric 
27610b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
27620b57cec5SDimitry Andric                                                        llvm::Function *F) {
27630b57cec5SDimitry Andric   // Only if we are checking indirect calls.
27640b57cec5SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
27650b57cec5SDimitry Andric     return;
27660b57cec5SDimitry Andric 
27670b57cec5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
27680b57cec5SDimitry Andric   // checks elsewhere.
27690b57cec5SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
27700b57cec5SDimitry Andric     return;
27710b57cec5SDimitry Andric 
27720b57cec5SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
27730b57cec5SDimitry Andric   F->addTypeMetadata(0, MD);
27740b57cec5SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
27750b57cec5SDimitry Andric 
27760b57cec5SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
27770b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
27780b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
27790b57cec5SDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
27800b57cec5SDimitry Andric }
27810b57cec5SDimitry Andric 
2782bdd1243dSDimitry Andric void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2783bdd1243dSDimitry Andric   llvm::LLVMContext &Ctx = F->getContext();
2784bdd1243dSDimitry Andric   llvm::MDBuilder MDB(Ctx);
2785bdd1243dSDimitry Andric   F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2786bdd1243dSDimitry Andric                  llvm::MDNode::get(
2787bdd1243dSDimitry Andric                      Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2788bdd1243dSDimitry Andric }
2789bdd1243dSDimitry Andric 
2790bdd1243dSDimitry Andric static bool allowKCFIIdentifier(StringRef Name) {
2791bdd1243dSDimitry Andric   // KCFI type identifier constants are only necessary for external assembly
2792bdd1243dSDimitry Andric   // functions, which means it's safe to skip unusual names. Subset of
2793bdd1243dSDimitry Andric   // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2794bdd1243dSDimitry Andric   return llvm::all_of(Name, [](const char &C) {
2795bdd1243dSDimitry Andric     return llvm::isAlnum(C) || C == '_' || C == '.';
2796bdd1243dSDimitry Andric   });
2797bdd1243dSDimitry Andric }
2798bdd1243dSDimitry Andric 
2799bdd1243dSDimitry Andric void CodeGenModule::finalizeKCFITypes() {
2800bdd1243dSDimitry Andric   llvm::Module &M = getModule();
2801bdd1243dSDimitry Andric   for (auto &F : M.functions()) {
2802bdd1243dSDimitry Andric     // Remove KCFI type metadata from non-address-taken local functions.
2803bdd1243dSDimitry Andric     bool AddressTaken = F.hasAddressTaken();
2804bdd1243dSDimitry Andric     if (!AddressTaken && F.hasLocalLinkage())
2805bdd1243dSDimitry Andric       F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2806bdd1243dSDimitry Andric 
2807bdd1243dSDimitry Andric     // Generate a constant with the expected KCFI type identifier for all
2808bdd1243dSDimitry Andric     // address-taken function declarations to support annotating indirectly
2809bdd1243dSDimitry Andric     // called assembly functions.
2810bdd1243dSDimitry Andric     if (!AddressTaken || !F.isDeclaration())
2811bdd1243dSDimitry Andric       continue;
2812bdd1243dSDimitry Andric 
2813bdd1243dSDimitry Andric     const llvm::ConstantInt *Type;
2814bdd1243dSDimitry Andric     if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2815bdd1243dSDimitry Andric       Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2816bdd1243dSDimitry Andric     else
2817bdd1243dSDimitry Andric       continue;
2818bdd1243dSDimitry Andric 
2819bdd1243dSDimitry Andric     StringRef Name = F.getName();
2820bdd1243dSDimitry Andric     if (!allowKCFIIdentifier(Name))
2821bdd1243dSDimitry Andric       continue;
2822bdd1243dSDimitry Andric 
2823bdd1243dSDimitry Andric     std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2824bdd1243dSDimitry Andric                        Name + ", " + Twine(Type->getZExtValue()) + "\n")
2825bdd1243dSDimitry Andric                           .str();
2826bdd1243dSDimitry Andric     M.appendModuleInlineAsm(Asm);
2827bdd1243dSDimitry Andric   }
2828bdd1243dSDimitry Andric }
2829bdd1243dSDimitry Andric 
28300b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
28310b57cec5SDimitry Andric                                           bool IsIncompleteFunction,
28320b57cec5SDimitry Andric                                           bool IsThunk) {
28330b57cec5SDimitry Andric 
28340b57cec5SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
28350b57cec5SDimitry Andric     // If this is an intrinsic function, set the function's attributes
28360b57cec5SDimitry Andric     // to the intrinsic's attributes.
28370b57cec5SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
28380b57cec5SDimitry Andric     return;
28390b57cec5SDimitry Andric   }
28400b57cec5SDimitry Andric 
28410b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
28420b57cec5SDimitry Andric 
28430b57cec5SDimitry Andric   if (!IsIncompleteFunction)
2844fe6060f1SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2845fe6060f1SDimitry Andric                               IsThunk);
28460b57cec5SDimitry Andric 
28470b57cec5SDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
28480b57cec5SDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
28490b57cec5SDimitry Andric   // GCC and does not actually return "this".
28500b57cec5SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
28510b57cec5SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
28520b57cec5SDimitry Andric     assert(!F->arg_empty() &&
28530b57cec5SDimitry Andric            F->arg_begin()->getType()
28540b57cec5SDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
28550b57cec5SDimitry Andric            "unexpected this return");
2856349cc55cSDimitry Andric     F->addParamAttr(0, llvm::Attribute::Returned);
28570b57cec5SDimitry Andric   }
28580b57cec5SDimitry Andric 
28590b57cec5SDimitry Andric   // Only a few attributes are set on declarations; these may later be
28600b57cec5SDimitry Andric   // overridden by a definition.
28610b57cec5SDimitry Andric 
28620b57cec5SDimitry Andric   setLinkageForGV(F, FD);
28630b57cec5SDimitry Andric   setGVProperties(F, FD);
28640b57cec5SDimitry Andric 
28650b57cec5SDimitry Andric   // Setup target-specific attributes.
28660b57cec5SDimitry Andric   if (!IsIncompleteFunction && F->isDeclaration())
28670b57cec5SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
28700b57cec5SDimitry Andric     F->setSection(CSA->getName());
28710b57cec5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
28720b57cec5SDimitry Andric      F->setSection(SA->getName());
28730b57cec5SDimitry Andric 
2874349cc55cSDimitry Andric   if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2875349cc55cSDimitry Andric     if (EA->isError())
2876349cc55cSDimitry Andric       F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2877349cc55cSDimitry Andric     else if (EA->isWarning())
2878349cc55cSDimitry Andric       F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2879349cc55cSDimitry Andric   }
2880349cc55cSDimitry Andric 
2881d65cd7a5SDimitry Andric   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2882480093f4SDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
2883d65cd7a5SDimitry Andric     const FunctionDecl *FDBody;
2884d65cd7a5SDimitry Andric     bool HasBody = FD->hasBody(FDBody);
2885d65cd7a5SDimitry Andric     (void)HasBody;
2886d65cd7a5SDimitry Andric     assert(HasBody && "Inline builtin declarations should always have an "
2887d65cd7a5SDimitry Andric                       "available body!");
2888d65cd7a5SDimitry Andric     if (shouldEmitFunction(FDBody))
2889349cc55cSDimitry Andric       F->addFnAttr(llvm::Attribute::NoBuiltin);
2890480093f4SDimitry Andric   }
2891480093f4SDimitry Andric 
28920b57cec5SDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
28930b57cec5SDimitry Andric     // A replaceable global allocation function does not act like a builtin by
28940b57cec5SDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
2895349cc55cSDimitry Andric     F->addFnAttr(llvm::Attribute::NoBuiltin);
28960b57cec5SDimitry Andric   }
28970b57cec5SDimitry Andric 
28980b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
28990b57cec5SDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
29000b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
29010b57cec5SDimitry Andric     if (MD->isVirtual())
29020b57cec5SDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
29030b57cec5SDimitry Andric 
29040b57cec5SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
2905a7dea167SDimitry Andric   // is handled with better precision by the receiving DSO. But if jump tables
2906a7dea167SDimitry Andric   // are non-canonical then we need type metadata in order to produce the local
2907a7dea167SDimitry Andric   // jump table.
2908a7dea167SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2909a7dea167SDimitry Andric       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
29100b57cec5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
29110b57cec5SDimitry Andric 
2912bdd1243dSDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2913bdd1243dSDimitry Andric     setKCFIType(FD, F);
2914bdd1243dSDimitry Andric 
29150b57cec5SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
29160b57cec5SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
29170b57cec5SDimitry Andric 
2918bdd1243dSDimitry Andric   if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2919bdd1243dSDimitry Andric     F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2920bdd1243dSDimitry Andric 
29210b57cec5SDimitry Andric   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
29220b57cec5SDimitry Andric     // Annotate the callback behavior as metadata:
29230b57cec5SDimitry Andric     //  - The callback callee (as argument number).
29240b57cec5SDimitry Andric     //  - The callback payloads (as argument numbers).
29250b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = F->getContext();
29260b57cec5SDimitry Andric     llvm::MDBuilder MDB(Ctx);
29270b57cec5SDimitry Andric 
29280b57cec5SDimitry Andric     // The payload indices are all but the first one in the encoding. The first
29290b57cec5SDimitry Andric     // identifies the callback callee.
29300b57cec5SDimitry Andric     int CalleeIdx = *CB->encoding_begin();
29310b57cec5SDimitry Andric     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
29320b57cec5SDimitry Andric     F->addMetadata(llvm::LLVMContext::MD_callback,
29330b57cec5SDimitry Andric                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
29340b57cec5SDimitry Andric                                                CalleeIdx, PayloadIndices,
29350b57cec5SDimitry Andric                                                /* VarArgsArePassed */ false)}));
29360b57cec5SDimitry Andric   }
29370b57cec5SDimitry Andric }
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2940e8d8bef9SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
29410b57cec5SDimitry Andric          "Only globals with definition can force usage.");
29420b57cec5SDimitry Andric   LLVMUsed.emplace_back(GV);
29430b57cec5SDimitry Andric }
29440b57cec5SDimitry Andric 
29450b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
29460b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
29470b57cec5SDimitry Andric          "Only globals with definition can force usage.");
29480b57cec5SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
29490b57cec5SDimitry Andric }
29500b57cec5SDimitry Andric 
2951fe6060f1SDimitry Andric void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2952fe6060f1SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2953fe6060f1SDimitry Andric          "Only globals with definition can force usage.");
2954fe6060f1SDimitry Andric   if (getTriple().isOSBinFormatELF())
2955fe6060f1SDimitry Andric     LLVMCompilerUsed.emplace_back(GV);
2956fe6060f1SDimitry Andric   else
2957fe6060f1SDimitry Andric     LLVMUsed.emplace_back(GV);
2958fe6060f1SDimitry Andric }
2959fe6060f1SDimitry Andric 
29600b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
29610b57cec5SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
29620b57cec5SDimitry Andric   // Don't create llvm.used if there is no need.
29630b57cec5SDimitry Andric   if (List.empty())
29640b57cec5SDimitry Andric     return;
29650b57cec5SDimitry Andric 
29660b57cec5SDimitry Andric   // Convert List to what ConstantArray needs.
29670b57cec5SDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
29680b57cec5SDimitry Andric   UsedArray.resize(List.size());
29690b57cec5SDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
29700b57cec5SDimitry Andric     UsedArray[i] =
29710b57cec5SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
29720b57cec5SDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
29730b57cec5SDimitry Andric   }
29740b57cec5SDimitry Andric 
29750b57cec5SDimitry Andric   if (UsedArray.empty())
29760b57cec5SDimitry Andric     return;
29770b57cec5SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
29780b57cec5SDimitry Andric 
29790b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
29800b57cec5SDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
29810b57cec5SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
29820b57cec5SDimitry Andric 
29830b57cec5SDimitry Andric   GV->setSection("llvm.metadata");
29840b57cec5SDimitry Andric }
29850b57cec5SDimitry Andric 
29860b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() {
29870b57cec5SDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
29880b57cec5SDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
29890b57cec5SDimitry Andric }
29900b57cec5SDimitry Andric 
29910b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
29920b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
29930b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
29940b57cec5SDimitry Andric }
29950b57cec5SDimitry Andric 
29960b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
29970b57cec5SDimitry Andric   llvm::SmallString<32> Opt;
29980b57cec5SDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2999480093f4SDimitry Andric   if (Opt.empty())
3000480093f4SDimitry Andric     return;
30010b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
30020b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
30030b57cec5SDimitry Andric }
30040b57cec5SDimitry Andric 
30050b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
30060b57cec5SDimitry Andric   auto &C = getLLVMContext();
30070b57cec5SDimitry Andric   if (getTarget().getTriple().isOSBinFormatELF()) {
30080b57cec5SDimitry Andric       ELFDependentLibraries.push_back(
30090b57cec5SDimitry Andric         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
30100b57cec5SDimitry Andric     return;
30110b57cec5SDimitry Andric   }
30120b57cec5SDimitry Andric 
30130b57cec5SDimitry Andric   llvm::SmallString<24> Opt;
30140b57cec5SDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
30150b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
30160b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
30170b57cec5SDimitry Andric }
30180b57cec5SDimitry Andric 
30190b57cec5SDimitry Andric /// Add link options implied by the given module, including modules
30200b57cec5SDimitry Andric /// it depends on, using a postorder walk.
30210b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
30220b57cec5SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
30230b57cec5SDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
30240b57cec5SDimitry Andric   // Import this module's parent.
30250b57cec5SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
30260b57cec5SDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
30270b57cec5SDimitry Andric   }
30280b57cec5SDimitry Andric 
30290b57cec5SDimitry Andric   // Import this module's dependencies.
3030349cc55cSDimitry Andric   for (Module *Import : llvm::reverse(Mod->Imports)) {
3031349cc55cSDimitry Andric     if (Visited.insert(Import).second)
3032349cc55cSDimitry Andric       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
30330b57cec5SDimitry Andric   }
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric   // Add linker options to link against the libraries/frameworks
30360b57cec5SDimitry Andric   // described by this module.
30370b57cec5SDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
30380b57cec5SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
30390b57cec5SDimitry Andric 
30400b57cec5SDimitry Andric   // For modules that use export_as for linking, use that module
30410b57cec5SDimitry Andric   // name instead.
30420b57cec5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
30430b57cec5SDimitry Andric     return;
30440b57cec5SDimitry Andric 
3045349cc55cSDimitry Andric   for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
30460b57cec5SDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
30470b57cec5SDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
3048349cc55cSDimitry Andric     if (LL.IsFramework) {
3049349cc55cSDimitry Andric       llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3050349cc55cSDimitry Andric                                  llvm::MDString::get(Context, LL.Library)};
30510b57cec5SDimitry Andric 
30520b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
30530b57cec5SDimitry Andric       continue;
30540b57cec5SDimitry Andric     }
30550b57cec5SDimitry Andric 
30560b57cec5SDimitry Andric     // Link against a library.
30570b57cec5SDimitry Andric     if (IsELF) {
30580b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
30590b57cec5SDimitry Andric           llvm::MDString::get(Context, "lib"),
3060349cc55cSDimitry Andric           llvm::MDString::get(Context, LL.Library),
30610b57cec5SDimitry Andric       };
30620b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
30630b57cec5SDimitry Andric     } else {
30640b57cec5SDimitry Andric       llvm::SmallString<24> Opt;
3065349cc55cSDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
30660b57cec5SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
30670b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
30680b57cec5SDimitry Andric     }
30690b57cec5SDimitry Andric   }
30700b57cec5SDimitry Andric }
30710b57cec5SDimitry Andric 
3072fcaf7f86SDimitry Andric void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
30735f757f3fSDimitry Andric   assert(Primary->isNamedModuleUnit() &&
30745f757f3fSDimitry Andric          "We should only emit module initializers for named modules.");
30755f757f3fSDimitry Andric 
3076fcaf7f86SDimitry Andric   // Emit the initializers in the order that sub-modules appear in the
3077fcaf7f86SDimitry Andric   // source, first Global Module Fragments, if present.
3078fcaf7f86SDimitry Andric   if (auto GMF = Primary->getGlobalModuleFragment()) {
3079fcaf7f86SDimitry Andric     for (Decl *D : getContext().getModuleInitializers(GMF)) {
308061cfbce3SDimitry Andric       if (isa<ImportDecl>(D))
308161cfbce3SDimitry Andric         continue;
308261cfbce3SDimitry Andric       assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
3083fcaf7f86SDimitry Andric       EmitTopLevelDecl(D);
3084fcaf7f86SDimitry Andric     }
3085fcaf7f86SDimitry Andric   }
3086fcaf7f86SDimitry Andric   // Second any associated with the module, itself.
3087fcaf7f86SDimitry Andric   for (Decl *D : getContext().getModuleInitializers(Primary)) {
3088fcaf7f86SDimitry Andric     // Skip import decls, the inits for those are called explicitly.
308961cfbce3SDimitry Andric     if (isa<ImportDecl>(D))
3090fcaf7f86SDimitry Andric       continue;
3091fcaf7f86SDimitry Andric     EmitTopLevelDecl(D);
3092fcaf7f86SDimitry Andric   }
3093fcaf7f86SDimitry Andric   // Third any associated with the Privat eMOdule Fragment, if present.
3094fcaf7f86SDimitry Andric   if (auto PMF = Primary->getPrivateModuleFragment()) {
3095fcaf7f86SDimitry Andric     for (Decl *D : getContext().getModuleInitializers(PMF)) {
30965f757f3fSDimitry Andric       // Skip import decls, the inits for those are called explicitly.
30975f757f3fSDimitry Andric       if (isa<ImportDecl>(D))
30985f757f3fSDimitry Andric         continue;
309961cfbce3SDimitry Andric       assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
3100fcaf7f86SDimitry Andric       EmitTopLevelDecl(D);
3101fcaf7f86SDimitry Andric     }
3102fcaf7f86SDimitry Andric   }
3103fcaf7f86SDimitry Andric }
3104fcaf7f86SDimitry Andric 
31050b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
31060b57cec5SDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
31070b57cec5SDimitry Andric   // options, which is essentially the imported modules and all of their
31080b57cec5SDimitry Andric   // non-explicit child modules.
31090b57cec5SDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
31100b57cec5SDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
31110b57cec5SDimitry Andric   SmallVector<clang::Module *, 16> Stack;
31120b57cec5SDimitry Andric 
31130b57cec5SDimitry Andric   // Seed the stack with imported modules.
31140b57cec5SDimitry Andric   for (Module *M : ImportedModules) {
31150b57cec5SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
31160b57cec5SDimitry Andric     // a header of that same module.
31170b57cec5SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
31180b57cec5SDimitry Andric         !getLangOpts().isCompilingModule())
31190b57cec5SDimitry Andric       continue;
31200b57cec5SDimitry Andric     if (Visited.insert(M).second)
31210b57cec5SDimitry Andric       Stack.push_back(M);
31220b57cec5SDimitry Andric   }
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   // Find all of the modules to import, making a little effort to prune
31250b57cec5SDimitry Andric   // non-leaf modules.
31260b57cec5SDimitry Andric   while (!Stack.empty()) {
31270b57cec5SDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric     bool AnyChildren = false;
31300b57cec5SDimitry Andric 
31310b57cec5SDimitry Andric     // Visit the submodules of this module.
31320b57cec5SDimitry Andric     for (const auto &SM : Mod->submodules()) {
31330b57cec5SDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
31340b57cec5SDimitry Andric       // linked against.
31350b57cec5SDimitry Andric       if (SM->IsExplicit)
31360b57cec5SDimitry Andric         continue;
31370b57cec5SDimitry Andric 
31380b57cec5SDimitry Andric       if (Visited.insert(SM).second) {
31390b57cec5SDimitry Andric         Stack.push_back(SM);
31400b57cec5SDimitry Andric         AnyChildren = true;
31410b57cec5SDimitry Andric       }
31420b57cec5SDimitry Andric     }
31430b57cec5SDimitry Andric 
31440b57cec5SDimitry Andric     // We didn't find any children, so add this module to the list of
31450b57cec5SDimitry Andric     // modules to link against.
31460b57cec5SDimitry Andric     if (!AnyChildren) {
31470b57cec5SDimitry Andric       LinkModules.insert(Mod);
31480b57cec5SDimitry Andric     }
31490b57cec5SDimitry Andric   }
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric   // Add link options for all of the imported modules in reverse topological
31520b57cec5SDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
31530b57cec5SDimitry Andric   // to linker options inserted by things like #pragma comment().
31540b57cec5SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
31550b57cec5SDimitry Andric   Visited.clear();
31560b57cec5SDimitry Andric   for (Module *M : LinkModules)
31570b57cec5SDimitry Andric     if (Visited.insert(M).second)
31580b57cec5SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
31590b57cec5SDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
31600b57cec5SDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric   // Add the linker options metadata flag.
31630b57cec5SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
31640b57cec5SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
31650b57cec5SDimitry Andric     NMD->addOperand(MD);
31660b57cec5SDimitry Andric }
31670b57cec5SDimitry Andric 
31680b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() {
31690b57cec5SDimitry Andric   // Emit deferred declare target declarations.
31700b57cec5SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
31710b57cec5SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
31720b57cec5SDimitry Andric 
31730b57cec5SDimitry Andric   // Emit code for any potentially referenced deferred decls.  Since a
31740b57cec5SDimitry Andric   // previously unused static decl may become used during the generation of code
31750b57cec5SDimitry Andric   // for a static function, iterate until no changes are made.
31760b57cec5SDimitry Andric 
31770b57cec5SDimitry Andric   if (!DeferredVTables.empty()) {
31780b57cec5SDimitry Andric     EmitDeferredVTables();
31790b57cec5SDimitry Andric 
31800b57cec5SDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
31810b57cec5SDimitry Andric     // become deferred, although it can cause functions to be
31820b57cec5SDimitry Andric     // emitted that then need those vtables.
31830b57cec5SDimitry Andric     assert(DeferredVTables.empty());
31840b57cec5SDimitry Andric   }
31850b57cec5SDimitry Andric 
3186e8d8bef9SDimitry Andric   // Emit CUDA/HIP static device variables referenced by host code only.
3187fe6060f1SDimitry Andric   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3188fe6060f1SDimitry Andric   // needed for further handling.
3189fe6060f1SDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
319081ad6265SDimitry Andric     llvm::append_range(DeferredDeclsToEmit,
319181ad6265SDimitry Andric                        getContext().CUDADeviceVarODRUsedByHost);
3192e8d8bef9SDimitry Andric 
31930b57cec5SDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
31940b57cec5SDimitry Andric   if (DeferredDeclsToEmit.empty())
31950b57cec5SDimitry Andric     return;
31960b57cec5SDimitry Andric 
31970b57cec5SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
31980b57cec5SDimitry Andric   // work, it will not interfere with this.
31990b57cec5SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
32000b57cec5SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
32010b57cec5SDimitry Andric 
32020b57cec5SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
32030b57cec5SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
32040b57cec5SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
32050b57cec5SDimitry Andric     // might had been created for another decl with the same mangled name but
32060b57cec5SDimitry Andric     // different type.
32070b57cec5SDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
32080b57cec5SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric     // In case of different address spaces, we may still get a cast, even with
32110b57cec5SDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
32120b57cec5SDimitry Andric     // GlobalValue.
32130b57cec5SDimitry Andric     if (!GV)
32140b57cec5SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
32150b57cec5SDimitry Andric 
32160b57cec5SDimitry Andric     // Make sure GetGlobalValue returned non-null.
32170b57cec5SDimitry Andric     assert(GV);
32180b57cec5SDimitry Andric 
32190b57cec5SDimitry Andric     // Check to see if we've already emitted this.  This is necessary
32200b57cec5SDimitry Andric     // for a couple of reasons: first, decls can end up in the
32210b57cec5SDimitry Andric     // deferred-decls queue multiple times, and second, decls can end
32220b57cec5SDimitry Andric     // up with definitions in unusual ways (e.g. by an extern inline
32230b57cec5SDimitry Andric     // function acquiring a strong function redefinition).  Just
32240b57cec5SDimitry Andric     // ignore these cases.
32250b57cec5SDimitry Andric     if (!GV->isDeclaration())
32260b57cec5SDimitry Andric       continue;
32270b57cec5SDimitry Andric 
3228a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
3229a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3230a7dea167SDimitry Andric       continue;
3231a7dea167SDimitry Andric 
32320b57cec5SDimitry Andric     // Otherwise, emit the definition and move on to the next one.
32330b57cec5SDimitry Andric     EmitGlobalDefinition(D, GV);
32340b57cec5SDimitry Andric 
32350b57cec5SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
32360b57cec5SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
32370b57cec5SDimitry Andric     // ones are close together, which is convenient for testing.
32380b57cec5SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
32390b57cec5SDimitry Andric       EmitDeferred();
32400b57cec5SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
32410b57cec5SDimitry Andric     }
32420b57cec5SDimitry Andric   }
32430b57cec5SDimitry Andric }
32440b57cec5SDimitry Andric 
32450b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
32460b57cec5SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
32470b57cec5SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
32480b57cec5SDimitry Andric   // is not allowed to create new references to things that need to be emitted
32490b57cec5SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
32500b57cec5SDimitry Andric 
32510b57cec5SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
32520b57cec5SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
32550b57cec5SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
32560b57cec5SDimitry Andric            "This queue should only contain external vtables");
32570b57cec5SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
32580b57cec5SDimitry Andric       VTables.GenerateClassData(RD);
32590b57cec5SDimitry Andric   }
32600b57cec5SDimitry Andric   OpportunisticVTables.clear();
32610b57cec5SDimitry Andric }
32620b57cec5SDimitry Andric 
32630b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
32645f757f3fSDimitry Andric   for (const auto& [MangledName, VD] : DeferredAnnotations) {
32655f757f3fSDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(MangledName);
32665f757f3fSDimitry Andric     if (GV)
32675f757f3fSDimitry Andric       AddGlobalAnnotations(VD, GV);
32685f757f3fSDimitry Andric   }
32695f757f3fSDimitry Andric   DeferredAnnotations.clear();
32705f757f3fSDimitry Andric 
32710b57cec5SDimitry Andric   if (Annotations.empty())
32720b57cec5SDimitry Andric     return;
32730b57cec5SDimitry Andric 
32740b57cec5SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
32750b57cec5SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
32760b57cec5SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
32770b57cec5SDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
32780b57cec5SDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
32790b57cec5SDimitry Andric                                       Array, "llvm.global.annotations");
32800b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
32810b57cec5SDimitry Andric }
32820b57cec5SDimitry Andric 
32830b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
32840b57cec5SDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
32850b57cec5SDimitry Andric   if (AStr)
32860b57cec5SDimitry Andric     return AStr;
32870b57cec5SDimitry Andric 
32880b57cec5SDimitry Andric   // Not found yet, create a new global.
32890b57cec5SDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3290bdd1243dSDimitry Andric   auto *gv = new llvm::GlobalVariable(
3291bdd1243dSDimitry Andric       getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3292bdd1243dSDimitry Andric       ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3293bdd1243dSDimitry Andric       ConstGlobalsPtrTy->getAddressSpace());
32940b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
32950b57cec5SDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
32960b57cec5SDimitry Andric   AStr = gv;
32970b57cec5SDimitry Andric   return gv;
32980b57cec5SDimitry Andric }
32990b57cec5SDimitry Andric 
33000b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
33010b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
33020b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
33030b57cec5SDimitry Andric   if (PLoc.isValid())
33040b57cec5SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
33050b57cec5SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
33060b57cec5SDimitry Andric }
33070b57cec5SDimitry Andric 
33080b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
33090b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
33100b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
33110b57cec5SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
33120b57cec5SDimitry Andric     SM.getExpansionLineNumber(L);
33130b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
33140b57cec5SDimitry Andric }
33150b57cec5SDimitry Andric 
3316e8d8bef9SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3317e8d8bef9SDimitry Andric   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3318e8d8bef9SDimitry Andric   if (Exprs.empty())
3319bdd1243dSDimitry Andric     return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3320e8d8bef9SDimitry Andric 
3321e8d8bef9SDimitry Andric   llvm::FoldingSetNodeID ID;
3322e8d8bef9SDimitry Andric   for (Expr *E : Exprs) {
3323e8d8bef9SDimitry Andric     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3324e8d8bef9SDimitry Andric   }
3325e8d8bef9SDimitry Andric   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3326e8d8bef9SDimitry Andric   if (Lookup)
3327e8d8bef9SDimitry Andric     return Lookup;
3328e8d8bef9SDimitry Andric 
3329e8d8bef9SDimitry Andric   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3330e8d8bef9SDimitry Andric   LLVMArgs.reserve(Exprs.size());
3331e8d8bef9SDimitry Andric   ConstantEmitter ConstEmiter(*this);
3332e8d8bef9SDimitry Andric   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3333e8d8bef9SDimitry Andric     const auto *CE = cast<clang::ConstantExpr>(E);
3334e8d8bef9SDimitry Andric     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3335e8d8bef9SDimitry Andric                                     CE->getType());
3336e8d8bef9SDimitry Andric   });
3337e8d8bef9SDimitry Andric   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3338e8d8bef9SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3339e8d8bef9SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Struct,
3340e8d8bef9SDimitry Andric                                       ".args");
3341e8d8bef9SDimitry Andric   GV->setSection(AnnotationSection);
3342e8d8bef9SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3343e8d8bef9SDimitry Andric 
33445f757f3fSDimitry Andric   Lookup = GV;
33455f757f3fSDimitry Andric   return GV;
3346e8d8bef9SDimitry Andric }
3347e8d8bef9SDimitry Andric 
33480b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
33490b57cec5SDimitry Andric                                                 const AnnotateAttr *AA,
33500b57cec5SDimitry Andric                                                 SourceLocation L) {
33510b57cec5SDimitry Andric   // Get the globals for file name, annotation, and the line number.
33520b57cec5SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
33530b57cec5SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
3354e8d8bef9SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L),
3355e8d8bef9SDimitry Andric                  *Args = EmitAnnotationArgs(AA);
33560b57cec5SDimitry Andric 
3357349cc55cSDimitry Andric   llvm::Constant *GVInGlobalsAS = GV;
3358349cc55cSDimitry Andric   if (GV->getAddressSpace() !=
3359349cc55cSDimitry Andric       getDataLayout().getDefaultGlobalsAddressSpace()) {
3360349cc55cSDimitry Andric     GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
33615f757f3fSDimitry Andric         GV,
33625f757f3fSDimitry Andric         llvm::PointerType::get(
33635f757f3fSDimitry Andric             GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3364480093f4SDimitry Andric   }
3365480093f4SDimitry Andric 
33660b57cec5SDimitry Andric   // Create the ConstantStruct for the global annotation.
3367e8d8bef9SDimitry Andric   llvm::Constant *Fields[] = {
33685f757f3fSDimitry Andric       GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
33690b57cec5SDimitry Andric   };
33700b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
33710b57cec5SDimitry Andric }
33720b57cec5SDimitry Andric 
33730b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
33740b57cec5SDimitry Andric                                          llvm::GlobalValue *GV) {
33750b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
33760b57cec5SDimitry Andric   // Get the struct elements for these annotations.
33770b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
33780b57cec5SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
33790b57cec5SDimitry Andric }
33800b57cec5SDimitry Andric 
3381fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
33820b57cec5SDimitry Andric                                        SourceLocation Loc) const {
3383fe6060f1SDimitry Andric   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3384fe6060f1SDimitry Andric   // NoSanitize by function name.
3385fe6060f1SDimitry Andric   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
33860b57cec5SDimitry Andric     return true;
3387fcaf7f86SDimitry Andric   // NoSanitize by location. Check "mainfile" prefix.
3388fcaf7f86SDimitry Andric   auto &SM = Context.getSourceManager();
33895f757f3fSDimitry Andric   FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
3390fcaf7f86SDimitry Andric   if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3391fcaf7f86SDimitry Andric     return true;
3392fcaf7f86SDimitry Andric 
3393fcaf7f86SDimitry Andric   // Check "src" prefix.
33940b57cec5SDimitry Andric   if (Loc.isValid())
3395fe6060f1SDimitry Andric     return NoSanitizeL.containsLocation(Kind, Loc);
33960b57cec5SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
33970b57cec5SDimitry Andric   // it's located in the main file.
3398fcaf7f86SDimitry Andric   return NoSanitizeL.containsFile(Kind, MainFile.getName());
33990b57cec5SDimitry Andric }
34000b57cec5SDimitry Andric 
340181ad6265SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
340281ad6265SDimitry Andric                                        llvm::GlobalVariable *GV,
34030b57cec5SDimitry Andric                                        SourceLocation Loc, QualType Ty,
34040b57cec5SDimitry Andric                                        StringRef Category) const {
3405fe6060f1SDimitry Andric   const auto &NoSanitizeL = getContext().getNoSanitizeList();
340681ad6265SDimitry Andric   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
34070b57cec5SDimitry Andric     return true;
3408fcaf7f86SDimitry Andric   auto &SM = Context.getSourceManager();
3409fcaf7f86SDimitry Andric   if (NoSanitizeL.containsMainFile(
34105f757f3fSDimitry Andric           Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
34115f757f3fSDimitry Andric           Category))
3412fcaf7f86SDimitry Andric     return true;
341381ad6265SDimitry Andric   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
34140b57cec5SDimitry Andric     return true;
3415fcaf7f86SDimitry Andric 
34160b57cec5SDimitry Andric   // Check global type.
34170b57cec5SDimitry Andric   if (!Ty.isNull()) {
34180b57cec5SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
3419fe6060f1SDimitry Andric     // not sanitized, we also don't instrument arrays of them.
34200b57cec5SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
34210b57cec5SDimitry Andric       Ty = AT->getElementType();
34220b57cec5SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
3423fe6060f1SDimitry Andric     // Only record types (classes, structs etc.) are ignored.
34240b57cec5SDimitry Andric     if (Ty->isRecordType()) {
34250b57cec5SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
342681ad6265SDimitry Andric       if (NoSanitizeL.containsType(Kind, TypeStr, Category))
34270b57cec5SDimitry Andric         return true;
34280b57cec5SDimitry Andric     }
34290b57cec5SDimitry Andric   }
34300b57cec5SDimitry Andric   return false;
34310b57cec5SDimitry Andric }
34320b57cec5SDimitry Andric 
34330b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
34340b57cec5SDimitry Andric                                    StringRef Category) const {
34350b57cec5SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
34360b57cec5SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
34370b57cec5SDimitry Andric   auto Attr = ImbueAttr::NONE;
34380b57cec5SDimitry Andric   if (Loc.isValid())
34390b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
34400b57cec5SDimitry Andric   if (Attr == ImbueAttr::NONE)
34410b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
34420b57cec5SDimitry Andric   switch (Attr) {
34430b57cec5SDimitry Andric   case ImbueAttr::NONE:
34440b57cec5SDimitry Andric     return false;
34450b57cec5SDimitry Andric   case ImbueAttr::ALWAYS:
34460b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
34470b57cec5SDimitry Andric     break;
34480b57cec5SDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
34490b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
34500b57cec5SDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
34510b57cec5SDimitry Andric     break;
34520b57cec5SDimitry Andric   case ImbueAttr::NEVER:
34530b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
34540b57cec5SDimitry Andric     break;
34550b57cec5SDimitry Andric   }
34560b57cec5SDimitry Andric   return true;
34570b57cec5SDimitry Andric }
34580b57cec5SDimitry Andric 
3459bdd1243dSDimitry Andric ProfileList::ExclusionType
3460bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3461e8d8bef9SDimitry Andric                                               SourceLocation Loc) const {
3462e8d8bef9SDimitry Andric   const auto &ProfileList = getContext().getProfileList();
3463e8d8bef9SDimitry Andric   // If the profile list is empty, then instrument everything.
3464e8d8bef9SDimitry Andric   if (ProfileList.isEmpty())
3465bdd1243dSDimitry Andric     return ProfileList::Allow;
3466e8d8bef9SDimitry Andric   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3467e8d8bef9SDimitry Andric   // First, check the function name.
3468bdd1243dSDimitry Andric   if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3469e8d8bef9SDimitry Andric     return *V;
3470e8d8bef9SDimitry Andric   // Next, check the source location.
3471bdd1243dSDimitry Andric   if (Loc.isValid())
3472bdd1243dSDimitry Andric     if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3473e8d8bef9SDimitry Andric       return *V;
3474e8d8bef9SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
3475e8d8bef9SDimitry Andric   // it's located in the main file.
3476e8d8bef9SDimitry Andric   auto &SM = Context.getSourceManager();
34775f757f3fSDimitry Andric   if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
3478bdd1243dSDimitry Andric     if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3479e8d8bef9SDimitry Andric       return *V;
3480bdd1243dSDimitry Andric   return ProfileList.getDefault(Kind);
3481e8d8bef9SDimitry Andric }
3482e8d8bef9SDimitry Andric 
3483bdd1243dSDimitry Andric ProfileList::ExclusionType
3484bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3485bdd1243dSDimitry Andric                                                  SourceLocation Loc) const {
3486bdd1243dSDimitry Andric   auto V = isFunctionBlockedByProfileList(Fn, Loc);
3487bdd1243dSDimitry Andric   if (V != ProfileList::Allow)
3488bdd1243dSDimitry Andric     return V;
3489fcaf7f86SDimitry Andric 
3490fcaf7f86SDimitry Andric   auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3491fcaf7f86SDimitry Andric   if (NumGroups > 1) {
3492fcaf7f86SDimitry Andric     auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3493fcaf7f86SDimitry Andric     if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3494bdd1243dSDimitry Andric       return ProfileList::Skip;
3495fcaf7f86SDimitry Andric   }
3496bdd1243dSDimitry Andric   return ProfileList::Allow;
3497fcaf7f86SDimitry Andric }
3498fcaf7f86SDimitry Andric 
34990b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
35000b57cec5SDimitry Andric   // Never defer when EmitAllDecls is specified.
35010b57cec5SDimitry Andric   if (LangOpts.EmitAllDecls)
35020b57cec5SDimitry Andric     return true;
35030b57cec5SDimitry Andric 
35040b57cec5SDimitry Andric   const auto *VD = dyn_cast<VarDecl>(Global);
350506c3fb27SDimitry Andric   if (VD &&
350606c3fb27SDimitry Andric       ((CodeGenOpts.KeepPersistentStorageVariables &&
350706c3fb27SDimitry Andric         (VD->getStorageDuration() == SD_Static ||
350806c3fb27SDimitry Andric          VD->getStorageDuration() == SD_Thread)) ||
350906c3fb27SDimitry Andric        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
351006c3fb27SDimitry Andric         VD->getType().isConstQualified())))
35110b57cec5SDimitry Andric     return true;
35120b57cec5SDimitry Andric 
35130b57cec5SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
35140b57cec5SDimitry Andric }
35150b57cec5SDimitry Andric 
35160b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3517fe6060f1SDimitry Andric   // In OpenMP 5.0 variables and function may be marked as
3518fe6060f1SDimitry Andric   // device_type(host/nohost) and we should not emit them eagerly unless we sure
3519fe6060f1SDimitry Andric   // that they must be emitted on the host/device. To be sure we need to have
3520fe6060f1SDimitry Andric   // seen a declare target with an explicit mentioning of the function, we know
3521fe6060f1SDimitry Andric   // we have if the level of the declare target attribute is -1. Note that we
3522fe6060f1SDimitry Andric   // check somewhere else if we should emit this at all.
3523fe6060f1SDimitry Andric   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3524bdd1243dSDimitry Andric     std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3525fe6060f1SDimitry Andric         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3526fe6060f1SDimitry Andric     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3527fe6060f1SDimitry Andric       return false;
3528fe6060f1SDimitry Andric   }
3529fe6060f1SDimitry Andric 
3530a7dea167SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
35310b57cec5SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
35320b57cec5SDimitry Andric       // Implicit template instantiations may change linkage if they are later
35330b57cec5SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
35340b57cec5SDimitry Andric       return false;
35350fca6ea1SDimitry Andric     // Defer until all versions have been semantically checked.
35360fca6ea1SDimitry Andric     if (FD->hasAttr<TargetVersionAttr>() && !FD->isMultiVersion())
35370fca6ea1SDimitry Andric       return false;
3538a7dea167SDimitry Andric   }
3539fcaf7f86SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global)) {
35400b57cec5SDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
35410b57cec5SDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
35420b57cec5SDimitry Andric       // A definition of an inline constexpr static data member may change
35430b57cec5SDimitry Andric       // linkage later if it's redeclared outside the class.
35440b57cec5SDimitry Andric       return false;
3545fcaf7f86SDimitry Andric     if (CXX20ModuleInits && VD->getOwningModule() &&
3546fcaf7f86SDimitry Andric         !VD->getOwningModule()->isModuleMapModule()) {
3547fcaf7f86SDimitry Andric       // For CXX20, module-owned initializers need to be deferred, since it is
3548fcaf7f86SDimitry Andric       // not known at this point if they will be run for the current module or
3549fcaf7f86SDimitry Andric       // as part of the initializer for an imported one.
3550fcaf7f86SDimitry Andric       return false;
3551fcaf7f86SDimitry Andric     }
3552fcaf7f86SDimitry Andric   }
35530b57cec5SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
35540b57cec5SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
35550b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
35560b57cec5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
35575f757f3fSDimitry Andric       !Global->getType().isConstantStorage(getContext(), false, false) &&
35580b57cec5SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
35590b57cec5SDimitry Andric     return false;
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric   return true;
35620b57cec5SDimitry Andric }
35630b57cec5SDimitry Andric 
35645ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
35655ffd83dbSDimitry Andric   StringRef Name = getMangledName(GD);
35660b57cec5SDimitry Andric 
35670b57cec5SDimitry Andric   // The UUID descriptor should be pointer aligned.
35680b57cec5SDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
35690b57cec5SDimitry Andric 
35700b57cec5SDimitry Andric   // Look for an existing global.
35710b57cec5SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
35720eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
35730b57cec5SDimitry Andric 
35745ffd83dbSDimitry Andric   ConstantEmitter Emitter(*this);
35755ffd83dbSDimitry Andric   llvm::Constant *Init;
35765ffd83dbSDimitry Andric 
35775ffd83dbSDimitry Andric   APValue &V = GD->getAsAPValue();
35785ffd83dbSDimitry Andric   if (!V.isAbsent()) {
35795ffd83dbSDimitry Andric     // If possible, emit the APValue version of the initializer. In particular,
35805ffd83dbSDimitry Andric     // this gets the type of the constant right.
35815ffd83dbSDimitry Andric     Init = Emitter.emitForInitializer(
35825ffd83dbSDimitry Andric         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
35835ffd83dbSDimitry Andric   } else {
35845ffd83dbSDimitry Andric     // As a fallback, directly construct the constant.
35855ffd83dbSDimitry Andric     // FIXME: This may get padding wrong under esoteric struct layout rules.
35865ffd83dbSDimitry Andric     // MSVC appears to create a complete type 'struct __s_GUID' that it
35875ffd83dbSDimitry Andric     // presumably uses to represent these constants.
35885ffd83dbSDimitry Andric     MSGuidDecl::Parts Parts = GD->getParts();
35895ffd83dbSDimitry Andric     llvm::Constant *Fields[4] = {
35905ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
35915ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
35925ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
35935ffd83dbSDimitry Andric         llvm::ConstantDataArray::getRaw(
35945ffd83dbSDimitry Andric             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
35955ffd83dbSDimitry Andric             Int8Ty)};
35965ffd83dbSDimitry Andric     Init = llvm::ConstantStruct::getAnon(Fields);
35975ffd83dbSDimitry Andric   }
35980b57cec5SDimitry Andric 
35990b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
36000b57cec5SDimitry Andric       getModule(), Init->getType(),
36010b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
36020b57cec5SDimitry Andric   if (supportsCOMDAT())
36030b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
36040b57cec5SDimitry Andric   setDSOLocal(GV);
36055ffd83dbSDimitry Andric 
36065ffd83dbSDimitry Andric   if (!V.isAbsent()) {
36075ffd83dbSDimitry Andric     Emitter.finalize(GV);
36080eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
36095ffd83dbSDimitry Andric   }
36100eae32dcSDimitry Andric 
36110eae32dcSDimitry Andric   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
36125f757f3fSDimitry Andric   return ConstantAddress(GV, Ty, Alignment);
36130b57cec5SDimitry Andric }
36140b57cec5SDimitry Andric 
361581ad6265SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
361681ad6265SDimitry Andric     const UnnamedGlobalConstantDecl *GCD) {
361781ad6265SDimitry Andric   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
361881ad6265SDimitry Andric 
361981ad6265SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
362081ad6265SDimitry Andric   Entry = &UnnamedGlobalConstantDeclMap[GCD];
362181ad6265SDimitry Andric   if (*Entry)
362281ad6265SDimitry Andric     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
362381ad6265SDimitry Andric 
362481ad6265SDimitry Andric   ConstantEmitter Emitter(*this);
362581ad6265SDimitry Andric   llvm::Constant *Init;
362681ad6265SDimitry Andric 
362781ad6265SDimitry Andric   const APValue &V = GCD->getValue();
362881ad6265SDimitry Andric 
362981ad6265SDimitry Andric   assert(!V.isAbsent());
363081ad6265SDimitry Andric   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
363181ad6265SDimitry Andric                                     GCD->getType());
363281ad6265SDimitry Andric 
363381ad6265SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
363481ad6265SDimitry Andric                                       /*isConstant=*/true,
363581ad6265SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Init,
363681ad6265SDimitry Andric                                       ".constant");
363781ad6265SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
363881ad6265SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
363981ad6265SDimitry Andric 
364081ad6265SDimitry Andric   Emitter.finalize(GV);
364181ad6265SDimitry Andric 
364281ad6265SDimitry Andric   *Entry = GV;
364381ad6265SDimitry Andric   return ConstantAddress(GV, GV->getValueType(), Alignment);
364481ad6265SDimitry Andric }
364581ad6265SDimitry Andric 
3646e8d8bef9SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3647e8d8bef9SDimitry Andric     const TemplateParamObjectDecl *TPO) {
3648e8d8bef9SDimitry Andric   StringRef Name = getMangledName(TPO);
3649e8d8bef9SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3650e8d8bef9SDimitry Andric 
3651e8d8bef9SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
36520eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
3653e8d8bef9SDimitry Andric 
3654e8d8bef9SDimitry Andric   ConstantEmitter Emitter(*this);
3655e8d8bef9SDimitry Andric   llvm::Constant *Init = Emitter.emitForInitializer(
3656e8d8bef9SDimitry Andric         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3657e8d8bef9SDimitry Andric 
3658e8d8bef9SDimitry Andric   if (!Init) {
3659e8d8bef9SDimitry Andric     ErrorUnsupported(TPO, "template parameter object");
3660e8d8bef9SDimitry Andric     return ConstantAddress::invalid();
3661e8d8bef9SDimitry Andric   }
3662e8d8bef9SDimitry Andric 
366306c3fb27SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
366406c3fb27SDimitry Andric       isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
366506c3fb27SDimitry Andric           ? llvm::GlobalValue::LinkOnceODRLinkage
366606c3fb27SDimitry Andric           : llvm::GlobalValue::InternalLinkage;
366706c3fb27SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
366806c3fb27SDimitry Andric                                       /*isConstant=*/true, Linkage, Init, Name);
366906c3fb27SDimitry Andric   setGVProperties(GV, TPO);
3670e8d8bef9SDimitry Andric   if (supportsCOMDAT())
3671e8d8bef9SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3672e8d8bef9SDimitry Andric   Emitter.finalize(GV);
3673e8d8bef9SDimitry Andric 
36740eae32dcSDimitry Andric     return ConstantAddress(GV, GV->getValueType(), Alignment);
3675e8d8bef9SDimitry Andric }
3676e8d8bef9SDimitry Andric 
36770b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
36780b57cec5SDimitry Andric   const AliasAttr *AA = VD->getAttr<AliasAttr>();
36790b57cec5SDimitry Andric   assert(AA && "No alias?");
36800b57cec5SDimitry Andric 
36810b57cec5SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
36820b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
36830b57cec5SDimitry Andric 
36840b57cec5SDimitry Andric   // See if there is already something with the target's name in the module.
36850b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
36865f757f3fSDimitry Andric   if (Entry)
36875f757f3fSDimitry Andric     return ConstantAddress(Entry, DeclTy, Alignment);
36880b57cec5SDimitry Andric 
36890b57cec5SDimitry Andric   llvm::Constant *Aliasee;
36900b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy))
36910b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
36920b57cec5SDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
36930b57cec5SDimitry Andric                                       /*ForVTable=*/false);
36940b57cec5SDimitry Andric   else
3695349cc55cSDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3696349cc55cSDimitry Andric                                     nullptr);
36970b57cec5SDimitry Andric 
36980b57cec5SDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
36990b57cec5SDimitry Andric   F->setLinkage(llvm::Function::ExternalWeakLinkage);
37000b57cec5SDimitry Andric   WeakRefReferences.insert(F);
37010b57cec5SDimitry Andric 
37020eae32dcSDimitry Andric   return ConstantAddress(Aliasee, DeclTy, Alignment);
37030b57cec5SDimitry Andric }
37040b57cec5SDimitry Andric 
37055f757f3fSDimitry Andric template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
37065f757f3fSDimitry Andric   if (!D)
37075f757f3fSDimitry Andric     return false;
37085f757f3fSDimitry Andric   if (auto *A = D->getAttr<AttrT>())
37095f757f3fSDimitry Andric     return A->isImplicit();
37105f757f3fSDimitry Andric   return D->isImplicit();
37115f757f3fSDimitry Andric }
37125f757f3fSDimitry Andric 
37130fca6ea1SDimitry Andric bool CodeGenModule::shouldEmitCUDAGlobalVar(const VarDecl *Global) const {
37140fca6ea1SDimitry Andric   assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
37150fca6ea1SDimitry Andric   // We need to emit host-side 'shadows' for all global
37160fca6ea1SDimitry Andric   // device-side variables because the CUDA runtime needs their
37170fca6ea1SDimitry Andric   // size and host-side address in order to provide access to
37180fca6ea1SDimitry Andric   // their device-side incarnations.
37190fca6ea1SDimitry Andric   return !LangOpts.CUDAIsDevice || Global->hasAttr<CUDADeviceAttr>() ||
37200fca6ea1SDimitry Andric          Global->hasAttr<CUDAConstantAttr>() ||
37210fca6ea1SDimitry Andric          Global->hasAttr<CUDASharedAttr>() ||
37220fca6ea1SDimitry Andric          Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
37230fca6ea1SDimitry Andric          Global->getType()->isCUDADeviceBuiltinTextureType();
37240fca6ea1SDimitry Andric }
37250fca6ea1SDimitry Andric 
37260b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) {
37270b57cec5SDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric   // Weak references don't produce any output by themselves.
37300b57cec5SDimitry Andric   if (Global->hasAttr<WeakRefAttr>())
37310b57cec5SDimitry Andric     return;
37320b57cec5SDimitry Andric 
37330b57cec5SDimitry Andric   // If this is an alias definition (which otherwise looks like a declaration)
37340b57cec5SDimitry Andric   // emit it now.
37350b57cec5SDimitry Andric   if (Global->hasAttr<AliasAttr>())
37360b57cec5SDimitry Andric     return EmitAliasDefinition(GD);
37370b57cec5SDimitry Andric 
37380b57cec5SDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
37390b57cec5SDimitry Andric   if (Global->hasAttr<IFuncAttr>())
37400b57cec5SDimitry Andric     return emitIFuncDefinition(GD);
37410b57cec5SDimitry Andric 
37420b57cec5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
37430b57cec5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
37440b57cec5SDimitry Andric     return emitCPUDispatchDefinition(GD);
37450b57cec5SDimitry Andric 
37460b57cec5SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
37475f757f3fSDimitry Andric   // Non-constexpr non-lambda implicit host device functions are not emitted
37485f757f3fSDimitry Andric   // unless they are used on device side.
37490b57cec5SDimitry Andric   if (LangOpts.CUDA) {
37500fca6ea1SDimitry Andric     assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
37510fca6ea1SDimitry Andric            "Expected Variable or Function");
37520fca6ea1SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(Global)) {
37530fca6ea1SDimitry Andric       if (!shouldEmitCUDAGlobalVar(VD))
37540fca6ea1SDimitry Andric         return;
37550fca6ea1SDimitry Andric     } else if (LangOpts.CUDAIsDevice) {
37565f757f3fSDimitry Andric       const auto *FD = dyn_cast<FunctionDecl>(Global);
37575f757f3fSDimitry Andric       if ((!Global->hasAttr<CUDADeviceAttr>() ||
37580fca6ea1SDimitry Andric            (LangOpts.OffloadImplicitHostDeviceTemplates &&
37595f757f3fSDimitry Andric             hasImplicitAttr<CUDAHostAttr>(FD) &&
37605f757f3fSDimitry Andric             hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
37615f757f3fSDimitry Andric             !isLambdaCallOperator(FD) &&
37625f757f3fSDimitry Andric             !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
37630b57cec5SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
37645f757f3fSDimitry Andric           !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) &&
37655f757f3fSDimitry Andric             !Global->hasAttr<CUDAHostAttr>()))
37660b57cec5SDimitry Andric         return;
37670fca6ea1SDimitry Andric       // Device-only functions are the only things we skip.
37680fca6ea1SDimitry Andric     } else if (!Global->hasAttr<CUDAHostAttr>() &&
37690b57cec5SDimitry Andric                Global->hasAttr<CUDADeviceAttr>())
37700b57cec5SDimitry Andric       return;
37710b57cec5SDimitry Andric   }
37720b57cec5SDimitry Andric 
37730b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
3774a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
37750b57cec5SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
37760b57cec5SDimitry Andric       return;
37770b57cec5SDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
37780b57cec5SDimitry Andric       if (MustBeEmitted(Global))
37790b57cec5SDimitry Andric         EmitOMPDeclareReduction(DRD);
37800b57cec5SDimitry Andric       return;
378106c3fb27SDimitry Andric     }
378206c3fb27SDimitry Andric     if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
37830b57cec5SDimitry Andric       if (MustBeEmitted(Global))
37840b57cec5SDimitry Andric         EmitOMPDeclareMapper(DMD);
37850b57cec5SDimitry Andric       return;
37860b57cec5SDimitry Andric     }
37870b57cec5SDimitry Andric   }
37880b57cec5SDimitry Andric 
37890b57cec5SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
37900b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
37915f757f3fSDimitry Andric     // Update deferred annotations with the latest declaration if the function
37925f757f3fSDimitry Andric     // function was already used or defined.
37935f757f3fSDimitry Andric     if (FD->hasAttr<AnnotateAttr>()) {
37945f757f3fSDimitry Andric       StringRef MangledName = getMangledName(GD);
37955f757f3fSDimitry Andric       if (GetGlobalValue(MangledName))
37965f757f3fSDimitry Andric         DeferredAnnotations[MangledName] = FD;
37975f757f3fSDimitry Andric     }
37985f757f3fSDimitry Andric 
37990b57cec5SDimitry Andric     // Forward declarations are emitted lazily on first use.
38000b57cec5SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
38010fca6ea1SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
38020fca6ea1SDimitry Andric           (!FD->isMultiVersion() || !getTarget().getTriple().isAArch64()))
38030b57cec5SDimitry Andric         return;
38040b57cec5SDimitry Andric 
38050b57cec5SDimitry Andric       StringRef MangledName = getMangledName(GD);
38060b57cec5SDimitry Andric 
38070b57cec5SDimitry Andric       // Compute the function info and LLVM type.
38080b57cec5SDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
38090b57cec5SDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
38100b57cec5SDimitry Andric 
38110b57cec5SDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
38120b57cec5SDimitry Andric                               /*DontDefer=*/false);
38130b57cec5SDimitry Andric       return;
38140b57cec5SDimitry Andric     }
38150b57cec5SDimitry Andric   } else {
38160b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(Global);
38170b57cec5SDimitry Andric     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
38180b57cec5SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
38190b57cec5SDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
38200b57cec5SDimitry Andric       if (LangOpts.OpenMP) {
38210b57cec5SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
3822bdd1243dSDimitry Andric         if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
38230b57cec5SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
38248a4dda33SDimitry Andric 
38258a4dda33SDimitry Andric           // If this variable has external storage and doesn't require special
38268a4dda33SDimitry Andric           // link handling we defer to its canonical definition.
38278a4dda33SDimitry Andric           if (VD->hasExternalStorage() &&
38288a4dda33SDimitry Andric               Res != OMPDeclareTargetDeclAttr::MT_Link)
38298a4dda33SDimitry Andric             return;
38308a4dda33SDimitry Andric 
38310b57cec5SDimitry Andric           bool UnifiedMemoryEnabled =
38320b57cec5SDimitry Andric               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3833bdd1243dSDimitry Andric           if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3834bdd1243dSDimitry Andric                *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
38350b57cec5SDimitry Andric               !UnifiedMemoryEnabled) {
38360b57cec5SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
38370b57cec5SDimitry Andric           } else {
38380b57cec5SDimitry Andric             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3839bdd1243dSDimitry Andric                     ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3840bdd1243dSDimitry Andric                       *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
38410b57cec5SDimitry Andric                      UnifiedMemoryEnabled)) &&
38420b57cec5SDimitry Andric                    "Link clause or to clause with unified memory expected.");
38430b57cec5SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
38440b57cec5SDimitry Andric           }
38450b57cec5SDimitry Andric 
38460b57cec5SDimitry Andric           return;
38470b57cec5SDimitry Andric         }
38480b57cec5SDimitry Andric       }
38490b57cec5SDimitry Andric       // If this declaration may have caused an inline variable definition to
38500b57cec5SDimitry Andric       // change linkage, make sure that it's emitted.
38510b57cec5SDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
38520b57cec5SDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
38530b57cec5SDimitry Andric         GetAddrOfGlobalVar(VD);
38540b57cec5SDimitry Andric       return;
38550b57cec5SDimitry Andric     }
38560b57cec5SDimitry Andric   }
38570b57cec5SDimitry Andric 
38580b57cec5SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
38590b57cec5SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
38600b57cec5SDimitry Andric   // to benefit from cache locality.
38610b57cec5SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
38620b57cec5SDimitry Andric     // Emit the definition if it can't be deferred.
38630b57cec5SDimitry Andric     EmitGlobalDefinition(GD);
38648a4dda33SDimitry Andric     addEmittedDeferredDecl(GD);
38650b57cec5SDimitry Andric     return;
38660b57cec5SDimitry Andric   }
38670b57cec5SDimitry Andric 
38680b57cec5SDimitry Andric   // If we're deferring emission of a C++ variable with an
38690b57cec5SDimitry Andric   // initializer, remember the order in which it appeared in the file.
38700b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
38710b57cec5SDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
38720b57cec5SDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
38730b57cec5SDimitry Andric     CXXGlobalInits.push_back(nullptr);
38740b57cec5SDimitry Andric   }
38750b57cec5SDimitry Andric 
38760b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
38770b57cec5SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
38780b57cec5SDimitry Andric     // The value has already been used and should therefore be emitted.
38790b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
38800b57cec5SDimitry Andric   } else if (MustBeEmitted(Global)) {
38810b57cec5SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
38820b57cec5SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
38830b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
38840b57cec5SDimitry Andric   } else {
38850b57cec5SDimitry Andric     // Otherwise, remember that we saw a deferred decl with this name.  The
38860b57cec5SDimitry Andric     // first use of the mangled name will cause it to move into
38870b57cec5SDimitry Andric     // DeferredDeclsToEmit.
38880b57cec5SDimitry Andric     DeferredDecls[MangledName] = GD;
38890b57cec5SDimitry Andric   }
38900b57cec5SDimitry Andric }
38910b57cec5SDimitry Andric 
38920b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
38930b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
38940b57cec5SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
38950b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
38960b57cec5SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
38970b57cec5SDimitry Andric         return true;
38980b57cec5SDimitry Andric 
38990b57cec5SDimitry Andric   return false;
39000b57cec5SDimitry Andric }
39010b57cec5SDimitry Andric 
39020b57cec5SDimitry Andric namespace {
39030b57cec5SDimitry Andric   struct FunctionIsDirectlyRecursive
39040b57cec5SDimitry Andric       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
39050b57cec5SDimitry Andric     const StringRef Name;
39060b57cec5SDimitry Andric     const Builtin::Context &BI;
39070b57cec5SDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
39080b57cec5SDimitry Andric         : Name(N), BI(C) {}
39090b57cec5SDimitry Andric 
39100b57cec5SDimitry Andric     bool VisitCallExpr(const CallExpr *E) {
39110b57cec5SDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
39120b57cec5SDimitry Andric       if (!FD)
39130b57cec5SDimitry Andric         return false;
39140b57cec5SDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
39150b57cec5SDimitry Andric       if (Attr && Name == Attr->getLabel())
39160b57cec5SDimitry Andric         return true;
39170b57cec5SDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
39180b57cec5SDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
39190b57cec5SDimitry Andric         return false;
39200b57cec5SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
39215f757f3fSDimitry Andric       if (BuiltinName.starts_with("__builtin_") &&
39220b57cec5SDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
39230b57cec5SDimitry Andric         return true;
39240b57cec5SDimitry Andric       }
39250b57cec5SDimitry Andric       return false;
39260b57cec5SDimitry Andric     }
39270b57cec5SDimitry Andric 
39280b57cec5SDimitry Andric     bool VisitStmt(const Stmt *S) {
39290b57cec5SDimitry Andric       for (const Stmt *Child : S->children())
39300b57cec5SDimitry Andric         if (Child && this->Visit(Child))
39310b57cec5SDimitry Andric           return true;
39320b57cec5SDimitry Andric       return false;
39330b57cec5SDimitry Andric     }
39340b57cec5SDimitry Andric   };
39350b57cec5SDimitry Andric 
39360b57cec5SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
39370b57cec5SDimitry Andric   struct DLLImportFunctionVisitor
39380b57cec5SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
39390b57cec5SDimitry Andric     bool SafeToInline = true;
39400b57cec5SDimitry Andric 
39410b57cec5SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
39420b57cec5SDimitry Andric 
39430b57cec5SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
39440b57cec5SDimitry Andric       if (VD->getTLSKind()) {
39450b57cec5SDimitry Andric         // A thread-local variable cannot be imported.
39460b57cec5SDimitry Andric         SafeToInline = false;
39470b57cec5SDimitry Andric         return SafeToInline;
39480b57cec5SDimitry Andric       }
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric       // A variable definition might imply a destructor call.
39510b57cec5SDimitry Andric       if (VD->isThisDeclarationADefinition())
39520b57cec5SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric       return SafeToInline;
39550b57cec5SDimitry Andric     }
39560b57cec5SDimitry Andric 
39570b57cec5SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
39580b57cec5SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
39590b57cec5SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
39600b57cec5SDimitry Andric       return SafeToInline;
39610b57cec5SDimitry Andric     }
39620b57cec5SDimitry Andric 
39630b57cec5SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
39640b57cec5SDimitry Andric       ValueDecl *VD = E->getDecl();
39650b57cec5SDimitry Andric       if (isa<FunctionDecl>(VD))
39660b57cec5SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
39670b57cec5SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
39680b57cec5SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
39690b57cec5SDimitry Andric       return SafeToInline;
39700b57cec5SDimitry Andric     }
39710b57cec5SDimitry Andric 
39720b57cec5SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
39730b57cec5SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
39740b57cec5SDimitry Andric       return SafeToInline;
39750b57cec5SDimitry Andric     }
39760b57cec5SDimitry Andric 
39770b57cec5SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
39780b57cec5SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
39790b57cec5SDimitry Andric       if (!M) {
39800b57cec5SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
39810b57cec5SDimitry Andric         SafeToInline = true;
39820b57cec5SDimitry Andric       } else {
39830b57cec5SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
39840b57cec5SDimitry Andric       }
39850b57cec5SDimitry Andric       return SafeToInline;
39860b57cec5SDimitry Andric     }
39870b57cec5SDimitry Andric 
39880b57cec5SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
39890b57cec5SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
39900b57cec5SDimitry Andric       return SafeToInline;
39910b57cec5SDimitry Andric     }
39920b57cec5SDimitry Andric 
39930b57cec5SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
39940b57cec5SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
39950b57cec5SDimitry Andric       return SafeToInline;
39960b57cec5SDimitry Andric     }
39970b57cec5SDimitry Andric   };
39980b57cec5SDimitry Andric }
39990b57cec5SDimitry Andric 
40000b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another
40010b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
40020b57cec5SDimitry Andric // ends up pointing to itself.
40030b57cec5SDimitry Andric bool
40040b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
40050b57cec5SDimitry Andric   StringRef Name;
40060b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
40070b57cec5SDimitry Andric     // asm labels are a special kind of mangling we have to support.
40080b57cec5SDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
40090b57cec5SDimitry Andric     if (!Attr)
40100b57cec5SDimitry Andric       return false;
40110b57cec5SDimitry Andric     Name = Attr->getLabel();
40120b57cec5SDimitry Andric   } else {
40130b57cec5SDimitry Andric     Name = FD->getName();
40140b57cec5SDimitry Andric   }
40150b57cec5SDimitry Andric 
40160b57cec5SDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
40170b57cec5SDimitry Andric   const Stmt *Body = FD->getBody();
40180b57cec5SDimitry Andric   return Body ? Walker.Visit(Body) : false;
40190b57cec5SDimitry Andric }
40200b57cec5SDimitry Andric 
40210b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
40220b57cec5SDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
40230b57cec5SDimitry Andric     return true;
40245f757f3fSDimitry Andric 
40250b57cec5SDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
40260b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
40270b57cec5SDimitry Andric     return false;
40280b57cec5SDimitry Andric 
40295f757f3fSDimitry Andric   // We don't import function bodies from other named module units since that
40305f757f3fSDimitry Andric   // behavior may break ABI compatibility of the current unit.
40315f757f3fSDimitry Andric   if (const Module *M = F->getOwningModule();
40325f757f3fSDimitry Andric       M && M->getTopLevelModule()->isNamedModule() &&
40330fca6ea1SDimitry Andric       getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
40340fca6ea1SDimitry Andric     // There are practices to mark template member function as always-inline
40350fca6ea1SDimitry Andric     // and mark the template as extern explicit instantiation but not give
40360fca6ea1SDimitry Andric     // the definition for member function. So we have to emit the function
40370fca6ea1SDimitry Andric     // from explicitly instantiation with always-inline.
40380fca6ea1SDimitry Andric     //
40390fca6ea1SDimitry Andric     // See https://github.com/llvm/llvm-project/issues/86893 for details.
40400fca6ea1SDimitry Andric     //
40410fca6ea1SDimitry Andric     // TODO: Maybe it is better to give it a warning if we call a non-inline
40420fca6ea1SDimitry Andric     // function from other module units which is marked as always-inline.
40430fca6ea1SDimitry Andric     if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
40445f757f3fSDimitry Andric       return false;
40450fca6ea1SDimitry Andric     }
40460fca6ea1SDimitry Andric   }
40475f757f3fSDimitry Andric 
40485f757f3fSDimitry Andric   if (F->hasAttr<NoInlineAttr>())
40495f757f3fSDimitry Andric     return false;
40505f757f3fSDimitry Andric 
4051fe6060f1SDimitry Andric   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
40520b57cec5SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
40530b57cec5SDimitry Andric     DLLImportFunctionVisitor Visitor;
40540b57cec5SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
40550b57cec5SDimitry Andric     if (!Visitor.SafeToInline)
40560b57cec5SDimitry Andric       return false;
40570b57cec5SDimitry Andric 
40580b57cec5SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
40590b57cec5SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
40600b57cec5SDimitry Andric       // check above can't see them. Check for them manually here.
40610b57cec5SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
40620b57cec5SDimitry Andric         if (isa<FieldDecl>(Member))
40630b57cec5SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
40640b57cec5SDimitry Andric             return false;
40650b57cec5SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
40660b57cec5SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
40670b57cec5SDimitry Andric           return false;
40680b57cec5SDimitry Andric     }
40690b57cec5SDimitry Andric   }
40700b57cec5SDimitry Andric 
4071349cc55cSDimitry Andric   // Inline builtins declaration must be emitted. They often are fortified
4072349cc55cSDimitry Andric   // functions.
4073349cc55cSDimitry Andric   if (F->isInlineBuiltinDeclaration())
4074349cc55cSDimitry Andric     return true;
4075349cc55cSDimitry Andric 
40760b57cec5SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
40770b57cec5SDimitry Andric   // externally function should have an equivalent function somewhere else,
40785ffd83dbSDimitry Andric   // but a function that calls itself through asm label/`__builtin_` trickery is
40795ffd83dbSDimitry Andric   // clearly not equivalent to the real implementation.
40800b57cec5SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
40810b57cec5SDimitry Andric   return !isTriviallyRecursive(F);
40820b57cec5SDimitry Andric }
40830b57cec5SDimitry Andric 
40840b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
40850b57cec5SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
40860b57cec5SDimitry Andric }
40870b57cec5SDimitry Andric 
40880b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
40890b57cec5SDimitry Andric                                                        llvm::GlobalValue *GV) {
40900b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
40930b57cec5SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
40940b57cec5SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
40950b57cec5SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
40960fca6ea1SDimitry Andric   } else if (auto *TC = FD->getAttr<TargetClonesAttr>()) {
40970fca6ea1SDimitry Andric     for (unsigned I = 0; I < TC->featuresStrs_size(); ++I)
40980fca6ea1SDimitry Andric       // AArch64 favors the default target version over the clone if any.
40990fca6ea1SDimitry Andric       if ((!TC->isDefaultVersion(I) || !getTarget().getTriple().isAArch64()) &&
41000fca6ea1SDimitry Andric           TC->isFirstOfVersion(I))
41014824e7fdSDimitry Andric         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
410281ad6265SDimitry Andric     // Ensure that the resolver function is also emitted.
410381ad6265SDimitry Andric     GetOrCreateMultiVersionResolver(GD);
41040b57cec5SDimitry Andric   } else
41050b57cec5SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
41060fca6ea1SDimitry Andric 
41070fca6ea1SDimitry Andric   // Defer the resolver emission until we can reason whether the TU
41080fca6ea1SDimitry Andric   // contains a default target version implementation.
41090fca6ea1SDimitry Andric   if (FD->isTargetVersionMultiVersion())
41100fca6ea1SDimitry Andric     AddDeferredMultiVersionResolverToEmit(GD);
41110b57cec5SDimitry Andric }
41120b57cec5SDimitry Andric 
41130b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
41140b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
41150b57cec5SDimitry Andric 
41160b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
41170b57cec5SDimitry Andric                                  Context.getSourceManager(),
41180b57cec5SDimitry Andric                                  "Generating code for declaration");
41190b57cec5SDimitry Andric 
41200b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
41210b57cec5SDimitry Andric     // At -O0, don't generate IR for functions with available_externally
41220b57cec5SDimitry Andric     // linkage.
41230b57cec5SDimitry Andric     if (!shouldEmitFunction(GD))
41240b57cec5SDimitry Andric       return;
41250b57cec5SDimitry Andric 
41260b57cec5SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
41270b57cec5SDimitry Andric       std::string Name;
41280b57cec5SDimitry Andric       llvm::raw_string_ostream OS(Name);
41290b57cec5SDimitry Andric       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
41300b57cec5SDimitry Andric                                /*Qualified=*/true);
41310b57cec5SDimitry Andric       return Name;
41320b57cec5SDimitry Andric     });
41330b57cec5SDimitry Andric 
41340b57cec5SDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
41350b57cec5SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
41360b57cec5SDimitry Andric       // This is necessary for the generation of certain thunks.
41370b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
41380b57cec5SDimitry Andric         ABI->emitCXXStructor(GD);
41390b57cec5SDimitry Andric       else if (FD->isMultiVersion())
41400b57cec5SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
41410b57cec5SDimitry Andric       else
41420b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
41430b57cec5SDimitry Andric 
41440b57cec5SDimitry Andric       if (Method->isVirtual())
41450b57cec5SDimitry Andric         getVTables().EmitThunks(GD);
41460b57cec5SDimitry Andric 
41470b57cec5SDimitry Andric       return;
41480b57cec5SDimitry Andric     }
41490b57cec5SDimitry Andric 
41500b57cec5SDimitry Andric     if (FD->isMultiVersion())
41510b57cec5SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
41520b57cec5SDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
41530b57cec5SDimitry Andric   }
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
41560b57cec5SDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
41570b57cec5SDimitry Andric 
41580b57cec5SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
41590b57cec5SDimitry Andric }
41600b57cec5SDimitry Andric 
41610b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
41620b57cec5SDimitry Andric                                                       llvm::Function *NewFn);
41630b57cec5SDimitry Andric 
41640b57cec5SDimitry Andric static unsigned
41650b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
41660b57cec5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
41670b57cec5SDimitry Andric   unsigned Priority = 0;
4168bdd1243dSDimitry Andric   unsigned NumFeatures = 0;
4169bdd1243dSDimitry Andric   for (StringRef Feat : RO.Conditions.Features) {
41700b57cec5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
4171bdd1243dSDimitry Andric     NumFeatures++;
4172bdd1243dSDimitry Andric   }
41730b57cec5SDimitry Andric 
41740b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
41750b57cec5SDimitry Andric     Priority = std::max(
41760b57cec5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
4177bdd1243dSDimitry Andric 
4178bdd1243dSDimitry Andric   Priority += TI.multiVersionFeatureCost() * NumFeatures;
4179bdd1243dSDimitry Andric 
41800b57cec5SDimitry Andric   return Priority;
41810b57cec5SDimitry Andric }
41820b57cec5SDimitry Andric 
4183349cc55cSDimitry Andric // Multiversion functions should be at most 'WeakODRLinkage' so that a different
4184349cc55cSDimitry Andric // TU can forward declare the function without causing problems.  Particularly
4185349cc55cSDimitry Andric // in the cases of CPUDispatch, this causes issues. This also makes sure we
4186349cc55cSDimitry Andric // work with internal linkage functions, so that the same function name can be
4187349cc55cSDimitry Andric // used with internal linkage in multiple TUs.
4188349cc55cSDimitry Andric llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
4189349cc55cSDimitry Andric                                                        GlobalDecl GD) {
4190349cc55cSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
41915f757f3fSDimitry Andric   if (FD->getFormalLinkage() == Linkage::Internal)
4192349cc55cSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
4193349cc55cSDimitry Andric   return llvm::GlobalValue::WeakODRLinkage;
4194349cc55cSDimitry Andric }
4195349cc55cSDimitry Andric 
41960b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
4197fe6060f1SDimitry Andric   std::vector<GlobalDecl> MVFuncsToEmit;
4198fe6060f1SDimitry Andric   MultiVersionFuncs.swap(MVFuncsToEmit);
4199fe6060f1SDimitry Andric   for (GlobalDecl GD : MVFuncsToEmit) {
420081ad6265SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
420181ad6265SDimitry Andric     assert(FD && "Expected a FunctionDecl");
420281ad6265SDimitry Andric 
42030fca6ea1SDimitry Andric     auto createFunction = [&](const FunctionDecl *Decl, unsigned MVIdx = 0) {
42040fca6ea1SDimitry Andric       GlobalDecl CurGD{Decl->isDefined() ? Decl->getDefinition() : Decl, MVIdx};
42050fca6ea1SDimitry Andric       StringRef MangledName = getMangledName(CurGD);
42060fca6ea1SDimitry Andric       llvm::Constant *Func = GetGlobalValue(MangledName);
42070fca6ea1SDimitry Andric       if (!Func) {
42080fca6ea1SDimitry Andric         if (Decl->isDefined()) {
42090fca6ea1SDimitry Andric           EmitGlobalFunctionDefinition(CurGD, nullptr);
42100fca6ea1SDimitry Andric           Func = GetGlobalValue(MangledName);
42110fca6ea1SDimitry Andric         } else {
42120fca6ea1SDimitry Andric           const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(CurGD);
42130fca6ea1SDimitry Andric           llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
42140fca6ea1SDimitry Andric           Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
42150fca6ea1SDimitry Andric                                    /*DontDefer=*/false, ForDefinition);
42160fca6ea1SDimitry Andric         }
42170fca6ea1SDimitry Andric         assert(Func && "This should have just been created");
42180fca6ea1SDimitry Andric       }
42190fca6ea1SDimitry Andric       return cast<llvm::Function>(Func);
42200fca6ea1SDimitry Andric     };
42210fca6ea1SDimitry Andric 
42220fca6ea1SDimitry Andric     // For AArch64, a resolver is only emitted if a function marked with
42230fca6ea1SDimitry Andric     // target_version("default")) or target_clones() is present and defined
42240fca6ea1SDimitry Andric     // in this TU. For other architectures it is always emitted.
42250fca6ea1SDimitry Andric     bool ShouldEmitResolver = !getTarget().getTriple().isAArch64();
42260b57cec5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
42270fca6ea1SDimitry Andric 
42280b57cec5SDimitry Andric     getContext().forEachMultiversionedFunctionVersion(
42290fca6ea1SDimitry Andric         FD, [&](const FunctionDecl *CurFD) {
42300b57cec5SDimitry Andric           llvm::SmallVector<StringRef, 8> Feats;
42310fca6ea1SDimitry Andric           bool IsDefined = CurFD->doesThisDeclarationHaveABody();
42320fca6ea1SDimitry Andric 
42330fca6ea1SDimitry Andric           if (const auto *TA = CurFD->getAttr<TargetAttr>()) {
42340b57cec5SDimitry Andric             TA->getAddedFeatures(Feats);
42350fca6ea1SDimitry Andric             llvm::Function *Func = createFunction(CurFD);
42360fca6ea1SDimitry Andric             Options.emplace_back(Func, TA->getArchitecture(), Feats);
42370fca6ea1SDimitry Andric           } else if (const auto *TVA = CurFD->getAttr<TargetVersionAttr>()) {
42380fca6ea1SDimitry Andric             if (TVA->isDefaultVersion() && IsDefined)
42390fca6ea1SDimitry Andric               ShouldEmitResolver = true;
4240bdd1243dSDimitry Andric             TVA->getFeatures(Feats);
42410fca6ea1SDimitry Andric             llvm::Function *Func = createFunction(CurFD);
42420fca6ea1SDimitry Andric             Options.emplace_back(Func, /*Architecture*/ "", Feats);
42430fca6ea1SDimitry Andric           } else if (const auto *TC = CurFD->getAttr<TargetClonesAttr>()) {
42440fca6ea1SDimitry Andric             if (IsDefined)
42450fca6ea1SDimitry Andric               ShouldEmitResolver = true;
42460fca6ea1SDimitry Andric             for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
42470fca6ea1SDimitry Andric               if (!TC->isFirstOfVersion(I))
424881ad6265SDimitry Andric                 continue;
424981ad6265SDimitry Andric 
42500fca6ea1SDimitry Andric               llvm::Function *Func = createFunction(CurFD, I);
425181ad6265SDimitry Andric               StringRef Architecture;
42520fca6ea1SDimitry Andric               Feats.clear();
42530fca6ea1SDimitry Andric               if (getTarget().getTriple().isAArch64())
42540fca6ea1SDimitry Andric                 TC->getFeatures(Feats, I);
42550fca6ea1SDimitry Andric               else {
42560fca6ea1SDimitry Andric                 StringRef Version = TC->getFeatureStr(I);
42575f757f3fSDimitry Andric                 if (Version.starts_with("arch="))
425881ad6265SDimitry Andric                   Architecture = Version.drop_front(sizeof("arch=") - 1);
425981ad6265SDimitry Andric                 else if (Version != "default")
42600fca6ea1SDimitry Andric                   Feats.push_back(Version);
4261bdd1243dSDimitry Andric               }
42620fca6ea1SDimitry Andric               Options.emplace_back(Func, Architecture, Feats);
42630fca6ea1SDimitry Andric             }
42640fca6ea1SDimitry Andric           } else
42650fca6ea1SDimitry Andric             llvm_unreachable("unexpected MultiVersionKind");
42660fca6ea1SDimitry Andric         });
426781ad6265SDimitry Andric 
42680fca6ea1SDimitry Andric     if (!ShouldEmitResolver)
426981ad6265SDimitry Andric       continue;
427081ad6265SDimitry Andric 
427181ad6265SDimitry Andric     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
42725f757f3fSDimitry Andric     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
427381ad6265SDimitry Andric       ResolverConstant = IFunc->getResolver();
42740fca6ea1SDimitry Andric       if (FD->isTargetClonesMultiVersion() &&
42750fca6ea1SDimitry Andric           !getTarget().getTriple().isAArch64()) {
42765f757f3fSDimitry Andric         std::string MangledName = getMangledNameImpl(
42775f757f3fSDimitry Andric             *this, GD, FD, /*OmitMultiVersionMangling=*/true);
42780fca6ea1SDimitry Andric         if (!GetGlobalValue(MangledName + ".ifunc")) {
42790fca6ea1SDimitry Andric           const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
42800fca6ea1SDimitry Andric           llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
42815f757f3fSDimitry Andric           // In prior versions of Clang, the mangling for ifuncs incorrectly
42825f757f3fSDimitry Andric           // included an .ifunc suffix. This alias is generated for backward
42835f757f3fSDimitry Andric           // compatibility. It is deprecated, and may be removed in the future.
42845f757f3fSDimitry Andric           auto *Alias = llvm::GlobalAlias::create(
42855f757f3fSDimitry Andric               DeclTy, 0, getMultiversionLinkage(*this, GD),
42865f757f3fSDimitry Andric               MangledName + ".ifunc", IFunc, &getModule());
42875f757f3fSDimitry Andric           SetCommonAttributes(FD, Alias);
42885f757f3fSDimitry Andric         }
42895f757f3fSDimitry Andric       }
42900fca6ea1SDimitry Andric     }
429181ad6265SDimitry Andric     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
429281ad6265SDimitry Andric 
429381ad6265SDimitry Andric     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
42940b57cec5SDimitry Andric 
42955f757f3fSDimitry Andric     if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT())
42960b57cec5SDimitry Andric       ResolverFunc->setComdat(
42970b57cec5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
42980b57cec5SDimitry Andric 
429981ad6265SDimitry Andric     const TargetInfo &TI = getTarget();
43000b57cec5SDimitry Andric     llvm::stable_sort(
43010b57cec5SDimitry Andric         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
43020b57cec5SDimitry Andric                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
43030b57cec5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
43040b57cec5SDimitry Andric         });
43050b57cec5SDimitry Andric     CodeGenFunction CGF(*this);
43060b57cec5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
43070b57cec5SDimitry Andric   }
4308fe6060f1SDimitry Andric 
4309fe6060f1SDimitry Andric   // Ensure that any additions to the deferred decls list caused by emitting a
4310fe6060f1SDimitry Andric   // variant are emitted.  This can happen when the variant itself is inline and
4311fe6060f1SDimitry Andric   // calls a function without linkage.
4312fe6060f1SDimitry Andric   if (!MVFuncsToEmit.empty())
4313fe6060f1SDimitry Andric     EmitDeferred();
4314fe6060f1SDimitry Andric 
4315fe6060f1SDimitry Andric   // Ensure that any additions to the multiversion funcs list from either the
4316fe6060f1SDimitry Andric   // deferred decls or the multiversion functions themselves are emitted.
4317fe6060f1SDimitry Andric   if (!MultiVersionFuncs.empty())
4318fe6060f1SDimitry Andric     emitMultiVersionFunctions();
43190b57cec5SDimitry Andric }
43200b57cec5SDimitry Andric 
43210fca6ea1SDimitry Andric static void replaceDeclarationWith(llvm::GlobalValue *Old,
43220fca6ea1SDimitry Andric                                    llvm::Constant *New) {
43230fca6ea1SDimitry Andric   assert(cast<llvm::Function>(Old)->isDeclaration() && "Not a declaration");
43240fca6ea1SDimitry Andric   New->takeName(Old);
43250fca6ea1SDimitry Andric   Old->replaceAllUsesWith(New);
43260fca6ea1SDimitry Andric   Old->eraseFromParent();
43270fca6ea1SDimitry Andric }
43280fca6ea1SDimitry Andric 
43290b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
43300b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
43310b57cec5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
433204eeddc0SDimitry Andric   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
43330b57cec5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
43340b57cec5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
43350b57cec5SDimitry Andric 
433681ad6265SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
433781ad6265SDimitry Andric   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
43380b57cec5SDimitry Andric 
43390b57cec5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
434004eeddc0SDimitry Andric   UpdateMultiVersionNames(GD, FD, ResolverName);
43410b57cec5SDimitry Andric 
43420b57cec5SDimitry Andric   llvm::Type *ResolverType;
43430b57cec5SDimitry Andric   GlobalDecl ResolverGD;
434404eeddc0SDimitry Andric   if (getTarget().supportsIFunc()) {
43450b57cec5SDimitry Andric     ResolverType = llvm::FunctionType::get(
43460b57cec5SDimitry Andric         llvm::PointerType::get(DeclTy,
4347bdd1243dSDimitry Andric                                getTypes().getTargetAddressSpace(FD->getType())),
43480b57cec5SDimitry Andric         false);
434904eeddc0SDimitry Andric   }
43500b57cec5SDimitry Andric   else {
43510b57cec5SDimitry Andric     ResolverType = DeclTy;
43520b57cec5SDimitry Andric     ResolverGD = GD;
43530b57cec5SDimitry Andric   }
43540b57cec5SDimitry Andric 
43550b57cec5SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
43560b57cec5SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4357349cc55cSDimitry Andric   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4358a7dea167SDimitry Andric   if (supportsCOMDAT())
4359a7dea167SDimitry Andric     ResolverFunc->setComdat(
4360a7dea167SDimitry Andric         getModule().getOrInsertComdat(ResolverFunc->getName()));
43610b57cec5SDimitry Andric 
43620b57cec5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
43630b57cec5SDimitry Andric   const TargetInfo &Target = getTarget();
43640b57cec5SDimitry Andric   unsigned Index = 0;
43650b57cec5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
43660b57cec5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
43670b57cec5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
43680b57cec5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
43690b57cec5SDimitry Andric 
43700b57cec5SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
43710b57cec5SDimitry Andric 
43720b57cec5SDimitry Andric     if (!Func) {
43730b57cec5SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
43740b57cec5SDimitry Andric       if (ExistingDecl.getDecl() &&
43750b57cec5SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
43760b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
43770b57cec5SDimitry Andric         Func = GetGlobalValue(MangledName);
43780b57cec5SDimitry Andric       } else {
43790b57cec5SDimitry Andric         if (!ExistingDecl.getDecl())
43800b57cec5SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
43810b57cec5SDimitry Andric 
43820b57cec5SDimitry Andric       Func = GetOrCreateLLVMFunction(
43830b57cec5SDimitry Andric           MangledName, DeclTy, ExistingDecl,
43840b57cec5SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
43850b57cec5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
43860b57cec5SDimitry Andric       }
43870b57cec5SDimitry Andric     }
43880b57cec5SDimitry Andric 
43890b57cec5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
43900b57cec5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
43910b57cec5SDimitry Andric     llvm::transform(Features, Features.begin(),
43920b57cec5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
4393349cc55cSDimitry Andric     llvm::erase_if(Features, [&Target](StringRef Feat) {
43940b57cec5SDimitry Andric       return !Target.validateCpuSupports(Feat);
4395349cc55cSDimitry Andric     });
43960b57cec5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
43970b57cec5SDimitry Andric     ++Index;
43980b57cec5SDimitry Andric   }
43990b57cec5SDimitry Andric 
4400fe6060f1SDimitry Andric   llvm::stable_sort(
44010b57cec5SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
44020b57cec5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
4403349cc55cSDimitry Andric         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4404349cc55cSDimitry Andric                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
44050b57cec5SDimitry Andric       });
44060b57cec5SDimitry Andric 
44070b57cec5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
44080b57cec5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
44090b57cec5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
44100b57cec5SDimitry Andric   // advanced' (read, lowest mangling letter).
44110b57cec5SDimitry Andric   while (Options.size() > 1 &&
44125f757f3fSDimitry Andric          llvm::all_of(llvm::X86::getCpuSupportsMask(
44135f757f3fSDimitry Andric                           (Options.end() - 2)->Conditions.Features),
44145f757f3fSDimitry Andric                       [](auto X) { return X == 0; })) {
44150b57cec5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
44160b57cec5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
44170b57cec5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
44180b57cec5SDimitry Andric       Options.erase(Options.end() - 2);
44190b57cec5SDimitry Andric     else
44200b57cec5SDimitry Andric       Options.erase(Options.end() - 1);
44210b57cec5SDimitry Andric   }
44220b57cec5SDimitry Andric 
44230b57cec5SDimitry Andric   CodeGenFunction CGF(*this);
44240b57cec5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4425a7dea167SDimitry Andric 
4426a7dea167SDimitry Andric   if (getTarget().supportsIFunc()) {
442781ad6265SDimitry Andric     llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
442881ad6265SDimitry Andric     auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
442981ad6265SDimitry Andric 
443081ad6265SDimitry Andric     // Fix up function declarations that were created for cpu_specific before
443181ad6265SDimitry Andric     // cpu_dispatch was known
443281ad6265SDimitry Andric     if (!isa<llvm::GlobalIFunc>(IFunc)) {
443381ad6265SDimitry Andric       auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
443481ad6265SDimitry Andric                                            &getModule());
44350fca6ea1SDimitry Andric       replaceDeclarationWith(IFunc, GI);
443681ad6265SDimitry Andric       IFunc = GI;
443781ad6265SDimitry Andric     }
443881ad6265SDimitry Andric 
4439a7dea167SDimitry Andric     std::string AliasName = getMangledNameImpl(
4440a7dea167SDimitry Andric         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4441a7dea167SDimitry Andric     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4442a7dea167SDimitry Andric     if (!AliasFunc) {
444381ad6265SDimitry Andric       auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
444481ad6265SDimitry Andric                                            &getModule());
4445a7dea167SDimitry Andric       SetCommonAttributes(GD, GA);
4446a7dea167SDimitry Andric     }
4447a7dea167SDimitry Andric   }
44480b57cec5SDimitry Andric }
44490b57cec5SDimitry Andric 
44500fca6ea1SDimitry Andric /// Adds a declaration to the list of multi version functions if not present.
44510fca6ea1SDimitry Andric void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
44520fca6ea1SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
44530fca6ea1SDimitry Andric   assert(FD && "Not a FunctionDecl?");
44540fca6ea1SDimitry Andric 
44550fca6ea1SDimitry Andric   if (FD->isTargetVersionMultiVersion() || FD->isTargetClonesMultiVersion()) {
44560fca6ea1SDimitry Andric     std::string MangledName =
44570fca6ea1SDimitry Andric         getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
44580fca6ea1SDimitry Andric     if (!DeferredResolversToEmit.insert(MangledName).second)
44590fca6ea1SDimitry Andric       return;
44600fca6ea1SDimitry Andric   }
44610fca6ea1SDimitry Andric   MultiVersionFuncs.push_back(GD);
44620fca6ea1SDimitry Andric }
44630fca6ea1SDimitry Andric 
44640b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
44650fca6ea1SDimitry Andric /// and return it. The dispatcher is either an llvm Function with the specified
44660fca6ea1SDimitry Andric /// type, or a global ifunc.
446781ad6265SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
446881ad6265SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
446981ad6265SDimitry Andric   assert(FD && "Not a FunctionDecl?");
447081ad6265SDimitry Andric 
44710b57cec5SDimitry Andric   std::string MangledName =
44720b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
44730b57cec5SDimitry Andric 
44740b57cec5SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
44750b57cec5SDimitry Andric   // a separate resolver).
44760b57cec5SDimitry Andric   std::string ResolverName = MangledName;
44775f757f3fSDimitry Andric   if (getTarget().supportsIFunc()) {
44780fca6ea1SDimitry Andric     switch (FD->getMultiVersionKind()) {
44790fca6ea1SDimitry Andric     case MultiVersionKind::None:
44800fca6ea1SDimitry Andric       llvm_unreachable("unexpected MultiVersionKind::None for resolver");
44810fca6ea1SDimitry Andric     case MultiVersionKind::Target:
44820fca6ea1SDimitry Andric     case MultiVersionKind::CPUSpecific:
44830fca6ea1SDimitry Andric     case MultiVersionKind::CPUDispatch:
44840b57cec5SDimitry Andric       ResolverName += ".ifunc";
44850fca6ea1SDimitry Andric       break;
44860fca6ea1SDimitry Andric     case MultiVersionKind::TargetClones:
44870fca6ea1SDimitry Andric     case MultiVersionKind::TargetVersion:
44880fca6ea1SDimitry Andric       break;
44890fca6ea1SDimitry Andric     }
44905f757f3fSDimitry Andric   } else if (FD->isTargetMultiVersion()) {
44910b57cec5SDimitry Andric     ResolverName += ".resolver";
44925f757f3fSDimitry Andric   }
44930b57cec5SDimitry Andric 
44940fca6ea1SDimitry Andric   // If the resolver has already been created, just return it. This lookup may
44950fca6ea1SDimitry Andric   // yield a function declaration instead of a resolver on AArch64. That is
44960fca6ea1SDimitry Andric   // because we didn't know whether a resolver will be generated when we first
44970fca6ea1SDimitry Andric   // encountered a use of the symbol named after this resolver. Therefore,
44980fca6ea1SDimitry Andric   // targets which support ifuncs should not return here unless we actually
44990fca6ea1SDimitry Andric   // found an ifunc.
45000fca6ea1SDimitry Andric   llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName);
45010fca6ea1SDimitry Andric   if (ResolverGV &&
45020fca6ea1SDimitry Andric       (isa<llvm::GlobalIFunc>(ResolverGV) || !getTarget().supportsIFunc()))
45030b57cec5SDimitry Andric     return ResolverGV;
45040b57cec5SDimitry Andric 
450581ad6265SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
450681ad6265SDimitry Andric   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
45070b57cec5SDimitry Andric 
450881ad6265SDimitry Andric   // The resolver needs to be created. For target and target_clones, defer
450981ad6265SDimitry Andric   // creation until the end of the TU.
451081ad6265SDimitry Andric   if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
45110fca6ea1SDimitry Andric     AddDeferredMultiVersionResolverToEmit(GD);
451281ad6265SDimitry Andric 
451381ad6265SDimitry Andric   // For cpu_specific, don't create an ifunc yet because we don't know if the
451481ad6265SDimitry Andric   // cpu_dispatch will be emitted in this translation unit.
451581ad6265SDimitry Andric   if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
45160b57cec5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
4517bdd1243dSDimitry Andric         llvm::PointerType::get(DeclTy,
4518bdd1243dSDimitry Andric                                getTypes().getTargetAddressSpace(FD->getType())),
45190b57cec5SDimitry Andric         false);
45200b57cec5SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
45210b57cec5SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
45220b57cec5SDimitry Andric         /*ForVTable=*/false);
4523349cc55cSDimitry Andric     llvm::GlobalIFunc *GIF =
4524349cc55cSDimitry Andric         llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
4525349cc55cSDimitry Andric                                   "", Resolver, &getModule());
45260b57cec5SDimitry Andric     GIF->setName(ResolverName);
45270b57cec5SDimitry Andric     SetCommonAttributes(FD, GIF);
45280fca6ea1SDimitry Andric     if (ResolverGV)
45290fca6ea1SDimitry Andric       replaceDeclarationWith(ResolverGV, GIF);
45300b57cec5SDimitry Andric     return GIF;
45310b57cec5SDimitry Andric   }
45320b57cec5SDimitry Andric 
45330b57cec5SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
45340b57cec5SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
45350b57cec5SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
45360b57cec5SDimitry Andric          "Resolver should be created for the first time");
45370b57cec5SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
45380fca6ea1SDimitry Andric   if (ResolverGV)
45390fca6ea1SDimitry Andric     replaceDeclarationWith(ResolverGV, Resolver);
45400b57cec5SDimitry Andric   return Resolver;
45410b57cec5SDimitry Andric }
45420b57cec5SDimitry Andric 
45430fca6ea1SDimitry Andric bool CodeGenModule::shouldDropDLLAttribute(const Decl *D,
45440fca6ea1SDimitry Andric                                            const llvm::GlobalValue *GV) const {
45450fca6ea1SDimitry Andric   auto SC = GV->getDLLStorageClass();
45460fca6ea1SDimitry Andric   if (SC == llvm::GlobalValue::DefaultStorageClass)
45470fca6ea1SDimitry Andric     return false;
45480fca6ea1SDimitry Andric   const Decl *MRD = D->getMostRecentDecl();
45490fca6ea1SDimitry Andric   return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
45500fca6ea1SDimitry Andric             !MRD->hasAttr<DLLImportAttr>()) ||
45510fca6ea1SDimitry Andric            (SC == llvm::GlobalValue::DLLExportStorageClass &&
45520fca6ea1SDimitry Andric             !MRD->hasAttr<DLLExportAttr>())) &&
45530fca6ea1SDimitry Andric           !shouldMapVisibilityToDLLExport(cast<NamedDecl>(MRD)));
45540fca6ea1SDimitry Andric }
45550fca6ea1SDimitry Andric 
45560b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
45570b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there
45580b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
45590b57cec5SDimitry Andric /// bitcasted to the right type.
45600b57cec5SDimitry Andric ///
45610b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
45620b57cec5SDimitry Andric /// to set the attributes on the function when it is first created.
45630b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
45640b57cec5SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
45650b57cec5SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
45660b57cec5SDimitry Andric     ForDefinition_t IsForDefinition) {
45670b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
45680b57cec5SDimitry Andric 
45690fca6ea1SDimitry Andric   std::string NameWithoutMultiVersionMangling;
45700b57cec5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
45710b57cec5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
45720b57cec5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
45730b57cec5SDimitry Andric     // For the device mark the function as one that should be emitted.
457406c3fb27SDimitry Andric     if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
45750b57cec5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
45760b57cec5SDimitry Andric         !DontDefer && !IsForDefinition) {
45770b57cec5SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
45780b57cec5SDimitry Andric         GlobalDecl GDDef;
45790b57cec5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
45800b57cec5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
45810b57cec5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
45820b57cec5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
45830b57cec5SDimitry Andric         else
45840b57cec5SDimitry Andric           GDDef = GlobalDecl(FDDef);
45850b57cec5SDimitry Andric         EmitGlobal(GDDef);
45860b57cec5SDimitry Andric       }
45870b57cec5SDimitry Andric     }
45880b57cec5SDimitry Andric 
45890b57cec5SDimitry Andric     if (FD->isMultiVersion()) {
459004eeddc0SDimitry Andric       UpdateMultiVersionNames(GD, FD, MangledName);
45910fca6ea1SDimitry Andric       if (!IsForDefinition) {
45920fca6ea1SDimitry Andric         // On AArch64 we do not immediatelly emit an ifunc resolver when a
45930fca6ea1SDimitry Andric         // function is used. Instead we defer the emission until we see a
45940fca6ea1SDimitry Andric         // default definition. In the meantime we just reference the symbol
45950fca6ea1SDimitry Andric         // without FMV mangling (it may or may not be replaced later).
45960fca6ea1SDimitry Andric         if (getTarget().getTriple().isAArch64()) {
45970fca6ea1SDimitry Andric           AddDeferredMultiVersionResolverToEmit(GD);
45980fca6ea1SDimitry Andric           NameWithoutMultiVersionMangling = getMangledNameImpl(
45990fca6ea1SDimitry Andric               *this, GD, FD, /*OmitMultiVersionMangling=*/true);
46000fca6ea1SDimitry Andric         } else
460181ad6265SDimitry Andric           return GetOrCreateMultiVersionResolver(GD);
46020b57cec5SDimitry Andric       }
46030b57cec5SDimitry Andric     }
46040fca6ea1SDimitry Andric   }
46050fca6ea1SDimitry Andric 
46060fca6ea1SDimitry Andric   if (!NameWithoutMultiVersionMangling.empty())
46070fca6ea1SDimitry Andric     MangledName = NameWithoutMultiVersionMangling;
46080b57cec5SDimitry Andric 
46090b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
46100b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
46110b57cec5SDimitry Andric   if (Entry) {
46120b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
46130b57cec5SDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
46140b57cec5SDimitry Andric       if (FD && !FD->hasAttr<WeakAttr>())
46150b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
46160b57cec5SDimitry Andric     }
46170b57cec5SDimitry Andric 
46180b57cec5SDimitry Andric     // Handle dropped DLL attributes.
46190fca6ea1SDimitry Andric     if (D && shouldDropDLLAttribute(D, Entry)) {
46200b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
46210b57cec5SDimitry Andric       setDSOLocal(Entry);
46220b57cec5SDimitry Andric     }
46230b57cec5SDimitry Andric 
46240b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
46250b57cec5SDimitry Andric     // error.
46260b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
46270b57cec5SDimitry Andric       GlobalDecl OtherGD;
46280b57cec5SDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
46290b57cec5SDimitry Andric       // to make sure that we issue an error only once.
46300b57cec5SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
46310b57cec5SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
46320b57cec5SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
46330b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
46340b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
46350b57cec5SDimitry Andric             << MangledName;
46360b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
46370b57cec5SDimitry Andric                           diag::note_previous_definition);
46380b57cec5SDimitry Andric       }
46390b57cec5SDimitry Andric     }
46400b57cec5SDimitry Andric 
46410b57cec5SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
46425ffd83dbSDimitry Andric         (Entry->getValueType() == Ty)) {
46430b57cec5SDimitry Andric       return Entry;
46440b57cec5SDimitry Andric     }
46450b57cec5SDimitry Andric 
46460b57cec5SDimitry Andric     // Make sure the result is of the correct type.
46470b57cec5SDimitry Andric     // (If function is requested for a definition, we always need to create a new
46480b57cec5SDimitry Andric     // function, not just return a bitcast.)
46490b57cec5SDimitry Andric     if (!IsForDefinition)
46505f757f3fSDimitry Andric       return Entry;
46510b57cec5SDimitry Andric   }
46520b57cec5SDimitry Andric 
46530b57cec5SDimitry Andric   // This function doesn't have a complete type (for example, the return
46540b57cec5SDimitry Andric   // type is an incomplete struct). Use a fake type instead, and make
46550b57cec5SDimitry Andric   // sure not to try to set attributes.
46560b57cec5SDimitry Andric   bool IsIncompleteFunction = false;
46570b57cec5SDimitry Andric 
46580b57cec5SDimitry Andric   llvm::FunctionType *FTy;
46590b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(Ty)) {
46600b57cec5SDimitry Andric     FTy = cast<llvm::FunctionType>(Ty);
46610b57cec5SDimitry Andric   } else {
46620b57cec5SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
46630b57cec5SDimitry Andric     IsIncompleteFunction = true;
46640b57cec5SDimitry Andric   }
46650b57cec5SDimitry Andric 
46660b57cec5SDimitry Andric   llvm::Function *F =
46670b57cec5SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
46680b57cec5SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
46690b57cec5SDimitry Andric 
46705f757f3fSDimitry Andric   // Store the declaration associated with this function so it is potentially
46715f757f3fSDimitry Andric   // updated by further declarations or definitions and emitted at the end.
46725f757f3fSDimitry Andric   if (D && D->hasAttr<AnnotateAttr>())
46735f757f3fSDimitry Andric     DeferredAnnotations[MangledName] = cast<ValueDecl>(D);
46745f757f3fSDimitry Andric 
46750b57cec5SDimitry Andric   // If we already created a function with the same mangled name (but different
46760b57cec5SDimitry Andric   // type) before, take its name and add it to the list of functions to be
46770b57cec5SDimitry Andric   // replaced with F at the end of CodeGen.
46780b57cec5SDimitry Andric   //
46790b57cec5SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
46800b57cec5SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
46810b57cec5SDimitry Andric   if (Entry) {
46820b57cec5SDimitry Andric     F->takeName(Entry);
46830b57cec5SDimitry Andric 
46840b57cec5SDimitry Andric     // This might be an implementation of a function without a prototype, in
46850b57cec5SDimitry Andric     // which case, try to do special replacement of calls which match the new
46860b57cec5SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
46870b57cec5SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
46880b57cec5SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
46890b57cec5SDimitry Andric     // dropping arguments.
46900b57cec5SDimitry Andric     if (!Entry->use_empty()) {
46910b57cec5SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
46920b57cec5SDimitry Andric       Entry->removeDeadConstantUsers();
46930b57cec5SDimitry Andric     }
46940b57cec5SDimitry Andric 
46955f757f3fSDimitry Andric     addGlobalValReplacement(Entry, F);
46960b57cec5SDimitry Andric   }
46970b57cec5SDimitry Andric 
46980b57cec5SDimitry Andric   assert(F->getName() == MangledName && "name was uniqued!");
46990b57cec5SDimitry Andric   if (D)
47000b57cec5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4701349cc55cSDimitry Andric   if (ExtraAttrs.hasFnAttrs()) {
470204eeddc0SDimitry Andric     llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4703349cc55cSDimitry Andric     F->addFnAttrs(B);
47040b57cec5SDimitry Andric   }
47050b57cec5SDimitry Andric 
47060b57cec5SDimitry Andric   if (!DontDefer) {
47070b57cec5SDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
47080b57cec5SDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
47090b57cec5SDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
4710bdd1243dSDimitry Andric     if (isa_and_nonnull<CXXDestructorDecl>(D) &&
47110b57cec5SDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
47120b57cec5SDimitry Andric                                            GD.getDtorType()))
47130b57cec5SDimitry Andric       addDeferredDeclToEmit(GD);
47140b57cec5SDimitry Andric 
47150b57cec5SDimitry Andric     // This is the first use or definition of a mangled name.  If there is a
47160b57cec5SDimitry Andric     // deferred decl with this name, remember that we need to emit it at the end
47170b57cec5SDimitry Andric     // of the file.
47180b57cec5SDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
47190b57cec5SDimitry Andric     if (DDI != DeferredDecls.end()) {
47200b57cec5SDimitry Andric       // Move the potentially referenced deferred decl to the
47210b57cec5SDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
47220b57cec5SDimitry Andric       // don't need it anymore).
47230b57cec5SDimitry Andric       addDeferredDeclToEmit(DDI->second);
47240b57cec5SDimitry Andric       DeferredDecls.erase(DDI);
47250b57cec5SDimitry Andric 
47260b57cec5SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
47270b57cec5SDimitry Andric       // using a declaration for which we must emit a definition but where
47280b57cec5SDimitry Andric       // we might not find a top-level definition:
47290b57cec5SDimitry Andric       //   - member functions defined inline in their classes
47300b57cec5SDimitry Andric       //   - friend functions defined inline in some class
47310b57cec5SDimitry Andric       //   - special member functions with implicit definitions
47320b57cec5SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
47330b57cec5SDimitry Andric       // this will be unnecessary.
47340b57cec5SDimitry Andric       //
47350b57cec5SDimitry Andric       // We also don't emit a definition for a function if it's going to be an
47360b57cec5SDimitry Andric       // entry in a vtable, unless it's already marked as used.
47370b57cec5SDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
47380b57cec5SDimitry Andric       // Look for a declaration that's lexically in a record.
47390b57cec5SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
47400b57cec5SDimitry Andric            FD = FD->getPreviousDecl()) {
47410b57cec5SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
47420b57cec5SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
47430b57cec5SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
47440b57cec5SDimitry Andric             break;
47450b57cec5SDimitry Andric           }
47460b57cec5SDimitry Andric         }
47470b57cec5SDimitry Andric       }
47480b57cec5SDimitry Andric     }
47490b57cec5SDimitry Andric   }
47500b57cec5SDimitry Andric 
47510b57cec5SDimitry Andric   // Make sure the result is of the requested type.
47520b57cec5SDimitry Andric   if (!IsIncompleteFunction) {
47535ffd83dbSDimitry Andric     assert(F->getFunctionType() == Ty);
47540b57cec5SDimitry Andric     return F;
47550b57cec5SDimitry Andric   }
47560b57cec5SDimitry Andric 
47575f757f3fSDimitry Andric   return F;
47580b57cec5SDimitry Andric }
47590b57cec5SDimitry Andric 
47600b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function.  If Ty is
47610b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to
47620b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function).
476306c3fb27SDimitry Andric llvm::Constant *
476406c3fb27SDimitry Andric CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
47650b57cec5SDimitry Andric                                  bool DontDefer,
47660b57cec5SDimitry Andric                                  ForDefinition_t IsForDefinition) {
47670b57cec5SDimitry Andric   // If there was no specific requested type, just convert it now.
47680b57cec5SDimitry Andric   if (!Ty) {
47690b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
47700b57cec5SDimitry Andric     Ty = getTypes().ConvertType(FD->getType());
47710b57cec5SDimitry Andric   }
47720b57cec5SDimitry Andric 
47730b57cec5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
47740b57cec5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
47750b57cec5SDimitry Andric   // of the complete destructor when necessary.
47760b57cec5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
47770b57cec5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
47780b57cec5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
47790b57cec5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
47800b57cec5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
47810b57cec5SDimitry Andric   }
47820b57cec5SDimitry Andric 
47830b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
4784fe6060f1SDimitry Andric   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
47850b57cec5SDimitry Andric                                     /*IsThunk=*/false, llvm::AttributeList(),
47860b57cec5SDimitry Andric                                     IsForDefinition);
4787fe6060f1SDimitry Andric   // Returns kernel handle for HIP kernel stub function.
4788fe6060f1SDimitry Andric   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4789fe6060f1SDimitry Andric       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4790fe6060f1SDimitry Andric     auto *Handle = getCUDARuntime().getKernelHandle(
4791fe6060f1SDimitry Andric         cast<llvm::Function>(F->stripPointerCasts()), GD);
4792fe6060f1SDimitry Andric     if (IsForDefinition)
4793fe6060f1SDimitry Andric       return F;
47945f757f3fSDimitry Andric     return Handle;
4795fe6060f1SDimitry Andric   }
4796fe6060f1SDimitry Andric   return F;
47970b57cec5SDimitry Andric }
47980b57cec5SDimitry Andric 
47990eae32dcSDimitry Andric llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
48000eae32dcSDimitry Andric   llvm::GlobalValue *F =
48010eae32dcSDimitry Andric       cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
48020eae32dcSDimitry Andric 
48035f757f3fSDimitry Andric   return llvm::NoCFIValue::get(F);
48040eae32dcSDimitry Andric }
48050eae32dcSDimitry Andric 
48060b57cec5SDimitry Andric static const FunctionDecl *
48070b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
48080b57cec5SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
48090b57cec5SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
48100b57cec5SDimitry Andric 
48110b57cec5SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
4812fe6060f1SDimitry Andric   for (const auto *Result : DC->lookup(&CII))
4813fe6060f1SDimitry Andric     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
48140b57cec5SDimitry Andric       return FD;
48150b57cec5SDimitry Andric 
48160b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
48170b57cec5SDimitry Andric     return nullptr;
48180b57cec5SDimitry Andric 
48190b57cec5SDimitry Andric   // Demangle the premangled name from getTerminateFn()
48200b57cec5SDimitry Andric   IdentifierInfo &CXXII =
48210b57cec5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
48220b57cec5SDimitry Andric           ? C.Idents.get("terminate")
48230b57cec5SDimitry Andric           : C.Idents.get(Name);
48240b57cec5SDimitry Andric 
48250b57cec5SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
48260b57cec5SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
4827fe6060f1SDimitry Andric     for (const auto *Result : DC->lookup(&NS)) {
4828fe6060f1SDimitry Andric       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4829fe6060f1SDimitry Andric       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4830fe6060f1SDimitry Andric         for (const auto *Result : LSD->lookup(&NS))
48310b57cec5SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
48320b57cec5SDimitry Andric             break;
48330b57cec5SDimitry Andric 
48340b57cec5SDimitry Andric       if (ND)
4835fe6060f1SDimitry Andric         for (const auto *Result : ND->lookup(&CXXII))
48360b57cec5SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
48370b57cec5SDimitry Andric             return FD;
48380b57cec5SDimitry Andric     }
48390b57cec5SDimitry Andric   }
48400b57cec5SDimitry Andric 
48410b57cec5SDimitry Andric   return nullptr;
48420b57cec5SDimitry Andric }
48430b57cec5SDimitry Andric 
48440b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified
48450b57cec5SDimitry Andric /// type and name.
48460b57cec5SDimitry Andric llvm::FunctionCallee
48470b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4848480093f4SDimitry Andric                                      llvm::AttributeList ExtraAttrs, bool Local,
4849480093f4SDimitry Andric                                      bool AssumeConvergent) {
4850480093f4SDimitry Andric   if (AssumeConvergent) {
4851480093f4SDimitry Andric     ExtraAttrs =
4852349cc55cSDimitry Andric         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4853480093f4SDimitry Andric   }
4854480093f4SDimitry Andric 
48550b57cec5SDimitry Andric   llvm::Constant *C =
48560b57cec5SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
48570b57cec5SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
48580b57cec5SDimitry Andric                               ExtraAttrs);
48590b57cec5SDimitry Andric 
48600b57cec5SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
48610b57cec5SDimitry Andric     if (F->empty()) {
48620b57cec5SDimitry Andric       F->setCallingConv(getRuntimeCC());
48630b57cec5SDimitry Andric 
48640b57cec5SDimitry Andric       // In Windows Itanium environments, try to mark runtime functions
48650b57cec5SDimitry Andric       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
48660b57cec5SDimitry Andric       // will link their standard library statically or dynamically. Marking
48670b57cec5SDimitry Andric       // functions imported when they are not imported can cause linker errors
48680b57cec5SDimitry Andric       // and warnings.
48690b57cec5SDimitry Andric       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
48700b57cec5SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
48710b57cec5SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
48720b57cec5SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
48730b57cec5SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
48740b57cec5SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
48750b57cec5SDimitry Andric         }
48760b57cec5SDimitry Andric       }
48770b57cec5SDimitry Andric       setDSOLocal(F);
48780fca6ea1SDimitry Andric       // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead
48790fca6ea1SDimitry Andric       // of trying to approximate the attributes using the LLVM function
48800fca6ea1SDimitry Andric       // signature. This requires revising the API of CreateRuntimeFunction().
48810fca6ea1SDimitry Andric       markRegisterParameterAttributes(F);
48820b57cec5SDimitry Andric     }
48830b57cec5SDimitry Andric   }
48840b57cec5SDimitry Andric 
48850b57cec5SDimitry Andric   return {FTy, C};
48860b57cec5SDimitry Andric }
48870b57cec5SDimitry Andric 
48880b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4889fe6060f1SDimitry Andric /// create and return an llvm GlobalVariable with the specified type and address
4890fe6060f1SDimitry Andric /// space. If there is something in the module with the specified name, return
4891fe6060f1SDimitry Andric /// it potentially bitcasted to the right type.
48920b57cec5SDimitry Andric ///
48930b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
48940b57cec5SDimitry Andric /// to set the attributes on the global when it is first created.
48950b57cec5SDimitry Andric ///
48960b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
48970b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
48980b57cec5SDimitry Andric /// mangled name but some other type.
48990b57cec5SDimitry Andric llvm::Constant *
4900fe6060f1SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4901349cc55cSDimitry Andric                                      LangAS AddrSpace, const VarDecl *D,
49020b57cec5SDimitry Andric                                      ForDefinition_t IsForDefinition) {
49030b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
49040b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4905349cc55cSDimitry Andric   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
49060b57cec5SDimitry Andric   if (Entry) {
49070b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
49080b57cec5SDimitry Andric       if (D && !D->hasAttr<WeakAttr>())
49090b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
49100b57cec5SDimitry Andric     }
49110b57cec5SDimitry Andric 
49120b57cec5SDimitry Andric     // Handle dropped DLL attributes.
49130fca6ea1SDimitry Andric     if (D && shouldDropDLLAttribute(D, Entry))
49140b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
49150b57cec5SDimitry Andric 
49160b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
49170b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
49180b57cec5SDimitry Andric 
4919349cc55cSDimitry Andric     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
49200b57cec5SDimitry Andric       return Entry;
49210b57cec5SDimitry Andric 
49220b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
49230b57cec5SDimitry Andric     // error.
49240b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
49250b57cec5SDimitry Andric       GlobalDecl OtherGD;
49260b57cec5SDimitry Andric       const VarDecl *OtherD;
49270b57cec5SDimitry Andric 
49280b57cec5SDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
49290b57cec5SDimitry Andric       // to make sure that we issue an error only once.
49300b57cec5SDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
49310b57cec5SDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
49320b57cec5SDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
49330b57cec5SDimitry Andric           OtherD->hasInit() &&
49340b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
49350b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
49360b57cec5SDimitry Andric             << MangledName;
49370b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
49380b57cec5SDimitry Andric                           diag::note_previous_definition);
49390b57cec5SDimitry Andric       }
49400b57cec5SDimitry Andric     }
49410b57cec5SDimitry Andric 
49420b57cec5SDimitry Andric     // Make sure the result is of the correct type.
49435f757f3fSDimitry Andric     if (Entry->getType()->getAddressSpace() != TargetAS)
49445f757f3fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(
49455f757f3fSDimitry Andric           Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
49460b57cec5SDimitry Andric 
49470b57cec5SDimitry Andric     // (If global is requested for a definition, we always need to create a new
49480b57cec5SDimitry Andric     // global, not just return a bitcast.)
49490b57cec5SDimitry Andric     if (!IsForDefinition)
49505f757f3fSDimitry Andric       return Entry;
49510b57cec5SDimitry Andric   }
49520b57cec5SDimitry Andric 
4953fe6060f1SDimitry Andric   auto DAddrSpace = GetGlobalVarAddressSpace(D);
49540b57cec5SDimitry Andric 
49550b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
4956fe6060f1SDimitry Andric       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4957fe6060f1SDimitry Andric       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4958349cc55cSDimitry Andric       getContext().getTargetAddressSpace(DAddrSpace));
49590b57cec5SDimitry Andric 
49600b57cec5SDimitry Andric   // If we already created a global with the same mangled name (but different
49610b57cec5SDimitry Andric   // type) before, take its name and remove it from its parent.
49620b57cec5SDimitry Andric   if (Entry) {
49630b57cec5SDimitry Andric     GV->takeName(Entry);
49640b57cec5SDimitry Andric 
49650b57cec5SDimitry Andric     if (!Entry->use_empty()) {
49665f757f3fSDimitry Andric       Entry->replaceAllUsesWith(GV);
49670b57cec5SDimitry Andric     }
49680b57cec5SDimitry Andric 
49690b57cec5SDimitry Andric     Entry->eraseFromParent();
49700b57cec5SDimitry Andric   }
49710b57cec5SDimitry Andric 
49720b57cec5SDimitry Andric   // This is the first use or definition of a mangled name.  If there is a
49730b57cec5SDimitry Andric   // deferred decl with this name, remember that we need to emit it at the end
49740b57cec5SDimitry Andric   // of the file.
49750b57cec5SDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
49760b57cec5SDimitry Andric   if (DDI != DeferredDecls.end()) {
49770b57cec5SDimitry Andric     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
49780b57cec5SDimitry Andric     // list, and remove it from DeferredDecls (since we don't need it anymore).
49790b57cec5SDimitry Andric     addDeferredDeclToEmit(DDI->second);
49800b57cec5SDimitry Andric     DeferredDecls.erase(DDI);
49810b57cec5SDimitry Andric   }
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric   // Handle things which are present even on external declarations.
49840b57cec5SDimitry Andric   if (D) {
49850b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
49860b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
49870b57cec5SDimitry Andric 
49880b57cec5SDimitry Andric     // FIXME: This code is overly simple and should be merged with other global
49890b57cec5SDimitry Andric     // handling.
49905f757f3fSDimitry Andric     GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
49910b57cec5SDimitry Andric 
4992a7dea167SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
49930b57cec5SDimitry Andric 
49940b57cec5SDimitry Andric     setLinkageForGV(GV, D);
49950b57cec5SDimitry Andric 
49960b57cec5SDimitry Andric     if (D->getTLSKind()) {
49970b57cec5SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
49980b57cec5SDimitry Andric         CXXThreadLocals.push_back(D);
49990b57cec5SDimitry Andric       setTLSMode(GV, *D);
50000b57cec5SDimitry Andric     }
50010b57cec5SDimitry Andric 
50020b57cec5SDimitry Andric     setGVProperties(GV, D);
50030b57cec5SDimitry Andric 
50040b57cec5SDimitry Andric     // If required by the ABI, treat declarations of static data members with
50050b57cec5SDimitry Andric     // inline initializers as definitions.
50060b57cec5SDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
50070b57cec5SDimitry Andric       EmitGlobalVarDefinition(D);
50080b57cec5SDimitry Andric     }
50090b57cec5SDimitry Andric 
50100b57cec5SDimitry Andric     // Emit section information for extern variables.
50110b57cec5SDimitry Andric     if (D->hasExternalStorage()) {
50120b57cec5SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
50130b57cec5SDimitry Andric         GV->setSection(SA->getName());
50140b57cec5SDimitry Andric     }
50150b57cec5SDimitry Andric 
50160b57cec5SDimitry Andric     // Handle XCore specific ABI requirements.
50170b57cec5SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
50180b57cec5SDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
50190b57cec5SDimitry Andric         D->getType().isConstant(Context) &&
50200b57cec5SDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
50210b57cec5SDimitry Andric       GV->setSection(".cp.rodata");
50220b57cec5SDimitry Andric 
50231db9f3b2SDimitry Andric     // Handle code model attribute
50241db9f3b2SDimitry Andric     if (const auto *CMA = D->getAttr<CodeModelAttr>())
50251db9f3b2SDimitry Andric       GV->setCodeModel(CMA->getModel());
50261db9f3b2SDimitry Andric 
50270b57cec5SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
50280b57cec5SDimitry Andric     // able to emit it as available_externally to expose it's value to the
50290b57cec5SDimitry Andric     // optimizer.
50300b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
50310b57cec5SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
50320b57cec5SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
50330b57cec5SDimitry Andric       const auto *Record =
50340b57cec5SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
50350b57cec5SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
50360b57cec5SDimitry Andric       if (!HasMutableFields) {
50370b57cec5SDimitry Andric         const VarDecl *InitDecl;
50380b57cec5SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
50390b57cec5SDimitry Andric         if (InitExpr) {
50400b57cec5SDimitry Andric           ConstantEmitter emitter(*this);
50410b57cec5SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
50420b57cec5SDimitry Andric           if (Init) {
50430b57cec5SDimitry Andric             auto *InitType = Init->getType();
50445ffd83dbSDimitry Andric             if (GV->getValueType() != InitType) {
50450b57cec5SDimitry Andric               // The type of the initializer does not match the definition.
50460b57cec5SDimitry Andric               // This happens when an initializer has a different type from
50470b57cec5SDimitry Andric               // the type of the global (because of padding at the end of a
50480b57cec5SDimitry Andric               // structure for instance).
50490b57cec5SDimitry Andric               GV->setName(StringRef());
50500b57cec5SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
50510b57cec5SDimitry Andric               // to work.
50520b57cec5SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
5053a7dea167SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
5054a7dea167SDimitry Andric                       ->stripPointerCasts());
50550b57cec5SDimitry Andric 
50560b57cec5SDimitry Andric               // Erase the old global, since it is no longer used.
50570b57cec5SDimitry Andric               GV->eraseFromParent();
50580b57cec5SDimitry Andric               GV = NewGV;
50590b57cec5SDimitry Andric             } else {
50600b57cec5SDimitry Andric               GV->setInitializer(Init);
50610b57cec5SDimitry Andric               GV->setConstant(true);
50620b57cec5SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
50630b57cec5SDimitry Andric             }
50640b57cec5SDimitry Andric             emitter.finalize(GV);
50650b57cec5SDimitry Andric           }
50660b57cec5SDimitry Andric         }
50670b57cec5SDimitry Andric       }
50680b57cec5SDimitry Andric     }
50690b57cec5SDimitry Andric   }
50700b57cec5SDimitry Andric 
507106c3fb27SDimitry Andric   if (D &&
507206c3fb27SDimitry Andric       D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
5073480093f4SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
5074fe6060f1SDimitry Andric     // External HIP managed variables needed to be recorded for transformation
5075fe6060f1SDimitry Andric     // in both device and host compilations.
5076fe6060f1SDimitry Andric     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
5077fe6060f1SDimitry Andric         D->hasExternalStorage())
5078fe6060f1SDimitry Andric       getCUDARuntime().handleVarRegistration(D, *GV);
5079fe6060f1SDimitry Andric   }
5080480093f4SDimitry Andric 
5081753f127fSDimitry Andric   if (D)
5082753f127fSDimitry Andric     SanitizerMD->reportGlobal(GV, *D);
5083753f127fSDimitry Andric 
50840b57cec5SDimitry Andric   LangAS ExpectedAS =
50850b57cec5SDimitry Andric       D ? D->getType().getAddressSpace()
50860b57cec5SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
5087349cc55cSDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5088fe6060f1SDimitry Andric   if (DAddrSpace != ExpectedAS) {
5089fe6060f1SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(
50905f757f3fSDimitry Andric         *this, GV, DAddrSpace, ExpectedAS,
50915f757f3fSDimitry Andric         llvm::PointerType::get(getLLVMContext(), TargetAS));
5092fe6060f1SDimitry Andric   }
50930b57cec5SDimitry Andric 
50940b57cec5SDimitry Andric   return GV;
50950b57cec5SDimitry Andric }
50960b57cec5SDimitry Andric 
50970b57cec5SDimitry Andric llvm::Constant *
50985ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
50990b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
51005ffd83dbSDimitry Andric 
51010b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
51020b57cec5SDimitry Andric     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
51030b57cec5SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
51045ffd83dbSDimitry Andric 
51055ffd83dbSDimitry Andric   if (isa<CXXMethodDecl>(D)) {
51065ffd83dbSDimitry Andric     auto FInfo =
51075ffd83dbSDimitry Andric         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
51080b57cec5SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
51090b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
51100b57cec5SDimitry Andric                              IsForDefinition);
51115ffd83dbSDimitry Andric   }
51125ffd83dbSDimitry Andric 
51135ffd83dbSDimitry Andric   if (isa<FunctionDecl>(D)) {
51140b57cec5SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
51150b57cec5SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
51160b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
51170b57cec5SDimitry Andric                              IsForDefinition);
51185ffd83dbSDimitry Andric   }
51195ffd83dbSDimitry Andric 
51205ffd83dbSDimitry Andric   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
51210b57cec5SDimitry Andric }
51220b57cec5SDimitry Andric 
51230b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
51240b57cec5SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
5125bdd1243dSDimitry Andric     llvm::Align Alignment) {
51260b57cec5SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
51270b57cec5SDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
51280b57cec5SDimitry Andric 
51290b57cec5SDimitry Andric   if (GV) {
51300b57cec5SDimitry Andric     // Check if the variable has the right type.
51315ffd83dbSDimitry Andric     if (GV->getValueType() == Ty)
51320b57cec5SDimitry Andric       return GV;
51330b57cec5SDimitry Andric 
51340b57cec5SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
51350b57cec5SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
51360b57cec5SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
51370b57cec5SDimitry Andric     OldGV = GV;
51380b57cec5SDimitry Andric   }
51390b57cec5SDimitry Andric 
51400b57cec5SDimitry Andric   // Create a new variable.
51410b57cec5SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
51420b57cec5SDimitry Andric                                 Linkage, nullptr, Name);
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric   if (OldGV) {
51450b57cec5SDimitry Andric     // Replace occurrences of the old variable if needed.
51460b57cec5SDimitry Andric     GV->takeName(OldGV);
51470b57cec5SDimitry Andric 
51480b57cec5SDimitry Andric     if (!OldGV->use_empty()) {
51495f757f3fSDimitry Andric       OldGV->replaceAllUsesWith(GV);
51500b57cec5SDimitry Andric     }
51510b57cec5SDimitry Andric 
51520b57cec5SDimitry Andric     OldGV->eraseFromParent();
51530b57cec5SDimitry Andric   }
51540b57cec5SDimitry Andric 
51550b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
51560b57cec5SDimitry Andric       !GV->hasAvailableExternallyLinkage())
51570b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
51580b57cec5SDimitry Andric 
5159bdd1243dSDimitry Andric   GV->setAlignment(Alignment);
51600b57cec5SDimitry Andric 
51610b57cec5SDimitry Andric   return GV;
51620b57cec5SDimitry Andric }
51630b57cec5SDimitry Andric 
51640b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
51650b57cec5SDimitry Andric /// given global variable.  If Ty is non-null and if the global doesn't exist,
51660b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the
51670b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
51680b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
51690b57cec5SDimitry Andric /// variable with the same mangled name but some other type.
51700b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
51710b57cec5SDimitry Andric                                                   llvm::Type *Ty,
51720b57cec5SDimitry Andric                                            ForDefinition_t IsForDefinition) {
51730b57cec5SDimitry Andric   assert(D->hasGlobalStorage() && "Not a global variable");
51740b57cec5SDimitry Andric   QualType ASTTy = D->getType();
51750b57cec5SDimitry Andric   if (!Ty)
51760b57cec5SDimitry Andric     Ty = getTypes().ConvertTypeForMem(ASTTy);
51770b57cec5SDimitry Andric 
51780b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
5179349cc55cSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
5180fe6060f1SDimitry Andric                                IsForDefinition);
51810b57cec5SDimitry Andric }
51820b57cec5SDimitry Andric 
51830b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the
51840b57cec5SDimitry Andric /// specified type and name.
51850b57cec5SDimitry Andric llvm::Constant *
51860b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
51870b57cec5SDimitry Andric                                      StringRef Name) {
5188349cc55cSDimitry Andric   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
5189349cc55cSDimitry Andric                                                        : LangAS::Default;
5190fe6060f1SDimitry Andric   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
51910b57cec5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
51920b57cec5SDimitry Andric   return Ret;
51930b57cec5SDimitry Andric }
51940b57cec5SDimitry Andric 
51950b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
51960b57cec5SDimitry Andric   assert(!D->getInit() && "Cannot emit definite definitions here!");
51970b57cec5SDimitry Andric 
51980b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
51990b57cec5SDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
52000b57cec5SDimitry Andric 
52010b57cec5SDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
52020b57cec5SDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
52030b57cec5SDimitry Andric   // definition).
52040b57cec5SDimitry Andric   if (GV && !GV->isDeclaration())
52050b57cec5SDimitry Andric     return;
52060b57cec5SDimitry Andric 
52070b57cec5SDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
52080b57cec5SDimitry Andric   // deferred declarations table to be emitted if needed later.
52090b57cec5SDimitry Andric   if (!MustBeEmitted(D) && !GV) {
52100b57cec5SDimitry Andric       DeferredDecls[MangledName] = D;
52110b57cec5SDimitry Andric       return;
52120b57cec5SDimitry Andric   }
52130b57cec5SDimitry Andric 
52140b57cec5SDimitry Andric   // The tentative definition is the only definition.
52150b57cec5SDimitry Andric   EmitGlobalVarDefinition(D);
52160b57cec5SDimitry Andric }
52170b57cec5SDimitry Andric 
52180fca6ea1SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const DeclaratorDecl *D) {
52190fca6ea1SDimitry Andric   if (auto const *V = dyn_cast<const VarDecl>(D))
52200fca6ea1SDimitry Andric     EmitExternalVarDeclaration(V);
52210fca6ea1SDimitry Andric   if (auto const *FD = dyn_cast<const FunctionDecl>(D))
52220fca6ea1SDimitry Andric     EmitExternalFunctionDeclaration(FD);
5223480093f4SDimitry Andric }
5224480093f4SDimitry Andric 
52250b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
52260b57cec5SDimitry Andric   return Context.toCharUnitsFromBits(
52270b57cec5SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
52280b57cec5SDimitry Andric }
52290b57cec5SDimitry Andric 
52300b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
52310b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
5232349cc55cSDimitry Andric     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
5233349cc55cSDimitry Andric     assert(AS == LangAS::opencl_global ||
5234349cc55cSDimitry Andric            AS == LangAS::opencl_global_device ||
5235349cc55cSDimitry Andric            AS == LangAS::opencl_global_host ||
5236349cc55cSDimitry Andric            AS == LangAS::opencl_constant ||
5237349cc55cSDimitry Andric            AS == LangAS::opencl_local ||
5238349cc55cSDimitry Andric            AS >= LangAS::FirstTargetAddressSpace);
5239349cc55cSDimitry Andric     return AS;
52400b57cec5SDimitry Andric   }
52410b57cec5SDimitry Andric 
5242fe6060f1SDimitry Andric   if (LangOpts.SYCLIsDevice &&
5243fe6060f1SDimitry Andric       (!D || D->getType().getAddressSpace() == LangAS::Default))
5244fe6060f1SDimitry Andric     return LangAS::sycl_global;
5245fe6060f1SDimitry Andric 
52460b57cec5SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
524706c3fb27SDimitry Andric     if (D) {
524806c3fb27SDimitry Andric       if (D->hasAttr<CUDAConstantAttr>())
52490b57cec5SDimitry Andric         return LangAS::cuda_constant;
525006c3fb27SDimitry Andric       if (D->hasAttr<CUDASharedAttr>())
52510b57cec5SDimitry Andric         return LangAS::cuda_shared;
525206c3fb27SDimitry Andric       if (D->hasAttr<CUDADeviceAttr>())
52530b57cec5SDimitry Andric         return LangAS::cuda_device;
525406c3fb27SDimitry Andric       if (D->getType().isConstQualified())
52550b57cec5SDimitry Andric         return LangAS::cuda_constant;
525606c3fb27SDimitry Andric     }
52570b57cec5SDimitry Andric     return LangAS::cuda_device;
52580b57cec5SDimitry Andric   }
52590b57cec5SDimitry Andric 
52600b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
52610b57cec5SDimitry Andric     LangAS AS;
52620b57cec5SDimitry Andric     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
52630b57cec5SDimitry Andric       return AS;
52640b57cec5SDimitry Andric   }
52650b57cec5SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
52660b57cec5SDimitry Andric }
52670b57cec5SDimitry Andric 
5268fe6060f1SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
52690b57cec5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
52700b57cec5SDimitry Andric   if (LangOpts.OpenCL)
52710b57cec5SDimitry Andric     return LangAS::opencl_constant;
5272fe6060f1SDimitry Andric   if (LangOpts.SYCLIsDevice)
5273fe6060f1SDimitry Andric     return LangAS::sycl_global;
5274d56accc7SDimitry Andric   if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
5275d56accc7SDimitry Andric     // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
5276d56accc7SDimitry Andric     // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
5277d56accc7SDimitry Andric     // with OpVariable instructions with Generic storage class which is not
5278d56accc7SDimitry Andric     // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
5279d56accc7SDimitry Andric     // UniformConstant storage class is not viable as pointers to it may not be
5280d56accc7SDimitry Andric     // casted to Generic pointers which are used to model HIP's "flat" pointers.
5281d56accc7SDimitry Andric     return LangAS::cuda_device;
52820b57cec5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
528381ad6265SDimitry Andric     return *AS;
52840b57cec5SDimitry Andric   return LangAS::Default;
52850b57cec5SDimitry Andric }
52860b57cec5SDimitry Andric 
52870b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address
52880b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
52890b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
52900b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space
52910b57cec5SDimitry Andric // need to be casted to default address space before being put into address
52920b57cec5SDimitry Andric // map and referenced by other part of CodeGen.
52930b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
52940b57cec5SDimitry Andric // they should not be casted to default address space.
52950b57cec5SDimitry Andric static llvm::Constant *
52960b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
52970b57cec5SDimitry Andric                                        llvm::GlobalVariable *GV) {
52980b57cec5SDimitry Andric   llvm::Constant *Cast = GV;
52990b57cec5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
5300fe6060f1SDimitry Andric     auto AS = CGM.GetGlobalConstantAddressSpace();
53010b57cec5SDimitry Andric     if (AS != LangAS::Default)
53020b57cec5SDimitry Andric       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
5303fe6060f1SDimitry Andric           CGM, GV, AS, LangAS::Default,
53045f757f3fSDimitry Andric           llvm::PointerType::get(
53055f757f3fSDimitry Andric               CGM.getLLVMContext(),
53060b57cec5SDimitry Andric               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
53070b57cec5SDimitry Andric   }
53080b57cec5SDimitry Andric   return Cast;
53090b57cec5SDimitry Andric }
53100b57cec5SDimitry Andric 
53110b57cec5SDimitry Andric template<typename SomeDecl>
53120b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
53130b57cec5SDimitry Andric                                                llvm::GlobalValue *GV) {
53140b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus)
53150b57cec5SDimitry Andric     return;
53160b57cec5SDimitry Andric 
53170b57cec5SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
53180b57cec5SDimitry Andric   // the name existing.
53190b57cec5SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
53200b57cec5SDimitry Andric     return;
53210b57cec5SDimitry Andric 
53220b57cec5SDimitry Andric   // Must have internal linkage and an ordinary name.
53235f757f3fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal)
53240b57cec5SDimitry Andric     return;
53250b57cec5SDimitry Andric 
53260b57cec5SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
53270b57cec5SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
53280b57cec5SDimitry Andric   const SomeDecl *First = D->getFirstDecl();
53290b57cec5SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
53300b57cec5SDimitry Andric     return;
53310b57cec5SDimitry Andric 
53320b57cec5SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
53330b57cec5SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
53340b57cec5SDimitry Andric   // mangled name if nothing else is using that name.
53350b57cec5SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
53360b57cec5SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
53370b57cec5SDimitry Andric 
53380b57cec5SDimitry Andric   // If we have multiple internal linkage entities with the same name
53390b57cec5SDimitry Andric   // in extern "C" regions, none of them gets that name.
53400b57cec5SDimitry Andric   if (!R.second)
53410b57cec5SDimitry Andric     R.first->second = nullptr;
53420b57cec5SDimitry Andric }
53430b57cec5SDimitry Andric 
53440b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
53450b57cec5SDimitry Andric   if (!CGM.supportsCOMDAT())
53460b57cec5SDimitry Andric     return false;
53470b57cec5SDimitry Andric 
53480b57cec5SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
53490b57cec5SDimitry Andric     return true;
53500b57cec5SDimitry Andric 
53510b57cec5SDimitry Andric   GVALinkage Linkage;
53520b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
53530b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
53540b57cec5SDimitry Andric   else
53550b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
53560b57cec5SDimitry Andric 
53570b57cec5SDimitry Andric   switch (Linkage) {
53580b57cec5SDimitry Andric   case GVA_Internal:
53590b57cec5SDimitry Andric   case GVA_AvailableExternally:
53600b57cec5SDimitry Andric   case GVA_StrongExternal:
53610b57cec5SDimitry Andric     return false;
53620b57cec5SDimitry Andric   case GVA_DiscardableODR:
53630b57cec5SDimitry Andric   case GVA_StrongODR:
53640b57cec5SDimitry Andric     return true;
53650b57cec5SDimitry Andric   }
53660b57cec5SDimitry Andric   llvm_unreachable("No such linkage");
53670b57cec5SDimitry Andric }
53680b57cec5SDimitry Andric 
536906c3fb27SDimitry Andric bool CodeGenModule::supportsCOMDAT() const {
537006c3fb27SDimitry Andric   return getTriple().supportsCOMDAT();
537106c3fb27SDimitry Andric }
537206c3fb27SDimitry Andric 
53730b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
53740b57cec5SDimitry Andric                                           llvm::GlobalObject &GO) {
53750b57cec5SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
53760b57cec5SDimitry Andric     return;
53770b57cec5SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
53780b57cec5SDimitry Andric }
53790b57cec5SDimitry Andric 
5380*5deeebd8SDimitry Andric const ABIInfo &CodeGenModule::getABIInfo() {
5381*5deeebd8SDimitry Andric   return getTargetCodeGenInfo().getABIInfo();
5382*5deeebd8SDimitry Andric }
5383*5deeebd8SDimitry Andric 
53840b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
53850b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
53860b57cec5SDimitry Andric                                             bool IsTentative) {
53870b57cec5SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
53880b57cec5SDimitry Andric   // therefore no need to be translated.
53890b57cec5SDimitry Andric   QualType ASTTy = D->getType();
53900b57cec5SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
53910b57cec5SDimitry Andric     return;
53920b57cec5SDimitry Andric 
53930b57cec5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
53940b57cec5SDimitry Andric   // normally.
539506c3fb27SDimitry Andric   if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
53960b57cec5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
53970b57cec5SDimitry Andric     return;
53980b57cec5SDimitry Andric 
5399fe6060f1SDimitry Andric   llvm::TrackingVH<llvm::Constant> Init;
54000b57cec5SDimitry Andric   bool NeedsGlobalCtor = false;
5401bdd1243dSDimitry Andric   // Whether the definition of the variable is available externally.
5402bdd1243dSDimitry Andric   // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5403bdd1243dSDimitry Andric   // since this is the job for its original source.
5404bdd1243dSDimitry Andric   bool IsDefinitionAvailableExternally =
5405bdd1243dSDimitry Andric       getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
5406a7dea167SDimitry Andric   bool NeedsGlobalDtor =
5407bdd1243dSDimitry Andric       !IsDefinitionAvailableExternally &&
5408a7dea167SDimitry Andric       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
54090b57cec5SDimitry Andric 
54100fca6ea1SDimitry Andric   // It is helpless to emit the definition for an available_externally variable
54110fca6ea1SDimitry Andric   // which can't be marked as const.
54120fca6ea1SDimitry Andric   // We don't need to check if it needs global ctor or dtor. See the above
54130fca6ea1SDimitry Andric   // comment for ideas.
54140fca6ea1SDimitry Andric   if (IsDefinitionAvailableExternally &&
54150fca6ea1SDimitry Andric       (!D->hasConstantInitialization() ||
54160fca6ea1SDimitry Andric        // TODO: Update this when we have interface to check constexpr
54170fca6ea1SDimitry Andric        // destructor.
54180fca6ea1SDimitry Andric        D->needsDestruction(getContext()) ||
54190fca6ea1SDimitry Andric        !D->getType().isConstantStorage(getContext(), true, true)))
54200fca6ea1SDimitry Andric     return;
54210fca6ea1SDimitry Andric 
54220b57cec5SDimitry Andric   const VarDecl *InitDecl;
54230b57cec5SDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
54240b57cec5SDimitry Andric 
5425bdd1243dSDimitry Andric   std::optional<ConstantEmitter> emitter;
54260b57cec5SDimitry Andric 
54270b57cec5SDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
54280b57cec5SDimitry Andric   // as part of their declaration."  Sema has already checked for
54290b57cec5SDimitry Andric   // error cases, so we just need to set Init to UndefValue.
54300b57cec5SDimitry Andric   bool IsCUDASharedVar =
54310b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
54320b57cec5SDimitry Andric   // Shadows of initialized device-side global variables are also left
54330b57cec5SDimitry Andric   // undefined.
5434fe6060f1SDimitry Andric   // Managed Variables should be initialized on both host side and device side.
54350b57cec5SDimitry Andric   bool IsCUDAShadowVar =
5436e8d8bef9SDimitry Andric       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
54370b57cec5SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
54380b57cec5SDimitry Andric        D->hasAttr<CUDASharedAttr>());
54395ffd83dbSDimitry Andric   bool IsCUDADeviceShadowVar =
5440fe6060f1SDimitry Andric       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
54415ffd83dbSDimitry Andric       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5442fe6060f1SDimitry Andric        D->getType()->isCUDADeviceBuiltinTextureType());
54430b57cec5SDimitry Andric   if (getLangOpts().CUDA &&
54445ffd83dbSDimitry Andric       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5445fe6060f1SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
54465ffd83dbSDimitry Andric   else if (D->hasAttr<LoaderUninitializedAttr>())
5447fe6060f1SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
54480b57cec5SDimitry Andric   else if (!InitExpr) {
54490b57cec5SDimitry Andric     // This is a tentative definition; tentative definitions are
54500b57cec5SDimitry Andric     // implicitly initialized with { 0 }.
54510b57cec5SDimitry Andric     //
54520b57cec5SDimitry Andric     // Note that tentative definitions are only emitted at the end of
54530b57cec5SDimitry Andric     // a translation unit, so they should never have incomplete
54540b57cec5SDimitry Andric     // type. In addition, EmitTentativeDefinition makes sure that we
54550b57cec5SDimitry Andric     // never attempt to emit a tentative definition if a real one
54560b57cec5SDimitry Andric     // exists. A use may still exists, however, so we still may need
54570b57cec5SDimitry Andric     // to do a RAUW.
54580b57cec5SDimitry Andric     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
54590b57cec5SDimitry Andric     Init = EmitNullConstant(D->getType());
54600b57cec5SDimitry Andric   } else {
54610b57cec5SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
54620b57cec5SDimitry Andric     emitter.emplace(*this);
5463fe6060f1SDimitry Andric     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
5464fe6060f1SDimitry Andric     if (!Initializer) {
54650b57cec5SDimitry Andric       QualType T = InitExpr->getType();
54660b57cec5SDimitry Andric       if (D->getType()->isReferenceType())
54670b57cec5SDimitry Andric         T = D->getType();
54680b57cec5SDimitry Andric 
54690b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
547081ad6265SDimitry Andric         if (InitDecl->hasFlexibleArrayInit(getContext()))
547181ad6265SDimitry Andric           ErrorUnsupported(D, "flexible array initializer");
54720b57cec5SDimitry Andric         Init = EmitNullConstant(T);
5473bdd1243dSDimitry Andric 
5474bdd1243dSDimitry Andric         if (!IsDefinitionAvailableExternally)
54750b57cec5SDimitry Andric           NeedsGlobalCtor = true;
54760b57cec5SDimitry Andric       } else {
54770b57cec5SDimitry Andric         ErrorUnsupported(D, "static initializer");
54780b57cec5SDimitry Andric         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
54790b57cec5SDimitry Andric       }
54800b57cec5SDimitry Andric     } else {
5481fe6060f1SDimitry Andric       Init = Initializer;
54820b57cec5SDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
54830b57cec5SDimitry Andric       // initializer position (just in case this entry was delayed) if we
54840b57cec5SDimitry Andric       // also don't need to register a destructor.
54850b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
54860b57cec5SDimitry Andric         DelayedCXXInitPosition.erase(D);
548781ad6265SDimitry Andric 
548881ad6265SDimitry Andric #ifndef NDEBUG
548981ad6265SDimitry Andric       CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
549081ad6265SDimitry Andric                           InitDecl->getFlexibleArrayInitChars(getContext());
549181ad6265SDimitry Andric       CharUnits CstSize = CharUnits::fromQuantity(
549281ad6265SDimitry Andric           getDataLayout().getTypeAllocSize(Init->getType()));
549381ad6265SDimitry Andric       assert(VarSize == CstSize && "Emitted constant has unexpected size");
549481ad6265SDimitry Andric #endif
54950b57cec5SDimitry Andric     }
54960b57cec5SDimitry Andric   }
54970b57cec5SDimitry Andric 
54980b57cec5SDimitry Andric   llvm::Type* InitType = Init->getType();
54990b57cec5SDimitry Andric   llvm::Constant *Entry =
55000b57cec5SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
55010b57cec5SDimitry Andric 
5502a7dea167SDimitry Andric   // Strip off pointer casts if we got them.
5503a7dea167SDimitry Andric   Entry = Entry->stripPointerCasts();
55040b57cec5SDimitry Andric 
55050b57cec5SDimitry Andric   // Entry is now either a Function or GlobalVariable.
55060b57cec5SDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
55070b57cec5SDimitry Andric 
55080b57cec5SDimitry Andric   // We have a definition after a declaration with the wrong type.
55090b57cec5SDimitry Andric   // We must make a new GlobalVariable* and update everything that used OldGV
55100b57cec5SDimitry Andric   // (a declaration or tentative definition) with the new GlobalVariable*
55110b57cec5SDimitry Andric   // (which will be a definition).
55120b57cec5SDimitry Andric   //
55130b57cec5SDimitry Andric   // This happens if there is a prototype for a global (e.g.
55140b57cec5SDimitry Andric   // "extern int x[];") and then a definition of a different type (e.g.
55150b57cec5SDimitry Andric   // "int x[10];"). This also happens when an initializer has a different type
55160b57cec5SDimitry Andric   // from the type of the global (this happens with unions).
55175ffd83dbSDimitry Andric   if (!GV || GV->getValueType() != InitType ||
55180b57cec5SDimitry Andric       GV->getType()->getAddressSpace() !=
55190b57cec5SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
55200b57cec5SDimitry Andric 
55210b57cec5SDimitry Andric     // Move the old entry aside so that we'll create a new one.
55220b57cec5SDimitry Andric     Entry->setName(StringRef());
55230b57cec5SDimitry Andric 
55240b57cec5SDimitry Andric     // Make a new global with the correct type, this is now guaranteed to work.
55250b57cec5SDimitry Andric     GV = cast<llvm::GlobalVariable>(
5526a7dea167SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
5527a7dea167SDimitry Andric             ->stripPointerCasts());
55280b57cec5SDimitry Andric 
55290b57cec5SDimitry Andric     // Replace all uses of the old global with the new global
55300b57cec5SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
5531fe6060f1SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5532fe6060f1SDimitry Andric                                                              Entry->getType());
55330b57cec5SDimitry Andric     Entry->replaceAllUsesWith(NewPtrForOldDecl);
55340b57cec5SDimitry Andric 
55350b57cec5SDimitry Andric     // Erase the old global, since it is no longer used.
55360b57cec5SDimitry Andric     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
55370b57cec5SDimitry Andric   }
55380b57cec5SDimitry Andric 
55390b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
55400b57cec5SDimitry Andric 
55410b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
55420b57cec5SDimitry Andric     AddGlobalAnnotations(D, GV);
55430b57cec5SDimitry Andric 
55440b57cec5SDimitry Andric   // Set the llvm linkage type as appropriate.
55458a4dda33SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
55460b57cec5SDimitry Andric 
55470b57cec5SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
55480b57cec5SDimitry Andric   // the device. [...]"
55490b57cec5SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
55500b57cec5SDimitry Andric   // __device__, declares a variable that: [...]
55510b57cec5SDimitry Andric   // Is accessible from all the threads within the grid and from the host
55520b57cec5SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
55530b57cec5SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
555406c3fb27SDimitry Andric   if (LangOpts.CUDA) {
55550b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
55560b57cec5SDimitry Andric       if (Linkage != llvm::GlobalValue::InternalLinkage &&
5557349cc55cSDimitry Andric           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
5558349cc55cSDimitry Andric            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5559349cc55cSDimitry Andric            D->getType()->isCUDADeviceBuiltinTextureType()))
55600b57cec5SDimitry Andric         GV->setExternallyInitialized(true);
55610b57cec5SDimitry Andric     } else {
5562fe6060f1SDimitry Andric       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
55635ffd83dbSDimitry Andric     }
5564fe6060f1SDimitry Andric     getCUDARuntime().handleVarRegistration(D, *GV);
55650b57cec5SDimitry Andric   }
55660b57cec5SDimitry Andric 
55670b57cec5SDimitry Andric   GV->setInitializer(Init);
55685ffd83dbSDimitry Andric   if (emitter)
55695ffd83dbSDimitry Andric     emitter->finalize(GV);
55700b57cec5SDimitry Andric 
55710b57cec5SDimitry Andric   // If it is safe to mark the global 'constant', do so now.
55720b57cec5SDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
55735f757f3fSDimitry Andric                   D->getType().isConstantStorage(getContext(), true, true));
55740b57cec5SDimitry Andric 
55750b57cec5SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
55760b57cec5SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
55770b57cec5SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
55780b57cec5SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
55790b57cec5SDimitry Andric       GV->setConstant(true);
55800b57cec5SDimitry Andric   }
55810b57cec5SDimitry Andric 
558281ad6265SDimitry Andric   CharUnits AlignVal = getContext().getDeclAlign(D);
558381ad6265SDimitry Andric   // Check for alignment specifed in an 'omp allocate' directive.
5584bdd1243dSDimitry Andric   if (std::optional<CharUnits> AlignValFromAllocate =
558581ad6265SDimitry Andric           getOMPAllocateAlignment(D))
558681ad6265SDimitry Andric     AlignVal = *AlignValFromAllocate;
558781ad6265SDimitry Andric   GV->setAlignment(AlignVal.getAsAlign());
55880b57cec5SDimitry Andric 
55895ffd83dbSDimitry Andric   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
55905ffd83dbSDimitry Andric   // function is only defined alongside the variable, not also alongside
55915ffd83dbSDimitry Andric   // callers. Normally, all accesses to a thread_local go through the
55925ffd83dbSDimitry Andric   // thread-wrapper in order to ensure initialization has occurred, underlying
55935ffd83dbSDimitry Andric   // variable will never be used other than the thread-wrapper, so it can be
55945ffd83dbSDimitry Andric   // converted to internal linkage.
55955ffd83dbSDimitry Andric   //
55965ffd83dbSDimitry Andric   // However, if the variable has the 'constinit' attribute, it _can_ be
55975ffd83dbSDimitry Andric   // referenced directly, without calling the thread-wrapper, so the linkage
55985ffd83dbSDimitry Andric   // must not be changed.
55995ffd83dbSDimitry Andric   //
56005ffd83dbSDimitry Andric   // Additionally, if the variable isn't plain external linkage, e.g. if it's
56015ffd83dbSDimitry Andric   // weak or linkonce, the de-duplication semantics are important to preserve,
56025ffd83dbSDimitry Andric   // so we don't change the linkage.
56035ffd83dbSDimitry Andric   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
56045ffd83dbSDimitry Andric       Linkage == llvm::GlobalValue::ExternalLinkage &&
56050b57cec5SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
56065ffd83dbSDimitry Andric       !D->hasAttr<ConstInitAttr>())
56070b57cec5SDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
56080b57cec5SDimitry Andric 
56090b57cec5SDimitry Andric   GV->setLinkage(Linkage);
56100b57cec5SDimitry Andric   if (D->hasAttr<DLLImportAttr>())
56110b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
56120b57cec5SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
56130b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
56140b57cec5SDimitry Andric   else
56150b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
56160b57cec5SDimitry Andric 
56170b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
56180b57cec5SDimitry Andric     // common vars aren't constant even if declared const.
56190b57cec5SDimitry Andric     GV->setConstant(false);
56200b57cec5SDimitry Andric     // Tentative definition of global variables may be initialized with
56210b57cec5SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
56220b57cec5SDimitry Andric     // since common linkage must have zero initializer and must not have
56230b57cec5SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
56240b57cec5SDimitry Andric     if (!GV->getInitializer()->isNullValue())
56250b57cec5SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
56260b57cec5SDimitry Andric   }
56270b57cec5SDimitry Andric 
56280b57cec5SDimitry Andric   setNonAliasAttributes(D, GV);
56290b57cec5SDimitry Andric 
56300b57cec5SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
56310b57cec5SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
56320b57cec5SDimitry Andric       CXXThreadLocals.push_back(D);
56330b57cec5SDimitry Andric     setTLSMode(GV, *D);
56340b57cec5SDimitry Andric   }
56350b57cec5SDimitry Andric 
56360b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
56370b57cec5SDimitry Andric 
56380b57cec5SDimitry Andric   // Emit the initializer function if necessary.
56390b57cec5SDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
56400b57cec5SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
56410b57cec5SDimitry Andric 
564281ad6265SDimitry Andric   SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
56430b57cec5SDimitry Andric 
56440b57cec5SDimitry Andric   // Emit global variable debug information.
56450b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
5646480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo())
56470b57cec5SDimitry Andric       DI->EmitGlobalVariable(GV, D);
56480b57cec5SDimitry Andric }
56490b57cec5SDimitry Andric 
5650480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5651480093f4SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
5652480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
5653480093f4SDimitry Andric       QualType ASTTy = D->getType();
5654480093f4SDimitry Andric       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5655349cc55cSDimitry Andric       llvm::Constant *GV =
5656349cc55cSDimitry Andric           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5657480093f4SDimitry Andric       DI->EmitExternalVariable(
5658480093f4SDimitry Andric           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5659480093f4SDimitry Andric     }
5660480093f4SDimitry Andric }
5661480093f4SDimitry Andric 
56620fca6ea1SDimitry Andric void CodeGenModule::EmitExternalFunctionDeclaration(const FunctionDecl *FD) {
56630fca6ea1SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
56640fca6ea1SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
56650fca6ea1SDimitry Andric       auto *Ty = getTypes().ConvertType(FD->getType());
56660fca6ea1SDimitry Andric       StringRef MangledName = getMangledName(FD);
56670fca6ea1SDimitry Andric       auto *Fn = dyn_cast<llvm::Function>(
56680fca6ea1SDimitry Andric           GetOrCreateLLVMFunction(MangledName, Ty, FD, /* ForVTable */ false));
56690fca6ea1SDimitry Andric       if (!Fn->getSubprogram())
56700fca6ea1SDimitry Andric         DI->EmitFunctionDecl(FD, FD->getLocation(), FD->getType(), Fn);
56710fca6ea1SDimitry Andric     }
56720fca6ea1SDimitry Andric }
56730fca6ea1SDimitry Andric 
56740b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
56750b57cec5SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
56760b57cec5SDimitry Andric                                       bool NoCommon) {
56770b57cec5SDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
56780b57cec5SDimitry Andric   // was overridden by a NoCommon attribute.
56790b57cec5SDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
56800b57cec5SDimitry Andric     return true;
56810b57cec5SDimitry Andric 
56820b57cec5SDimitry Andric   // C11 6.9.2/2:
56830b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file scope without
56840b57cec5SDimitry Andric   //   an initializer, and without a storage-class specifier or with the
56850b57cec5SDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
56860b57cec5SDimitry Andric   if (D->getInit() || D->hasExternalStorage())
56870b57cec5SDimitry Andric     return true;
56880b57cec5SDimitry Andric 
56890b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
56900b57cec5SDimitry Andric   if (D->hasAttr<SectionAttr>())
56910b57cec5SDimitry Andric     return true;
56920b57cec5SDimitry Andric 
56930b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
56940b57cec5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
56950b57cec5SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
56960b57cec5SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
56970b57cec5SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
5698a7dea167SDimitry Andric       D->hasAttr<PragmaClangRelroSectionAttr>() ||
56990b57cec5SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
57000b57cec5SDimitry Andric     return true;
57010b57cec5SDimitry Andric 
57020b57cec5SDimitry Andric   // Thread local vars aren't considered common linkage.
57030b57cec5SDimitry Andric   if (D->getTLSKind())
57040b57cec5SDimitry Andric     return true;
57050b57cec5SDimitry Andric 
57060b57cec5SDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
57070b57cec5SDimitry Andric   if (D->hasAttr<WeakImportAttr>())
57080b57cec5SDimitry Andric     return true;
57090b57cec5SDimitry Andric 
57100b57cec5SDimitry Andric   // A variable cannot be both common and exist in a comdat.
57110b57cec5SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
57120b57cec5SDimitry Andric     return true;
57130b57cec5SDimitry Andric 
57140b57cec5SDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
57150b57cec5SDimitry Andric   // mode.
57160b57cec5SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
57170b57cec5SDimitry Andric     if (D->hasAttr<AlignedAttr>())
57180b57cec5SDimitry Andric       return true;
57190b57cec5SDimitry Andric     QualType VarType = D->getType();
57200b57cec5SDimitry Andric     if (Context.isAlignmentRequired(VarType))
57210b57cec5SDimitry Andric       return true;
57220b57cec5SDimitry Andric 
57230b57cec5SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
57240b57cec5SDimitry Andric       const RecordDecl *RD = RT->getDecl();
57250b57cec5SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
57260b57cec5SDimitry Andric         if (FD->isBitField())
57270b57cec5SDimitry Andric           continue;
57280b57cec5SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
57290b57cec5SDimitry Andric           return true;
57300b57cec5SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
57310b57cec5SDimitry Andric           return true;
57320b57cec5SDimitry Andric       }
57330b57cec5SDimitry Andric     }
57340b57cec5SDimitry Andric   }
57350b57cec5SDimitry Andric 
57360b57cec5SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
57370b57cec5SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
57380b57cec5SDimitry Andric   // common.
57390b57cec5SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
57400b57cec5SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
57410b57cec5SDimitry Andric   // restriction only applies to MSVC environments.
57420b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
57430b57cec5SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
57440b57cec5SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
57450b57cec5SDimitry Andric     return true;
57460b57cec5SDimitry Andric 
57470b57cec5SDimitry Andric   return false;
57480b57cec5SDimitry Andric }
57490b57cec5SDimitry Andric 
57508a4dda33SDimitry Andric llvm::GlobalValue::LinkageTypes
57518a4dda33SDimitry Andric CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D,
57528a4dda33SDimitry Andric                                            GVALinkage Linkage) {
57530b57cec5SDimitry Andric   if (Linkage == GVA_Internal)
57540b57cec5SDimitry Andric     return llvm::Function::InternalLinkage;
57550b57cec5SDimitry Andric 
575681ad6265SDimitry Andric   if (D->hasAttr<WeakAttr>())
57570b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakAnyLinkage;
57580b57cec5SDimitry Andric 
57590b57cec5SDimitry Andric   if (const auto *FD = D->getAsFunction())
57600b57cec5SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
57610b57cec5SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
57620b57cec5SDimitry Andric 
57630b57cec5SDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
57640b57cec5SDimitry Andric   // so we can use available_externally linkage.
57650b57cec5SDimitry Andric   if (Linkage == GVA_AvailableExternally)
57660b57cec5SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
57670b57cec5SDimitry Andric 
57680b57cec5SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
57690b57cec5SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
57700b57cec5SDimitry Andric   // Normally, this means we just map to internal, but for explicit
57710b57cec5SDimitry Andric   // instantiations we'll map to external.
57720b57cec5SDimitry Andric 
57730b57cec5SDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
57740b57cec5SDimitry Andric   // that references the function.  We should use linkonce_odr because
57750b57cec5SDimitry Andric   // a) if all references in this translation unit are optimized away, we
57760b57cec5SDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
57770b57cec5SDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
57780b57cec5SDimitry Andric   // definition is dependable.
57790b57cec5SDimitry Andric   if (Linkage == GVA_DiscardableODR)
57800b57cec5SDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
57810b57cec5SDimitry Andric                                             : llvm::Function::InternalLinkage;
57820b57cec5SDimitry Andric 
57830b57cec5SDimitry Andric   // An explicit instantiation of a template has weak linkage, since
57840b57cec5SDimitry Andric   // explicit instantiations can occur in multiple translation units
57850b57cec5SDimitry Andric   // and must all be equivalent. However, we are not allowed to
57860b57cec5SDimitry Andric   // throw away these explicit instantiations.
57870b57cec5SDimitry Andric   //
5788e8d8bef9SDimitry Andric   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
57890b57cec5SDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
5790e8d8bef9SDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations. For
5791e8d8bef9SDimitry Andric   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5792e8d8bef9SDimitry Andric   // therefore we need to follow the normal linkage paradigm.
57930b57cec5SDimitry Andric   if (Linkage == GVA_StrongODR) {
5794e8d8bef9SDimitry Andric     if (getLangOpts().AppleKext)
57950b57cec5SDimitry Andric       return llvm::Function::ExternalLinkage;
5796e8d8bef9SDimitry Andric     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5797e8d8bef9SDimitry Andric         !getLangOpts().GPURelocatableDeviceCode)
57980b57cec5SDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
57990b57cec5SDimitry Andric                                           : llvm::Function::InternalLinkage;
58000b57cec5SDimitry Andric     return llvm::Function::WeakODRLinkage;
58010b57cec5SDimitry Andric   }
58020b57cec5SDimitry Andric 
58030b57cec5SDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
58040b57cec5SDimitry Andric   // linkage.
58050b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
58060b57cec5SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
58070b57cec5SDimitry Andric                                  CodeGenOpts.NoCommon))
58080b57cec5SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
58090b57cec5SDimitry Andric 
58100b57cec5SDimitry Andric   // selectany symbols are externally visible, so use weak instead of
58110b57cec5SDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
58120b57cec5SDimitry Andric   // all definitions should be the same and ODR linkage should be used.
58130b57cec5SDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
58140b57cec5SDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
58150b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
58160b57cec5SDimitry Andric 
58170b57cec5SDimitry Andric   // Otherwise, we have strong external linkage.
58180b57cec5SDimitry Andric   assert(Linkage == GVA_StrongExternal);
58190b57cec5SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
58200b57cec5SDimitry Andric }
58210b57cec5SDimitry Andric 
58228a4dda33SDimitry Andric llvm::GlobalValue::LinkageTypes
58238a4dda33SDimitry Andric CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) {
58240b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
58258a4dda33SDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage);
58260b57cec5SDimitry Andric }
58270b57cec5SDimitry Andric 
58280b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
58290b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites
58300b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
58310b57cec5SDimitry Andric                                           llvm::Function *newFn) {
58320b57cec5SDimitry Andric   // Fast path.
58330fca6ea1SDimitry Andric   if (old->use_empty())
58340fca6ea1SDimitry Andric     return;
58350b57cec5SDimitry Andric 
58360b57cec5SDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
58370b57cec5SDimitry Andric   SmallVector<llvm::Value *, 4> newArgs;
58380b57cec5SDimitry Andric 
58390fca6ea1SDimitry Andric   SmallVector<llvm::CallBase *> callSitesToBeRemovedFromParent;
58400fca6ea1SDimitry Andric 
58410b57cec5SDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
58420fca6ea1SDimitry Andric        ui != ue; ui++) {
58430fca6ea1SDimitry Andric     llvm::User *user = ui->getUser();
58440b57cec5SDimitry Andric 
58450b57cec5SDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
58460b57cec5SDimitry Andric     // unprototyped functions will use bitcasts.
58470b57cec5SDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
58480b57cec5SDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
58490b57cec5SDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
58500b57cec5SDimitry Andric       continue;
58510b57cec5SDimitry Andric     }
58520b57cec5SDimitry Andric 
58530b57cec5SDimitry Andric     // Recognize calls to the function.
58540b57cec5SDimitry Andric     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
58550fca6ea1SDimitry Andric     if (!callSite)
58560fca6ea1SDimitry Andric       continue;
58570fca6ea1SDimitry Andric     if (!callSite->isCallee(&*ui))
58580b57cec5SDimitry Andric       continue;
58590b57cec5SDimitry Andric 
58600b57cec5SDimitry Andric     // If the return types don't match exactly, then we can't
58610b57cec5SDimitry Andric     // transform this call unless it's dead.
58620b57cec5SDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
58630b57cec5SDimitry Andric       continue;
58640b57cec5SDimitry Andric 
58650b57cec5SDimitry Andric     // Get the call site's attribute list.
58660b57cec5SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
58670b57cec5SDimitry Andric     llvm::AttributeList oldAttrs = callSite->getAttributes();
58680b57cec5SDimitry Andric 
58690b57cec5SDimitry Andric     // If the function was passed too few arguments, don't transform.
58700b57cec5SDimitry Andric     unsigned newNumArgs = newFn->arg_size();
58710b57cec5SDimitry Andric     if (callSite->arg_size() < newNumArgs)
58720b57cec5SDimitry Andric       continue;
58730b57cec5SDimitry Andric 
58740b57cec5SDimitry Andric     // If extra arguments were passed, we silently drop them.
58750b57cec5SDimitry Andric     // If any of the types mismatch, we don't transform.
58760b57cec5SDimitry Andric     unsigned argNo = 0;
58770b57cec5SDimitry Andric     bool dontTransform = false;
58780b57cec5SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
58790b57cec5SDimitry Andric       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
58800b57cec5SDimitry Andric         dontTransform = true;
58810b57cec5SDimitry Andric         break;
58820b57cec5SDimitry Andric       }
58830b57cec5SDimitry Andric 
58840b57cec5SDimitry Andric       // Add any parameter attributes.
5885349cc55cSDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
58860b57cec5SDimitry Andric       argNo++;
58870b57cec5SDimitry Andric     }
58880b57cec5SDimitry Andric     if (dontTransform)
58890b57cec5SDimitry Andric       continue;
58900b57cec5SDimitry Andric 
58910b57cec5SDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
58920b57cec5SDimitry Andric     // over the required information.
58930b57cec5SDimitry Andric     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
58940b57cec5SDimitry Andric 
58950b57cec5SDimitry Andric     // Copy over any operand bundles.
5896fe6060f1SDimitry Andric     SmallVector<llvm::OperandBundleDef, 1> newBundles;
58970b57cec5SDimitry Andric     callSite->getOperandBundlesAsDefs(newBundles);
58980b57cec5SDimitry Andric 
58990b57cec5SDimitry Andric     llvm::CallBase *newCall;
5900349cc55cSDimitry Andric     if (isa<llvm::CallInst>(callSite)) {
59010b57cec5SDimitry Andric       newCall =
59020b57cec5SDimitry Andric           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
59030b57cec5SDimitry Andric     } else {
59040b57cec5SDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
59050b57cec5SDimitry Andric       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
59060b57cec5SDimitry Andric                                          oldInvoke->getUnwindDest(), newArgs,
59070b57cec5SDimitry Andric                                          newBundles, "", callSite);
59080b57cec5SDimitry Andric     }
59090b57cec5SDimitry Andric     newArgs.clear(); // for the next iteration
59100b57cec5SDimitry Andric 
59110b57cec5SDimitry Andric     if (!newCall->getType()->isVoidTy())
59120b57cec5SDimitry Andric       newCall->takeName(callSite);
5913349cc55cSDimitry Andric     newCall->setAttributes(
5914349cc55cSDimitry Andric         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5915349cc55cSDimitry Andric                                  oldAttrs.getRetAttrs(), newArgAttrs));
59160b57cec5SDimitry Andric     newCall->setCallingConv(callSite->getCallingConv());
59170b57cec5SDimitry Andric 
59180b57cec5SDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
59190b57cec5SDimitry Andric     if (!callSite->use_empty())
59200b57cec5SDimitry Andric       callSite->replaceAllUsesWith(newCall);
59210b57cec5SDimitry Andric 
59220b57cec5SDimitry Andric     // Copy debug location attached to CI.
59230b57cec5SDimitry Andric     if (callSite->getDebugLoc())
59240b57cec5SDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
59250b57cec5SDimitry Andric 
59260fca6ea1SDimitry Andric     callSitesToBeRemovedFromParent.push_back(callSite);
59270fca6ea1SDimitry Andric   }
59280fca6ea1SDimitry Andric 
59290fca6ea1SDimitry Andric   for (auto *callSite : callSitesToBeRemovedFromParent) {
59300b57cec5SDimitry Andric     callSite->eraseFromParent();
59310b57cec5SDimitry Andric   }
59320b57cec5SDimitry Andric }
59330b57cec5SDimitry Andric 
59340b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
59350b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}".  If there are
59360b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to
59370b57cec5SDimitry Andric /// call the new function directly.
59380b57cec5SDimitry Andric ///
59390b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to
59400b57cec5SDimitry Andric /// functions to be able to inline them.  If there is a bitcast in the way, it
59410b57cec5SDimitry Andric /// won't inline them.  Instcombine normally deletes these calls, but it isn't
59420b57cec5SDimitry Andric /// run at -O0.
59430b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
59440b57cec5SDimitry Andric                                                       llvm::Function *NewFn) {
59450b57cec5SDimitry Andric   // If we're redefining a global as a function, don't transform it.
59460b57cec5SDimitry Andric   if (!isa<llvm::Function>(Old)) return;
59470b57cec5SDimitry Andric 
59480b57cec5SDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
59490b57cec5SDimitry Andric }
59500b57cec5SDimitry Andric 
59510b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
59520b57cec5SDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
59530fca6ea1SDimitry Andric   if ((DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) ||
59540fca6ea1SDimitry Andric       (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
59550b57cec5SDimitry Andric     return;
59560b57cec5SDimitry Andric 
59570b57cec5SDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
59580b57cec5SDimitry Andric   // If we have a definition, this might be a deferred decl. If the
59590b57cec5SDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
59600b57cec5SDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
59610b57cec5SDimitry Andric     GetAddrOfGlobalVar(VD);
59620b57cec5SDimitry Andric 
59630b57cec5SDimitry Andric   EmitTopLevelDecl(VD);
59640b57cec5SDimitry Andric }
59650b57cec5SDimitry Andric 
59660b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
59670b57cec5SDimitry Andric                                                  llvm::GlobalValue *GV) {
59680b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
59690b57cec5SDimitry Andric 
59700b57cec5SDimitry Andric   // Compute the function info and LLVM type.
59710b57cec5SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
59720b57cec5SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
59730b57cec5SDimitry Andric 
59740b57cec5SDimitry Andric   // Get or create the prototype for the function.
59755ffd83dbSDimitry Andric   if (!GV || (GV->getValueType() != Ty))
59760b57cec5SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
59770b57cec5SDimitry Andric                                                    /*DontDefer=*/true,
59780b57cec5SDimitry Andric                                                    ForDefinition));
59790b57cec5SDimitry Andric 
59800b57cec5SDimitry Andric   // Already emitted.
59810b57cec5SDimitry Andric   if (!GV->isDeclaration())
59820b57cec5SDimitry Andric     return;
59830b57cec5SDimitry Andric 
59840b57cec5SDimitry Andric   // We need to set linkage and visibility on the function before
59850b57cec5SDimitry Andric   // generating code for it because various parts of IR generation
59860b57cec5SDimitry Andric   // want to propagate this information down (e.g. to local static
59870b57cec5SDimitry Andric   // declarations).
59880b57cec5SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
59890b57cec5SDimitry Andric   setFunctionLinkage(GD, Fn);
59900b57cec5SDimitry Andric 
59910b57cec5SDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
59920b57cec5SDimitry Andric   setGVProperties(Fn, GD);
59930b57cec5SDimitry Andric 
59940b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
59950b57cec5SDimitry Andric 
59960b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
59970b57cec5SDimitry Andric 
59985ffd83dbSDimitry Andric   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
59990b57cec5SDimitry Andric 
60000b57cec5SDimitry Andric   setNonAliasAttributes(GD, Fn);
60010b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
60020b57cec5SDimitry Andric 
60030b57cec5SDimitry Andric   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
60040b57cec5SDimitry Andric     AddGlobalCtor(Fn, CA->getPriority());
60050b57cec5SDimitry Andric   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
6006e8d8bef9SDimitry Andric     AddGlobalDtor(Fn, DA->getPriority(), true);
60075f757f3fSDimitry Andric   if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>())
60085f757f3fSDimitry Andric     getOpenMPRuntime().emitDeclareTargetFunction(D, GV);
60090b57cec5SDimitry Andric }
60100b57cec5SDimitry Andric 
60110b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
60120b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
60130b57cec5SDimitry Andric   const AliasAttr *AA = D->getAttr<AliasAttr>();
60140b57cec5SDimitry Andric   assert(AA && "Not an alias?");
60150b57cec5SDimitry Andric 
60160b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
60170b57cec5SDimitry Andric 
60180b57cec5SDimitry Andric   if (AA->getAliasee() == MangledName) {
60190b57cec5SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
60200b57cec5SDimitry Andric     return;
60210b57cec5SDimitry Andric   }
60220b57cec5SDimitry Andric 
60230b57cec5SDimitry Andric   // If there is a definition in the module, then it wins over the alias.
60240b57cec5SDimitry Andric   // This is dubious, but allow it to be safe.  Just ignore the alias.
60250b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
60260b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration())
60270b57cec5SDimitry Andric     return;
60280b57cec5SDimitry Andric 
60290b57cec5SDimitry Andric   Aliases.push_back(GD);
60300b57cec5SDimitry Andric 
60310b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
60320b57cec5SDimitry Andric 
60330b57cec5SDimitry Andric   // Create a reference to the named value.  This ensures that it is emitted
60340b57cec5SDimitry Andric   // if a deferred decl.
60350b57cec5SDimitry Andric   llvm::Constant *Aliasee;
60360b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
60370b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy)) {
60380b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
60390b57cec5SDimitry Andric                                       /*ForVTable=*/false);
60400b57cec5SDimitry Andric     LT = getFunctionLinkage(GD);
60410b57cec5SDimitry Andric   } else {
6042349cc55cSDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
60430b57cec5SDimitry Andric                                     /*D=*/nullptr);
6044e8d8bef9SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
60458a4dda33SDimitry Andric       LT = getLLVMLinkageVarDefinition(VD);
6046e8d8bef9SDimitry Andric     else
6047e8d8bef9SDimitry Andric       LT = getFunctionLinkage(GD);
60480b57cec5SDimitry Andric   }
60490b57cec5SDimitry Andric 
60500b57cec5SDimitry Andric   // Create the new alias itself, but don't set a name yet.
60515ffd83dbSDimitry Andric   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
60520b57cec5SDimitry Andric   auto *GA =
60535ffd83dbSDimitry Andric       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
60540b57cec5SDimitry Andric 
60550b57cec5SDimitry Andric   if (Entry) {
60560b57cec5SDimitry Andric     if (GA->getAliasee() == Entry) {
60570b57cec5SDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
60580b57cec5SDimitry Andric       return;
60590b57cec5SDimitry Andric     }
60600b57cec5SDimitry Andric 
60610b57cec5SDimitry Andric     assert(Entry->isDeclaration());
60620b57cec5SDimitry Andric 
60630b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
60640b57cec5SDimitry Andric     // by the alias, as in:
60650b57cec5SDimitry Andric     //   extern int test6();
60660b57cec5SDimitry Andric     //   ...
60670b57cec5SDimitry Andric     //   int test6() __attribute__((alias("test7")));
60680b57cec5SDimitry Andric     //
60690b57cec5SDimitry Andric     // Remove it and replace uses of it with the alias.
60700b57cec5SDimitry Andric     GA->takeName(Entry);
60710b57cec5SDimitry Andric 
60725f757f3fSDimitry Andric     Entry->replaceAllUsesWith(GA);
60730b57cec5SDimitry Andric     Entry->eraseFromParent();
60740b57cec5SDimitry Andric   } else {
60750b57cec5SDimitry Andric     GA->setName(MangledName);
60760b57cec5SDimitry Andric   }
60770b57cec5SDimitry Andric 
60780b57cec5SDimitry Andric   // Set attributes which are particular to an alias; this is a
60790b57cec5SDimitry Andric   // specialization of the attributes which may be set on a global
60800b57cec5SDimitry Andric   // variable/function.
60810b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
60820b57cec5SDimitry Andric       D->isWeakImported()) {
60830b57cec5SDimitry Andric     GA->setLinkage(llvm::Function::WeakAnyLinkage);
60840b57cec5SDimitry Andric   }
60850b57cec5SDimitry Andric 
60860b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
60870b57cec5SDimitry Andric     if (VD->getTLSKind())
60880b57cec5SDimitry Andric       setTLSMode(GA, *VD);
60890b57cec5SDimitry Andric 
60900b57cec5SDimitry Andric   SetCommonAttributes(GD, GA);
609181ad6265SDimitry Andric 
609281ad6265SDimitry Andric   // Emit global alias debug information.
609381ad6265SDimitry Andric   if (isa<VarDecl>(D))
609481ad6265SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6095bdd1243dSDimitry Andric       DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
60960b57cec5SDimitry Andric }
60970b57cec5SDimitry Andric 
60980b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
60990b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
61000b57cec5SDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
61010b57cec5SDimitry Andric   assert(IFA && "Not an ifunc?");
61020b57cec5SDimitry Andric 
61030b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
61040b57cec5SDimitry Andric 
61050b57cec5SDimitry Andric   if (IFA->getResolver() == MangledName) {
61060b57cec5SDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
61070b57cec5SDimitry Andric     return;
61080b57cec5SDimitry Andric   }
61090b57cec5SDimitry Andric 
61100b57cec5SDimitry Andric   // Report an error if some definition overrides ifunc.
61110b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
61120b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration()) {
61130b57cec5SDimitry Andric     GlobalDecl OtherGD;
61140b57cec5SDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
61150b57cec5SDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
61160b57cec5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
61170b57cec5SDimitry Andric           << MangledName;
61180b57cec5SDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
61190b57cec5SDimitry Andric                    diag::note_previous_definition);
61200b57cec5SDimitry Andric     }
61210b57cec5SDimitry Andric     return;
61220b57cec5SDimitry Andric   }
61230b57cec5SDimitry Andric 
61240b57cec5SDimitry Andric   Aliases.push_back(GD);
61250b57cec5SDimitry Andric 
61260fca6ea1SDimitry Andric   // The resolver might not be visited yet. Specify a dummy non-function type to
61270fca6ea1SDimitry Andric   // indicate IsIncompleteFunction. Either the type is ignored (if the resolver
61280fca6ea1SDimitry Andric   // was emitted) or the whole function will be replaced (if the resolver has
61290fca6ea1SDimitry Andric   // not been emitted).
61300b57cec5SDimitry Andric   llvm::Constant *Resolver =
61310fca6ea1SDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), VoidTy, {},
61320b57cec5SDimitry Andric                               /*ForVTable=*/false);
61330fca6ea1SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
61340b57cec5SDimitry Andric   llvm::GlobalIFunc *GIF =
61350b57cec5SDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
61360b57cec5SDimitry Andric                                 "", Resolver, &getModule());
61370b57cec5SDimitry Andric   if (Entry) {
61380b57cec5SDimitry Andric     if (GIF->getResolver() == Entry) {
61390b57cec5SDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
61400b57cec5SDimitry Andric       return;
61410b57cec5SDimitry Andric     }
61420b57cec5SDimitry Andric     assert(Entry->isDeclaration());
61430b57cec5SDimitry Andric 
61440b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
61450b57cec5SDimitry Andric     // by the ifunc, as in:
61460b57cec5SDimitry Andric     //   extern int test();
61470b57cec5SDimitry Andric     //   ...
61480b57cec5SDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
61490b57cec5SDimitry Andric     //
61500b57cec5SDimitry Andric     // Remove it and replace uses of it with the ifunc.
61510b57cec5SDimitry Andric     GIF->takeName(Entry);
61520b57cec5SDimitry Andric 
61535f757f3fSDimitry Andric     Entry->replaceAllUsesWith(GIF);
61540b57cec5SDimitry Andric     Entry->eraseFromParent();
61550b57cec5SDimitry Andric   } else
61560b57cec5SDimitry Andric     GIF->setName(MangledName);
61570b57cec5SDimitry Andric   SetCommonAttributes(GD, GIF);
61580b57cec5SDimitry Andric }
61590b57cec5SDimitry Andric 
61600b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
61610b57cec5SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
61620b57cec5SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
61630b57cec5SDimitry Andric                                          Tys);
61640b57cec5SDimitry Andric }
61650b57cec5SDimitry Andric 
61660b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
61670b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
61680b57cec5SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
61690b57cec5SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
61700b57cec5SDimitry Andric   StringRef String = Literal->getString();
61710b57cec5SDimitry Andric   unsigned NumBytes = String.size();
61720b57cec5SDimitry Andric 
61730b57cec5SDimitry Andric   // Check for simple case.
61740b57cec5SDimitry Andric   if (!Literal->containsNonAsciiOrNull()) {
61750b57cec5SDimitry Andric     StringLength = NumBytes;
61760b57cec5SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
61770b57cec5SDimitry Andric   }
61780b57cec5SDimitry Andric 
61790b57cec5SDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
61800b57cec5SDimitry Andric   IsUTF16 = true;
61810b57cec5SDimitry Andric 
61820b57cec5SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
61830b57cec5SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
61840b57cec5SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
61850b57cec5SDimitry Andric 
61860b57cec5SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
61870b57cec5SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
61880b57cec5SDimitry Andric 
61890b57cec5SDimitry Andric   // ConvertUTF8toUTF16 returns the length in ToPtr.
61900b57cec5SDimitry Andric   StringLength = ToPtr - &ToBuf[0];
61910b57cec5SDimitry Andric 
61920b57cec5SDimitry Andric   // Add an explicit null.
61930b57cec5SDimitry Andric   *ToPtr = 0;
61940b57cec5SDimitry Andric   return *Map.insert(std::make_pair(
61950b57cec5SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
61960b57cec5SDimitry Andric                                    (StringLength + 1) * 2),
61970b57cec5SDimitry Andric                          nullptr)).first;
61980b57cec5SDimitry Andric }
61990b57cec5SDimitry Andric 
62000b57cec5SDimitry Andric ConstantAddress
62010b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
62020b57cec5SDimitry Andric   unsigned StringLength = 0;
62030b57cec5SDimitry Andric   bool isUTF16 = false;
62040b57cec5SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
62050b57cec5SDimitry Andric       GetConstantCFStringEntry(CFConstantStringMap, Literal,
62060b57cec5SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
62070b57cec5SDimitry Andric                                StringLength);
62080b57cec5SDimitry Andric 
62090b57cec5SDimitry Andric   if (auto *C = Entry.second)
62100eae32dcSDimitry Andric     return ConstantAddress(
62110eae32dcSDimitry Andric         C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
62120b57cec5SDimitry Andric 
62130b57cec5SDimitry Andric   const ASTContext &Context = getContext();
62140b57cec5SDimitry Andric   const llvm::Triple &Triple = getTriple();
62150b57cec5SDimitry Andric 
62160b57cec5SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
62170b57cec5SDimitry Andric   const bool IsSwiftABI =
62180b57cec5SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
62190b57cec5SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
62200b57cec5SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
62210b57cec5SDimitry Andric 
62220b57cec5SDimitry Andric   // If we don't already have it, get __CFConstantStringClassReference.
62230b57cec5SDimitry Andric   if (!CFConstantStringClassRef) {
62240b57cec5SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
62250b57cec5SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
62260b57cec5SDimitry Andric     Ty = llvm::ArrayType::get(Ty, 0);
62270b57cec5SDimitry Andric 
62280b57cec5SDimitry Andric     switch (CFRuntime) {
62290b57cec5SDimitry Andric     default: break;
6230bdd1243dSDimitry Andric     case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
62310b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
62320b57cec5SDimitry Andric       CFConstantStringClassName =
62330b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
62340b57cec5SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
62350b57cec5SDimitry Andric       Ty = IntPtrTy;
62360b57cec5SDimitry Andric       break;
62370b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
62380b57cec5SDimitry Andric       CFConstantStringClassName =
62390b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
62400b57cec5SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
62410b57cec5SDimitry Andric       Ty = IntPtrTy;
62420b57cec5SDimitry Andric       break;
62430b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
62440b57cec5SDimitry Andric       CFConstantStringClassName =
62450b57cec5SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
62460b57cec5SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
62470b57cec5SDimitry Andric       Ty = IntPtrTy;
62480b57cec5SDimitry Andric       break;
62490b57cec5SDimitry Andric     }
62500b57cec5SDimitry Andric 
62510b57cec5SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
62520b57cec5SDimitry Andric 
62530b57cec5SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
62540b57cec5SDimitry Andric       llvm::GlobalValue *GV = nullptr;
62550b57cec5SDimitry Andric 
62560b57cec5SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
62570b57cec5SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
62580b57cec5SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
62590b57cec5SDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
62600b57cec5SDimitry Andric 
62610b57cec5SDimitry Andric         const VarDecl *VD = nullptr;
6262fe6060f1SDimitry Andric         for (const auto *Result : DC->lookup(&II))
62630b57cec5SDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
62640b57cec5SDimitry Andric             break;
62650b57cec5SDimitry Andric 
62660b57cec5SDimitry Andric         if (Triple.isOSBinFormatELF()) {
62670b57cec5SDimitry Andric           if (!VD)
62680b57cec5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
62690b57cec5SDimitry Andric         } else {
62700b57cec5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
62710b57cec5SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
62720b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
62730b57cec5SDimitry Andric           else
62740b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
62750b57cec5SDimitry Andric         }
62760b57cec5SDimitry Andric 
62770b57cec5SDimitry Andric         setDSOLocal(GV);
62780b57cec5SDimitry Andric       }
62790b57cec5SDimitry Andric     }
62800b57cec5SDimitry Andric 
62810b57cec5SDimitry Andric     // Decay array -> ptr
62820b57cec5SDimitry Andric     CFConstantStringClassRef =
62830fca6ea1SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) : C;
62840b57cec5SDimitry Andric   }
62850b57cec5SDimitry Andric 
62860b57cec5SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
62870b57cec5SDimitry Andric 
62880b57cec5SDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
62890b57cec5SDimitry Andric 
62900b57cec5SDimitry Andric   ConstantInitBuilder Builder(*this);
62910b57cec5SDimitry Andric   auto Fields = Builder.beginStruct(STy);
62920b57cec5SDimitry Andric 
62930b57cec5SDimitry Andric   // Class pointer.
629481ad6265SDimitry Andric   Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
62950b57cec5SDimitry Andric 
62960b57cec5SDimitry Andric   // Flags.
62970b57cec5SDimitry Andric   if (IsSwiftABI) {
62980b57cec5SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
62990b57cec5SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
63000b57cec5SDimitry Andric   } else {
63010b57cec5SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
63020b57cec5SDimitry Andric   }
63030b57cec5SDimitry Andric 
63040b57cec5SDimitry Andric   // String pointer.
63050b57cec5SDimitry Andric   llvm::Constant *C = nullptr;
63060b57cec5SDimitry Andric   if (isUTF16) {
6307bdd1243dSDimitry Andric     auto Arr = llvm::ArrayRef(
63080b57cec5SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
63090b57cec5SDimitry Andric         Entry.first().size() / 2);
63100b57cec5SDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
63110b57cec5SDimitry Andric   } else {
63120b57cec5SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
63130b57cec5SDimitry Andric   }
63140b57cec5SDimitry Andric 
63150b57cec5SDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
63165f757f3fSDimitry Andric   // CFStrings writable.
63170b57cec5SDimitry Andric   auto *GV =
63180b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
63190b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
63200b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
63210b57cec5SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
63220b57cec5SDimitry Andric   // of the string is via this class initializer.
63230b57cec5SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
63240b57cec5SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
6325a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
63260b57cec5SDimitry Andric 
63270b57cec5SDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
63280b57cec5SDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
63290b57cec5SDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
63300b57cec5SDimitry Andric   if (Triple.isOSBinFormatMachO())
63310b57cec5SDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
63320b57cec5SDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
63330b57cec5SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
63340b57cec5SDimitry Andric   // the static linker to adjust permissions to read-only later on.
63350b57cec5SDimitry Andric   else if (Triple.isOSBinFormatELF())
63360b57cec5SDimitry Andric     GV->setSection(".rodata");
63370b57cec5SDimitry Andric 
63380b57cec5SDimitry Andric   // String.
63390fca6ea1SDimitry Andric   Fields.add(GV);
63400b57cec5SDimitry Andric 
63410b57cec5SDimitry Andric   // String length.
63420b57cec5SDimitry Andric   llvm::IntegerType *LengthTy =
63430b57cec5SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
63440b57cec5SDimitry Andric                              Context.getTargetInfo().getLongWidth());
63450b57cec5SDimitry Andric   if (IsSwiftABI) {
63460b57cec5SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
63470b57cec5SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
63480b57cec5SDimitry Andric       LengthTy = Int32Ty;
63490b57cec5SDimitry Andric     else
63500b57cec5SDimitry Andric       LengthTy = IntPtrTy;
63510b57cec5SDimitry Andric   }
63520b57cec5SDimitry Andric   Fields.addInt(LengthTy, StringLength);
63530b57cec5SDimitry Andric 
6354a7dea167SDimitry Andric   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6355a7dea167SDimitry Andric   // properly aligned on 32-bit platforms.
6356a7dea167SDimitry Andric   CharUnits Alignment =
6357a7dea167SDimitry Andric       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
63580b57cec5SDimitry Andric 
63590b57cec5SDimitry Andric   // The struct.
63600b57cec5SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
63610b57cec5SDimitry Andric                                     /*isConstant=*/false,
63620b57cec5SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
63630b57cec5SDimitry Andric   GV->addAttribute("objc_arc_inert");
63640b57cec5SDimitry Andric   switch (Triple.getObjectFormat()) {
63650b57cec5SDimitry Andric   case llvm::Triple::UnknownObjectFormat:
63660b57cec5SDimitry Andric     llvm_unreachable("unknown file format");
636781ad6265SDimitry Andric   case llvm::Triple::DXContainer:
6368e8d8bef9SDimitry Andric   case llvm::Triple::GOFF:
636981ad6265SDimitry Andric   case llvm::Triple::SPIRV:
63700b57cec5SDimitry Andric   case llvm::Triple::XCOFF:
637181ad6265SDimitry Andric     llvm_unreachable("unimplemented");
63720b57cec5SDimitry Andric   case llvm::Triple::COFF:
63730b57cec5SDimitry Andric   case llvm::Triple::ELF:
63740b57cec5SDimitry Andric   case llvm::Triple::Wasm:
63750b57cec5SDimitry Andric     GV->setSection("cfstring");
63760b57cec5SDimitry Andric     break;
63770b57cec5SDimitry Andric   case llvm::Triple::MachO:
63780b57cec5SDimitry Andric     GV->setSection("__DATA,__cfstring");
63790b57cec5SDimitry Andric     break;
63800b57cec5SDimitry Andric   }
63810b57cec5SDimitry Andric   Entry.second = GV;
63820b57cec5SDimitry Andric 
63830eae32dcSDimitry Andric   return ConstantAddress(GV, GV->getValueType(), Alignment);
63840b57cec5SDimitry Andric }
63850b57cec5SDimitry Andric 
63860b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
63870b57cec5SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
63880b57cec5SDimitry Andric }
63890b57cec5SDimitry Andric 
63900b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
63910b57cec5SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
63920b57cec5SDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
63930b57cec5SDimitry Andric     D->startDefinition();
63940b57cec5SDimitry Andric 
63950b57cec5SDimitry Andric     QualType FieldTypes[] = {
63965f757f3fSDimitry Andric         Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
63970b57cec5SDimitry Andric         Context.getPointerType(Context.UnsignedLongTy),
63985f757f3fSDimitry Andric         Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
63995f757f3fSDimitry Andric                                      nullptr, ArraySizeModifier::Normal, 0)};
64000b57cec5SDimitry Andric 
64010b57cec5SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
64020b57cec5SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
64030b57cec5SDimitry Andric                                            D,
64040b57cec5SDimitry Andric                                            SourceLocation(),
64050b57cec5SDimitry Andric                                            SourceLocation(), nullptr,
64060b57cec5SDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
64070b57cec5SDimitry Andric                                            /*BitWidth=*/nullptr,
64080b57cec5SDimitry Andric                                            /*Mutable=*/false,
64090b57cec5SDimitry Andric                                            ICIS_NoInit);
64100b57cec5SDimitry Andric       Field->setAccess(AS_public);
64110b57cec5SDimitry Andric       D->addDecl(Field);
64120b57cec5SDimitry Andric     }
64130b57cec5SDimitry Andric 
64140b57cec5SDimitry Andric     D->completeDefinition();
64150b57cec5SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
64160b57cec5SDimitry Andric   }
64170b57cec5SDimitry Andric 
64180b57cec5SDimitry Andric   return ObjCFastEnumerationStateType;
64190b57cec5SDimitry Andric }
64200b57cec5SDimitry Andric 
64210b57cec5SDimitry Andric llvm::Constant *
64220b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
64230b57cec5SDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
64240b57cec5SDimitry Andric 
64250b57cec5SDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
64260b57cec5SDimitry Andric   // as an inline array.
64270b57cec5SDimitry Andric   if (E->getCharByteWidth() == 1) {
64280b57cec5SDimitry Andric     SmallString<64> Str(E->getString());
64290b57cec5SDimitry Andric 
64300b57cec5SDimitry Andric     // Resize the string to the right size, which is indicated by its type.
64310b57cec5SDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
643206c3fb27SDimitry Andric     assert(CAT && "String literal not of constant array type!");
64330fca6ea1SDimitry Andric     Str.resize(CAT->getZExtSize());
64340b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
64350b57cec5SDimitry Andric   }
64360b57cec5SDimitry Andric 
64370b57cec5SDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
64380b57cec5SDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
64390b57cec5SDimitry Andric   unsigned NumElements = AType->getNumElements();
64400b57cec5SDimitry Andric 
64410b57cec5SDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
64420b57cec5SDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
64430b57cec5SDimitry Andric     SmallVector<uint16_t, 32> Elements;
64440b57cec5SDimitry Andric     Elements.reserve(NumElements);
64450b57cec5SDimitry Andric 
64460b57cec5SDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
64470b57cec5SDimitry Andric       Elements.push_back(E->getCodeUnit(i));
64480b57cec5SDimitry Andric     Elements.resize(NumElements);
64490b57cec5SDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
64500b57cec5SDimitry Andric   }
64510b57cec5SDimitry Andric 
64520b57cec5SDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
64530b57cec5SDimitry Andric   SmallVector<uint32_t, 32> Elements;
64540b57cec5SDimitry Andric   Elements.reserve(NumElements);
64550b57cec5SDimitry Andric 
64560b57cec5SDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
64570b57cec5SDimitry Andric     Elements.push_back(E->getCodeUnit(i));
64580b57cec5SDimitry Andric   Elements.resize(NumElements);
64590b57cec5SDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
64600b57cec5SDimitry Andric }
64610b57cec5SDimitry Andric 
64620b57cec5SDimitry Andric static llvm::GlobalVariable *
64630b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
64640b57cec5SDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
64650b57cec5SDimitry Andric                       CharUnits Alignment) {
64660b57cec5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
6467fe6060f1SDimitry Andric       CGM.GetGlobalConstantAddressSpace());
64680b57cec5SDimitry Andric 
64690b57cec5SDimitry Andric   llvm::Module &M = CGM.getModule();
64700b57cec5SDimitry Andric   // Create a global variable for this string
64710b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
64720b57cec5SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
64730b57cec5SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6474a7dea167SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
64750b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
64760b57cec5SDimitry Andric   if (GV->isWeakForLinker()) {
64770b57cec5SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
64780b57cec5SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
64790b57cec5SDimitry Andric   }
64800b57cec5SDimitry Andric   CGM.setDSOLocal(GV);
64810b57cec5SDimitry Andric 
64820b57cec5SDimitry Andric   return GV;
64830b57cec5SDimitry Andric }
64840b57cec5SDimitry Andric 
64850b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
64860b57cec5SDimitry Andric /// constant array for the given string literal.
64870b57cec5SDimitry Andric ConstantAddress
64880b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
64890b57cec5SDimitry Andric                                                   StringRef Name) {
64900fca6ea1SDimitry Andric   CharUnits Alignment =
64910fca6ea1SDimitry Andric       getContext().getAlignOfGlobalVarInChars(S->getType(), /*VD=*/nullptr);
64920b57cec5SDimitry Andric 
64930b57cec5SDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
64940b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
64950b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
64960b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
64970b57cec5SDimitry Andric     if (auto GV = *Entry) {
6498349cc55cSDimitry Andric       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6499a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
65000b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
65010eae32dcSDimitry Andric                              GV->getValueType(), Alignment);
65020b57cec5SDimitry Andric     }
65030b57cec5SDimitry Andric   }
65040b57cec5SDimitry Andric 
65050b57cec5SDimitry Andric   SmallString<256> MangledNameBuffer;
65060b57cec5SDimitry Andric   StringRef GlobalVariableName;
65070b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
65080b57cec5SDimitry Andric 
65090b57cec5SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
65100b57cec5SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
65110b57cec5SDimitry Andric   // affect strings in another.
65120b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
65130b57cec5SDimitry Andric       !LangOpts.WritableStrings) {
65140b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
65150b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
65160b57cec5SDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
65170b57cec5SDimitry Andric     GlobalVariableName = MangledNameBuffer;
65180b57cec5SDimitry Andric   } else {
65190b57cec5SDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
65200b57cec5SDimitry Andric     GlobalVariableName = Name;
65210b57cec5SDimitry Andric   }
65220b57cec5SDimitry Andric 
65230b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
652481ad6265SDimitry Andric 
652581ad6265SDimitry Andric   CGDebugInfo *DI = getModuleDebugInfo();
652681ad6265SDimitry Andric   if (DI && getCodeGenOpts().hasReducedDebugInfo())
652781ad6265SDimitry Andric     DI->AddStringLiteralDebugInfo(GV, S);
652881ad6265SDimitry Andric 
65290b57cec5SDimitry Andric   if (Entry)
65300b57cec5SDimitry Andric     *Entry = GV;
65310b57cec5SDimitry Andric 
653281ad6265SDimitry Andric   SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
65330b57cec5SDimitry Andric 
65340b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
65350eae32dcSDimitry Andric                          GV->getValueType(), Alignment);
65360b57cec5SDimitry Andric }
65370b57cec5SDimitry Andric 
65380b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
65390b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node.
65400b57cec5SDimitry Andric ConstantAddress
65410b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
65420b57cec5SDimitry Andric   std::string Str;
65430b57cec5SDimitry Andric   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
65440b57cec5SDimitry Andric 
65450b57cec5SDimitry Andric   return GetAddrOfConstantCString(Str);
65460b57cec5SDimitry Andric }
65470b57cec5SDimitry Andric 
65480b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
65490b57cec5SDimitry Andric /// the literal and a terminating '\0' character.
65500b57cec5SDimitry Andric /// The result has pointer to array type.
65510b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
65520b57cec5SDimitry Andric     const std::string &Str, const char *GlobalName) {
65530b57cec5SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
65540fca6ea1SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(
65550fca6ea1SDimitry Andric       getContext().CharTy, /*VD=*/nullptr);
65560b57cec5SDimitry Andric 
65570b57cec5SDimitry Andric   llvm::Constant *C =
65580b57cec5SDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
65590b57cec5SDimitry Andric 
65600b57cec5SDimitry Andric   // Don't share any string literals if strings aren't constant.
65610b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
65620b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
65630b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
65640b57cec5SDimitry Andric     if (auto GV = *Entry) {
6565349cc55cSDimitry Andric       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6566a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
65670b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
65680eae32dcSDimitry Andric                              GV->getValueType(), Alignment);
65690b57cec5SDimitry Andric     }
65700b57cec5SDimitry Andric   }
65710b57cec5SDimitry Andric 
65720b57cec5SDimitry Andric   // Get the default prefix if a name wasn't specified.
65730b57cec5SDimitry Andric   if (!GlobalName)
65740b57cec5SDimitry Andric     GlobalName = ".str";
65750b57cec5SDimitry Andric   // Create a global variable for this.
65760b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
65770b57cec5SDimitry Andric                                   GlobalName, Alignment);
65780b57cec5SDimitry Andric   if (Entry)
65790b57cec5SDimitry Andric     *Entry = GV;
65800b57cec5SDimitry Andric 
65810b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
65820eae32dcSDimitry Andric                          GV->getValueType(), Alignment);
65830b57cec5SDimitry Andric }
65840b57cec5SDimitry Andric 
65850b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
65860b57cec5SDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
65870b57cec5SDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
65880b57cec5SDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
65890b57cec5SDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
65900b57cec5SDimitry Andric 
65910b57cec5SDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
65920b57cec5SDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
65930b57cec5SDimitry Andric   QualType MaterializedType = Init->getType();
6594480093f4SDimitry Andric   if (Init == E->getSubExpr())
65950b57cec5SDimitry Andric     MaterializedType = E->getType();
65960b57cec5SDimitry Andric 
65970b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
65980b57cec5SDimitry Andric 
6599fe6060f1SDimitry Andric   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6600fe6060f1SDimitry Andric   if (!InsertResult.second) {
6601fe6060f1SDimitry Andric     // We've seen this before: either we already created it or we're in the
6602fe6060f1SDimitry Andric     // process of doing so.
6603fe6060f1SDimitry Andric     if (!InsertResult.first->second) {
6604fe6060f1SDimitry Andric       // We recursively re-entered this function, probably during emission of
6605fe6060f1SDimitry Andric       // the initializer. Create a placeholder. We'll clean this up in the
6606fe6060f1SDimitry Andric       // outer call, at the end of this function.
6607fe6060f1SDimitry Andric       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6608fe6060f1SDimitry Andric       InsertResult.first->second = new llvm::GlobalVariable(
6609fe6060f1SDimitry Andric           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6610fe6060f1SDimitry Andric           nullptr);
6611fe6060f1SDimitry Andric     }
661281ad6265SDimitry Andric     return ConstantAddress(InsertResult.first->second,
661381ad6265SDimitry Andric                            llvm::cast<llvm::GlobalVariable>(
661481ad6265SDimitry Andric                                InsertResult.first->second->stripPointerCasts())
661581ad6265SDimitry Andric                                ->getValueType(),
661681ad6265SDimitry Andric                            Align);
6617fe6060f1SDimitry Andric   }
66180b57cec5SDimitry Andric 
66190b57cec5SDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
66200b57cec5SDimitry Andric   // we need to give each temporary the same name in every translation unit (and
66210b57cec5SDimitry Andric   // we also need to make the temporaries externally-visible).
66220b57cec5SDimitry Andric   SmallString<256> Name;
66230b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Name);
66240b57cec5SDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
66250b57cec5SDimitry Andric       VD, E->getManglingNumber(), Out);
66260b57cec5SDimitry Andric 
66270b57cec5SDimitry Andric   APValue *Value = nullptr;
66285f757f3fSDimitry Andric   if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) {
6629a7dea167SDimitry Andric     // If the initializer of the extending declaration is a constant
6630a7dea167SDimitry Andric     // initializer, we should have a cached constant initializer for this
6631a7dea167SDimitry Andric     // temporary. Note that this might have a different value from the value
6632a7dea167SDimitry Andric     // computed by evaluating the initializer if the surrounding constant
6633a7dea167SDimitry Andric     // expression modifies the temporary.
6634480093f4SDimitry Andric     Value = E->getOrCreateValue(false);
66350b57cec5SDimitry Andric   }
66360b57cec5SDimitry Andric 
66370b57cec5SDimitry Andric   // Try evaluating it now, it might have a constant initializer.
66380b57cec5SDimitry Andric   Expr::EvalResult EvalResult;
66390b57cec5SDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
66400b57cec5SDimitry Andric       !EvalResult.hasSideEffects())
66410b57cec5SDimitry Andric     Value = &EvalResult.Val;
66420b57cec5SDimitry Andric 
66435f757f3fSDimitry Andric   LangAS AddrSpace = GetGlobalVarAddressSpace(VD);
66440b57cec5SDimitry Andric 
6645bdd1243dSDimitry Andric   std::optional<ConstantEmitter> emitter;
66460b57cec5SDimitry Andric   llvm::Constant *InitialValue = nullptr;
66470b57cec5SDimitry Andric   bool Constant = false;
66480b57cec5SDimitry Andric   llvm::Type *Type;
66490b57cec5SDimitry Andric   if (Value) {
66500b57cec5SDimitry Andric     // The temporary has a constant initializer, use it.
66510b57cec5SDimitry Andric     emitter.emplace(*this);
66520b57cec5SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
66530b57cec5SDimitry Andric                                                MaterializedType);
66545f757f3fSDimitry Andric     Constant =
66555f757f3fSDimitry Andric         MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
665606c3fb27SDimitry Andric                                            /*ExcludeDtor*/ false);
66570b57cec5SDimitry Andric     Type = InitialValue->getType();
66580b57cec5SDimitry Andric   } else {
66590b57cec5SDimitry Andric     // No initializer, the initialization will be provided when we
66600b57cec5SDimitry Andric     // initialize the declaration which performed lifetime extension.
66610b57cec5SDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
66620b57cec5SDimitry Andric   }
66630b57cec5SDimitry Andric 
66640b57cec5SDimitry Andric   // Create a global variable for this lifetime-extended temporary.
66658a4dda33SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
66660b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
66670b57cec5SDimitry Andric     const VarDecl *InitVD;
66680b57cec5SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
66690b57cec5SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
66700b57cec5SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
66710b57cec5SDimitry Andric       // class can be defined in multiple translation units.
66720b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
66730b57cec5SDimitry Andric     } else {
66740b57cec5SDimitry Andric       // There is no need for this temporary to have external linkage if the
66750b57cec5SDimitry Andric       // VarDecl has external linkage.
66760b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
66770b57cec5SDimitry Andric     }
66780b57cec5SDimitry Andric   }
66790b57cec5SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
66800b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
66810b57cec5SDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
66820b57cec5SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
66830b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
6684bdd1243dSDimitry Andric   // Don't assign dllimport or dllexport to local linkage globals.
6685bdd1243dSDimitry Andric   if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
66860b57cec5SDimitry Andric     setGVProperties(GV, VD);
668781ad6265SDimitry Andric     if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
668881ad6265SDimitry Andric       // The reference temporary should never be dllexport.
668981ad6265SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6690bdd1243dSDimitry Andric   }
6691a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
66920b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
66930b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
66940b57cec5SDimitry Andric   if (VD->getTLSKind())
66950b57cec5SDimitry Andric     setTLSMode(GV, *VD);
66960b57cec5SDimitry Andric   llvm::Constant *CV = GV;
66970b57cec5SDimitry Andric   if (AddrSpace != LangAS::Default)
66980b57cec5SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
66990b57cec5SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
67005f757f3fSDimitry Andric         llvm::PointerType::get(
67015f757f3fSDimitry Andric             getLLVMContext(),
67020b57cec5SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
6703fe6060f1SDimitry Andric 
6704fe6060f1SDimitry Andric   // Update the map with the new temporary. If we created a placeholder above,
6705fe6060f1SDimitry Andric   // replace it with the new global now.
6706fe6060f1SDimitry Andric   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6707fe6060f1SDimitry Andric   if (Entry) {
67085f757f3fSDimitry Andric     Entry->replaceAllUsesWith(CV);
6709fe6060f1SDimitry Andric     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6710fe6060f1SDimitry Andric   }
6711fe6060f1SDimitry Andric   Entry = CV;
6712fe6060f1SDimitry Andric 
67130eae32dcSDimitry Andric   return ConstantAddress(CV, Type, Align);
67140b57cec5SDimitry Andric }
67150b57cec5SDimitry Andric 
67160b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized
67170b57cec5SDimitry Andric /// properties for an implementation.
67180b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const
67190b57cec5SDimitry Andric                                                     ObjCImplementationDecl *D) {
67200b57cec5SDimitry Andric   for (const auto *PID : D->property_impls()) {
67210b57cec5SDimitry Andric     // Dynamic is just for type-checking.
67220b57cec5SDimitry Andric     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
67230b57cec5SDimitry Andric       ObjCPropertyDecl *PD = PID->getPropertyDecl();
67240b57cec5SDimitry Andric 
67250b57cec5SDimitry Andric       // Determine which methods need to be implemented, some may have
67260b57cec5SDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
67270b57cec5SDimitry Andric       // we want, that just indicates if the decl came from a
67280b57cec5SDimitry Andric       // property. What we want to know is if the method is defined in
67290b57cec5SDimitry Andric       // this implementation.
6730480093f4SDimitry Andric       auto *Getter = PID->getGetterMethodDecl();
6731480093f4SDimitry Andric       if (!Getter || Getter->isSynthesizedAccessorStub())
67320b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCGetter(
67330b57cec5SDimitry Andric             const_cast<ObjCImplementationDecl *>(D), PID);
6734480093f4SDimitry Andric       auto *Setter = PID->getSetterMethodDecl();
6735480093f4SDimitry Andric       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
67360b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCSetter(
67370b57cec5SDimitry Andric                                  const_cast<ObjCImplementationDecl *>(D), PID);
67380b57cec5SDimitry Andric     }
67390b57cec5SDimitry Andric   }
67400b57cec5SDimitry Andric }
67410b57cec5SDimitry Andric 
67420b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
67430b57cec5SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
67440b57cec5SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
67450b57cec5SDimitry Andric        ivar; ivar = ivar->getNextIvar())
67460b57cec5SDimitry Andric     if (ivar->getType().isDestructedType())
67470b57cec5SDimitry Andric       return true;
67480b57cec5SDimitry Andric 
67490b57cec5SDimitry Andric   return false;
67500b57cec5SDimitry Andric }
67510b57cec5SDimitry Andric 
67520b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
67530b57cec5SDimitry Andric                                    ObjCImplementationDecl *D) {
67540b57cec5SDimitry Andric   CodeGenFunction CGF(CGM);
67550b57cec5SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
67560b57cec5SDimitry Andric        E = D->init_end(); B != E; ++B) {
67570b57cec5SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
67580b57cec5SDimitry Andric     Expr *Init = CtorInitExp->getInit();
67590b57cec5SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
67600b57cec5SDimitry Andric       return false;
67610b57cec5SDimitry Andric   }
67620b57cec5SDimitry Andric   return true;
67630b57cec5SDimitry Andric }
67640b57cec5SDimitry Andric 
67650b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization
67660b57cec5SDimitry Andric /// for an implementation.
67670b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
67680b57cec5SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
67690b57cec5SDimitry Andric   if (needsDestructMethod(D)) {
67700fca6ea1SDimitry Andric     const IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
67710b57cec5SDimitry Andric     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6772480093f4SDimitry Andric     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6773480093f4SDimitry Andric         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6774480093f4SDimitry Andric         getContext().VoidTy, nullptr, D,
67750b57cec5SDimitry Andric         /*isInstance=*/true, /*isVariadic=*/false,
6776480093f4SDimitry Andric         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6777480093f4SDimitry Andric         /*isImplicitlyDeclared=*/true,
67785f757f3fSDimitry Andric         /*isDefined=*/false, ObjCImplementationControl::Required);
67790b57cec5SDimitry Andric     D->addInstanceMethod(DTORMethod);
67800b57cec5SDimitry Andric     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
67810b57cec5SDimitry Andric     D->setHasDestructors(true);
67820b57cec5SDimitry Andric   }
67830b57cec5SDimitry Andric 
67840b57cec5SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
67850b57cec5SDimitry Andric   // a .cxx_construct.
67860b57cec5SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
67870b57cec5SDimitry Andric       AllTrivialInitializers(*this, D))
67880b57cec5SDimitry Andric     return;
67890b57cec5SDimitry Andric 
67900fca6ea1SDimitry Andric   const IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
67910b57cec5SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
67920b57cec5SDimitry Andric   // The constructor returns 'self'.
6793480093f4SDimitry Andric   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6794480093f4SDimitry Andric       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6795480093f4SDimitry Andric       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
67960b57cec5SDimitry Andric       /*isVariadic=*/false,
6797480093f4SDimitry Andric       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
67980b57cec5SDimitry Andric       /*isImplicitlyDeclared=*/true,
67995f757f3fSDimitry Andric       /*isDefined=*/false, ObjCImplementationControl::Required);
68000b57cec5SDimitry Andric   D->addInstanceMethod(CTORMethod);
68010b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
68020b57cec5SDimitry Andric   D->setHasNonZeroConstructors(true);
68030b57cec5SDimitry Andric }
68040b57cec5SDimitry Andric 
68050b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec.
68060b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
68075f757f3fSDimitry Andric   if (LSD->getLanguage() != LinkageSpecLanguageIDs::C &&
68085f757f3fSDimitry Andric       LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) {
68090b57cec5SDimitry Andric     ErrorUnsupported(LSD, "linkage spec");
68100b57cec5SDimitry Andric     return;
68110b57cec5SDimitry Andric   }
68120b57cec5SDimitry Andric 
68130b57cec5SDimitry Andric   EmitDeclContext(LSD);
68140b57cec5SDimitry Andric }
68150b57cec5SDimitry Andric 
6816bdd1243dSDimitry Andric void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
681706c3fb27SDimitry Andric   // Device code should not be at top level.
681806c3fb27SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
681906c3fb27SDimitry Andric     return;
682006c3fb27SDimitry Andric 
6821bdd1243dSDimitry Andric   std::unique_ptr<CodeGenFunction> &CurCGF =
6822bdd1243dSDimitry Andric       GlobalTopLevelStmtBlockInFlight.first;
6823bdd1243dSDimitry Andric 
6824bdd1243dSDimitry Andric   // We emitted a top-level stmt but after it there is initialization.
6825bdd1243dSDimitry Andric   // Stop squashing the top-level stmts into a single function.
6826bdd1243dSDimitry Andric   if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6827bdd1243dSDimitry Andric     CurCGF->FinishFunction(D->getEndLoc());
6828bdd1243dSDimitry Andric     CurCGF = nullptr;
6829bdd1243dSDimitry Andric   }
6830bdd1243dSDimitry Andric 
6831bdd1243dSDimitry Andric   if (!CurCGF) {
6832bdd1243dSDimitry Andric     // void __stmts__N(void)
6833bdd1243dSDimitry Andric     // FIXME: Ask the ABI name mangler to pick a name.
6834bdd1243dSDimitry Andric     std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6835bdd1243dSDimitry Andric     FunctionArgList Args;
6836bdd1243dSDimitry Andric     QualType RetTy = getContext().VoidTy;
6837bdd1243dSDimitry Andric     const CGFunctionInfo &FnInfo =
6838bdd1243dSDimitry Andric         getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6839bdd1243dSDimitry Andric     llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6840bdd1243dSDimitry Andric     llvm::Function *Fn = llvm::Function::Create(
6841bdd1243dSDimitry Andric         FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6842bdd1243dSDimitry Andric 
6843bdd1243dSDimitry Andric     CurCGF.reset(new CodeGenFunction(*this));
6844bdd1243dSDimitry Andric     GlobalTopLevelStmtBlockInFlight.second = D;
6845bdd1243dSDimitry Andric     CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6846bdd1243dSDimitry Andric                           D->getBeginLoc(), D->getBeginLoc());
6847bdd1243dSDimitry Andric     CXXGlobalInits.push_back(Fn);
6848bdd1243dSDimitry Andric   }
6849bdd1243dSDimitry Andric 
6850bdd1243dSDimitry Andric   CurCGF->EmitStmt(D->getStmt());
6851bdd1243dSDimitry Andric }
6852bdd1243dSDimitry Andric 
68530b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
68540b57cec5SDimitry Andric   for (auto *I : DC->decls()) {
68550b57cec5SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
68560b57cec5SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
68570b57cec5SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
68580b57cec5SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
68590b57cec5SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
68600b57cec5SDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
68610b57cec5SDimitry Andric       for (auto *M : OID->methods())
68620b57cec5SDimitry Andric         EmitTopLevelDecl(M);
68630b57cec5SDimitry Andric     }
68640b57cec5SDimitry Andric 
68650b57cec5SDimitry Andric     EmitTopLevelDecl(I);
68660b57cec5SDimitry Andric   }
68670b57cec5SDimitry Andric }
68680b57cec5SDimitry Andric 
68690b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration.
68700b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) {
68710b57cec5SDimitry Andric   // Ignore dependent declarations.
68720b57cec5SDimitry Andric   if (D->isTemplated())
68730b57cec5SDimitry Andric     return;
68740b57cec5SDimitry Andric 
68755ffd83dbSDimitry Andric   // Consteval function shouldn't be emitted.
687606c3fb27SDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
68775ffd83dbSDimitry Andric     return;
68785ffd83dbSDimitry Andric 
68790b57cec5SDimitry Andric   switch (D->getKind()) {
68800b57cec5SDimitry Andric   case Decl::CXXConversion:
68810b57cec5SDimitry Andric   case Decl::CXXMethod:
68820b57cec5SDimitry Andric   case Decl::Function:
68830b57cec5SDimitry Andric     EmitGlobal(cast<FunctionDecl>(D));
68840b57cec5SDimitry Andric     // Always provide some coverage mapping
68850b57cec5SDimitry Andric     // even for the functions that aren't emitted.
68860b57cec5SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
68870b57cec5SDimitry Andric     break;
68880b57cec5SDimitry Andric 
68890b57cec5SDimitry Andric   case Decl::CXXDeductionGuide:
68900b57cec5SDimitry Andric     // Function-like, but does not result in code emission.
68910b57cec5SDimitry Andric     break;
68920b57cec5SDimitry Andric 
68930b57cec5SDimitry Andric   case Decl::Var:
68940b57cec5SDimitry Andric   case Decl::Decomposition:
68950b57cec5SDimitry Andric   case Decl::VarTemplateSpecialization:
68960b57cec5SDimitry Andric     EmitGlobal(cast<VarDecl>(D));
68970b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
68980b57cec5SDimitry Andric       for (auto *B : DD->bindings())
68990b57cec5SDimitry Andric         if (auto *HD = B->getHoldingVar())
69000b57cec5SDimitry Andric           EmitGlobal(HD);
69010b57cec5SDimitry Andric     break;
69020b57cec5SDimitry Andric 
69030b57cec5SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
69040b57cec5SDimitry Andric   // ignored; only the actual variable requires IR gen support.
69050b57cec5SDimitry Andric   case Decl::IndirectField:
69060b57cec5SDimitry Andric     break;
69070b57cec5SDimitry Andric 
69080b57cec5SDimitry Andric   // C++ Decls
69090b57cec5SDimitry Andric   case Decl::Namespace:
69100b57cec5SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
69110b57cec5SDimitry Andric     break;
69120b57cec5SDimitry Andric   case Decl::ClassTemplateSpecialization: {
69130b57cec5SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
69145ffd83dbSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
69155ffd83dbSDimitry Andric       if (Spec->getSpecializationKind() ==
69165ffd83dbSDimitry Andric               TSK_ExplicitInstantiationDefinition &&
69170b57cec5SDimitry Andric           Spec->hasDefinition())
69185ffd83dbSDimitry Andric         DI->completeTemplateDefinition(*Spec);
6919bdd1243dSDimitry Andric   } [[fallthrough]];
6920e8d8bef9SDimitry Andric   case Decl::CXXRecord: {
6921e8d8bef9SDimitry Andric     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6922e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo()) {
6923e8d8bef9SDimitry Andric       if (CRD->hasDefinition())
6924e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
69250b57cec5SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
69260b57cec5SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6927e8d8bef9SDimitry Andric           DI->completeUnusedClass(*CRD);
6928e8d8bef9SDimitry Andric     }
69290b57cec5SDimitry Andric     // Emit any static data members, they may be definitions.
6930e8d8bef9SDimitry Andric     for (auto *I : CRD->decls())
69310b57cec5SDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
69320b57cec5SDimitry Andric         EmitTopLevelDecl(I);
69330b57cec5SDimitry Andric     break;
6934e8d8bef9SDimitry Andric   }
69350b57cec5SDimitry Andric     // No code generation needed.
69360b57cec5SDimitry Andric   case Decl::UsingShadow:
69370b57cec5SDimitry Andric   case Decl::ClassTemplate:
69380b57cec5SDimitry Andric   case Decl::VarTemplate:
69390b57cec5SDimitry Andric   case Decl::Concept:
69400b57cec5SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
69410b57cec5SDimitry Andric   case Decl::FunctionTemplate:
69420b57cec5SDimitry Andric   case Decl::TypeAliasTemplate:
69430b57cec5SDimitry Andric   case Decl::Block:
69440b57cec5SDimitry Andric   case Decl::Empty:
69450b57cec5SDimitry Andric   case Decl::Binding:
69460b57cec5SDimitry Andric     break;
69470b57cec5SDimitry Andric   case Decl::Using:          // using X; [C++]
69480b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
69490b57cec5SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
69505ffd83dbSDimitry Andric     break;
6951fe6060f1SDimitry Andric   case Decl::UsingEnum: // using enum X; [C++]
6952fe6060f1SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
6953fe6060f1SDimitry Andric       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6954fe6060f1SDimitry Andric     break;
69550b57cec5SDimitry Andric   case Decl::NamespaceAlias:
69560b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
69570b57cec5SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
69585ffd83dbSDimitry Andric     break;
69590b57cec5SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
69600b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
69610b57cec5SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
69625ffd83dbSDimitry Andric     break;
69630b57cec5SDimitry Andric   case Decl::CXXConstructor:
69640b57cec5SDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
69650b57cec5SDimitry Andric     break;
69660b57cec5SDimitry Andric   case Decl::CXXDestructor:
69670b57cec5SDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
69680b57cec5SDimitry Andric     break;
69690b57cec5SDimitry Andric 
69700b57cec5SDimitry Andric   case Decl::StaticAssert:
69710b57cec5SDimitry Andric     // Nothing to do.
69720b57cec5SDimitry Andric     break;
69730b57cec5SDimitry Andric 
69740b57cec5SDimitry Andric   // Objective-C Decls
69750b57cec5SDimitry Andric 
69760b57cec5SDimitry Andric   // Forward declarations, no (immediate) code generation.
69770b57cec5SDimitry Andric   case Decl::ObjCInterface:
69780b57cec5SDimitry Andric   case Decl::ObjCCategory:
69790b57cec5SDimitry Andric     break;
69800b57cec5SDimitry Andric 
69810b57cec5SDimitry Andric   case Decl::ObjCProtocol: {
69820b57cec5SDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
69830b57cec5SDimitry Andric     if (Proto->isThisDeclarationADefinition())
69840b57cec5SDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
69850b57cec5SDimitry Andric     break;
69860b57cec5SDimitry Andric   }
69870b57cec5SDimitry Andric 
69880b57cec5SDimitry Andric   case Decl::ObjCCategoryImpl:
69890b57cec5SDimitry Andric     // Categories have properties but don't support synthesize so we
69900b57cec5SDimitry Andric     // can ignore them here.
69910b57cec5SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
69920b57cec5SDimitry Andric     break;
69930b57cec5SDimitry Andric 
69940b57cec5SDimitry Andric   case Decl::ObjCImplementation: {
69950b57cec5SDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
69960b57cec5SDimitry Andric     EmitObjCPropertyImplementations(OMD);
69970b57cec5SDimitry Andric     EmitObjCIvarInitializations(OMD);
69980b57cec5SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
69990b57cec5SDimitry Andric     // Emit global variable debug information.
70000b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
7001480093f4SDimitry Andric       if (getCodeGenOpts().hasReducedDebugInfo())
70020b57cec5SDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
70030b57cec5SDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
70040b57cec5SDimitry Andric     break;
70050b57cec5SDimitry Andric   }
70060b57cec5SDimitry Andric   case Decl::ObjCMethod: {
70070b57cec5SDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
70080b57cec5SDimitry Andric     // If this is not a prototype, emit the body.
70090b57cec5SDimitry Andric     if (OMD->getBody())
70100b57cec5SDimitry Andric       CodeGenFunction(*this).GenerateObjCMethod(OMD);
70110b57cec5SDimitry Andric     break;
70120b57cec5SDimitry Andric   }
70130b57cec5SDimitry Andric   case Decl::ObjCCompatibleAlias:
70140b57cec5SDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
70150b57cec5SDimitry Andric     break;
70160b57cec5SDimitry Andric 
70170b57cec5SDimitry Andric   case Decl::PragmaComment: {
70180b57cec5SDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
70190b57cec5SDimitry Andric     switch (PCD->getCommentKind()) {
70200b57cec5SDimitry Andric     case PCK_Unknown:
70210b57cec5SDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
70220b57cec5SDimitry Andric     case PCK_Linker:
70230b57cec5SDimitry Andric       AppendLinkerOptions(PCD->getArg());
70240b57cec5SDimitry Andric       break;
70250b57cec5SDimitry Andric     case PCK_Lib:
70260b57cec5SDimitry Andric         AddDependentLib(PCD->getArg());
70270b57cec5SDimitry Andric       break;
70280b57cec5SDimitry Andric     case PCK_Compiler:
70290b57cec5SDimitry Andric     case PCK_ExeStr:
70300b57cec5SDimitry Andric     case PCK_User:
70310b57cec5SDimitry Andric       break; // We ignore all of these.
70320b57cec5SDimitry Andric     }
70330b57cec5SDimitry Andric     break;
70340b57cec5SDimitry Andric   }
70350b57cec5SDimitry Andric 
70360b57cec5SDimitry Andric   case Decl::PragmaDetectMismatch: {
70370b57cec5SDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
70380b57cec5SDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
70390b57cec5SDimitry Andric     break;
70400b57cec5SDimitry Andric   }
70410b57cec5SDimitry Andric 
70420b57cec5SDimitry Andric   case Decl::LinkageSpec:
70430b57cec5SDimitry Andric     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
70440b57cec5SDimitry Andric     break;
70450b57cec5SDimitry Andric 
70460b57cec5SDimitry Andric   case Decl::FileScopeAsm: {
70470b57cec5SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
70480b57cec5SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
70490b57cec5SDimitry Andric       break;
70500b57cec5SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
705106c3fb27SDimitry Andric     if (LangOpts.OpenMPIsTargetDevice)
70520b57cec5SDimitry Andric       break;
7053fe6060f1SDimitry Andric     // File-scope asm is ignored during device-side SYCL compilation.
7054fe6060f1SDimitry Andric     if (LangOpts.SYCLIsDevice)
7055fe6060f1SDimitry Andric       break;
70560b57cec5SDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
70570b57cec5SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
70580b57cec5SDimitry Andric     break;
70590b57cec5SDimitry Andric   }
70600b57cec5SDimitry Andric 
7061bdd1243dSDimitry Andric   case Decl::TopLevelStmt:
7062bdd1243dSDimitry Andric     EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
7063bdd1243dSDimitry Andric     break;
7064bdd1243dSDimitry Andric 
70650b57cec5SDimitry Andric   case Decl::Import: {
70660b57cec5SDimitry Andric     auto *Import = cast<ImportDecl>(D);
70670b57cec5SDimitry Andric 
70680b57cec5SDimitry Andric     // If we've already imported this module, we're done.
70690b57cec5SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
70700b57cec5SDimitry Andric       break;
70710b57cec5SDimitry Andric 
70720b57cec5SDimitry Andric     // Emit debug information for direct imports.
70730b57cec5SDimitry Andric     if (!Import->getImportedOwningModule()) {
70740b57cec5SDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
70750b57cec5SDimitry Andric         DI->EmitImportDecl(*Import);
70760b57cec5SDimitry Andric     }
70770b57cec5SDimitry Andric 
7078fcaf7f86SDimitry Andric     // For C++ standard modules we are done - we will call the module
7079fcaf7f86SDimitry Andric     // initializer for imported modules, and that will likewise call those for
7080fcaf7f86SDimitry Andric     // any imports it has.
7081fcaf7f86SDimitry Andric     if (CXX20ModuleInits && Import->getImportedOwningModule() &&
7082fcaf7f86SDimitry Andric         !Import->getImportedOwningModule()->isModuleMapModule())
7083fcaf7f86SDimitry Andric       break;
7084fcaf7f86SDimitry Andric 
7085fcaf7f86SDimitry Andric     // For clang C++ module map modules the initializers for sub-modules are
7086fcaf7f86SDimitry Andric     // emitted here.
7087fcaf7f86SDimitry Andric 
70880b57cec5SDimitry Andric     // Find all of the submodules and emit the module initializers.
70890b57cec5SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
70900b57cec5SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
70910b57cec5SDimitry Andric     Visited.insert(Import->getImportedModule());
70920b57cec5SDimitry Andric     Stack.push_back(Import->getImportedModule());
70930b57cec5SDimitry Andric 
70940b57cec5SDimitry Andric     while (!Stack.empty()) {
70950b57cec5SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
70960b57cec5SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
70970b57cec5SDimitry Andric         continue;
70980b57cec5SDimitry Andric 
70990b57cec5SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
71000b57cec5SDimitry Andric         EmitTopLevelDecl(D);
71010b57cec5SDimitry Andric 
71020b57cec5SDimitry Andric       // Visit the submodules of this module.
710306c3fb27SDimitry Andric       for (auto *Submodule : Mod->submodules()) {
71040b57cec5SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
71050b57cec5SDimitry Andric         // the initializers.
710606c3fb27SDimitry Andric         if (Submodule->IsExplicit)
71070b57cec5SDimitry Andric           continue;
71080b57cec5SDimitry Andric 
710906c3fb27SDimitry Andric         if (Visited.insert(Submodule).second)
711006c3fb27SDimitry Andric           Stack.push_back(Submodule);
71110b57cec5SDimitry Andric       }
71120b57cec5SDimitry Andric     }
71130b57cec5SDimitry Andric     break;
71140b57cec5SDimitry Andric   }
71150b57cec5SDimitry Andric 
71160b57cec5SDimitry Andric   case Decl::Export:
71170b57cec5SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
71180b57cec5SDimitry Andric     break;
71190b57cec5SDimitry Andric 
71200b57cec5SDimitry Andric   case Decl::OMPThreadPrivate:
71210b57cec5SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
71220b57cec5SDimitry Andric     break;
71230b57cec5SDimitry Andric 
71240b57cec5SDimitry Andric   case Decl::OMPAllocate:
7125fe6060f1SDimitry Andric     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
71260b57cec5SDimitry Andric     break;
71270b57cec5SDimitry Andric 
71280b57cec5SDimitry Andric   case Decl::OMPDeclareReduction:
71290b57cec5SDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
71300b57cec5SDimitry Andric     break;
71310b57cec5SDimitry Andric 
71320b57cec5SDimitry Andric   case Decl::OMPDeclareMapper:
71330b57cec5SDimitry Andric     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
71340b57cec5SDimitry Andric     break;
71350b57cec5SDimitry Andric 
71360b57cec5SDimitry Andric   case Decl::OMPRequires:
71370b57cec5SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
71380b57cec5SDimitry Andric     break;
71390b57cec5SDimitry Andric 
7140e8d8bef9SDimitry Andric   case Decl::Typedef:
7141e8d8bef9SDimitry Andric   case Decl::TypeAlias: // using foo = bar; [C++11]
7142e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
7143e8d8bef9SDimitry Andric       DI->EmitAndRetainType(
7144e8d8bef9SDimitry Andric           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
7145e8d8bef9SDimitry Andric     break;
7146e8d8bef9SDimitry Andric 
7147e8d8bef9SDimitry Andric   case Decl::Record:
7148e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
7149e8d8bef9SDimitry Andric       if (cast<RecordDecl>(D)->getDefinition())
7150e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
7151e8d8bef9SDimitry Andric     break;
7152e8d8bef9SDimitry Andric 
7153e8d8bef9SDimitry Andric   case Decl::Enum:
7154e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
7155e8d8bef9SDimitry Andric       if (cast<EnumDecl>(D)->getDefinition())
7156e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
7157e8d8bef9SDimitry Andric     break;
7158e8d8bef9SDimitry Andric 
7159bdd1243dSDimitry Andric   case Decl::HLSLBuffer:
7160bdd1243dSDimitry Andric     getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
7161bdd1243dSDimitry Andric     break;
7162bdd1243dSDimitry Andric 
71630b57cec5SDimitry Andric   default:
71640b57cec5SDimitry Andric     // Make sure we handled everything we should, every other kind is a
71650b57cec5SDimitry Andric     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
71660b57cec5SDimitry Andric     // function. Need to recode Decl::Kind to do that easily.
71670b57cec5SDimitry Andric     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
71680b57cec5SDimitry Andric     break;
71690b57cec5SDimitry Andric   }
71700b57cec5SDimitry Andric }
71710b57cec5SDimitry Andric 
71720b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
71730b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
71740b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
71750b57cec5SDimitry Andric     return;
71760b57cec5SDimitry Andric   switch (D->getKind()) {
71770b57cec5SDimitry Andric   case Decl::CXXConversion:
71780b57cec5SDimitry Andric   case Decl::CXXMethod:
71790b57cec5SDimitry Andric   case Decl::Function:
71800b57cec5SDimitry Andric   case Decl::ObjCMethod:
71810b57cec5SDimitry Andric   case Decl::CXXConstructor:
71820b57cec5SDimitry Andric   case Decl::CXXDestructor: {
71830b57cec5SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
71845ffd83dbSDimitry Andric       break;
71850b57cec5SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
71860b57cec5SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
71875ffd83dbSDimitry Andric       break;
71880fca6ea1SDimitry Andric     if (!llvm::coverage::SystemHeadersCoverage &&
71890fca6ea1SDimitry Andric         SM.isInSystemHeader(D->getBeginLoc()))
71900fca6ea1SDimitry Andric       break;
71915f757f3fSDimitry Andric     DeferredEmptyCoverageMappingDecls.try_emplace(D, true);
71920b57cec5SDimitry Andric     break;
71930b57cec5SDimitry Andric   }
71940b57cec5SDimitry Andric   default:
71950b57cec5SDimitry Andric     break;
71960b57cec5SDimitry Andric   };
71970b57cec5SDimitry Andric }
71980b57cec5SDimitry Andric 
71990b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
72000b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
72010b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
72020b57cec5SDimitry Andric     return;
72030b57cec5SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
72040b57cec5SDimitry Andric     if (Fn->isTemplateInstantiation())
72050b57cec5SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
72060b57cec5SDimitry Andric   }
72075f757f3fSDimitry Andric   DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false);
72080b57cec5SDimitry Andric }
72090b57cec5SDimitry Andric 
72100b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
72110b57cec5SDimitry Andric   // We call takeVector() here to avoid use-after-free.
72120b57cec5SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
72130b57cec5SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
72140b57cec5SDimitry Andric   // deserializes more declarations. How should we handle that case?
72150b57cec5SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
72160b57cec5SDimitry Andric     if (!Entry.second)
72170b57cec5SDimitry Andric       continue;
72180b57cec5SDimitry Andric     const Decl *D = Entry.first;
72190b57cec5SDimitry Andric     switch (D->getKind()) {
72200b57cec5SDimitry Andric     case Decl::CXXConversion:
72210b57cec5SDimitry Andric     case Decl::CXXMethod:
72220b57cec5SDimitry Andric     case Decl::Function:
72230b57cec5SDimitry Andric     case Decl::ObjCMethod: {
72240b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
72250b57cec5SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
72260b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
72270b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
72280b57cec5SDimitry Andric       break;
72290b57cec5SDimitry Andric     }
72300b57cec5SDimitry Andric     case Decl::CXXConstructor: {
72310b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
72320b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
72330b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
72340b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
72350b57cec5SDimitry Andric       break;
72360b57cec5SDimitry Andric     }
72370b57cec5SDimitry Andric     case Decl::CXXDestructor: {
72380b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
72390b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
72400b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
72410b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
72420b57cec5SDimitry Andric       break;
72430b57cec5SDimitry Andric     }
72440b57cec5SDimitry Andric     default:
72450b57cec5SDimitry Andric       break;
72460b57cec5SDimitry Andric     };
72470b57cec5SDimitry Andric   }
72480b57cec5SDimitry Andric }
72490b57cec5SDimitry Andric 
72505ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() {
72515ffd83dbSDimitry Andric   // In order to transition away from "__original_main" gracefully, emit an
72525ffd83dbSDimitry Andric   // alias for "main" in the no-argument case so that libc can detect when
72535ffd83dbSDimitry Andric   // new-style no-argument main is in used.
72545ffd83dbSDimitry Andric   if (llvm::Function *F = getModule().getFunction("main")) {
72555ffd83dbSDimitry Andric     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
725681ad6265SDimitry Andric         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
725781ad6265SDimitry Andric       auto *GA = llvm::GlobalAlias::create("__main_void", F);
725881ad6265SDimitry Andric       GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
725981ad6265SDimitry Andric     }
72605ffd83dbSDimitry Andric   }
72615ffd83dbSDimitry Andric }
72625ffd83dbSDimitry Andric 
72630b57cec5SDimitry Andric /// Turns the given pointer into a constant.
72640b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
72650b57cec5SDimitry Andric                                           const void *Ptr) {
72660b57cec5SDimitry Andric   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
72670b57cec5SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
72680b57cec5SDimitry Andric   return llvm::ConstantInt::get(i64, PtrInt);
72690b57cec5SDimitry Andric }
72700b57cec5SDimitry Andric 
72710b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
72720b57cec5SDimitry Andric                                    llvm::NamedMDNode *&GlobalMetadata,
72730b57cec5SDimitry Andric                                    GlobalDecl D,
72740b57cec5SDimitry Andric                                    llvm::GlobalValue *Addr) {
72750b57cec5SDimitry Andric   if (!GlobalMetadata)
72760b57cec5SDimitry Andric     GlobalMetadata =
72770b57cec5SDimitry Andric       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
72780b57cec5SDimitry Andric 
72790b57cec5SDimitry Andric   // TODO: should we report variant information for ctors/dtors?
72800b57cec5SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
72810b57cec5SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
72820b57cec5SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
72830b57cec5SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
72840b57cec5SDimitry Andric }
72850b57cec5SDimitry Andric 
728681ad6265SDimitry Andric bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
728781ad6265SDimitry Andric                                                  llvm::GlobalValue *CppFunc) {
728881ad6265SDimitry Andric   // Store the list of ifuncs we need to replace uses in.
728981ad6265SDimitry Andric   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
729081ad6265SDimitry Andric   // List of ConstantExprs that we should be able to delete when we're done
729181ad6265SDimitry Andric   // here.
729281ad6265SDimitry Andric   llvm::SmallVector<llvm::ConstantExpr *> CEs;
729381ad6265SDimitry Andric 
729481ad6265SDimitry Andric   // It isn't valid to replace the extern-C ifuncs if all we find is itself!
729581ad6265SDimitry Andric   if (Elem == CppFunc)
729681ad6265SDimitry Andric     return false;
729781ad6265SDimitry Andric 
729881ad6265SDimitry Andric   // First make sure that all users of this are ifuncs (or ifuncs via a
729981ad6265SDimitry Andric   // bitcast), and collect the list of ifuncs and CEs so we can work on them
730081ad6265SDimitry Andric   // later.
730181ad6265SDimitry Andric   for (llvm::User *User : Elem->users()) {
730281ad6265SDimitry Andric     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
730381ad6265SDimitry Andric     // ifunc directly. In any other case, just give up, as we don't know what we
730481ad6265SDimitry Andric     // could break by changing those.
730581ad6265SDimitry Andric     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
730681ad6265SDimitry Andric       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
730781ad6265SDimitry Andric         return false;
730881ad6265SDimitry Andric 
730981ad6265SDimitry Andric       for (llvm::User *CEUser : ConstExpr->users()) {
731081ad6265SDimitry Andric         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
731181ad6265SDimitry Andric           IFuncs.push_back(IFunc);
731281ad6265SDimitry Andric         } else {
731381ad6265SDimitry Andric           return false;
731481ad6265SDimitry Andric         }
731581ad6265SDimitry Andric       }
731681ad6265SDimitry Andric       CEs.push_back(ConstExpr);
731781ad6265SDimitry Andric     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
731881ad6265SDimitry Andric       IFuncs.push_back(IFunc);
731981ad6265SDimitry Andric     } else {
732081ad6265SDimitry Andric       // This user is one we don't know how to handle, so fail redirection. This
732181ad6265SDimitry Andric       // will result in an ifunc retaining a resolver name that will ultimately
732281ad6265SDimitry Andric       // fail to be resolved to a defined function.
732381ad6265SDimitry Andric       return false;
732481ad6265SDimitry Andric     }
732581ad6265SDimitry Andric   }
732681ad6265SDimitry Andric 
732781ad6265SDimitry Andric   // Now we know this is a valid case where we can do this alias replacement, we
732881ad6265SDimitry Andric   // need to remove all of the references to Elem (and the bitcasts!) so we can
732981ad6265SDimitry Andric   // delete it.
733081ad6265SDimitry Andric   for (llvm::GlobalIFunc *IFunc : IFuncs)
733181ad6265SDimitry Andric     IFunc->setResolver(nullptr);
733281ad6265SDimitry Andric   for (llvm::ConstantExpr *ConstExpr : CEs)
733381ad6265SDimitry Andric     ConstExpr->destroyConstant();
733481ad6265SDimitry Andric 
733581ad6265SDimitry Andric   // We should now be out of uses for the 'old' version of this function, so we
733681ad6265SDimitry Andric   // can erase it as well.
733781ad6265SDimitry Andric   Elem->eraseFromParent();
733881ad6265SDimitry Andric 
733981ad6265SDimitry Andric   for (llvm::GlobalIFunc *IFunc : IFuncs) {
734081ad6265SDimitry Andric     // The type of the resolver is always just a function-type that returns the
734181ad6265SDimitry Andric     // type of the IFunc, so create that here. If the type of the actual
734281ad6265SDimitry Andric     // resolver doesn't match, it just gets bitcast to the right thing.
734381ad6265SDimitry Andric     auto *ResolverTy =
734481ad6265SDimitry Andric         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
734581ad6265SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
734681ad6265SDimitry Andric         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
734781ad6265SDimitry Andric     IFunc->setResolver(Resolver);
734881ad6265SDimitry Andric   }
734981ad6265SDimitry Andric   return true;
735081ad6265SDimitry Andric }
735181ad6265SDimitry Andric 
73520b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked
73530b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
73540b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
73550b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
73560b57cec5SDimitry Andric /// same translation unit.
73570b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
73580b57cec5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
73590b57cec5SDimitry Andric     return;
73600b57cec5SDimitry Andric   for (auto &I : StaticExternCValues) {
73610fca6ea1SDimitry Andric     const IdentifierInfo *Name = I.first;
73620b57cec5SDimitry Andric     llvm::GlobalValue *Val = I.second;
736381ad6265SDimitry Andric 
736481ad6265SDimitry Andric     // If Val is null, that implies there were multiple declarations that each
736581ad6265SDimitry Andric     // had a claim to the unmangled name. In this case, generation of the alias
736681ad6265SDimitry Andric     // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
736781ad6265SDimitry Andric     if (!Val)
736881ad6265SDimitry Andric       break;
736981ad6265SDimitry Andric 
737081ad6265SDimitry Andric     llvm::GlobalValue *ExistingElem =
737181ad6265SDimitry Andric         getModule().getNamedValue(Name->getName());
737281ad6265SDimitry Andric 
737381ad6265SDimitry Andric     // If there is either not something already by this name, or we were able to
737481ad6265SDimitry Andric     // replace all uses from IFuncs, create the alias.
737581ad6265SDimitry Andric     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7376fe6060f1SDimitry Andric       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
73770b57cec5SDimitry Andric   }
73780b57cec5SDimitry Andric }
73790b57cec5SDimitry Andric 
73800b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
73810b57cec5SDimitry Andric                                              GlobalDecl &Result) const {
73820b57cec5SDimitry Andric   auto Res = Manglings.find(MangledName);
73830b57cec5SDimitry Andric   if (Res == Manglings.end())
73840b57cec5SDimitry Andric     return false;
73850b57cec5SDimitry Andric   Result = Res->getValue();
73860b57cec5SDimitry Andric   return true;
73870b57cec5SDimitry Andric }
73880b57cec5SDimitry Andric 
73890b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the
73900b57cec5SDimitry Andric /// current module with the Decls they came from.  This is useful for
73910b57cec5SDimitry Andric /// projects using IR gen as a subroutine.
73920b57cec5SDimitry Andric ///
73930b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly
73940b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata
73950b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'.
73960b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() {
73970b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
73980b57cec5SDimitry Andric 
73990b57cec5SDimitry Andric   for (auto &I : MangledDeclNames) {
74000b57cec5SDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
74010b57cec5SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
74020b57cec5SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
74030b57cec5SDimitry Andric     if (Addr)
74040b57cec5SDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
74050b57cec5SDimitry Andric   }
74060b57cec5SDimitry Andric }
74070b57cec5SDimitry Andric 
74080b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current
74090b57cec5SDimitry Andric /// function.
74100b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() {
74110b57cec5SDimitry Andric   if (LocalDeclMap.empty()) return;
74120b57cec5SDimitry Andric 
74130b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
74140b57cec5SDimitry Andric 
74150b57cec5SDimitry Andric   // Find the unique metadata ID for this name.
74160b57cec5SDimitry Andric   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
74170b57cec5SDimitry Andric 
74180b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
74190b57cec5SDimitry Andric 
74200b57cec5SDimitry Andric   for (auto &I : LocalDeclMap) {
74210b57cec5SDimitry Andric     const Decl *D = I.first;
74220fca6ea1SDimitry Andric     llvm::Value *Addr = I.second.emitRawPointer(*this);
74230b57cec5SDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
74240b57cec5SDimitry Andric       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
74250b57cec5SDimitry Andric       Alloca->setMetadata(
74260b57cec5SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
74270b57cec5SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
74280b57cec5SDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
74290b57cec5SDimitry Andric       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
74300b57cec5SDimitry Andric       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
74310b57cec5SDimitry Andric     }
74320b57cec5SDimitry Andric   }
74330b57cec5SDimitry Andric }
74340b57cec5SDimitry Andric 
74350b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
74360b57cec5SDimitry Andric   llvm::NamedMDNode *IdentMetadata =
74370b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
74380b57cec5SDimitry Andric   std::string Version = getClangFullVersion();
74390b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
74400b57cec5SDimitry Andric 
74410b57cec5SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
74420b57cec5SDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
74430b57cec5SDimitry Andric }
74440b57cec5SDimitry Andric 
74450b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
74460b57cec5SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
74470b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
74480b57cec5SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
74490b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
74500b57cec5SDimitry Andric 
74510b57cec5SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
74520b57cec5SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
74530b57cec5SDimitry Andric }
74540b57cec5SDimitry Andric 
74550b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() {
74560b57cec5SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
74570b57cec5SDimitry Andric   if (!CUNode)
74580b57cec5SDimitry Andric     return;
74590b57cec5SDimitry Andric 
74600b57cec5SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
74610b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
74620b57cec5SDimitry Andric   auto *CoverageDataFile =
74630b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
74640b57cec5SDimitry Andric   auto *CoverageNotesFile =
74650b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
74660b57cec5SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
74670b57cec5SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
74680b57cec5SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
74690b57cec5SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
74700b57cec5SDimitry Andric   }
74710b57cec5SDimitry Andric }
74720b57cec5SDimitry Andric 
74730b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
74740b57cec5SDimitry Andric                                                        bool ForEH) {
74750b57cec5SDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
74760b57cec5SDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
74770b57cec5SDimitry Andric   // and it's not for EH?
747806c3fb27SDimitry Andric   if (!shouldEmitRTTI(ForEH))
747906c3fb27SDimitry Andric     return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
74800b57cec5SDimitry Andric 
74810b57cec5SDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
74820b57cec5SDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
74830b57cec5SDimitry Andric     return ObjCRuntime->GetEHType(Ty);
74840b57cec5SDimitry Andric 
74850b57cec5SDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
74860b57cec5SDimitry Andric }
74870b57cec5SDimitry Andric 
74880b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
74890b57cec5SDimitry Andric   // Do not emit threadprivates in simd-only mode.
74900b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
74910b57cec5SDimitry Andric     return;
74920b57cec5SDimitry Andric   for (auto RefExpr : D->varlists()) {
74930b57cec5SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
74940b57cec5SDimitry Andric     bool PerformInit =
74950b57cec5SDimitry Andric         VD->getAnyInitializer() &&
74960b57cec5SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
74970b57cec5SDimitry Andric                                                         /*ForRef=*/false);
74980b57cec5SDimitry Andric 
749981ad6265SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD),
750081ad6265SDimitry Andric                  getTypes().ConvertTypeForMem(VD->getType()),
750181ad6265SDimitry Andric                  getContext().getDeclAlign(VD));
75020b57cec5SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
75030b57cec5SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
75040b57cec5SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
75050b57cec5SDimitry Andric   }
75060b57cec5SDimitry Andric }
75070b57cec5SDimitry Andric 
75080b57cec5SDimitry Andric llvm::Metadata *
75090b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
75100b57cec5SDimitry Andric                                             StringRef Suffix) {
75110eae32dcSDimitry Andric   if (auto *FnType = T->getAs<FunctionProtoType>())
75120eae32dcSDimitry Andric     T = getContext().getFunctionType(
75130eae32dcSDimitry Andric         FnType->getReturnType(), FnType->getParamTypes(),
75140eae32dcSDimitry Andric         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
75150eae32dcSDimitry Andric 
75160b57cec5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
75170b57cec5SDimitry Andric   if (InternalId)
75180b57cec5SDimitry Andric     return InternalId;
75190b57cec5SDimitry Andric 
75200b57cec5SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
75210b57cec5SDimitry Andric     std::string OutName;
75220b57cec5SDimitry Andric     llvm::raw_string_ostream Out(OutName);
75235f757f3fSDimitry Andric     getCXXABI().getMangleContext().mangleCanonicalTypeName(
752406c3fb27SDimitry Andric         T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
752506c3fb27SDimitry Andric 
752606c3fb27SDimitry Andric     if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
752706c3fb27SDimitry Andric       Out << ".normalized";
752806c3fb27SDimitry Andric 
75290b57cec5SDimitry Andric     Out << Suffix;
75300b57cec5SDimitry Andric 
75310b57cec5SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
75320b57cec5SDimitry Andric   } else {
75330b57cec5SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
75340b57cec5SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
75350b57cec5SDimitry Andric   }
75360b57cec5SDimitry Andric 
75370b57cec5SDimitry Andric   return InternalId;
75380b57cec5SDimitry Andric }
75390b57cec5SDimitry Andric 
75400b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
75410b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
75420b57cec5SDimitry Andric }
75430b57cec5SDimitry Andric 
75440b57cec5SDimitry Andric llvm::Metadata *
75450b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
75460b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
75470b57cec5SDimitry Andric }
75480b57cec5SDimitry Andric 
75490b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
75500b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
75510b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
75520b57cec5SDimitry Andric // 'void *'.
75530b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
75540b57cec5SDimitry Andric   if (!Ty->isPointerType())
75550b57cec5SDimitry Andric     return Ty;
75560b57cec5SDimitry Andric 
75570b57cec5SDimitry Andric   return Ctx.getPointerType(
75580b57cec5SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
75590b57cec5SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
75600b57cec5SDimitry Andric }
75610b57cec5SDimitry Andric 
75620b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
75630b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
75640b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
75650b57cec5SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
75660b57cec5SDimitry Andric     for (auto &Param : FnType->param_types())
75670b57cec5SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
75680b57cec5SDimitry Andric 
75690b57cec5SDimitry Andric     return Ctx.getFunctionType(
75700b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
75710b57cec5SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
75720b57cec5SDimitry Andric   }
75730b57cec5SDimitry Andric 
75740b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
75750b57cec5SDimitry Andric     return Ctx.getFunctionNoProtoType(
75760b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
75770b57cec5SDimitry Andric 
75780b57cec5SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
75790b57cec5SDimitry Andric }
75800b57cec5SDimitry Andric 
75810b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
75820b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
75830b57cec5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
75840b57cec5SDimitry Andric }
75850b57cec5SDimitry Andric 
75860b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
75870b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
75880b57cec5SDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
75890b57cec5SDimitry Andric   // is not in the trapping mode.
75900b57cec5SDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
75910b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
75920b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
75930b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
75940b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
75950b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
75960b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
75970b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
75980b57cec5SDimitry Andric }
75990b57cec5SDimitry Andric 
76000b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
76010b57cec5SDimitry Andric                                           CharUnits Offset,
76020b57cec5SDimitry Andric                                           const CXXRecordDecl *RD) {
76030b57cec5SDimitry Andric   llvm::Metadata *MD =
76040b57cec5SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
76050b57cec5SDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
76060b57cec5SDimitry Andric 
76070b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
76080b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
76090b57cec5SDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
76100b57cec5SDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
76110b57cec5SDimitry Andric 
76120b57cec5SDimitry Andric   if (NeedAllVtablesTypeId()) {
76130b57cec5SDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
76140b57cec5SDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
76150b57cec5SDimitry Andric   }
76160b57cec5SDimitry Andric }
76170b57cec5SDimitry Andric 
76180b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
76190b57cec5SDimitry Andric   if (!SanStats)
7620a7dea167SDimitry Andric     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
76210b57cec5SDimitry Andric 
76220b57cec5SDimitry Andric   return *SanStats;
76230b57cec5SDimitry Andric }
762423408297SDimitry Andric 
76250b57cec5SDimitry Andric llvm::Value *
76260b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
76270b57cec5SDimitry Andric                                                   CodeGenFunction &CGF) {
76280b57cec5SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
762923408297SDimitry Andric   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
763023408297SDimitry Andric   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7631fe6060f1SDimitry Andric   auto *Call = CGF.EmitRuntimeCall(
763223408297SDimitry Andric       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
763323408297SDimitry Andric   return Call;
76340b57cec5SDimitry Andric }
76355ffd83dbSDimitry Andric 
76365ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
76375ffd83dbSDimitry Andric     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
76385ffd83dbSDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
76395ffd83dbSDimitry Andric                                  /* forPointeeType= */ true);
76405ffd83dbSDimitry Andric }
76415ffd83dbSDimitry Andric 
76425ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
76435ffd83dbSDimitry Andric                                                  LValueBaseInfo *BaseInfo,
76445ffd83dbSDimitry Andric                                                  TBAAAccessInfo *TBAAInfo,
76455ffd83dbSDimitry Andric                                                  bool forPointeeType) {
76465ffd83dbSDimitry Andric   if (TBAAInfo)
76475ffd83dbSDimitry Andric     *TBAAInfo = getTBAAAccessInfo(T);
76485ffd83dbSDimitry Andric 
76495ffd83dbSDimitry Andric   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
76505ffd83dbSDimitry Andric   // that doesn't return the information we need to compute BaseInfo.
76515ffd83dbSDimitry Andric 
76525ffd83dbSDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
76535ffd83dbSDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
76545ffd83dbSDimitry Andric   // there's an expressivity gap here.
76555ffd83dbSDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
76565ffd83dbSDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
76575ffd83dbSDimitry Andric       if (BaseInfo)
76585ffd83dbSDimitry Andric         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
76595ffd83dbSDimitry Andric       return getContext().toCharUnitsFromBits(Align);
76605ffd83dbSDimitry Andric     }
76615ffd83dbSDimitry Andric   }
76625ffd83dbSDimitry Andric 
76635ffd83dbSDimitry Andric   bool AlignForArray = T->isArrayType();
76645ffd83dbSDimitry Andric 
76655ffd83dbSDimitry Andric   // Analyze the base element type, so we don't get confused by incomplete
76665ffd83dbSDimitry Andric   // array types.
76675ffd83dbSDimitry Andric   T = getContext().getBaseElementType(T);
76685ffd83dbSDimitry Andric 
76695ffd83dbSDimitry Andric   if (T->isIncompleteType()) {
76705ffd83dbSDimitry Andric     // We could try to replicate the logic from
76715ffd83dbSDimitry Andric     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
76725ffd83dbSDimitry Andric     // type is incomplete, so it's impossible to test. We could try to reuse
76735ffd83dbSDimitry Andric     // getTypeAlignIfKnown, but that doesn't return the information we need
76745ffd83dbSDimitry Andric     // to set BaseInfo.  So just ignore the possibility that the alignment is
76755ffd83dbSDimitry Andric     // greater than one.
76765ffd83dbSDimitry Andric     if (BaseInfo)
76775ffd83dbSDimitry Andric       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
76785ffd83dbSDimitry Andric     return CharUnits::One();
76795ffd83dbSDimitry Andric   }
76805ffd83dbSDimitry Andric 
76815ffd83dbSDimitry Andric   if (BaseInfo)
76825ffd83dbSDimitry Andric     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
76835ffd83dbSDimitry Andric 
76845ffd83dbSDimitry Andric   CharUnits Alignment;
7685e8d8bef9SDimitry Andric   const CXXRecordDecl *RD;
7686e8d8bef9SDimitry Andric   if (T.getQualifiers().hasUnaligned()) {
7687e8d8bef9SDimitry Andric     Alignment = CharUnits::One();
7688e8d8bef9SDimitry Andric   } else if (forPointeeType && !AlignForArray &&
7689e8d8bef9SDimitry Andric              (RD = T->getAsCXXRecordDecl())) {
76905ffd83dbSDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
76915ffd83dbSDimitry Andric     // base or a complete object, so we generally need to use the
76925ffd83dbSDimitry Andric     // non-virtual alignment.
76935ffd83dbSDimitry Andric     Alignment = getClassPointerAlignment(RD);
76945ffd83dbSDimitry Andric   } else {
76955ffd83dbSDimitry Andric     Alignment = getContext().getTypeAlignInChars(T);
76965ffd83dbSDimitry Andric   }
76975ffd83dbSDimitry Andric 
76985ffd83dbSDimitry Andric   // Cap to the global maximum type alignment unless the alignment
76995ffd83dbSDimitry Andric   // was somehow explicit on the type.
77005ffd83dbSDimitry Andric   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
77015ffd83dbSDimitry Andric     if (Alignment.getQuantity() > MaxAlign &&
77025ffd83dbSDimitry Andric         !getContext().isAlignmentRequired(T))
77035ffd83dbSDimitry Andric       Alignment = CharUnits::fromQuantity(MaxAlign);
77045ffd83dbSDimitry Andric   }
77055ffd83dbSDimitry Andric   return Alignment;
77065ffd83dbSDimitry Andric }
77075ffd83dbSDimitry Andric 
77085ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() {
77095ffd83dbSDimitry Andric   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
77105ffd83dbSDimitry Andric   if (StopAfter) {
77115ffd83dbSDimitry Andric     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
77125ffd83dbSDimitry Andric     // used
77135ffd83dbSDimitry Andric     if (NumAutoVarInit >= StopAfter) {
77145ffd83dbSDimitry Andric       return true;
77155ffd83dbSDimitry Andric     }
77165ffd83dbSDimitry Andric     if (!NumAutoVarInit) {
77175ffd83dbSDimitry Andric       unsigned DiagID = getDiags().getCustomDiagID(
77185ffd83dbSDimitry Andric           DiagnosticsEngine::Warning,
77195ffd83dbSDimitry Andric           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
77205ffd83dbSDimitry Andric           "number of times ftrivial-auto-var-init=%1 gets applied.");
77215ffd83dbSDimitry Andric       getDiags().Report(DiagID)
77225ffd83dbSDimitry Andric           << StopAfter
77235ffd83dbSDimitry Andric           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
77245ffd83dbSDimitry Andric                       LangOptions::TrivialAutoVarInitKind::Zero
77255ffd83dbSDimitry Andric                   ? "zero"
77265ffd83dbSDimitry Andric                   : "pattern");
77275ffd83dbSDimitry Andric     }
77285ffd83dbSDimitry Andric     ++NumAutoVarInit;
77295ffd83dbSDimitry Andric   }
77305ffd83dbSDimitry Andric   return false;
77315ffd83dbSDimitry Andric }
7732fe6060f1SDimitry Andric 
77332a66634dSDimitry Andric void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
77342a66634dSDimitry Andric                                                     const Decl *D) const {
77352a66634dSDimitry Andric   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
77362a66634dSDimitry Andric   // postfix beginning with '.' since the symbol name can be demangled.
77372a66634dSDimitry Andric   if (LangOpts.HIP)
773881ad6265SDimitry Andric     OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
77392a66634dSDimitry Andric   else
774081ad6265SDimitry Andric     OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
774181ad6265SDimitry Andric 
774281ad6265SDimitry Andric   // If the CUID is not specified we try to generate a unique postfix.
774381ad6265SDimitry Andric   if (getLangOpts().CUID.empty()) {
774481ad6265SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
774581ad6265SDimitry Andric     PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
774681ad6265SDimitry Andric     assert(PLoc.isValid() && "Source location is expected to be valid.");
774781ad6265SDimitry Andric 
774881ad6265SDimitry Andric     // Get the hash of the user defined macros.
774981ad6265SDimitry Andric     llvm::MD5 Hash;
775081ad6265SDimitry Andric     llvm::MD5::MD5Result Result;
775181ad6265SDimitry Andric     for (const auto &Arg : PreprocessorOpts.Macros)
775281ad6265SDimitry Andric       Hash.update(Arg.first);
775381ad6265SDimitry Andric     Hash.final(Result);
775481ad6265SDimitry Andric 
775581ad6265SDimitry Andric     // Get the UniqueID for the file containing the decl.
775681ad6265SDimitry Andric     llvm::sys::fs::UniqueID ID;
77575f757f3fSDimitry Andric     if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
775881ad6265SDimitry Andric       PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
775981ad6265SDimitry Andric       assert(PLoc.isValid() && "Source location is expected to be valid.");
776081ad6265SDimitry Andric       if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
776181ad6265SDimitry Andric         SM.getDiagnostics().Report(diag::err_cannot_open_file)
776281ad6265SDimitry Andric             << PLoc.getFilename() << EC.message();
776381ad6265SDimitry Andric     }
776481ad6265SDimitry Andric     OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
776581ad6265SDimitry Andric        << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
776681ad6265SDimitry Andric   } else {
776781ad6265SDimitry Andric     OS << getContext().getCUIDHash();
776881ad6265SDimitry Andric   }
7769fe6060f1SDimitry Andric }
7770fcaf7f86SDimitry Andric 
7771fcaf7f86SDimitry Andric void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7772fcaf7f86SDimitry Andric   assert(DeferredDeclsToEmit.empty() &&
7773fcaf7f86SDimitry Andric          "Should have emitted all decls deferred to emit.");
7774fcaf7f86SDimitry Andric   assert(NewBuilder->DeferredDecls.empty() &&
7775fcaf7f86SDimitry Andric          "Newly created module should not have deferred decls");
7776fcaf7f86SDimitry Andric   NewBuilder->DeferredDecls = std::move(DeferredDecls);
77775f757f3fSDimitry Andric   assert(EmittedDeferredDecls.empty() &&
77785f757f3fSDimitry Andric          "Still have (unmerged) EmittedDeferredDecls deferred decls");
7779fcaf7f86SDimitry Andric 
7780fcaf7f86SDimitry Andric   assert(NewBuilder->DeferredVTables.empty() &&
7781fcaf7f86SDimitry Andric          "Newly created module should not have deferred vtables");
7782fcaf7f86SDimitry Andric   NewBuilder->DeferredVTables = std::move(DeferredVTables);
7783fcaf7f86SDimitry Andric 
7784fcaf7f86SDimitry Andric   assert(NewBuilder->MangledDeclNames.empty() &&
7785fcaf7f86SDimitry Andric          "Newly created module should not have mangled decl names");
7786fcaf7f86SDimitry Andric   assert(NewBuilder->Manglings.empty() &&
7787fcaf7f86SDimitry Andric          "Newly created module should not have manglings");
7788fcaf7f86SDimitry Andric   NewBuilder->Manglings = std::move(Manglings);
7789fcaf7f86SDimitry Andric 
7790fcaf7f86SDimitry Andric   NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7791fcaf7f86SDimitry Andric 
7792972a253aSDimitry Andric   NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
7793fcaf7f86SDimitry Andric }
7794