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