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