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