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