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