xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 7c51f02effdbd0d5e12bfd26f9c3b2ab5687c93f)
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::Override, "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::Override, "cf-protection-branch",
754                               1);
755   }
756 
757   if (CodeGenOpts.IBTSeal)
758     getModule().addModuleFlag(llvm::Module::Override, "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 (const auto *TD = ty->getAs<TypedefType>())
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.
2784   if (Loc.isValid())
2785     return NoSanitizeL.containsLocation(Kind, Loc);
2786   // If location is unknown, this may be a compiler-generated function. Assume
2787   // it's located in the main file.
2788   auto &SM = Context.getSourceManager();
2789   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2790     return NoSanitizeL.containsFile(Kind, MainFile->getName());
2791   }
2792   return false;
2793 }
2794 
2795 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
2796                                        llvm::GlobalVariable *GV,
2797                                        SourceLocation Loc, QualType Ty,
2798                                        StringRef Category) const {
2799   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2800   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
2801     return true;
2802   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
2803     return true;
2804   // Check global type.
2805   if (!Ty.isNull()) {
2806     // Drill down the array types: if global variable of a fixed type is
2807     // not sanitized, we also don't instrument arrays of them.
2808     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2809       Ty = AT->getElementType();
2810     Ty = Ty.getCanonicalType().getUnqualifiedType();
2811     // Only record types (classes, structs etc.) are ignored.
2812     if (Ty->isRecordType()) {
2813       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2814       if (NoSanitizeL.containsType(Kind, TypeStr, Category))
2815         return true;
2816     }
2817   }
2818   return false;
2819 }
2820 
2821 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2822                                    StringRef Category) const {
2823   const auto &XRayFilter = getContext().getXRayFilter();
2824   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2825   auto Attr = ImbueAttr::NONE;
2826   if (Loc.isValid())
2827     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2828   if (Attr == ImbueAttr::NONE)
2829     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2830   switch (Attr) {
2831   case ImbueAttr::NONE:
2832     return false;
2833   case ImbueAttr::ALWAYS:
2834     Fn->addFnAttr("function-instrument", "xray-always");
2835     break;
2836   case ImbueAttr::ALWAYS_ARG1:
2837     Fn->addFnAttr("function-instrument", "xray-always");
2838     Fn->addFnAttr("xray-log-args", "1");
2839     break;
2840   case ImbueAttr::NEVER:
2841     Fn->addFnAttr("function-instrument", "xray-never");
2842     break;
2843   }
2844   return true;
2845 }
2846 
2847 bool CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
2848                                                    SourceLocation Loc) const {
2849   const auto &ProfileList = getContext().getProfileList();
2850   // If the profile list is empty, then instrument everything.
2851   if (ProfileList.isEmpty())
2852     return false;
2853   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
2854   // First, check the function name.
2855   Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
2856   if (V)
2857     return *V;
2858   // Next, check the source location.
2859   if (Loc.isValid()) {
2860     Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
2861     if (V)
2862       return *V;
2863   }
2864   // If location is unknown, this may be a compiler-generated function. Assume
2865   // it's located in the main file.
2866   auto &SM = Context.getSourceManager();
2867   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2868     Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
2869     if (V)
2870       return *V;
2871   }
2872   return ProfileList.getDefault();
2873 }
2874 
2875 bool CodeGenModule::isFunctionBlockedFromProfileInstr(
2876     llvm::Function *Fn, SourceLocation Loc) const {
2877   if (isFunctionBlockedByProfileList(Fn, Loc))
2878     return true;
2879 
2880   auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
2881   if (NumGroups > 1) {
2882     auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
2883     if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
2884       return true;
2885   }
2886   return false;
2887 }
2888 
2889 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2890   // Never defer when EmitAllDecls is specified.
2891   if (LangOpts.EmitAllDecls)
2892     return true;
2893 
2894   if (CodeGenOpts.KeepStaticConsts) {
2895     const auto *VD = dyn_cast<VarDecl>(Global);
2896     if (VD && VD->getType().isConstQualified() &&
2897         VD->getStorageDuration() == SD_Static)
2898       return true;
2899   }
2900 
2901   return getContext().DeclMustBeEmitted(Global);
2902 }
2903 
2904 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2905   // In OpenMP 5.0 variables and function may be marked as
2906   // device_type(host/nohost) and we should not emit them eagerly unless we sure
2907   // that they must be emitted on the host/device. To be sure we need to have
2908   // seen a declare target with an explicit mentioning of the function, we know
2909   // we have if the level of the declare target attribute is -1. Note that we
2910   // check somewhere else if we should emit this at all.
2911   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
2912     llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
2913         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
2914     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
2915       return false;
2916   }
2917 
2918   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2919     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2920       // Implicit template instantiations may change linkage if they are later
2921       // explicitly instantiated, so they should not be emitted eagerly.
2922       return false;
2923   }
2924   if (const auto *VD = dyn_cast<VarDecl>(Global))
2925     if (Context.getInlineVariableDefinitionKind(VD) ==
2926         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2927       // A definition of an inline constexpr static data member may change
2928       // linkage later if it's redeclared outside the class.
2929       return false;
2930   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2931   // codegen for global variables, because they may be marked as threadprivate.
2932   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2933       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2934       !isTypeConstant(Global->getType(), false) &&
2935       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2936     return false;
2937 
2938   return true;
2939 }
2940 
2941 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2942   StringRef Name = getMangledName(GD);
2943 
2944   // The UUID descriptor should be pointer aligned.
2945   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2946 
2947   // Look for an existing global.
2948   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2949     return ConstantAddress(GV, GV->getValueType(), Alignment);
2950 
2951   ConstantEmitter Emitter(*this);
2952   llvm::Constant *Init;
2953 
2954   APValue &V = GD->getAsAPValue();
2955   if (!V.isAbsent()) {
2956     // If possible, emit the APValue version of the initializer. In particular,
2957     // this gets the type of the constant right.
2958     Init = Emitter.emitForInitializer(
2959         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2960   } else {
2961     // As a fallback, directly construct the constant.
2962     // FIXME: This may get padding wrong under esoteric struct layout rules.
2963     // MSVC appears to create a complete type 'struct __s_GUID' that it
2964     // presumably uses to represent these constants.
2965     MSGuidDecl::Parts Parts = GD->getParts();
2966     llvm::Constant *Fields[4] = {
2967         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2968         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2969         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2970         llvm::ConstantDataArray::getRaw(
2971             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2972             Int8Ty)};
2973     Init = llvm::ConstantStruct::getAnon(Fields);
2974   }
2975 
2976   auto *GV = new llvm::GlobalVariable(
2977       getModule(), Init->getType(),
2978       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2979   if (supportsCOMDAT())
2980     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2981   setDSOLocal(GV);
2982 
2983   if (!V.isAbsent()) {
2984     Emitter.finalize(GV);
2985     return ConstantAddress(GV, GV->getValueType(), Alignment);
2986   }
2987 
2988   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2989   llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
2990       GV, Ty->getPointerTo(GV->getAddressSpace()));
2991   return ConstantAddress(Addr, Ty, Alignment);
2992 }
2993 
2994 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
2995     const UnnamedGlobalConstantDecl *GCD) {
2996   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
2997 
2998   llvm::GlobalVariable **Entry = nullptr;
2999   Entry = &UnnamedGlobalConstantDeclMap[GCD];
3000   if (*Entry)
3001     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3002 
3003   ConstantEmitter Emitter(*this);
3004   llvm::Constant *Init;
3005 
3006   const APValue &V = GCD->getValue();
3007 
3008   assert(!V.isAbsent());
3009   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3010                                     GCD->getType());
3011 
3012   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3013                                       /*isConstant=*/true,
3014                                       llvm::GlobalValue::PrivateLinkage, Init,
3015                                       ".constant");
3016   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3017   GV->setAlignment(Alignment.getAsAlign());
3018 
3019   Emitter.finalize(GV);
3020 
3021   *Entry = GV;
3022   return ConstantAddress(GV, GV->getValueType(), Alignment);
3023 }
3024 
3025 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3026     const TemplateParamObjectDecl *TPO) {
3027   StringRef Name = getMangledName(TPO);
3028   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3029 
3030   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3031     return ConstantAddress(GV, GV->getValueType(), Alignment);
3032 
3033   ConstantEmitter Emitter(*this);
3034   llvm::Constant *Init = Emitter.emitForInitializer(
3035         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3036 
3037   if (!Init) {
3038     ErrorUnsupported(TPO, "template parameter object");
3039     return ConstantAddress::invalid();
3040   }
3041 
3042   auto *GV = new llvm::GlobalVariable(
3043       getModule(), Init->getType(),
3044       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3045   if (supportsCOMDAT())
3046     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3047   Emitter.finalize(GV);
3048 
3049   return ConstantAddress(GV, GV->getValueType(), Alignment);
3050 }
3051 
3052 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
3053   const AliasAttr *AA = VD->getAttr<AliasAttr>();
3054   assert(AA && "No alias?");
3055 
3056   CharUnits Alignment = getContext().getDeclAlign(VD);
3057   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3058 
3059   // See if there is already something with the target's name in the module.
3060   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3061   if (Entry) {
3062     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
3063     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
3064     return ConstantAddress(Ptr, DeclTy, Alignment);
3065   }
3066 
3067   llvm::Constant *Aliasee;
3068   if (isa<llvm::FunctionType>(DeclTy))
3069     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3070                                       GlobalDecl(cast<FunctionDecl>(VD)),
3071                                       /*ForVTable=*/false);
3072   else
3073     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3074                                     nullptr);
3075 
3076   auto *F = cast<llvm::GlobalValue>(Aliasee);
3077   F->setLinkage(llvm::Function::ExternalWeakLinkage);
3078   WeakRefReferences.insert(F);
3079 
3080   return ConstantAddress(Aliasee, DeclTy, Alignment);
3081 }
3082 
3083 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3084   const auto *Global = cast<ValueDecl>(GD.getDecl());
3085 
3086   // Weak references don't produce any output by themselves.
3087   if (Global->hasAttr<WeakRefAttr>())
3088     return;
3089 
3090   // If this is an alias definition (which otherwise looks like a declaration)
3091   // emit it now.
3092   if (Global->hasAttr<AliasAttr>())
3093     return EmitAliasDefinition(GD);
3094 
3095   // IFunc like an alias whose value is resolved at runtime by calling resolver.
3096   if (Global->hasAttr<IFuncAttr>())
3097     return emitIFuncDefinition(GD);
3098 
3099   // If this is a cpu_dispatch multiversion function, emit the resolver.
3100   if (Global->hasAttr<CPUDispatchAttr>())
3101     return emitCPUDispatchDefinition(GD);
3102 
3103   // If this is CUDA, be selective about which declarations we emit.
3104   if (LangOpts.CUDA) {
3105     if (LangOpts.CUDAIsDevice) {
3106       if (!Global->hasAttr<CUDADeviceAttr>() &&
3107           !Global->hasAttr<CUDAGlobalAttr>() &&
3108           !Global->hasAttr<CUDAConstantAttr>() &&
3109           !Global->hasAttr<CUDASharedAttr>() &&
3110           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3111           !Global->getType()->isCUDADeviceBuiltinTextureType())
3112         return;
3113     } else {
3114       // We need to emit host-side 'shadows' for all global
3115       // device-side variables because the CUDA runtime needs their
3116       // size and host-side address in order to provide access to
3117       // their device-side incarnations.
3118 
3119       // So device-only functions are the only things we skip.
3120       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
3121           Global->hasAttr<CUDADeviceAttr>())
3122         return;
3123 
3124       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3125              "Expected Variable or Function");
3126     }
3127   }
3128 
3129   if (LangOpts.OpenMP) {
3130     // If this is OpenMP, check if it is legal to emit this global normally.
3131     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3132       return;
3133     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3134       if (MustBeEmitted(Global))
3135         EmitOMPDeclareReduction(DRD);
3136       return;
3137     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3138       if (MustBeEmitted(Global))
3139         EmitOMPDeclareMapper(DMD);
3140       return;
3141     }
3142   }
3143 
3144   // Ignore declarations, they will be emitted on their first use.
3145   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3146     // Forward declarations are emitted lazily on first use.
3147     if (!FD->doesThisDeclarationHaveABody()) {
3148       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
3149         return;
3150 
3151       StringRef MangledName = getMangledName(GD);
3152 
3153       // Compute the function info and LLVM type.
3154       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3155       llvm::Type *Ty = getTypes().GetFunctionType(FI);
3156 
3157       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3158                               /*DontDefer=*/false);
3159       return;
3160     }
3161   } else {
3162     const auto *VD = cast<VarDecl>(Global);
3163     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3164     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3165         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3166       if (LangOpts.OpenMP) {
3167         // Emit declaration of the must-be-emitted declare target variable.
3168         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3169                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3170           bool UnifiedMemoryEnabled =
3171               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3172           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
3173               !UnifiedMemoryEnabled) {
3174             (void)GetAddrOfGlobalVar(VD);
3175           } else {
3176             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3177                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
3178                      UnifiedMemoryEnabled)) &&
3179                    "Link clause or to clause with unified memory expected.");
3180             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3181           }
3182 
3183           return;
3184         }
3185       }
3186       // If this declaration may have caused an inline variable definition to
3187       // change linkage, make sure that it's emitted.
3188       if (Context.getInlineVariableDefinitionKind(VD) ==
3189           ASTContext::InlineVariableDefinitionKind::Strong)
3190         GetAddrOfGlobalVar(VD);
3191       return;
3192     }
3193   }
3194 
3195   // Defer code generation to first use when possible, e.g. if this is an inline
3196   // function. If the global must always be emitted, do it eagerly if possible
3197   // to benefit from cache locality.
3198   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3199     // Emit the definition if it can't be deferred.
3200     EmitGlobalDefinition(GD);
3201     return;
3202   }
3203 
3204   // If we're deferring emission of a C++ variable with an
3205   // initializer, remember the order in which it appeared in the file.
3206   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3207       cast<VarDecl>(Global)->hasInit()) {
3208     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3209     CXXGlobalInits.push_back(nullptr);
3210   }
3211 
3212   StringRef MangledName = getMangledName(GD);
3213   if (GetGlobalValue(MangledName) != nullptr) {
3214     // The value has already been used and should therefore be emitted.
3215     addDeferredDeclToEmit(GD);
3216   } else if (MustBeEmitted(Global)) {
3217     // The value must be emitted, but cannot be emitted eagerly.
3218     assert(!MayBeEmittedEagerly(Global));
3219     addDeferredDeclToEmit(GD);
3220   } else {
3221     // Otherwise, remember that we saw a deferred decl with this name.  The
3222     // first use of the mangled name will cause it to move into
3223     // DeferredDeclsToEmit.
3224     DeferredDecls[MangledName] = GD;
3225   }
3226 }
3227 
3228 // Check if T is a class type with a destructor that's not dllimport.
3229 static bool HasNonDllImportDtor(QualType T) {
3230   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3231     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3232       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3233         return true;
3234 
3235   return false;
3236 }
3237 
3238 namespace {
3239   struct FunctionIsDirectlyRecursive
3240       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3241     const StringRef Name;
3242     const Builtin::Context &BI;
3243     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3244         : Name(N), BI(C) {}
3245 
3246     bool VisitCallExpr(const CallExpr *E) {
3247       const FunctionDecl *FD = E->getDirectCallee();
3248       if (!FD)
3249         return false;
3250       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3251       if (Attr && Name == Attr->getLabel())
3252         return true;
3253       unsigned BuiltinID = FD->getBuiltinID();
3254       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3255         return false;
3256       StringRef BuiltinName = BI.getName(BuiltinID);
3257       if (BuiltinName.startswith("__builtin_") &&
3258           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3259         return true;
3260       }
3261       return false;
3262     }
3263 
3264     bool VisitStmt(const Stmt *S) {
3265       for (const Stmt *Child : S->children())
3266         if (Child && this->Visit(Child))
3267           return true;
3268       return false;
3269     }
3270   };
3271 
3272   // Make sure we're not referencing non-imported vars or functions.
3273   struct DLLImportFunctionVisitor
3274       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3275     bool SafeToInline = true;
3276 
3277     bool shouldVisitImplicitCode() const { return true; }
3278 
3279     bool VisitVarDecl(VarDecl *VD) {
3280       if (VD->getTLSKind()) {
3281         // A thread-local variable cannot be imported.
3282         SafeToInline = false;
3283         return SafeToInline;
3284       }
3285 
3286       // A variable definition might imply a destructor call.
3287       if (VD->isThisDeclarationADefinition())
3288         SafeToInline = !HasNonDllImportDtor(VD->getType());
3289 
3290       return SafeToInline;
3291     }
3292 
3293     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3294       if (const auto *D = E->getTemporary()->getDestructor())
3295         SafeToInline = D->hasAttr<DLLImportAttr>();
3296       return SafeToInline;
3297     }
3298 
3299     bool VisitDeclRefExpr(DeclRefExpr *E) {
3300       ValueDecl *VD = E->getDecl();
3301       if (isa<FunctionDecl>(VD))
3302         SafeToInline = VD->hasAttr<DLLImportAttr>();
3303       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3304         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3305       return SafeToInline;
3306     }
3307 
3308     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3309       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3310       return SafeToInline;
3311     }
3312 
3313     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3314       CXXMethodDecl *M = E->getMethodDecl();
3315       if (!M) {
3316         // Call through a pointer to member function. This is safe to inline.
3317         SafeToInline = true;
3318       } else {
3319         SafeToInline = M->hasAttr<DLLImportAttr>();
3320       }
3321       return SafeToInline;
3322     }
3323 
3324     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3325       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3326       return SafeToInline;
3327     }
3328 
3329     bool VisitCXXNewExpr(CXXNewExpr *E) {
3330       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3331       return SafeToInline;
3332     }
3333   };
3334 }
3335 
3336 // isTriviallyRecursive - Check if this function calls another
3337 // decl that, because of the asm attribute or the other decl being a builtin,
3338 // ends up pointing to itself.
3339 bool
3340 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3341   StringRef Name;
3342   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3343     // asm labels are a special kind of mangling we have to support.
3344     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3345     if (!Attr)
3346       return false;
3347     Name = Attr->getLabel();
3348   } else {
3349     Name = FD->getName();
3350   }
3351 
3352   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3353   const Stmt *Body = FD->getBody();
3354   return Body ? Walker.Visit(Body) : false;
3355 }
3356 
3357 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3358   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3359     return true;
3360   const auto *F = cast<FunctionDecl>(GD.getDecl());
3361   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3362     return false;
3363 
3364   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3365     // Check whether it would be safe to inline this dllimport function.
3366     DLLImportFunctionVisitor Visitor;
3367     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3368     if (!Visitor.SafeToInline)
3369       return false;
3370 
3371     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3372       // Implicit destructor invocations aren't captured in the AST, so the
3373       // check above can't see them. Check for them manually here.
3374       for (const Decl *Member : Dtor->getParent()->decls())
3375         if (isa<FieldDecl>(Member))
3376           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3377             return false;
3378       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3379         if (HasNonDllImportDtor(B.getType()))
3380           return false;
3381     }
3382   }
3383 
3384   // Inline builtins declaration must be emitted. They often are fortified
3385   // functions.
3386   if (F->isInlineBuiltinDeclaration())
3387     return true;
3388 
3389   // PR9614. Avoid cases where the source code is lying to us. An available
3390   // externally function should have an equivalent function somewhere else,
3391   // but a function that calls itself through asm label/`__builtin_` trickery is
3392   // clearly not equivalent to the real implementation.
3393   // This happens in glibc's btowc and in some configure checks.
3394   return !isTriviallyRecursive(F);
3395 }
3396 
3397 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3398   return CodeGenOpts.OptimizationLevel > 0;
3399 }
3400 
3401 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3402                                                        llvm::GlobalValue *GV) {
3403   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3404 
3405   if (FD->isCPUSpecificMultiVersion()) {
3406     auto *Spec = FD->getAttr<CPUSpecificAttr>();
3407     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3408       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3409   } else if (FD->isTargetClonesMultiVersion()) {
3410     auto *Clone = FD->getAttr<TargetClonesAttr>();
3411     for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
3412       if (Clone->isFirstOfVersion(I))
3413         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3414     // Ensure that the resolver function is also emitted.
3415     GetOrCreateMultiVersionResolver(GD);
3416   } else
3417     EmitGlobalFunctionDefinition(GD, GV);
3418 }
3419 
3420 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3421   const auto *D = cast<ValueDecl>(GD.getDecl());
3422 
3423   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3424                                  Context.getSourceManager(),
3425                                  "Generating code for declaration");
3426 
3427   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3428     // At -O0, don't generate IR for functions with available_externally
3429     // linkage.
3430     if (!shouldEmitFunction(GD))
3431       return;
3432 
3433     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3434       std::string Name;
3435       llvm::raw_string_ostream OS(Name);
3436       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3437                                /*Qualified=*/true);
3438       return Name;
3439     });
3440 
3441     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3442       // Make sure to emit the definition(s) before we emit the thunks.
3443       // This is necessary for the generation of certain thunks.
3444       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3445         ABI->emitCXXStructor(GD);
3446       else if (FD->isMultiVersion())
3447         EmitMultiVersionFunctionDefinition(GD, GV);
3448       else
3449         EmitGlobalFunctionDefinition(GD, GV);
3450 
3451       if (Method->isVirtual())
3452         getVTables().EmitThunks(GD);
3453 
3454       return;
3455     }
3456 
3457     if (FD->isMultiVersion())
3458       return EmitMultiVersionFunctionDefinition(GD, GV);
3459     return EmitGlobalFunctionDefinition(GD, GV);
3460   }
3461 
3462   if (const auto *VD = dyn_cast<VarDecl>(D))
3463     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3464 
3465   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
3466 }
3467 
3468 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3469                                                       llvm::Function *NewFn);
3470 
3471 static unsigned
3472 TargetMVPriority(const TargetInfo &TI,
3473                  const CodeGenFunction::MultiVersionResolverOption &RO) {
3474   unsigned Priority = 0;
3475   for (StringRef Feat : RO.Conditions.Features)
3476     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3477 
3478   if (!RO.Conditions.Architecture.empty())
3479     Priority = std::max(
3480         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3481   return Priority;
3482 }
3483 
3484 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
3485 // TU can forward declare the function without causing problems.  Particularly
3486 // in the cases of CPUDispatch, this causes issues. This also makes sure we
3487 // work with internal linkage functions, so that the same function name can be
3488 // used with internal linkage in multiple TUs.
3489 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
3490                                                        GlobalDecl GD) {
3491   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3492   if (FD->getFormalLinkage() == InternalLinkage)
3493     return llvm::GlobalValue::InternalLinkage;
3494   return llvm::GlobalValue::WeakODRLinkage;
3495 }
3496 
3497 void CodeGenModule::emitMultiVersionFunctions() {
3498   std::vector<GlobalDecl> MVFuncsToEmit;
3499   MultiVersionFuncs.swap(MVFuncsToEmit);
3500   for (GlobalDecl GD : MVFuncsToEmit) {
3501     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3502     assert(FD && "Expected a FunctionDecl");
3503 
3504     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3505     if (FD->isTargetMultiVersion()) {
3506       getContext().forEachMultiversionedFunctionVersion(
3507           FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3508             GlobalDecl CurGD{
3509                 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3510             StringRef MangledName = getMangledName(CurGD);
3511             llvm::Constant *Func = GetGlobalValue(MangledName);
3512             if (!Func) {
3513               if (CurFD->isDefined()) {
3514                 EmitGlobalFunctionDefinition(CurGD, nullptr);
3515                 Func = GetGlobalValue(MangledName);
3516               } else {
3517                 const CGFunctionInfo &FI =
3518                     getTypes().arrangeGlobalDeclaration(GD);
3519                 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3520                 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3521                                          /*DontDefer=*/false, ForDefinition);
3522               }
3523               assert(Func && "This should have just been created");
3524             }
3525 
3526             const auto *TA = CurFD->getAttr<TargetAttr>();
3527             llvm::SmallVector<StringRef, 8> Feats;
3528             TA->getAddedFeatures(Feats);
3529 
3530             Options.emplace_back(cast<llvm::Function>(Func),
3531                                  TA->getArchitecture(), Feats);
3532           });
3533     } else if (FD->isTargetClonesMultiVersion()) {
3534       const auto *TC = FD->getAttr<TargetClonesAttr>();
3535       for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
3536            ++VersionIndex) {
3537         if (!TC->isFirstOfVersion(VersionIndex))
3538           continue;
3539         GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
3540                          VersionIndex};
3541         StringRef Version = TC->getFeatureStr(VersionIndex);
3542         StringRef MangledName = getMangledName(CurGD);
3543         llvm::Constant *Func = GetGlobalValue(MangledName);
3544         if (!Func) {
3545           if (FD->isDefined()) {
3546             EmitGlobalFunctionDefinition(CurGD, nullptr);
3547             Func = GetGlobalValue(MangledName);
3548           } else {
3549             const CGFunctionInfo &FI =
3550                 getTypes().arrangeGlobalDeclaration(CurGD);
3551             llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3552             Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3553                                      /*DontDefer=*/false, ForDefinition);
3554           }
3555           assert(Func && "This should have just been created");
3556         }
3557 
3558         StringRef Architecture;
3559         llvm::SmallVector<StringRef, 1> Feature;
3560 
3561         if (Version.startswith("arch="))
3562           Architecture = Version.drop_front(sizeof("arch=") - 1);
3563         else if (Version != "default")
3564           Feature.push_back(Version);
3565 
3566         Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
3567       }
3568     } else {
3569       assert(0 && "Expected a target or target_clones multiversion function");
3570       continue;
3571     }
3572 
3573     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
3574     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant))
3575       ResolverConstant = IFunc->getResolver();
3576     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
3577 
3578     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
3579 
3580     if (supportsCOMDAT())
3581       ResolverFunc->setComdat(
3582           getModule().getOrInsertComdat(ResolverFunc->getName()));
3583 
3584     const TargetInfo &TI = getTarget();
3585     llvm::stable_sort(
3586         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3587                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
3588           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3589         });
3590     CodeGenFunction CGF(*this);
3591     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3592   }
3593 
3594   // Ensure that any additions to the deferred decls list caused by emitting a
3595   // variant are emitted.  This can happen when the variant itself is inline and
3596   // calls a function without linkage.
3597   if (!MVFuncsToEmit.empty())
3598     EmitDeferred();
3599 
3600   // Ensure that any additions to the multiversion funcs list from either the
3601   // deferred decls or the multiversion functions themselves are emitted.
3602   if (!MultiVersionFuncs.empty())
3603     emitMultiVersionFunctions();
3604 }
3605 
3606 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3607   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3608   assert(FD && "Not a FunctionDecl?");
3609   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
3610   const auto *DD = FD->getAttr<CPUDispatchAttr>();
3611   assert(DD && "Not a cpu_dispatch Function?");
3612 
3613   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3614   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
3615 
3616   StringRef ResolverName = getMangledName(GD);
3617   UpdateMultiVersionNames(GD, FD, ResolverName);
3618 
3619   llvm::Type *ResolverType;
3620   GlobalDecl ResolverGD;
3621   if (getTarget().supportsIFunc()) {
3622     ResolverType = llvm::FunctionType::get(
3623         llvm::PointerType::get(DeclTy,
3624                                Context.getTargetAddressSpace(FD->getType())),
3625         false);
3626   }
3627   else {
3628     ResolverType = DeclTy;
3629     ResolverGD = GD;
3630   }
3631 
3632   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3633       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3634   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
3635   if (supportsCOMDAT())
3636     ResolverFunc->setComdat(
3637         getModule().getOrInsertComdat(ResolverFunc->getName()));
3638 
3639   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3640   const TargetInfo &Target = getTarget();
3641   unsigned Index = 0;
3642   for (const IdentifierInfo *II : DD->cpus()) {
3643     // Get the name of the target function so we can look it up/create it.
3644     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3645                               getCPUSpecificMangling(*this, II->getName());
3646 
3647     llvm::Constant *Func = GetGlobalValue(MangledName);
3648 
3649     if (!Func) {
3650       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3651       if (ExistingDecl.getDecl() &&
3652           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3653         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3654         Func = GetGlobalValue(MangledName);
3655       } else {
3656         if (!ExistingDecl.getDecl())
3657           ExistingDecl = GD.getWithMultiVersionIndex(Index);
3658 
3659       Func = GetOrCreateLLVMFunction(
3660           MangledName, DeclTy, ExistingDecl,
3661           /*ForVTable=*/false, /*DontDefer=*/true,
3662           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3663       }
3664     }
3665 
3666     llvm::SmallVector<StringRef, 32> Features;
3667     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3668     llvm::transform(Features, Features.begin(),
3669                     [](StringRef Str) { return Str.substr(1); });
3670     llvm::erase_if(Features, [&Target](StringRef Feat) {
3671       return !Target.validateCpuSupports(Feat);
3672     });
3673     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3674     ++Index;
3675   }
3676 
3677   llvm::stable_sort(
3678       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3679                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
3680         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
3681                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
3682       });
3683 
3684   // If the list contains multiple 'default' versions, such as when it contains
3685   // 'pentium' and 'generic', don't emit the call to the generic one (since we
3686   // always run on at least a 'pentium'). We do this by deleting the 'least
3687   // advanced' (read, lowest mangling letter).
3688   while (Options.size() > 1 &&
3689          llvm::X86::getCpuSupportsMask(
3690              (Options.end() - 2)->Conditions.Features) == 0) {
3691     StringRef LHSName = (Options.end() - 2)->Function->getName();
3692     StringRef RHSName = (Options.end() - 1)->Function->getName();
3693     if (LHSName.compare(RHSName) < 0)
3694       Options.erase(Options.end() - 2);
3695     else
3696       Options.erase(Options.end() - 1);
3697   }
3698 
3699   CodeGenFunction CGF(*this);
3700   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3701 
3702   if (getTarget().supportsIFunc()) {
3703     llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
3704     auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
3705 
3706     // Fix up function declarations that were created for cpu_specific before
3707     // cpu_dispatch was known
3708     if (!isa<llvm::GlobalIFunc>(IFunc)) {
3709       assert(cast<llvm::Function>(IFunc)->isDeclaration());
3710       auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
3711                                            &getModule());
3712       GI->takeName(IFunc);
3713       IFunc->replaceAllUsesWith(GI);
3714       IFunc->eraseFromParent();
3715       IFunc = GI;
3716     }
3717 
3718     std::string AliasName = getMangledNameImpl(
3719         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3720     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3721     if (!AliasFunc) {
3722       auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
3723                                            &getModule());
3724       SetCommonAttributes(GD, GA);
3725     }
3726   }
3727 }
3728 
3729 /// If a dispatcher for the specified mangled name is not in the module, create
3730 /// and return an llvm Function with the specified type.
3731 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
3732   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3733   assert(FD && "Not a FunctionDecl?");
3734 
3735   std::string MangledName =
3736       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3737 
3738   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3739   // a separate resolver).
3740   std::string ResolverName = MangledName;
3741   if (getTarget().supportsIFunc())
3742     ResolverName += ".ifunc";
3743   else if (FD->isTargetMultiVersion())
3744     ResolverName += ".resolver";
3745 
3746   // If the resolver has already been created, just return it.
3747   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3748     return ResolverGV;
3749 
3750   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3751   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
3752 
3753   // The resolver needs to be created. For target and target_clones, defer
3754   // creation until the end of the TU.
3755   if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
3756     MultiVersionFuncs.push_back(GD);
3757 
3758   // For cpu_specific, don't create an ifunc yet because we don't know if the
3759   // cpu_dispatch will be emitted in this translation unit.
3760   if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
3761     llvm::Type *ResolverType = llvm::FunctionType::get(
3762         llvm::PointerType::get(
3763             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3764         false);
3765     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3766         MangledName + ".resolver", ResolverType, GlobalDecl{},
3767         /*ForVTable=*/false);
3768     llvm::GlobalIFunc *GIF =
3769         llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
3770                                   "", Resolver, &getModule());
3771     GIF->setName(ResolverName);
3772     SetCommonAttributes(FD, GIF);
3773 
3774     return GIF;
3775   }
3776 
3777   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3778       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3779   assert(isa<llvm::GlobalValue>(Resolver) &&
3780          "Resolver should be created for the first time");
3781   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3782   return Resolver;
3783 }
3784 
3785 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3786 /// module, create and return an llvm Function with the specified type. If there
3787 /// is something in the module with the specified name, return it potentially
3788 /// bitcasted to the right type.
3789 ///
3790 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3791 /// to set the attributes on the function when it is first created.
3792 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3793     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3794     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3795     ForDefinition_t IsForDefinition) {
3796   const Decl *D = GD.getDecl();
3797 
3798   // Any attempts to use a MultiVersion function should result in retrieving
3799   // the iFunc instead. Name Mangling will handle the rest of the changes.
3800   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3801     // For the device mark the function as one that should be emitted.
3802     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3803         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3804         !DontDefer && !IsForDefinition) {
3805       if (const FunctionDecl *FDDef = FD->getDefinition()) {
3806         GlobalDecl GDDef;
3807         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3808           GDDef = GlobalDecl(CD, GD.getCtorType());
3809         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3810           GDDef = GlobalDecl(DD, GD.getDtorType());
3811         else
3812           GDDef = GlobalDecl(FDDef);
3813         EmitGlobal(GDDef);
3814       }
3815     }
3816 
3817     if (FD->isMultiVersion()) {
3818       UpdateMultiVersionNames(GD, FD, MangledName);
3819       if (!IsForDefinition)
3820         return GetOrCreateMultiVersionResolver(GD);
3821     }
3822   }
3823 
3824   // Lookup the entry, lazily creating it if necessary.
3825   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3826   if (Entry) {
3827     if (WeakRefReferences.erase(Entry)) {
3828       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3829       if (FD && !FD->hasAttr<WeakAttr>())
3830         Entry->setLinkage(llvm::Function::ExternalLinkage);
3831     }
3832 
3833     // Handle dropped DLL attributes.
3834     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
3835         !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) {
3836       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3837       setDSOLocal(Entry);
3838     }
3839 
3840     // If there are two attempts to define the same mangled name, issue an
3841     // error.
3842     if (IsForDefinition && !Entry->isDeclaration()) {
3843       GlobalDecl OtherGD;
3844       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3845       // to make sure that we issue an error only once.
3846       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3847           (GD.getCanonicalDecl().getDecl() !=
3848            OtherGD.getCanonicalDecl().getDecl()) &&
3849           DiagnosedConflictingDefinitions.insert(GD).second) {
3850         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3851             << MangledName;
3852         getDiags().Report(OtherGD.getDecl()->getLocation(),
3853                           diag::note_previous_definition);
3854       }
3855     }
3856 
3857     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3858         (Entry->getValueType() == Ty)) {
3859       return Entry;
3860     }
3861 
3862     // Make sure the result is of the correct type.
3863     // (If function is requested for a definition, we always need to create a new
3864     // function, not just return a bitcast.)
3865     if (!IsForDefinition)
3866       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3867   }
3868 
3869   // This function doesn't have a complete type (for example, the return
3870   // type is an incomplete struct). Use a fake type instead, and make
3871   // sure not to try to set attributes.
3872   bool IsIncompleteFunction = false;
3873 
3874   llvm::FunctionType *FTy;
3875   if (isa<llvm::FunctionType>(Ty)) {
3876     FTy = cast<llvm::FunctionType>(Ty);
3877   } else {
3878     FTy = llvm::FunctionType::get(VoidTy, false);
3879     IsIncompleteFunction = true;
3880   }
3881 
3882   llvm::Function *F =
3883       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3884                              Entry ? StringRef() : MangledName, &getModule());
3885 
3886   // If we already created a function with the same mangled name (but different
3887   // type) before, take its name and add it to the list of functions to be
3888   // replaced with F at the end of CodeGen.
3889   //
3890   // This happens if there is a prototype for a function (e.g. "int f()") and
3891   // then a definition of a different type (e.g. "int f(int x)").
3892   if (Entry) {
3893     F->takeName(Entry);
3894 
3895     // This might be an implementation of a function without a prototype, in
3896     // which case, try to do special replacement of calls which match the new
3897     // prototype.  The really key thing here is that we also potentially drop
3898     // arguments from the call site so as to make a direct call, which makes the
3899     // inliner happier and suppresses a number of optimizer warnings (!) about
3900     // dropping arguments.
3901     if (!Entry->use_empty()) {
3902       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3903       Entry->removeDeadConstantUsers();
3904     }
3905 
3906     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3907         F, Entry->getValueType()->getPointerTo());
3908     addGlobalValReplacement(Entry, BC);
3909   }
3910 
3911   assert(F->getName() == MangledName && "name was uniqued!");
3912   if (D)
3913     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3914   if (ExtraAttrs.hasFnAttrs()) {
3915     llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
3916     F->addFnAttrs(B);
3917   }
3918 
3919   if (!DontDefer) {
3920     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3921     // each other bottoming out with the base dtor.  Therefore we emit non-base
3922     // dtors on usage, even if there is no dtor definition in the TU.
3923     if (D && isa<CXXDestructorDecl>(D) &&
3924         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3925                                            GD.getDtorType()))
3926       addDeferredDeclToEmit(GD);
3927 
3928     // This is the first use or definition of a mangled name.  If there is a
3929     // deferred decl with this name, remember that we need to emit it at the end
3930     // of the file.
3931     auto DDI = DeferredDecls.find(MangledName);
3932     if (DDI != DeferredDecls.end()) {
3933       // Move the potentially referenced deferred decl to the
3934       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3935       // don't need it anymore).
3936       addDeferredDeclToEmit(DDI->second);
3937       DeferredDecls.erase(DDI);
3938 
3939       // Otherwise, there are cases we have to worry about where we're
3940       // using a declaration for which we must emit a definition but where
3941       // we might not find a top-level definition:
3942       //   - member functions defined inline in their classes
3943       //   - friend functions defined inline in some class
3944       //   - special member functions with implicit definitions
3945       // If we ever change our AST traversal to walk into class methods,
3946       // this will be unnecessary.
3947       //
3948       // We also don't emit a definition for a function if it's going to be an
3949       // entry in a vtable, unless it's already marked as used.
3950     } else if (getLangOpts().CPlusPlus && D) {
3951       // Look for a declaration that's lexically in a record.
3952       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3953            FD = FD->getPreviousDecl()) {
3954         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3955           if (FD->doesThisDeclarationHaveABody()) {
3956             addDeferredDeclToEmit(GD.getWithDecl(FD));
3957             break;
3958           }
3959         }
3960       }
3961     }
3962   }
3963 
3964   // Make sure the result is of the requested type.
3965   if (!IsIncompleteFunction) {
3966     assert(F->getFunctionType() == Ty);
3967     return F;
3968   }
3969 
3970   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3971   return llvm::ConstantExpr::getBitCast(F, PTy);
3972 }
3973 
3974 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
3975 /// non-null, then this function will use the specified type if it has to
3976 /// create it (this occurs when we see a definition of the function).
3977 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3978                                                  llvm::Type *Ty,
3979                                                  bool ForVTable,
3980                                                  bool DontDefer,
3981                                               ForDefinition_t IsForDefinition) {
3982   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
3983          "consteval function should never be emitted");
3984   // If there was no specific requested type, just convert it now.
3985   if (!Ty) {
3986     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3987     Ty = getTypes().ConvertType(FD->getType());
3988   }
3989 
3990   // Devirtualized destructor calls may come through here instead of via
3991   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3992   // of the complete destructor when necessary.
3993   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3994     if (getTarget().getCXXABI().isMicrosoft() &&
3995         GD.getDtorType() == Dtor_Complete &&
3996         DD->getParent()->getNumVBases() == 0)
3997       GD = GlobalDecl(DD, Dtor_Base);
3998   }
3999 
4000   StringRef MangledName = getMangledName(GD);
4001   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4002                                     /*IsThunk=*/false, llvm::AttributeList(),
4003                                     IsForDefinition);
4004   // Returns kernel handle for HIP kernel stub function.
4005   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4006       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4007     auto *Handle = getCUDARuntime().getKernelHandle(
4008         cast<llvm::Function>(F->stripPointerCasts()), GD);
4009     if (IsForDefinition)
4010       return F;
4011     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
4012   }
4013   return F;
4014 }
4015 
4016 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
4017   llvm::GlobalValue *F =
4018       cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
4019 
4020   return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F),
4021                                         llvm::Type::getInt8PtrTy(VMContext));
4022 }
4023 
4024 static const FunctionDecl *
4025 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
4026   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
4027   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4028 
4029   IdentifierInfo &CII = C.Idents.get(Name);
4030   for (const auto *Result : DC->lookup(&CII))
4031     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4032       return FD;
4033 
4034   if (!C.getLangOpts().CPlusPlus)
4035     return nullptr;
4036 
4037   // Demangle the premangled name from getTerminateFn()
4038   IdentifierInfo &CXXII =
4039       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
4040           ? C.Idents.get("terminate")
4041           : C.Idents.get(Name);
4042 
4043   for (const auto &N : {"__cxxabiv1", "std"}) {
4044     IdentifierInfo &NS = C.Idents.get(N);
4045     for (const auto *Result : DC->lookup(&NS)) {
4046       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4047       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4048         for (const auto *Result : LSD->lookup(&NS))
4049           if ((ND = dyn_cast<NamespaceDecl>(Result)))
4050             break;
4051 
4052       if (ND)
4053         for (const auto *Result : ND->lookup(&CXXII))
4054           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4055             return FD;
4056     }
4057   }
4058 
4059   return nullptr;
4060 }
4061 
4062 /// CreateRuntimeFunction - Create a new runtime function with the specified
4063 /// type and name.
4064 llvm::FunctionCallee
4065 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4066                                      llvm::AttributeList ExtraAttrs, bool Local,
4067                                      bool AssumeConvergent) {
4068   if (AssumeConvergent) {
4069     ExtraAttrs =
4070         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4071   }
4072 
4073   llvm::Constant *C =
4074       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
4075                               /*DontDefer=*/false, /*IsThunk=*/false,
4076                               ExtraAttrs);
4077 
4078   if (auto *F = dyn_cast<llvm::Function>(C)) {
4079     if (F->empty()) {
4080       F->setCallingConv(getRuntimeCC());
4081 
4082       // In Windows Itanium environments, try to mark runtime functions
4083       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4084       // will link their standard library statically or dynamically. Marking
4085       // functions imported when they are not imported can cause linker errors
4086       // and warnings.
4087       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4088           !getCodeGenOpts().LTOVisibilityPublicStd) {
4089         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4090         if (!FD || FD->hasAttr<DLLImportAttr>()) {
4091           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4092           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4093         }
4094       }
4095       setDSOLocal(F);
4096     }
4097   }
4098 
4099   return {FTy, C};
4100 }
4101 
4102 /// isTypeConstant - Determine whether an object of this type can be emitted
4103 /// as a constant.
4104 ///
4105 /// If ExcludeCtor is true, the duration when the object's constructor runs
4106 /// will not be considered. The caller will need to verify that the object is
4107 /// not written to during its construction.
4108 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
4109   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
4110     return false;
4111 
4112   if (Context.getLangOpts().CPlusPlus) {
4113     if (const CXXRecordDecl *Record
4114           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
4115       return ExcludeCtor && !Record->hasMutableFields() &&
4116              Record->hasTrivialDestructor();
4117   }
4118 
4119   return true;
4120 }
4121 
4122 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4123 /// create and return an llvm GlobalVariable with the specified type and address
4124 /// space. If there is something in the module with the specified name, return
4125 /// it potentially bitcasted to the right type.
4126 ///
4127 /// If D is non-null, it specifies a decl that correspond to this.  This is used
4128 /// to set the attributes on the global when it is first created.
4129 ///
4130 /// If IsForDefinition is true, it is guaranteed that an actual global with
4131 /// type Ty will be returned, not conversion of a variable with the same
4132 /// mangled name but some other type.
4133 llvm::Constant *
4134 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4135                                      LangAS AddrSpace, const VarDecl *D,
4136                                      ForDefinition_t IsForDefinition) {
4137   // Lookup the entry, lazily creating it if necessary.
4138   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4139   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4140   if (Entry) {
4141     if (WeakRefReferences.erase(Entry)) {
4142       if (D && !D->hasAttr<WeakAttr>())
4143         Entry->setLinkage(llvm::Function::ExternalLinkage);
4144     }
4145 
4146     // Handle dropped DLL attributes.
4147     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4148         !shouldMapVisibilityToDLLExport(D))
4149       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4150 
4151     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4152       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
4153 
4154     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4155       return Entry;
4156 
4157     // If there are two attempts to define the same mangled name, issue an
4158     // error.
4159     if (IsForDefinition && !Entry->isDeclaration()) {
4160       GlobalDecl OtherGD;
4161       const VarDecl *OtherD;
4162 
4163       // Check that D is not yet in DiagnosedConflictingDefinitions is required
4164       // to make sure that we issue an error only once.
4165       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4166           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4167           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4168           OtherD->hasInit() &&
4169           DiagnosedConflictingDefinitions.insert(D).second) {
4170         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4171             << MangledName;
4172         getDiags().Report(OtherGD.getDecl()->getLocation(),
4173                           diag::note_previous_definition);
4174       }
4175     }
4176 
4177     // Make sure the result is of the correct type.
4178     if (Entry->getType()->getAddressSpace() != TargetAS) {
4179       return llvm::ConstantExpr::getAddrSpaceCast(Entry,
4180                                                   Ty->getPointerTo(TargetAS));
4181     }
4182 
4183     // (If global is requested for a definition, we always need to create a new
4184     // global, not just return a bitcast.)
4185     if (!IsForDefinition)
4186       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
4187   }
4188 
4189   auto DAddrSpace = GetGlobalVarAddressSpace(D);
4190 
4191   auto *GV = new llvm::GlobalVariable(
4192       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4193       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4194       getContext().getTargetAddressSpace(DAddrSpace));
4195 
4196   // If we already created a global with the same mangled name (but different
4197   // type) before, take its name and remove it from its parent.
4198   if (Entry) {
4199     GV->takeName(Entry);
4200 
4201     if (!Entry->use_empty()) {
4202       llvm::Constant *NewPtrForOldDecl =
4203           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4204       Entry->replaceAllUsesWith(NewPtrForOldDecl);
4205     }
4206 
4207     Entry->eraseFromParent();
4208   }
4209 
4210   // This is the first use or definition of a mangled name.  If there is a
4211   // deferred decl with this name, remember that we need to emit it at the end
4212   // of the file.
4213   auto DDI = DeferredDecls.find(MangledName);
4214   if (DDI != DeferredDecls.end()) {
4215     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
4216     // list, and remove it from DeferredDecls (since we don't need it anymore).
4217     addDeferredDeclToEmit(DDI->second);
4218     DeferredDecls.erase(DDI);
4219   }
4220 
4221   // Handle things which are present even on external declarations.
4222   if (D) {
4223     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4224       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
4225 
4226     // FIXME: This code is overly simple and should be merged with other global
4227     // handling.
4228     GV->setConstant(isTypeConstant(D->getType(), false));
4229 
4230     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4231 
4232     setLinkageForGV(GV, D);
4233 
4234     if (D->getTLSKind()) {
4235       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4236         CXXThreadLocals.push_back(D);
4237       setTLSMode(GV, *D);
4238     }
4239 
4240     setGVProperties(GV, D);
4241 
4242     // If required by the ABI, treat declarations of static data members with
4243     // inline initializers as definitions.
4244     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
4245       EmitGlobalVarDefinition(D);
4246     }
4247 
4248     // Emit section information for extern variables.
4249     if (D->hasExternalStorage()) {
4250       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4251         GV->setSection(SA->getName());
4252     }
4253 
4254     // Handle XCore specific ABI requirements.
4255     if (getTriple().getArch() == llvm::Triple::xcore &&
4256         D->getLanguageLinkage() == CLanguageLinkage &&
4257         D->getType().isConstant(Context) &&
4258         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
4259       GV->setSection(".cp.rodata");
4260 
4261     // Check if we a have a const declaration with an initializer, we may be
4262     // able to emit it as available_externally to expose it's value to the
4263     // optimizer.
4264     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
4265         D->getType().isConstQualified() && !GV->hasInitializer() &&
4266         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
4267       const auto *Record =
4268           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
4269       bool HasMutableFields = Record && Record->hasMutableFields();
4270       if (!HasMutableFields) {
4271         const VarDecl *InitDecl;
4272         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4273         if (InitExpr) {
4274           ConstantEmitter emitter(*this);
4275           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
4276           if (Init) {
4277             auto *InitType = Init->getType();
4278             if (GV->getValueType() != InitType) {
4279               // The type of the initializer does not match the definition.
4280               // This happens when an initializer has a different type from
4281               // the type of the global (because of padding at the end of a
4282               // structure for instance).
4283               GV->setName(StringRef());
4284               // Make a new global with the correct type, this is now guaranteed
4285               // to work.
4286               auto *NewGV = cast<llvm::GlobalVariable>(
4287                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4288                       ->stripPointerCasts());
4289 
4290               // Erase the old global, since it is no longer used.
4291               GV->eraseFromParent();
4292               GV = NewGV;
4293             } else {
4294               GV->setInitializer(Init);
4295               GV->setConstant(true);
4296               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
4297             }
4298             emitter.finalize(GV);
4299           }
4300         }
4301       }
4302     }
4303   }
4304 
4305   if (GV->isDeclaration()) {
4306     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4307     // External HIP managed variables needed to be recorded for transformation
4308     // in both device and host compilations.
4309     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4310         D->hasExternalStorage())
4311       getCUDARuntime().handleVarRegistration(D, *GV);
4312   }
4313 
4314   if (D)
4315     SanitizerMD->reportGlobal(GV, *D);
4316 
4317   LangAS ExpectedAS =
4318       D ? D->getType().getAddressSpace()
4319         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4320   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4321   if (DAddrSpace != ExpectedAS) {
4322     return getTargetCodeGenInfo().performAddrSpaceCast(
4323         *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
4324   }
4325 
4326   return GV;
4327 }
4328 
4329 llvm::Constant *
4330 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4331   const Decl *D = GD.getDecl();
4332 
4333   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4334     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4335                                 /*DontDefer=*/false, IsForDefinition);
4336 
4337   if (isa<CXXMethodDecl>(D)) {
4338     auto FInfo =
4339         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4340     auto Ty = getTypes().GetFunctionType(*FInfo);
4341     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4342                              IsForDefinition);
4343   }
4344 
4345   if (isa<FunctionDecl>(D)) {
4346     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4347     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4348     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4349                              IsForDefinition);
4350   }
4351 
4352   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4353 }
4354 
4355 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4356     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4357     unsigned Alignment) {
4358   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4359   llvm::GlobalVariable *OldGV = nullptr;
4360 
4361   if (GV) {
4362     // Check if the variable has the right type.
4363     if (GV->getValueType() == Ty)
4364       return GV;
4365 
4366     // Because C++ name mangling, the only way we can end up with an already
4367     // existing global with the same name is if it has been declared extern "C".
4368     assert(GV->isDeclaration() && "Declaration has wrong type!");
4369     OldGV = GV;
4370   }
4371 
4372   // Create a new variable.
4373   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4374                                 Linkage, nullptr, Name);
4375 
4376   if (OldGV) {
4377     // Replace occurrences of the old variable if needed.
4378     GV->takeName(OldGV);
4379 
4380     if (!OldGV->use_empty()) {
4381       llvm::Constant *NewPtrForOldDecl =
4382       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4383       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4384     }
4385 
4386     OldGV->eraseFromParent();
4387   }
4388 
4389   if (supportsCOMDAT() && GV->isWeakForLinker() &&
4390       !GV->hasAvailableExternallyLinkage())
4391     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4392 
4393   GV->setAlignment(llvm::MaybeAlign(Alignment));
4394 
4395   return GV;
4396 }
4397 
4398 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4399 /// given global variable.  If Ty is non-null and if the global doesn't exist,
4400 /// then it will be created with the specified type instead of whatever the
4401 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4402 /// that an actual global with type Ty will be returned, not conversion of a
4403 /// variable with the same mangled name but some other type.
4404 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4405                                                   llvm::Type *Ty,
4406                                            ForDefinition_t IsForDefinition) {
4407   assert(D->hasGlobalStorage() && "Not a global variable");
4408   QualType ASTTy = D->getType();
4409   if (!Ty)
4410     Ty = getTypes().ConvertTypeForMem(ASTTy);
4411 
4412   StringRef MangledName = getMangledName(D);
4413   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
4414                                IsForDefinition);
4415 }
4416 
4417 /// CreateRuntimeVariable - Create a new runtime global variable with the
4418 /// specified type and name.
4419 llvm::Constant *
4420 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4421                                      StringRef Name) {
4422   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
4423                                                        : LangAS::Default;
4424   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4425   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4426   return Ret;
4427 }
4428 
4429 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4430   assert(!D->getInit() && "Cannot emit definite definitions here!");
4431 
4432   StringRef MangledName = getMangledName(D);
4433   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4434 
4435   // We already have a definition, not declaration, with the same mangled name.
4436   // Emitting of declaration is not required (and actually overwrites emitted
4437   // definition).
4438   if (GV && !GV->isDeclaration())
4439     return;
4440 
4441   // If we have not seen a reference to this variable yet, place it into the
4442   // deferred declarations table to be emitted if needed later.
4443   if (!MustBeEmitted(D) && !GV) {
4444       DeferredDecls[MangledName] = D;
4445       return;
4446   }
4447 
4448   // The tentative definition is the only definition.
4449   EmitGlobalVarDefinition(D);
4450 }
4451 
4452 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4453   EmitExternalVarDeclaration(D);
4454 }
4455 
4456 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4457   return Context.toCharUnitsFromBits(
4458       getDataLayout().getTypeStoreSizeInBits(Ty));
4459 }
4460 
4461 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4462   if (LangOpts.OpenCL) {
4463     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4464     assert(AS == LangAS::opencl_global ||
4465            AS == LangAS::opencl_global_device ||
4466            AS == LangAS::opencl_global_host ||
4467            AS == LangAS::opencl_constant ||
4468            AS == LangAS::opencl_local ||
4469            AS >= LangAS::FirstTargetAddressSpace);
4470     return AS;
4471   }
4472 
4473   if (LangOpts.SYCLIsDevice &&
4474       (!D || D->getType().getAddressSpace() == LangAS::Default))
4475     return LangAS::sycl_global;
4476 
4477   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4478     if (D && D->hasAttr<CUDAConstantAttr>())
4479       return LangAS::cuda_constant;
4480     else if (D && D->hasAttr<CUDASharedAttr>())
4481       return LangAS::cuda_shared;
4482     else if (D && D->hasAttr<CUDADeviceAttr>())
4483       return LangAS::cuda_device;
4484     else if (D && D->getType().isConstQualified())
4485       return LangAS::cuda_constant;
4486     else
4487       return LangAS::cuda_device;
4488   }
4489 
4490   if (LangOpts.OpenMP) {
4491     LangAS AS;
4492     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4493       return AS;
4494   }
4495   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4496 }
4497 
4498 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4499   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4500   if (LangOpts.OpenCL)
4501     return LangAS::opencl_constant;
4502   if (LangOpts.SYCLIsDevice)
4503     return LangAS::sycl_global;
4504   if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
4505     // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
4506     // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
4507     // with OpVariable instructions with Generic storage class which is not
4508     // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
4509     // UniformConstant storage class is not viable as pointers to it may not be
4510     // casted to Generic pointers which are used to model HIP's "flat" pointers.
4511     return LangAS::cuda_device;
4512   if (auto AS = getTarget().getConstantAddressSpace())
4513     return *AS;
4514   return LangAS::Default;
4515 }
4516 
4517 // In address space agnostic languages, string literals are in default address
4518 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4519 // emitted in constant address space in LLVM IR. To be consistent with other
4520 // parts of AST, string literal global variables in constant address space
4521 // need to be casted to default address space before being put into address
4522 // map and referenced by other part of CodeGen.
4523 // In OpenCL, string literals are in constant address space in AST, therefore
4524 // they should not be casted to default address space.
4525 static llvm::Constant *
4526 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4527                                        llvm::GlobalVariable *GV) {
4528   llvm::Constant *Cast = GV;
4529   if (!CGM.getLangOpts().OpenCL) {
4530     auto AS = CGM.GetGlobalConstantAddressSpace();
4531     if (AS != LangAS::Default)
4532       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4533           CGM, GV, AS, LangAS::Default,
4534           GV->getValueType()->getPointerTo(
4535               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4536   }
4537   return Cast;
4538 }
4539 
4540 template<typename SomeDecl>
4541 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4542                                                llvm::GlobalValue *GV) {
4543   if (!getLangOpts().CPlusPlus)
4544     return;
4545 
4546   // Must have 'used' attribute, or else inline assembly can't rely on
4547   // the name existing.
4548   if (!D->template hasAttr<UsedAttr>())
4549     return;
4550 
4551   // Must have internal linkage and an ordinary name.
4552   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4553     return;
4554 
4555   // Must be in an extern "C" context. Entities declared directly within
4556   // a record are not extern "C" even if the record is in such a context.
4557   const SomeDecl *First = D->getFirstDecl();
4558   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4559     return;
4560 
4561   // OK, this is an internal linkage entity inside an extern "C" linkage
4562   // specification. Make a note of that so we can give it the "expected"
4563   // mangled name if nothing else is using that name.
4564   std::pair<StaticExternCMap::iterator, bool> R =
4565       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4566 
4567   // If we have multiple internal linkage entities with the same name
4568   // in extern "C" regions, none of them gets that name.
4569   if (!R.second)
4570     R.first->second = nullptr;
4571 }
4572 
4573 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4574   if (!CGM.supportsCOMDAT())
4575     return false;
4576 
4577   if (D.hasAttr<SelectAnyAttr>())
4578     return true;
4579 
4580   GVALinkage Linkage;
4581   if (auto *VD = dyn_cast<VarDecl>(&D))
4582     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4583   else
4584     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4585 
4586   switch (Linkage) {
4587   case GVA_Internal:
4588   case GVA_AvailableExternally:
4589   case GVA_StrongExternal:
4590     return false;
4591   case GVA_DiscardableODR:
4592   case GVA_StrongODR:
4593     return true;
4594   }
4595   llvm_unreachable("No such linkage");
4596 }
4597 
4598 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4599                                           llvm::GlobalObject &GO) {
4600   if (!shouldBeInCOMDAT(*this, D))
4601     return;
4602   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4603 }
4604 
4605 /// Pass IsTentative as true if you want to create a tentative definition.
4606 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4607                                             bool IsTentative) {
4608   // OpenCL global variables of sampler type are translated to function calls,
4609   // therefore no need to be translated.
4610   QualType ASTTy = D->getType();
4611   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4612     return;
4613 
4614   // If this is OpenMP device, check if it is legal to emit this global
4615   // normally.
4616   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4617       OpenMPRuntime->emitTargetGlobalVariable(D))
4618     return;
4619 
4620   llvm::TrackingVH<llvm::Constant> Init;
4621   bool NeedsGlobalCtor = false;
4622   bool NeedsGlobalDtor =
4623       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4624 
4625   const VarDecl *InitDecl;
4626   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4627 
4628   Optional<ConstantEmitter> emitter;
4629 
4630   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4631   // as part of their declaration."  Sema has already checked for
4632   // error cases, so we just need to set Init to UndefValue.
4633   bool IsCUDASharedVar =
4634       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4635   // Shadows of initialized device-side global variables are also left
4636   // undefined.
4637   // Managed Variables should be initialized on both host side and device side.
4638   bool IsCUDAShadowVar =
4639       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4640       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4641        D->hasAttr<CUDASharedAttr>());
4642   bool IsCUDADeviceShadowVar =
4643       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4644       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4645        D->getType()->isCUDADeviceBuiltinTextureType());
4646   if (getLangOpts().CUDA &&
4647       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4648     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4649   else if (D->hasAttr<LoaderUninitializedAttr>())
4650     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4651   else if (!InitExpr) {
4652     // This is a tentative definition; tentative definitions are
4653     // implicitly initialized with { 0 }.
4654     //
4655     // Note that tentative definitions are only emitted at the end of
4656     // a translation unit, so they should never have incomplete
4657     // type. In addition, EmitTentativeDefinition makes sure that we
4658     // never attempt to emit a tentative definition if a real one
4659     // exists. A use may still exists, however, so we still may need
4660     // to do a RAUW.
4661     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4662     Init = EmitNullConstant(D->getType());
4663   } else {
4664     initializedGlobalDecl = GlobalDecl(D);
4665     emitter.emplace(*this);
4666     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
4667     if (!Initializer) {
4668       QualType T = InitExpr->getType();
4669       if (D->getType()->isReferenceType())
4670         T = D->getType();
4671 
4672       if (getLangOpts().CPlusPlus) {
4673         if (InitDecl->hasFlexibleArrayInit(getContext()))
4674           ErrorUnsupported(D, "flexible array initializer");
4675         Init = EmitNullConstant(T);
4676         NeedsGlobalCtor = true;
4677       } else {
4678         ErrorUnsupported(D, "static initializer");
4679         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4680       }
4681     } else {
4682       Init = Initializer;
4683       // We don't need an initializer, so remove the entry for the delayed
4684       // initializer position (just in case this entry was delayed) if we
4685       // also don't need to register a destructor.
4686       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4687         DelayedCXXInitPosition.erase(D);
4688 
4689 #ifndef NDEBUG
4690       CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
4691                           InitDecl->getFlexibleArrayInitChars(getContext());
4692       CharUnits CstSize = CharUnits::fromQuantity(
4693           getDataLayout().getTypeAllocSize(Init->getType()));
4694       assert(VarSize == CstSize && "Emitted constant has unexpected size");
4695 #endif
4696     }
4697   }
4698 
4699   llvm::Type* InitType = Init->getType();
4700   llvm::Constant *Entry =
4701       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4702 
4703   // Strip off pointer casts if we got them.
4704   Entry = Entry->stripPointerCasts();
4705 
4706   // Entry is now either a Function or GlobalVariable.
4707   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4708 
4709   // We have a definition after a declaration with the wrong type.
4710   // We must make a new GlobalVariable* and update everything that used OldGV
4711   // (a declaration or tentative definition) with the new GlobalVariable*
4712   // (which will be a definition).
4713   //
4714   // This happens if there is a prototype for a global (e.g.
4715   // "extern int x[];") and then a definition of a different type (e.g.
4716   // "int x[10];"). This also happens when an initializer has a different type
4717   // from the type of the global (this happens with unions).
4718   if (!GV || GV->getValueType() != InitType ||
4719       GV->getType()->getAddressSpace() !=
4720           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4721 
4722     // Move the old entry aside so that we'll create a new one.
4723     Entry->setName(StringRef());
4724 
4725     // Make a new global with the correct type, this is now guaranteed to work.
4726     GV = cast<llvm::GlobalVariable>(
4727         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4728             ->stripPointerCasts());
4729 
4730     // Replace all uses of the old global with the new global
4731     llvm::Constant *NewPtrForOldDecl =
4732         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4733                                                              Entry->getType());
4734     Entry->replaceAllUsesWith(NewPtrForOldDecl);
4735 
4736     // Erase the old global, since it is no longer used.
4737     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4738   }
4739 
4740   MaybeHandleStaticInExternC(D, GV);
4741 
4742   if (D->hasAttr<AnnotateAttr>())
4743     AddGlobalAnnotations(D, GV);
4744 
4745   // Set the llvm linkage type as appropriate.
4746   llvm::GlobalValue::LinkageTypes Linkage =
4747       getLLVMLinkageVarDefinition(D, GV->isConstant());
4748 
4749   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4750   // the device. [...]"
4751   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4752   // __device__, declares a variable that: [...]
4753   // Is accessible from all the threads within the grid and from the host
4754   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4755   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4756   if (GV && LangOpts.CUDA) {
4757     if (LangOpts.CUDAIsDevice) {
4758       if (Linkage != llvm::GlobalValue::InternalLinkage &&
4759           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
4760            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4761            D->getType()->isCUDADeviceBuiltinTextureType()))
4762         GV->setExternallyInitialized(true);
4763     } else {
4764       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4765     }
4766     getCUDARuntime().handleVarRegistration(D, *GV);
4767   }
4768 
4769   GV->setInitializer(Init);
4770   if (emitter)
4771     emitter->finalize(GV);
4772 
4773   // If it is safe to mark the global 'constant', do so now.
4774   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4775                   isTypeConstant(D->getType(), true));
4776 
4777   // If it is in a read-only section, mark it 'constant'.
4778   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4779     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4780     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4781       GV->setConstant(true);
4782   }
4783 
4784   CharUnits AlignVal = getContext().getDeclAlign(D);
4785   // Check for alignment specifed in an 'omp allocate' directive.
4786   if (llvm::Optional<CharUnits> AlignValFromAllocate =
4787           getOMPAllocateAlignment(D))
4788     AlignVal = *AlignValFromAllocate;
4789   GV->setAlignment(AlignVal.getAsAlign());
4790 
4791   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4792   // function is only defined alongside the variable, not also alongside
4793   // callers. Normally, all accesses to a thread_local go through the
4794   // thread-wrapper in order to ensure initialization has occurred, underlying
4795   // variable will never be used other than the thread-wrapper, so it can be
4796   // converted to internal linkage.
4797   //
4798   // However, if the variable has the 'constinit' attribute, it _can_ be
4799   // referenced directly, without calling the thread-wrapper, so the linkage
4800   // must not be changed.
4801   //
4802   // Additionally, if the variable isn't plain external linkage, e.g. if it's
4803   // weak or linkonce, the de-duplication semantics are important to preserve,
4804   // so we don't change the linkage.
4805   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4806       Linkage == llvm::GlobalValue::ExternalLinkage &&
4807       Context.getTargetInfo().getTriple().isOSDarwin() &&
4808       !D->hasAttr<ConstInitAttr>())
4809     Linkage = llvm::GlobalValue::InternalLinkage;
4810 
4811   GV->setLinkage(Linkage);
4812   if (D->hasAttr<DLLImportAttr>())
4813     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4814   else if (D->hasAttr<DLLExportAttr>())
4815     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4816   else
4817     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4818 
4819   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4820     // common vars aren't constant even if declared const.
4821     GV->setConstant(false);
4822     // Tentative definition of global variables may be initialized with
4823     // non-zero null pointers. In this case they should have weak linkage
4824     // since common linkage must have zero initializer and must not have
4825     // explicit section therefore cannot have non-zero initial value.
4826     if (!GV->getInitializer()->isNullValue())
4827       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4828   }
4829 
4830   setNonAliasAttributes(D, GV);
4831 
4832   if (D->getTLSKind() && !GV->isThreadLocal()) {
4833     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4834       CXXThreadLocals.push_back(D);
4835     setTLSMode(GV, *D);
4836   }
4837 
4838   maybeSetTrivialComdat(*D, *GV);
4839 
4840   // Emit the initializer function if necessary.
4841   if (NeedsGlobalCtor || NeedsGlobalDtor)
4842     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4843 
4844   SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
4845 
4846   // Emit global variable debug information.
4847   if (CGDebugInfo *DI = getModuleDebugInfo())
4848     if (getCodeGenOpts().hasReducedDebugInfo())
4849       DI->EmitGlobalVariable(GV, D);
4850 }
4851 
4852 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4853   if (CGDebugInfo *DI = getModuleDebugInfo())
4854     if (getCodeGenOpts().hasReducedDebugInfo()) {
4855       QualType ASTTy = D->getType();
4856       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4857       llvm::Constant *GV =
4858           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
4859       DI->EmitExternalVariable(
4860           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4861     }
4862 }
4863 
4864 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4865                                       CodeGenModule &CGM, const VarDecl *D,
4866                                       bool NoCommon) {
4867   // Don't give variables common linkage if -fno-common was specified unless it
4868   // was overridden by a NoCommon attribute.
4869   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4870     return true;
4871 
4872   // C11 6.9.2/2:
4873   //   A declaration of an identifier for an object that has file scope without
4874   //   an initializer, and without a storage-class specifier or with the
4875   //   storage-class specifier static, constitutes a tentative definition.
4876   if (D->getInit() || D->hasExternalStorage())
4877     return true;
4878 
4879   // A variable cannot be both common and exist in a section.
4880   if (D->hasAttr<SectionAttr>())
4881     return true;
4882 
4883   // A variable cannot be both common and exist in a section.
4884   // We don't try to determine which is the right section in the front-end.
4885   // If no specialized section name is applicable, it will resort to default.
4886   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4887       D->hasAttr<PragmaClangDataSectionAttr>() ||
4888       D->hasAttr<PragmaClangRelroSectionAttr>() ||
4889       D->hasAttr<PragmaClangRodataSectionAttr>())
4890     return true;
4891 
4892   // Thread local vars aren't considered common linkage.
4893   if (D->getTLSKind())
4894     return true;
4895 
4896   // Tentative definitions marked with WeakImportAttr are true definitions.
4897   if (D->hasAttr<WeakImportAttr>())
4898     return true;
4899 
4900   // A variable cannot be both common and exist in a comdat.
4901   if (shouldBeInCOMDAT(CGM, *D))
4902     return true;
4903 
4904   // Declarations with a required alignment do not have common linkage in MSVC
4905   // mode.
4906   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4907     if (D->hasAttr<AlignedAttr>())
4908       return true;
4909     QualType VarType = D->getType();
4910     if (Context.isAlignmentRequired(VarType))
4911       return true;
4912 
4913     if (const auto *RT = VarType->getAs<RecordType>()) {
4914       const RecordDecl *RD = RT->getDecl();
4915       for (const FieldDecl *FD : RD->fields()) {
4916         if (FD->isBitField())
4917           continue;
4918         if (FD->hasAttr<AlignedAttr>())
4919           return true;
4920         if (Context.isAlignmentRequired(FD->getType()))
4921           return true;
4922       }
4923     }
4924   }
4925 
4926   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4927   // common symbols, so symbols with greater alignment requirements cannot be
4928   // common.
4929   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4930   // alignments for common symbols via the aligncomm directive, so this
4931   // restriction only applies to MSVC environments.
4932   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4933       Context.getTypeAlignIfKnown(D->getType()) >
4934           Context.toBits(CharUnits::fromQuantity(32)))
4935     return true;
4936 
4937   return false;
4938 }
4939 
4940 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4941     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4942   if (Linkage == GVA_Internal)
4943     return llvm::Function::InternalLinkage;
4944 
4945   if (D->hasAttr<WeakAttr>())
4946     return llvm::GlobalVariable::WeakAnyLinkage;
4947 
4948   if (const auto *FD = D->getAsFunction())
4949     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4950       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4951 
4952   // We are guaranteed to have a strong definition somewhere else,
4953   // so we can use available_externally linkage.
4954   if (Linkage == GVA_AvailableExternally)
4955     return llvm::GlobalValue::AvailableExternallyLinkage;
4956 
4957   // Note that Apple's kernel linker doesn't support symbol
4958   // coalescing, so we need to avoid linkonce and weak linkages there.
4959   // Normally, this means we just map to internal, but for explicit
4960   // instantiations we'll map to external.
4961 
4962   // In C++, the compiler has to emit a definition in every translation unit
4963   // that references the function.  We should use linkonce_odr because
4964   // a) if all references in this translation unit are optimized away, we
4965   // don't need to codegen it.  b) if the function persists, it needs to be
4966   // merged with other definitions. c) C++ has the ODR, so we know the
4967   // definition is dependable.
4968   if (Linkage == GVA_DiscardableODR)
4969     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4970                                             : llvm::Function::InternalLinkage;
4971 
4972   // An explicit instantiation of a template has weak linkage, since
4973   // explicit instantiations can occur in multiple translation units
4974   // and must all be equivalent. However, we are not allowed to
4975   // throw away these explicit instantiations.
4976   //
4977   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
4978   // so say that CUDA templates are either external (for kernels) or internal.
4979   // This lets llvm perform aggressive inter-procedural optimizations. For
4980   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4981   // therefore we need to follow the normal linkage paradigm.
4982   if (Linkage == GVA_StrongODR) {
4983     if (getLangOpts().AppleKext)
4984       return llvm::Function::ExternalLinkage;
4985     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4986         !getLangOpts().GPURelocatableDeviceCode)
4987       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4988                                           : llvm::Function::InternalLinkage;
4989     return llvm::Function::WeakODRLinkage;
4990   }
4991 
4992   // C++ doesn't have tentative definitions and thus cannot have common
4993   // linkage.
4994   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4995       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4996                                  CodeGenOpts.NoCommon))
4997     return llvm::GlobalVariable::CommonLinkage;
4998 
4999   // selectany symbols are externally visible, so use weak instead of
5000   // linkonce.  MSVC optimizes away references to const selectany globals, so
5001   // all definitions should be the same and ODR linkage should be used.
5002   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
5003   if (D->hasAttr<SelectAnyAttr>())
5004     return llvm::GlobalVariable::WeakODRLinkage;
5005 
5006   // Otherwise, we have strong external linkage.
5007   assert(Linkage == GVA_StrongExternal);
5008   return llvm::GlobalVariable::ExternalLinkage;
5009 }
5010 
5011 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
5012     const VarDecl *VD, bool IsConstant) {
5013   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5014   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
5015 }
5016 
5017 /// Replace the uses of a function that was declared with a non-proto type.
5018 /// We want to silently drop extra arguments from call sites
5019 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
5020                                           llvm::Function *newFn) {
5021   // Fast path.
5022   if (old->use_empty()) return;
5023 
5024   llvm::Type *newRetTy = newFn->getReturnType();
5025   SmallVector<llvm::Value*, 4> newArgs;
5026 
5027   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5028          ui != ue; ) {
5029     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
5030     llvm::User *user = use->getUser();
5031 
5032     // Recognize and replace uses of bitcasts.  Most calls to
5033     // unprototyped functions will use bitcasts.
5034     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5035       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5036         replaceUsesOfNonProtoConstant(bitcast, newFn);
5037       continue;
5038     }
5039 
5040     // Recognize calls to the function.
5041     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5042     if (!callSite) continue;
5043     if (!callSite->isCallee(&*use))
5044       continue;
5045 
5046     // If the return types don't match exactly, then we can't
5047     // transform this call unless it's dead.
5048     if (callSite->getType() != newRetTy && !callSite->use_empty())
5049       continue;
5050 
5051     // Get the call site's attribute list.
5052     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
5053     llvm::AttributeList oldAttrs = callSite->getAttributes();
5054 
5055     // If the function was passed too few arguments, don't transform.
5056     unsigned newNumArgs = newFn->arg_size();
5057     if (callSite->arg_size() < newNumArgs)
5058       continue;
5059 
5060     // If extra arguments were passed, we silently drop them.
5061     // If any of the types mismatch, we don't transform.
5062     unsigned argNo = 0;
5063     bool dontTransform = false;
5064     for (llvm::Argument &A : newFn->args()) {
5065       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5066         dontTransform = true;
5067         break;
5068       }
5069 
5070       // Add any parameter attributes.
5071       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5072       argNo++;
5073     }
5074     if (dontTransform)
5075       continue;
5076 
5077     // Okay, we can transform this.  Create the new call instruction and copy
5078     // over the required information.
5079     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5080 
5081     // Copy over any operand bundles.
5082     SmallVector<llvm::OperandBundleDef, 1> newBundles;
5083     callSite->getOperandBundlesAsDefs(newBundles);
5084 
5085     llvm::CallBase *newCall;
5086     if (isa<llvm::CallInst>(callSite)) {
5087       newCall =
5088           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
5089     } else {
5090       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5091       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5092                                          oldInvoke->getUnwindDest(), newArgs,
5093                                          newBundles, "", callSite);
5094     }
5095     newArgs.clear(); // for the next iteration
5096 
5097     if (!newCall->getType()->isVoidTy())
5098       newCall->takeName(callSite);
5099     newCall->setAttributes(
5100         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5101                                  oldAttrs.getRetAttrs(), newArgAttrs));
5102     newCall->setCallingConv(callSite->getCallingConv());
5103 
5104     // Finally, remove the old call, replacing any uses with the new one.
5105     if (!callSite->use_empty())
5106       callSite->replaceAllUsesWith(newCall);
5107 
5108     // Copy debug location attached to CI.
5109     if (callSite->getDebugLoc())
5110       newCall->setDebugLoc(callSite->getDebugLoc());
5111 
5112     callSite->eraseFromParent();
5113   }
5114 }
5115 
5116 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
5117 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
5118 /// existing call uses of the old function in the module, this adjusts them to
5119 /// call the new function directly.
5120 ///
5121 /// This is not just a cleanup: the always_inline pass requires direct calls to
5122 /// functions to be able to inline them.  If there is a bitcast in the way, it
5123 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
5124 /// run at -O0.
5125 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
5126                                                       llvm::Function *NewFn) {
5127   // If we're redefining a global as a function, don't transform it.
5128   if (!isa<llvm::Function>(Old)) return;
5129 
5130   replaceUsesOfNonProtoConstant(Old, NewFn);
5131 }
5132 
5133 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
5134   auto DK = VD->isThisDeclarationADefinition();
5135   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
5136     return;
5137 
5138   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
5139   // If we have a definition, this might be a deferred decl. If the
5140   // instantiation is explicit, make sure we emit it at the end.
5141   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
5142     GetAddrOfGlobalVar(VD);
5143 
5144   EmitTopLevelDecl(VD);
5145 }
5146 
5147 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
5148                                                  llvm::GlobalValue *GV) {
5149   const auto *D = cast<FunctionDecl>(GD.getDecl());
5150 
5151   // Compute the function info and LLVM type.
5152   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5153   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5154 
5155   // Get or create the prototype for the function.
5156   if (!GV || (GV->getValueType() != Ty))
5157     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
5158                                                    /*DontDefer=*/true,
5159                                                    ForDefinition));
5160 
5161   // Already emitted.
5162   if (!GV->isDeclaration())
5163     return;
5164 
5165   // We need to set linkage and visibility on the function before
5166   // generating code for it because various parts of IR generation
5167   // want to propagate this information down (e.g. to local static
5168   // declarations).
5169   auto *Fn = cast<llvm::Function>(GV);
5170   setFunctionLinkage(GD, Fn);
5171 
5172   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
5173   setGVProperties(Fn, GD);
5174 
5175   MaybeHandleStaticInExternC(D, Fn);
5176 
5177   maybeSetTrivialComdat(*D, *Fn);
5178 
5179   // Set CodeGen attributes that represent floating point environment.
5180   setLLVMFunctionFEnvAttributes(D, Fn);
5181 
5182   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
5183 
5184   setNonAliasAttributes(GD, Fn);
5185   SetLLVMFunctionAttributesForDefinition(D, Fn);
5186 
5187   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
5188     AddGlobalCtor(Fn, CA->getPriority());
5189   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5190     AddGlobalDtor(Fn, DA->getPriority(), true);
5191   if (D->hasAttr<AnnotateAttr>())
5192     AddGlobalAnnotations(D, Fn);
5193 }
5194 
5195 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
5196   const auto *D = cast<ValueDecl>(GD.getDecl());
5197   const AliasAttr *AA = D->getAttr<AliasAttr>();
5198   assert(AA && "Not an alias?");
5199 
5200   StringRef MangledName = getMangledName(GD);
5201 
5202   if (AA->getAliasee() == MangledName) {
5203     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5204     return;
5205   }
5206 
5207   // If there is a definition in the module, then it wins over the alias.
5208   // This is dubious, but allow it to be safe.  Just ignore the alias.
5209   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5210   if (Entry && !Entry->isDeclaration())
5211     return;
5212 
5213   Aliases.push_back(GD);
5214 
5215   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5216 
5217   // Create a reference to the named value.  This ensures that it is emitted
5218   // if a deferred decl.
5219   llvm::Constant *Aliasee;
5220   llvm::GlobalValue::LinkageTypes LT;
5221   if (isa<llvm::FunctionType>(DeclTy)) {
5222     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
5223                                       /*ForVTable=*/false);
5224     LT = getFunctionLinkage(GD);
5225   } else {
5226     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
5227                                     /*D=*/nullptr);
5228     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5229       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
5230     else
5231       LT = getFunctionLinkage(GD);
5232   }
5233 
5234   // Create the new alias itself, but don't set a name yet.
5235   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
5236   auto *GA =
5237       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
5238 
5239   if (Entry) {
5240     if (GA->getAliasee() == Entry) {
5241       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5242       return;
5243     }
5244 
5245     assert(Entry->isDeclaration());
5246 
5247     // If there is a declaration in the module, then we had an extern followed
5248     // by the alias, as in:
5249     //   extern int test6();
5250     //   ...
5251     //   int test6() __attribute__((alias("test7")));
5252     //
5253     // Remove it and replace uses of it with the alias.
5254     GA->takeName(Entry);
5255 
5256     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
5257                                                           Entry->getType()));
5258     Entry->eraseFromParent();
5259   } else {
5260     GA->setName(MangledName);
5261   }
5262 
5263   // Set attributes which are particular to an alias; this is a
5264   // specialization of the attributes which may be set on a global
5265   // variable/function.
5266   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
5267       D->isWeakImported()) {
5268     GA->setLinkage(llvm::Function::WeakAnyLinkage);
5269   }
5270 
5271   if (const auto *VD = dyn_cast<VarDecl>(D))
5272     if (VD->getTLSKind())
5273       setTLSMode(GA, *VD);
5274 
5275   SetCommonAttributes(GD, GA);
5276 
5277   // Emit global alias debug information.
5278   if (isa<VarDecl>(D))
5279     if (CGDebugInfo *DI = getModuleDebugInfo())
5280       DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()), GD);
5281 }
5282 
5283 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
5284   const auto *D = cast<ValueDecl>(GD.getDecl());
5285   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
5286   assert(IFA && "Not an ifunc?");
5287 
5288   StringRef MangledName = getMangledName(GD);
5289 
5290   if (IFA->getResolver() == MangledName) {
5291     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5292     return;
5293   }
5294 
5295   // Report an error if some definition overrides ifunc.
5296   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5297   if (Entry && !Entry->isDeclaration()) {
5298     GlobalDecl OtherGD;
5299     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
5300         DiagnosedConflictingDefinitions.insert(GD).second) {
5301       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
5302           << MangledName;
5303       Diags.Report(OtherGD.getDecl()->getLocation(),
5304                    diag::note_previous_definition);
5305     }
5306     return;
5307   }
5308 
5309   Aliases.push_back(GD);
5310 
5311   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5312   llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
5313   llvm::Constant *Resolver =
5314       GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
5315                               /*ForVTable=*/false);
5316   llvm::GlobalIFunc *GIF =
5317       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
5318                                 "", Resolver, &getModule());
5319   if (Entry) {
5320     if (GIF->getResolver() == Entry) {
5321       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5322       return;
5323     }
5324     assert(Entry->isDeclaration());
5325 
5326     // If there is a declaration in the module, then we had an extern followed
5327     // by the ifunc, as in:
5328     //   extern int test();
5329     //   ...
5330     //   int test() __attribute__((ifunc("resolver")));
5331     //
5332     // Remove it and replace uses of it with the ifunc.
5333     GIF->takeName(Entry);
5334 
5335     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
5336                                                           Entry->getType()));
5337     Entry->eraseFromParent();
5338   } else
5339     GIF->setName(MangledName);
5340 
5341   SetCommonAttributes(GD, GIF);
5342 }
5343 
5344 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
5345                                             ArrayRef<llvm::Type*> Tys) {
5346   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
5347                                          Tys);
5348 }
5349 
5350 static llvm::StringMapEntry<llvm::GlobalVariable *> &
5351 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5352                          const StringLiteral *Literal, bool TargetIsLSB,
5353                          bool &IsUTF16, unsigned &StringLength) {
5354   StringRef String = Literal->getString();
5355   unsigned NumBytes = String.size();
5356 
5357   // Check for simple case.
5358   if (!Literal->containsNonAsciiOrNull()) {
5359     StringLength = NumBytes;
5360     return *Map.insert(std::make_pair(String, nullptr)).first;
5361   }
5362 
5363   // Otherwise, convert the UTF8 literals into a string of shorts.
5364   IsUTF16 = true;
5365 
5366   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5367   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5368   llvm::UTF16 *ToPtr = &ToBuf[0];
5369 
5370   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5371                                  ToPtr + NumBytes, llvm::strictConversion);
5372 
5373   // ConvertUTF8toUTF16 returns the length in ToPtr.
5374   StringLength = ToPtr - &ToBuf[0];
5375 
5376   // Add an explicit null.
5377   *ToPtr = 0;
5378   return *Map.insert(std::make_pair(
5379                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5380                                    (StringLength + 1) * 2),
5381                          nullptr)).first;
5382 }
5383 
5384 ConstantAddress
5385 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5386   unsigned StringLength = 0;
5387   bool isUTF16 = false;
5388   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5389       GetConstantCFStringEntry(CFConstantStringMap, Literal,
5390                                getDataLayout().isLittleEndian(), isUTF16,
5391                                StringLength);
5392 
5393   if (auto *C = Entry.second)
5394     return ConstantAddress(
5395         C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
5396 
5397   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5398   llvm::Constant *Zeros[] = { Zero, Zero };
5399 
5400   const ASTContext &Context = getContext();
5401   const llvm::Triple &Triple = getTriple();
5402 
5403   const auto CFRuntime = getLangOpts().CFRuntime;
5404   const bool IsSwiftABI =
5405       static_cast<unsigned>(CFRuntime) >=
5406       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5407   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5408 
5409   // If we don't already have it, get __CFConstantStringClassReference.
5410   if (!CFConstantStringClassRef) {
5411     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5412     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5413     Ty = llvm::ArrayType::get(Ty, 0);
5414 
5415     switch (CFRuntime) {
5416     default: break;
5417     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
5418     case LangOptions::CoreFoundationABI::Swift5_0:
5419       CFConstantStringClassName =
5420           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5421                               : "$s10Foundation19_NSCFConstantStringCN";
5422       Ty = IntPtrTy;
5423       break;
5424     case LangOptions::CoreFoundationABI::Swift4_2:
5425       CFConstantStringClassName =
5426           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5427                               : "$S10Foundation19_NSCFConstantStringCN";
5428       Ty = IntPtrTy;
5429       break;
5430     case LangOptions::CoreFoundationABI::Swift4_1:
5431       CFConstantStringClassName =
5432           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5433                               : "__T010Foundation19_NSCFConstantStringCN";
5434       Ty = IntPtrTy;
5435       break;
5436     }
5437 
5438     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5439 
5440     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5441       llvm::GlobalValue *GV = nullptr;
5442 
5443       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5444         IdentifierInfo &II = Context.Idents.get(GV->getName());
5445         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5446         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5447 
5448         const VarDecl *VD = nullptr;
5449         for (const auto *Result : DC->lookup(&II))
5450           if ((VD = dyn_cast<VarDecl>(Result)))
5451             break;
5452 
5453         if (Triple.isOSBinFormatELF()) {
5454           if (!VD)
5455             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5456         } else {
5457           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5458           if (!VD || !VD->hasAttr<DLLExportAttr>())
5459             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5460           else
5461             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5462         }
5463 
5464         setDSOLocal(GV);
5465       }
5466     }
5467 
5468     // Decay array -> ptr
5469     CFConstantStringClassRef =
5470         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5471                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5472   }
5473 
5474   QualType CFTy = Context.getCFConstantStringType();
5475 
5476   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5477 
5478   ConstantInitBuilder Builder(*this);
5479   auto Fields = Builder.beginStruct(STy);
5480 
5481   // Class pointer.
5482   Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
5483 
5484   // Flags.
5485   if (IsSwiftABI) {
5486     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5487     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5488   } else {
5489     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5490   }
5491 
5492   // String pointer.
5493   llvm::Constant *C = nullptr;
5494   if (isUTF16) {
5495     auto Arr = llvm::makeArrayRef(
5496         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5497         Entry.first().size() / 2);
5498     C = llvm::ConstantDataArray::get(VMContext, Arr);
5499   } else {
5500     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5501   }
5502 
5503   // Note: -fwritable-strings doesn't make the backing store strings of
5504   // CFStrings writable. (See <rdar://problem/10657500>)
5505   auto *GV =
5506       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5507                                llvm::GlobalValue::PrivateLinkage, C, ".str");
5508   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5509   // Don't enforce the target's minimum global alignment, since the only use
5510   // of the string is via this class initializer.
5511   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5512                             : Context.getTypeAlignInChars(Context.CharTy);
5513   GV->setAlignment(Align.getAsAlign());
5514 
5515   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5516   // Without it LLVM can merge the string with a non unnamed_addr one during
5517   // LTO.  Doing that changes the section it ends in, which surprises ld64.
5518   if (Triple.isOSBinFormatMachO())
5519     GV->setSection(isUTF16 ? "__TEXT,__ustring"
5520                            : "__TEXT,__cstring,cstring_literals");
5521   // Make sure the literal ends up in .rodata to allow for safe ICF and for
5522   // the static linker to adjust permissions to read-only later on.
5523   else if (Triple.isOSBinFormatELF())
5524     GV->setSection(".rodata");
5525 
5526   // String.
5527   llvm::Constant *Str =
5528       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5529 
5530   if (isUTF16)
5531     // Cast the UTF16 string to the correct type.
5532     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5533   Fields.add(Str);
5534 
5535   // String length.
5536   llvm::IntegerType *LengthTy =
5537       llvm::IntegerType::get(getModule().getContext(),
5538                              Context.getTargetInfo().getLongWidth());
5539   if (IsSwiftABI) {
5540     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5541         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5542       LengthTy = Int32Ty;
5543     else
5544       LengthTy = IntPtrTy;
5545   }
5546   Fields.addInt(LengthTy, StringLength);
5547 
5548   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5549   // properly aligned on 32-bit platforms.
5550   CharUnits Alignment =
5551       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5552 
5553   // The struct.
5554   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5555                                     /*isConstant=*/false,
5556                                     llvm::GlobalVariable::PrivateLinkage);
5557   GV->addAttribute("objc_arc_inert");
5558   switch (Triple.getObjectFormat()) {
5559   case llvm::Triple::UnknownObjectFormat:
5560     llvm_unreachable("unknown file format");
5561   case llvm::Triple::DXContainer:
5562   case llvm::Triple::GOFF:
5563   case llvm::Triple::SPIRV:
5564   case llvm::Triple::XCOFF:
5565     llvm_unreachable("unimplemented");
5566   case llvm::Triple::COFF:
5567   case llvm::Triple::ELF:
5568   case llvm::Triple::Wasm:
5569     GV->setSection("cfstring");
5570     break;
5571   case llvm::Triple::MachO:
5572     GV->setSection("__DATA,__cfstring");
5573     break;
5574   }
5575   Entry.second = GV;
5576 
5577   return ConstantAddress(GV, GV->getValueType(), Alignment);
5578 }
5579 
5580 bool CodeGenModule::getExpressionLocationsEnabled() const {
5581   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5582 }
5583 
5584 QualType CodeGenModule::getObjCFastEnumerationStateType() {
5585   if (ObjCFastEnumerationStateType.isNull()) {
5586     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5587     D->startDefinition();
5588 
5589     QualType FieldTypes[] = {
5590       Context.UnsignedLongTy,
5591       Context.getPointerType(Context.getObjCIdType()),
5592       Context.getPointerType(Context.UnsignedLongTy),
5593       Context.getConstantArrayType(Context.UnsignedLongTy,
5594                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5595     };
5596 
5597     for (size_t i = 0; i < 4; ++i) {
5598       FieldDecl *Field = FieldDecl::Create(Context,
5599                                            D,
5600                                            SourceLocation(),
5601                                            SourceLocation(), nullptr,
5602                                            FieldTypes[i], /*TInfo=*/nullptr,
5603                                            /*BitWidth=*/nullptr,
5604                                            /*Mutable=*/false,
5605                                            ICIS_NoInit);
5606       Field->setAccess(AS_public);
5607       D->addDecl(Field);
5608     }
5609 
5610     D->completeDefinition();
5611     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5612   }
5613 
5614   return ObjCFastEnumerationStateType;
5615 }
5616 
5617 llvm::Constant *
5618 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5619   assert(!E->getType()->isPointerType() && "Strings are always arrays");
5620 
5621   // Don't emit it as the address of the string, emit the string data itself
5622   // as an inline array.
5623   if (E->getCharByteWidth() == 1) {
5624     SmallString<64> Str(E->getString());
5625 
5626     // Resize the string to the right size, which is indicated by its type.
5627     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5628     Str.resize(CAT->getSize().getZExtValue());
5629     return llvm::ConstantDataArray::getString(VMContext, Str, false);
5630   }
5631 
5632   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5633   llvm::Type *ElemTy = AType->getElementType();
5634   unsigned NumElements = AType->getNumElements();
5635 
5636   // Wide strings have either 2-byte or 4-byte elements.
5637   if (ElemTy->getPrimitiveSizeInBits() == 16) {
5638     SmallVector<uint16_t, 32> Elements;
5639     Elements.reserve(NumElements);
5640 
5641     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5642       Elements.push_back(E->getCodeUnit(i));
5643     Elements.resize(NumElements);
5644     return llvm::ConstantDataArray::get(VMContext, Elements);
5645   }
5646 
5647   assert(ElemTy->getPrimitiveSizeInBits() == 32);
5648   SmallVector<uint32_t, 32> Elements;
5649   Elements.reserve(NumElements);
5650 
5651   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5652     Elements.push_back(E->getCodeUnit(i));
5653   Elements.resize(NumElements);
5654   return llvm::ConstantDataArray::get(VMContext, Elements);
5655 }
5656 
5657 static llvm::GlobalVariable *
5658 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5659                       CodeGenModule &CGM, StringRef GlobalName,
5660                       CharUnits Alignment) {
5661   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5662       CGM.GetGlobalConstantAddressSpace());
5663 
5664   llvm::Module &M = CGM.getModule();
5665   // Create a global variable for this string
5666   auto *GV = new llvm::GlobalVariable(
5667       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5668       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5669   GV->setAlignment(Alignment.getAsAlign());
5670   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5671   if (GV->isWeakForLinker()) {
5672     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5673     GV->setComdat(M.getOrInsertComdat(GV->getName()));
5674   }
5675   CGM.setDSOLocal(GV);
5676 
5677   return GV;
5678 }
5679 
5680 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5681 /// constant array for the given string literal.
5682 ConstantAddress
5683 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5684                                                   StringRef Name) {
5685   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5686 
5687   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5688   llvm::GlobalVariable **Entry = nullptr;
5689   if (!LangOpts.WritableStrings) {
5690     Entry = &ConstantStringMap[C];
5691     if (auto GV = *Entry) {
5692       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
5693         GV->setAlignment(Alignment.getAsAlign());
5694       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5695                              GV->getValueType(), Alignment);
5696     }
5697   }
5698 
5699   SmallString<256> MangledNameBuffer;
5700   StringRef GlobalVariableName;
5701   llvm::GlobalValue::LinkageTypes LT;
5702 
5703   // Mangle the string literal if that's how the ABI merges duplicate strings.
5704   // Don't do it if they are writable, since we don't want writes in one TU to
5705   // affect strings in another.
5706   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5707       !LangOpts.WritableStrings) {
5708     llvm::raw_svector_ostream Out(MangledNameBuffer);
5709     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5710     LT = llvm::GlobalValue::LinkOnceODRLinkage;
5711     GlobalVariableName = MangledNameBuffer;
5712   } else {
5713     LT = llvm::GlobalValue::PrivateLinkage;
5714     GlobalVariableName = Name;
5715   }
5716 
5717   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5718 
5719   CGDebugInfo *DI = getModuleDebugInfo();
5720   if (DI && getCodeGenOpts().hasReducedDebugInfo())
5721     DI->AddStringLiteralDebugInfo(GV, S);
5722 
5723   if (Entry)
5724     *Entry = GV;
5725 
5726   SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
5727 
5728   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5729                          GV->getValueType(), Alignment);
5730 }
5731 
5732 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5733 /// array for the given ObjCEncodeExpr node.
5734 ConstantAddress
5735 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5736   std::string Str;
5737   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5738 
5739   return GetAddrOfConstantCString(Str);
5740 }
5741 
5742 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5743 /// the literal and a terminating '\0' character.
5744 /// The result has pointer to array type.
5745 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5746     const std::string &Str, const char *GlobalName) {
5747   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5748   CharUnits Alignment =
5749     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5750 
5751   llvm::Constant *C =
5752       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5753 
5754   // Don't share any string literals if strings aren't constant.
5755   llvm::GlobalVariable **Entry = nullptr;
5756   if (!LangOpts.WritableStrings) {
5757     Entry = &ConstantStringMap[C];
5758     if (auto GV = *Entry) {
5759       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
5760         GV->setAlignment(Alignment.getAsAlign());
5761       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5762                              GV->getValueType(), Alignment);
5763     }
5764   }
5765 
5766   // Get the default prefix if a name wasn't specified.
5767   if (!GlobalName)
5768     GlobalName = ".str";
5769   // Create a global variable for this.
5770   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5771                                   GlobalName, Alignment);
5772   if (Entry)
5773     *Entry = GV;
5774 
5775   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5776                          GV->getValueType(), Alignment);
5777 }
5778 
5779 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5780     const MaterializeTemporaryExpr *E, const Expr *Init) {
5781   assert((E->getStorageDuration() == SD_Static ||
5782           E->getStorageDuration() == SD_Thread) && "not a global temporary");
5783   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5784 
5785   // If we're not materializing a subobject of the temporary, keep the
5786   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5787   QualType MaterializedType = Init->getType();
5788   if (Init == E->getSubExpr())
5789     MaterializedType = E->getType();
5790 
5791   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5792 
5793   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
5794   if (!InsertResult.second) {
5795     // We've seen this before: either we already created it or we're in the
5796     // process of doing so.
5797     if (!InsertResult.first->second) {
5798       // We recursively re-entered this function, probably during emission of
5799       // the initializer. Create a placeholder. We'll clean this up in the
5800       // outer call, at the end of this function.
5801       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
5802       InsertResult.first->second = new llvm::GlobalVariable(
5803           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
5804           nullptr);
5805     }
5806     return ConstantAddress(InsertResult.first->second,
5807                            llvm::cast<llvm::GlobalVariable>(
5808                                InsertResult.first->second->stripPointerCasts())
5809                                ->getValueType(),
5810                            Align);
5811   }
5812 
5813   // FIXME: If an externally-visible declaration extends multiple temporaries,
5814   // we need to give each temporary the same name in every translation unit (and
5815   // we also need to make the temporaries externally-visible).
5816   SmallString<256> Name;
5817   llvm::raw_svector_ostream Out(Name);
5818   getCXXABI().getMangleContext().mangleReferenceTemporary(
5819       VD, E->getManglingNumber(), Out);
5820 
5821   APValue *Value = nullptr;
5822   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5823     // If the initializer of the extending declaration is a constant
5824     // initializer, we should have a cached constant initializer for this
5825     // temporary. Note that this might have a different value from the value
5826     // computed by evaluating the initializer if the surrounding constant
5827     // expression modifies the temporary.
5828     Value = E->getOrCreateValue(false);
5829   }
5830 
5831   // Try evaluating it now, it might have a constant initializer.
5832   Expr::EvalResult EvalResult;
5833   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5834       !EvalResult.hasSideEffects())
5835     Value = &EvalResult.Val;
5836 
5837   LangAS AddrSpace =
5838       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5839 
5840   Optional<ConstantEmitter> emitter;
5841   llvm::Constant *InitialValue = nullptr;
5842   bool Constant = false;
5843   llvm::Type *Type;
5844   if (Value) {
5845     // The temporary has a constant initializer, use it.
5846     emitter.emplace(*this);
5847     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5848                                                MaterializedType);
5849     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5850     Type = InitialValue->getType();
5851   } else {
5852     // No initializer, the initialization will be provided when we
5853     // initialize the declaration which performed lifetime extension.
5854     Type = getTypes().ConvertTypeForMem(MaterializedType);
5855   }
5856 
5857   // Create a global variable for this lifetime-extended temporary.
5858   llvm::GlobalValue::LinkageTypes Linkage =
5859       getLLVMLinkageVarDefinition(VD, Constant);
5860   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5861     const VarDecl *InitVD;
5862     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5863         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5864       // Temporaries defined inside a class get linkonce_odr linkage because the
5865       // class can be defined in multiple translation units.
5866       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5867     } else {
5868       // There is no need for this temporary to have external linkage if the
5869       // VarDecl has external linkage.
5870       Linkage = llvm::GlobalVariable::InternalLinkage;
5871     }
5872   }
5873   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5874   auto *GV = new llvm::GlobalVariable(
5875       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5876       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5877   if (emitter) emitter->finalize(GV);
5878   setGVProperties(GV, VD);
5879   if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
5880     // The reference temporary should never be dllexport.
5881     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5882   GV->setAlignment(Align.getAsAlign());
5883   if (supportsCOMDAT() && GV->isWeakForLinker())
5884     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5885   if (VD->getTLSKind())
5886     setTLSMode(GV, *VD);
5887   llvm::Constant *CV = GV;
5888   if (AddrSpace != LangAS::Default)
5889     CV = getTargetCodeGenInfo().performAddrSpaceCast(
5890         *this, GV, AddrSpace, LangAS::Default,
5891         Type->getPointerTo(
5892             getContext().getTargetAddressSpace(LangAS::Default)));
5893 
5894   // Update the map with the new temporary. If we created a placeholder above,
5895   // replace it with the new global now.
5896   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
5897   if (Entry) {
5898     Entry->replaceAllUsesWith(
5899         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
5900     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
5901   }
5902   Entry = CV;
5903 
5904   return ConstantAddress(CV, Type, Align);
5905 }
5906 
5907 /// EmitObjCPropertyImplementations - Emit information for synthesized
5908 /// properties for an implementation.
5909 void CodeGenModule::EmitObjCPropertyImplementations(const
5910                                                     ObjCImplementationDecl *D) {
5911   for (const auto *PID : D->property_impls()) {
5912     // Dynamic is just for type-checking.
5913     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5914       ObjCPropertyDecl *PD = PID->getPropertyDecl();
5915 
5916       // Determine which methods need to be implemented, some may have
5917       // been overridden. Note that ::isPropertyAccessor is not the method
5918       // we want, that just indicates if the decl came from a
5919       // property. What we want to know is if the method is defined in
5920       // this implementation.
5921       auto *Getter = PID->getGetterMethodDecl();
5922       if (!Getter || Getter->isSynthesizedAccessorStub())
5923         CodeGenFunction(*this).GenerateObjCGetter(
5924             const_cast<ObjCImplementationDecl *>(D), PID);
5925       auto *Setter = PID->getSetterMethodDecl();
5926       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5927         CodeGenFunction(*this).GenerateObjCSetter(
5928                                  const_cast<ObjCImplementationDecl *>(D), PID);
5929     }
5930   }
5931 }
5932 
5933 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5934   const ObjCInterfaceDecl *iface = impl->getClassInterface();
5935   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5936        ivar; ivar = ivar->getNextIvar())
5937     if (ivar->getType().isDestructedType())
5938       return true;
5939 
5940   return false;
5941 }
5942 
5943 static bool AllTrivialInitializers(CodeGenModule &CGM,
5944                                    ObjCImplementationDecl *D) {
5945   CodeGenFunction CGF(CGM);
5946   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5947        E = D->init_end(); B != E; ++B) {
5948     CXXCtorInitializer *CtorInitExp = *B;
5949     Expr *Init = CtorInitExp->getInit();
5950     if (!CGF.isTrivialInitializer(Init))
5951       return false;
5952   }
5953   return true;
5954 }
5955 
5956 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5957 /// for an implementation.
5958 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5959   // We might need a .cxx_destruct even if we don't have any ivar initializers.
5960   if (needsDestructMethod(D)) {
5961     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5962     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5963     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5964         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5965         getContext().VoidTy, nullptr, D,
5966         /*isInstance=*/true, /*isVariadic=*/false,
5967         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5968         /*isImplicitlyDeclared=*/true,
5969         /*isDefined=*/false, ObjCMethodDecl::Required);
5970     D->addInstanceMethod(DTORMethod);
5971     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5972     D->setHasDestructors(true);
5973   }
5974 
5975   // If the implementation doesn't have any ivar initializers, we don't need
5976   // a .cxx_construct.
5977   if (D->getNumIvarInitializers() == 0 ||
5978       AllTrivialInitializers(*this, D))
5979     return;
5980 
5981   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5982   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5983   // The constructor returns 'self'.
5984   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5985       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5986       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5987       /*isVariadic=*/false,
5988       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5989       /*isImplicitlyDeclared=*/true,
5990       /*isDefined=*/false, ObjCMethodDecl::Required);
5991   D->addInstanceMethod(CTORMethod);
5992   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5993   D->setHasNonZeroConstructors(true);
5994 }
5995 
5996 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5997 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5998   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5999       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
6000     ErrorUnsupported(LSD, "linkage spec");
6001     return;
6002   }
6003 
6004   EmitDeclContext(LSD);
6005 }
6006 
6007 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
6008   for (auto *I : DC->decls()) {
6009     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6010     // are themselves considered "top-level", so EmitTopLevelDecl on an
6011     // ObjCImplDecl does not recursively visit them. We need to do that in
6012     // case they're nested inside another construct (LinkageSpecDecl /
6013     // ExportDecl) that does stop them from being considered "top-level".
6014     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6015       for (auto *M : OID->methods())
6016         EmitTopLevelDecl(M);
6017     }
6018 
6019     EmitTopLevelDecl(I);
6020   }
6021 }
6022 
6023 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6024 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
6025   // Ignore dependent declarations.
6026   if (D->isTemplated())
6027     return;
6028 
6029   // Consteval function shouldn't be emitted.
6030   if (auto *FD = dyn_cast<FunctionDecl>(D))
6031     if (FD->isConsteval())
6032       return;
6033 
6034   switch (D->getKind()) {
6035   case Decl::CXXConversion:
6036   case Decl::CXXMethod:
6037   case Decl::Function:
6038     EmitGlobal(cast<FunctionDecl>(D));
6039     // Always provide some coverage mapping
6040     // even for the functions that aren't emitted.
6041     AddDeferredUnusedCoverageMapping(D);
6042     break;
6043 
6044   case Decl::CXXDeductionGuide:
6045     // Function-like, but does not result in code emission.
6046     break;
6047 
6048   case Decl::Var:
6049   case Decl::Decomposition:
6050   case Decl::VarTemplateSpecialization:
6051     EmitGlobal(cast<VarDecl>(D));
6052     if (auto *DD = dyn_cast<DecompositionDecl>(D))
6053       for (auto *B : DD->bindings())
6054         if (auto *HD = B->getHoldingVar())
6055           EmitGlobal(HD);
6056     break;
6057 
6058   // Indirect fields from global anonymous structs and unions can be
6059   // ignored; only the actual variable requires IR gen support.
6060   case Decl::IndirectField:
6061     break;
6062 
6063   // C++ Decls
6064   case Decl::Namespace:
6065     EmitDeclContext(cast<NamespaceDecl>(D));
6066     break;
6067   case Decl::ClassTemplateSpecialization: {
6068     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6069     if (CGDebugInfo *DI = getModuleDebugInfo())
6070       if (Spec->getSpecializationKind() ==
6071               TSK_ExplicitInstantiationDefinition &&
6072           Spec->hasDefinition())
6073         DI->completeTemplateDefinition(*Spec);
6074   } LLVM_FALLTHROUGH;
6075   case Decl::CXXRecord: {
6076     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6077     if (CGDebugInfo *DI = getModuleDebugInfo()) {
6078       if (CRD->hasDefinition())
6079         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6080       if (auto *ES = D->getASTContext().getExternalSource())
6081         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6082           DI->completeUnusedClass(*CRD);
6083     }
6084     // Emit any static data members, they may be definitions.
6085     for (auto *I : CRD->decls())
6086       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6087         EmitTopLevelDecl(I);
6088     break;
6089   }
6090     // No code generation needed.
6091   case Decl::UsingShadow:
6092   case Decl::ClassTemplate:
6093   case Decl::VarTemplate:
6094   case Decl::Concept:
6095   case Decl::VarTemplatePartialSpecialization:
6096   case Decl::FunctionTemplate:
6097   case Decl::TypeAliasTemplate:
6098   case Decl::Block:
6099   case Decl::Empty:
6100   case Decl::Binding:
6101     break;
6102   case Decl::Using:          // using X; [C++]
6103     if (CGDebugInfo *DI = getModuleDebugInfo())
6104         DI->EmitUsingDecl(cast<UsingDecl>(*D));
6105     break;
6106   case Decl::UsingEnum: // using enum X; [C++]
6107     if (CGDebugInfo *DI = getModuleDebugInfo())
6108       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6109     break;
6110   case Decl::NamespaceAlias:
6111     if (CGDebugInfo *DI = getModuleDebugInfo())
6112         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6113     break;
6114   case Decl::UsingDirective: // using namespace X; [C++]
6115     if (CGDebugInfo *DI = getModuleDebugInfo())
6116       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6117     break;
6118   case Decl::CXXConstructor:
6119     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6120     break;
6121   case Decl::CXXDestructor:
6122     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6123     break;
6124 
6125   case Decl::StaticAssert:
6126     // Nothing to do.
6127     break;
6128 
6129   // Objective-C Decls
6130 
6131   // Forward declarations, no (immediate) code generation.
6132   case Decl::ObjCInterface:
6133   case Decl::ObjCCategory:
6134     break;
6135 
6136   case Decl::ObjCProtocol: {
6137     auto *Proto = cast<ObjCProtocolDecl>(D);
6138     if (Proto->isThisDeclarationADefinition())
6139       ObjCRuntime->GenerateProtocol(Proto);
6140     break;
6141   }
6142 
6143   case Decl::ObjCCategoryImpl:
6144     // Categories have properties but don't support synthesize so we
6145     // can ignore them here.
6146     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6147     break;
6148 
6149   case Decl::ObjCImplementation: {
6150     auto *OMD = cast<ObjCImplementationDecl>(D);
6151     EmitObjCPropertyImplementations(OMD);
6152     EmitObjCIvarInitializations(OMD);
6153     ObjCRuntime->GenerateClass(OMD);
6154     // Emit global variable debug information.
6155     if (CGDebugInfo *DI = getModuleDebugInfo())
6156       if (getCodeGenOpts().hasReducedDebugInfo())
6157         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
6158             OMD->getClassInterface()), OMD->getLocation());
6159     break;
6160   }
6161   case Decl::ObjCMethod: {
6162     auto *OMD = cast<ObjCMethodDecl>(D);
6163     // If this is not a prototype, emit the body.
6164     if (OMD->getBody())
6165       CodeGenFunction(*this).GenerateObjCMethod(OMD);
6166     break;
6167   }
6168   case Decl::ObjCCompatibleAlias:
6169     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6170     break;
6171 
6172   case Decl::PragmaComment: {
6173     const auto *PCD = cast<PragmaCommentDecl>(D);
6174     switch (PCD->getCommentKind()) {
6175     case PCK_Unknown:
6176       llvm_unreachable("unexpected pragma comment kind");
6177     case PCK_Linker:
6178       AppendLinkerOptions(PCD->getArg());
6179       break;
6180     case PCK_Lib:
6181         AddDependentLib(PCD->getArg());
6182       break;
6183     case PCK_Compiler:
6184     case PCK_ExeStr:
6185     case PCK_User:
6186       break; // We ignore all of these.
6187     }
6188     break;
6189   }
6190 
6191   case Decl::PragmaDetectMismatch: {
6192     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6193     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
6194     break;
6195   }
6196 
6197   case Decl::LinkageSpec:
6198     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6199     break;
6200 
6201   case Decl::FileScopeAsm: {
6202     // File-scope asm is ignored during device-side CUDA compilation.
6203     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6204       break;
6205     // File-scope asm is ignored during device-side OpenMP compilation.
6206     if (LangOpts.OpenMPIsDevice)
6207       break;
6208     // File-scope asm is ignored during device-side SYCL compilation.
6209     if (LangOpts.SYCLIsDevice)
6210       break;
6211     auto *AD = cast<FileScopeAsmDecl>(D);
6212     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6213     break;
6214   }
6215 
6216   case Decl::Import: {
6217     auto *Import = cast<ImportDecl>(D);
6218 
6219     // If we've already imported this module, we're done.
6220     if (!ImportedModules.insert(Import->getImportedModule()))
6221       break;
6222 
6223     // Emit debug information for direct imports.
6224     if (!Import->getImportedOwningModule()) {
6225       if (CGDebugInfo *DI = getModuleDebugInfo())
6226         DI->EmitImportDecl(*Import);
6227     }
6228 
6229     // Find all of the submodules and emit the module initializers.
6230     llvm::SmallPtrSet<clang::Module *, 16> Visited;
6231     SmallVector<clang::Module *, 16> Stack;
6232     Visited.insert(Import->getImportedModule());
6233     Stack.push_back(Import->getImportedModule());
6234 
6235     while (!Stack.empty()) {
6236       clang::Module *Mod = Stack.pop_back_val();
6237       if (!EmittedModuleInitializers.insert(Mod).second)
6238         continue;
6239 
6240       for (auto *D : Context.getModuleInitializers(Mod))
6241         EmitTopLevelDecl(D);
6242 
6243       // Visit the submodules of this module.
6244       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
6245                                              SubEnd = Mod->submodule_end();
6246            Sub != SubEnd; ++Sub) {
6247         // Skip explicit children; they need to be explicitly imported to emit
6248         // the initializers.
6249         if ((*Sub)->IsExplicit)
6250           continue;
6251 
6252         if (Visited.insert(*Sub).second)
6253           Stack.push_back(*Sub);
6254       }
6255     }
6256     break;
6257   }
6258 
6259   case Decl::Export:
6260     EmitDeclContext(cast<ExportDecl>(D));
6261     break;
6262 
6263   case Decl::OMPThreadPrivate:
6264     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
6265     break;
6266 
6267   case Decl::OMPAllocate:
6268     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
6269     break;
6270 
6271   case Decl::OMPDeclareReduction:
6272     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
6273     break;
6274 
6275   case Decl::OMPDeclareMapper:
6276     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
6277     break;
6278 
6279   case Decl::OMPRequires:
6280     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
6281     break;
6282 
6283   case Decl::Typedef:
6284   case Decl::TypeAlias: // using foo = bar; [C++11]
6285     if (CGDebugInfo *DI = getModuleDebugInfo())
6286       DI->EmitAndRetainType(
6287           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
6288     break;
6289 
6290   case Decl::Record:
6291     if (CGDebugInfo *DI = getModuleDebugInfo())
6292       if (cast<RecordDecl>(D)->getDefinition())
6293         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6294     break;
6295 
6296   case Decl::Enum:
6297     if (CGDebugInfo *DI = getModuleDebugInfo())
6298       if (cast<EnumDecl>(D)->getDefinition())
6299         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
6300     break;
6301 
6302   default:
6303     // Make sure we handled everything we should, every other kind is a
6304     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
6305     // function. Need to recode Decl::Kind to do that easily.
6306     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
6307     break;
6308   }
6309 }
6310 
6311 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
6312   // Do we need to generate coverage mapping?
6313   if (!CodeGenOpts.CoverageMapping)
6314     return;
6315   switch (D->getKind()) {
6316   case Decl::CXXConversion:
6317   case Decl::CXXMethod:
6318   case Decl::Function:
6319   case Decl::ObjCMethod:
6320   case Decl::CXXConstructor:
6321   case Decl::CXXDestructor: {
6322     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
6323       break;
6324     SourceManager &SM = getContext().getSourceManager();
6325     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
6326       break;
6327     auto I = DeferredEmptyCoverageMappingDecls.find(D);
6328     if (I == DeferredEmptyCoverageMappingDecls.end())
6329       DeferredEmptyCoverageMappingDecls[D] = true;
6330     break;
6331   }
6332   default:
6333     break;
6334   };
6335 }
6336 
6337 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
6338   // Do we need to generate coverage mapping?
6339   if (!CodeGenOpts.CoverageMapping)
6340     return;
6341   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
6342     if (Fn->isTemplateInstantiation())
6343       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
6344   }
6345   auto I = DeferredEmptyCoverageMappingDecls.find(D);
6346   if (I == DeferredEmptyCoverageMappingDecls.end())
6347     DeferredEmptyCoverageMappingDecls[D] = false;
6348   else
6349     I->second = false;
6350 }
6351 
6352 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
6353   // We call takeVector() here to avoid use-after-free.
6354   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
6355   // we deserialize function bodies to emit coverage info for them, and that
6356   // deserializes more declarations. How should we handle that case?
6357   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
6358     if (!Entry.second)
6359       continue;
6360     const Decl *D = Entry.first;
6361     switch (D->getKind()) {
6362     case Decl::CXXConversion:
6363     case Decl::CXXMethod:
6364     case Decl::Function:
6365     case Decl::ObjCMethod: {
6366       CodeGenPGO PGO(*this);
6367       GlobalDecl GD(cast<FunctionDecl>(D));
6368       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6369                                   getFunctionLinkage(GD));
6370       break;
6371     }
6372     case Decl::CXXConstructor: {
6373       CodeGenPGO PGO(*this);
6374       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
6375       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6376                                   getFunctionLinkage(GD));
6377       break;
6378     }
6379     case Decl::CXXDestructor: {
6380       CodeGenPGO PGO(*this);
6381       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
6382       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6383                                   getFunctionLinkage(GD));
6384       break;
6385     }
6386     default:
6387       break;
6388     };
6389   }
6390 }
6391 
6392 void CodeGenModule::EmitMainVoidAlias() {
6393   // In order to transition away from "__original_main" gracefully, emit an
6394   // alias for "main" in the no-argument case so that libc can detect when
6395   // new-style no-argument main is in used.
6396   if (llvm::Function *F = getModule().getFunction("main")) {
6397     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6398         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
6399       auto *GA = llvm::GlobalAlias::create("__main_void", F);
6400       GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
6401     }
6402   }
6403 }
6404 
6405 /// Turns the given pointer into a constant.
6406 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6407                                           const void *Ptr) {
6408   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6409   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6410   return llvm::ConstantInt::get(i64, PtrInt);
6411 }
6412 
6413 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6414                                    llvm::NamedMDNode *&GlobalMetadata,
6415                                    GlobalDecl D,
6416                                    llvm::GlobalValue *Addr) {
6417   if (!GlobalMetadata)
6418     GlobalMetadata =
6419       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6420 
6421   // TODO: should we report variant information for ctors/dtors?
6422   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6423                            llvm::ConstantAsMetadata::get(GetPointerConstant(
6424                                CGM.getLLVMContext(), D.getDecl()))};
6425   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6426 }
6427 
6428 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
6429                                                  llvm::GlobalValue *CppFunc) {
6430   // Store the list of ifuncs we need to replace uses in.
6431   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
6432   // List of ConstantExprs that we should be able to delete when we're done
6433   // here.
6434   llvm::SmallVector<llvm::ConstantExpr *> CEs;
6435 
6436   // It isn't valid to replace the extern-C ifuncs if all we find is itself!
6437   if (Elem == CppFunc)
6438     return false;
6439 
6440   // First make sure that all users of this are ifuncs (or ifuncs via a
6441   // bitcast), and collect the list of ifuncs and CEs so we can work on them
6442   // later.
6443   for (llvm::User *User : Elem->users()) {
6444     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
6445     // ifunc directly. In any other case, just give up, as we don't know what we
6446     // could break by changing those.
6447     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
6448       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
6449         return false;
6450 
6451       for (llvm::User *CEUser : ConstExpr->users()) {
6452         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
6453           IFuncs.push_back(IFunc);
6454         } else {
6455           return false;
6456         }
6457       }
6458       CEs.push_back(ConstExpr);
6459     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
6460       IFuncs.push_back(IFunc);
6461     } else {
6462       // This user is one we don't know how to handle, so fail redirection. This
6463       // will result in an ifunc retaining a resolver name that will ultimately
6464       // fail to be resolved to a defined function.
6465       return false;
6466     }
6467   }
6468 
6469   // Now we know this is a valid case where we can do this alias replacement, we
6470   // need to remove all of the references to Elem (and the bitcasts!) so we can
6471   // delete it.
6472   for (llvm::GlobalIFunc *IFunc : IFuncs)
6473     IFunc->setResolver(nullptr);
6474   for (llvm::ConstantExpr *ConstExpr : CEs)
6475     ConstExpr->destroyConstant();
6476 
6477   // We should now be out of uses for the 'old' version of this function, so we
6478   // can erase it as well.
6479   Elem->eraseFromParent();
6480 
6481   for (llvm::GlobalIFunc *IFunc : IFuncs) {
6482     // The type of the resolver is always just a function-type that returns the
6483     // type of the IFunc, so create that here. If the type of the actual
6484     // resolver doesn't match, it just gets bitcast to the right thing.
6485     auto *ResolverTy =
6486         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
6487     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
6488         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
6489     IFunc->setResolver(Resolver);
6490   }
6491   return true;
6492 }
6493 
6494 /// For each function which is declared within an extern "C" region and marked
6495 /// as 'used', but has internal linkage, create an alias from the unmangled
6496 /// name to the mangled name if possible. People expect to be able to refer
6497 /// to such functions with an unmangled name from inline assembly within the
6498 /// same translation unit.
6499 void CodeGenModule::EmitStaticExternCAliases() {
6500   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
6501     return;
6502   for (auto &I : StaticExternCValues) {
6503     IdentifierInfo *Name = I.first;
6504     llvm::GlobalValue *Val = I.second;
6505 
6506     // If Val is null, that implies there were multiple declarations that each
6507     // had a claim to the unmangled name. In this case, generation of the alias
6508     // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
6509     if (!Val)
6510       break;
6511 
6512     llvm::GlobalValue *ExistingElem =
6513         getModule().getNamedValue(Name->getName());
6514 
6515     // If there is either not something already by this name, or we were able to
6516     // replace all uses from IFuncs, create the alias.
6517     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
6518       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
6519   }
6520 }
6521 
6522 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
6523                                              GlobalDecl &Result) const {
6524   auto Res = Manglings.find(MangledName);
6525   if (Res == Manglings.end())
6526     return false;
6527   Result = Res->getValue();
6528   return true;
6529 }
6530 
6531 /// Emits metadata nodes associating all the global values in the
6532 /// current module with the Decls they came from.  This is useful for
6533 /// projects using IR gen as a subroutine.
6534 ///
6535 /// Since there's currently no way to associate an MDNode directly
6536 /// with an llvm::GlobalValue, we create a global named metadata
6537 /// with the name 'clang.global.decl.ptrs'.
6538 void CodeGenModule::EmitDeclMetadata() {
6539   llvm::NamedMDNode *GlobalMetadata = nullptr;
6540 
6541   for (auto &I : MangledDeclNames) {
6542     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
6543     // Some mangled names don't necessarily have an associated GlobalValue
6544     // in this module, e.g. if we mangled it for DebugInfo.
6545     if (Addr)
6546       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
6547   }
6548 }
6549 
6550 /// Emits metadata nodes for all the local variables in the current
6551 /// function.
6552 void CodeGenFunction::EmitDeclMetadata() {
6553   if (LocalDeclMap.empty()) return;
6554 
6555   llvm::LLVMContext &Context = getLLVMContext();
6556 
6557   // Find the unique metadata ID for this name.
6558   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
6559 
6560   llvm::NamedMDNode *GlobalMetadata = nullptr;
6561 
6562   for (auto &I : LocalDeclMap) {
6563     const Decl *D = I.first;
6564     llvm::Value *Addr = I.second.getPointer();
6565     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
6566       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
6567       Alloca->setMetadata(
6568           DeclPtrKind, llvm::MDNode::get(
6569                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
6570     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
6571       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
6572       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
6573     }
6574   }
6575 }
6576 
6577 void CodeGenModule::EmitVersionIdentMetadata() {
6578   llvm::NamedMDNode *IdentMetadata =
6579     TheModule.getOrInsertNamedMetadata("llvm.ident");
6580   std::string Version = getClangFullVersion();
6581   llvm::LLVMContext &Ctx = TheModule.getContext();
6582 
6583   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
6584   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
6585 }
6586 
6587 void CodeGenModule::EmitCommandLineMetadata() {
6588   llvm::NamedMDNode *CommandLineMetadata =
6589     TheModule.getOrInsertNamedMetadata("llvm.commandline");
6590   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
6591   llvm::LLVMContext &Ctx = TheModule.getContext();
6592 
6593   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
6594   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
6595 }
6596 
6597 void CodeGenModule::EmitCoverageFile() {
6598   if (getCodeGenOpts().CoverageDataFile.empty() &&
6599       getCodeGenOpts().CoverageNotesFile.empty())
6600     return;
6601 
6602   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
6603   if (!CUNode)
6604     return;
6605 
6606   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
6607   llvm::LLVMContext &Ctx = TheModule.getContext();
6608   auto *CoverageDataFile =
6609       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
6610   auto *CoverageNotesFile =
6611       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
6612   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
6613     llvm::MDNode *CU = CUNode->getOperand(i);
6614     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
6615     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
6616   }
6617 }
6618 
6619 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
6620                                                        bool ForEH) {
6621   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
6622   // FIXME: should we even be calling this method if RTTI is disabled
6623   // and it's not for EH?
6624   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6625       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6626        getTriple().isNVPTX()))
6627     return llvm::Constant::getNullValue(Int8PtrTy);
6628 
6629   if (ForEH && Ty->isObjCObjectPointerType() &&
6630       LangOpts.ObjCRuntime.isGNUFamily())
6631     return ObjCRuntime->GetEHType(Ty);
6632 
6633   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
6634 }
6635 
6636 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
6637   // Do not emit threadprivates in simd-only mode.
6638   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
6639     return;
6640   for (auto RefExpr : D->varlists()) {
6641     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
6642     bool PerformInit =
6643         VD->getAnyInitializer() &&
6644         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
6645                                                         /*ForRef=*/false);
6646 
6647     Address Addr(GetAddrOfGlobalVar(VD),
6648                  getTypes().ConvertTypeForMem(VD->getType()),
6649                  getContext().getDeclAlign(VD));
6650     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
6651             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
6652       CXXGlobalInits.push_back(InitFunction);
6653   }
6654 }
6655 
6656 llvm::Metadata *
6657 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
6658                                             StringRef Suffix) {
6659   if (auto *FnType = T->getAs<FunctionProtoType>())
6660     T = getContext().getFunctionType(
6661         FnType->getReturnType(), FnType->getParamTypes(),
6662         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
6663 
6664   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
6665   if (InternalId)
6666     return InternalId;
6667 
6668   if (isExternallyVisible(T->getLinkage())) {
6669     std::string OutName;
6670     llvm::raw_string_ostream Out(OutName);
6671     getCXXABI().getMangleContext().mangleTypeName(T, Out);
6672     Out << Suffix;
6673 
6674     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
6675   } else {
6676     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
6677                                            llvm::ArrayRef<llvm::Metadata *>());
6678   }
6679 
6680   return InternalId;
6681 }
6682 
6683 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
6684   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
6685 }
6686 
6687 llvm::Metadata *
6688 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6689   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6690 }
6691 
6692 // Generalize pointer types to a void pointer with the qualifiers of the
6693 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
6694 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
6695 // 'void *'.
6696 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6697   if (!Ty->isPointerType())
6698     return Ty;
6699 
6700   return Ctx.getPointerType(
6701       QualType(Ctx.VoidTy).withCVRQualifiers(
6702           Ty->getPointeeType().getCVRQualifiers()));
6703 }
6704 
6705 // Apply type generalization to a FunctionType's return and argument types
6706 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6707   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6708     SmallVector<QualType, 8> GeneralizedParams;
6709     for (auto &Param : FnType->param_types())
6710       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
6711 
6712     return Ctx.getFunctionType(
6713         GeneralizeType(Ctx, FnType->getReturnType()),
6714         GeneralizedParams, FnType->getExtProtoInfo());
6715   }
6716 
6717   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
6718     return Ctx.getFunctionNoProtoType(
6719         GeneralizeType(Ctx, FnType->getReturnType()));
6720 
6721   llvm_unreachable("Encountered unknown FunctionType");
6722 }
6723 
6724 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
6725   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
6726                                       GeneralizedMetadataIdMap, ".generalized");
6727 }
6728 
6729 /// Returns whether this module needs the "all-vtables" type identifier.
6730 bool CodeGenModule::NeedAllVtablesTypeId() const {
6731   // Returns true if at least one of vtable-based CFI checkers is enabled and
6732   // is not in the trapping mode.
6733   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
6734            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
6735           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
6736            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
6737           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
6738            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
6739           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
6740            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
6741 }
6742 
6743 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
6744                                           CharUnits Offset,
6745                                           const CXXRecordDecl *RD) {
6746   llvm::Metadata *MD =
6747       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
6748   VTable->addTypeMetadata(Offset.getQuantity(), MD);
6749 
6750   if (CodeGenOpts.SanitizeCfiCrossDso)
6751     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
6752       VTable->addTypeMetadata(Offset.getQuantity(),
6753                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
6754 
6755   if (NeedAllVtablesTypeId()) {
6756     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
6757     VTable->addTypeMetadata(Offset.getQuantity(), MD);
6758   }
6759 }
6760 
6761 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
6762   if (!SanStats)
6763     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
6764 
6765   return *SanStats;
6766 }
6767 
6768 llvm::Value *
6769 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
6770                                                   CodeGenFunction &CGF) {
6771   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6772   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6773   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6774   auto *Call = CGF.EmitRuntimeCall(
6775       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6776   return Call;
6777 }
6778 
6779 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6780     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6781   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6782                                  /* forPointeeType= */ true);
6783 }
6784 
6785 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6786                                                  LValueBaseInfo *BaseInfo,
6787                                                  TBAAAccessInfo *TBAAInfo,
6788                                                  bool forPointeeType) {
6789   if (TBAAInfo)
6790     *TBAAInfo = getTBAAAccessInfo(T);
6791 
6792   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6793   // that doesn't return the information we need to compute BaseInfo.
6794 
6795   // Honor alignment typedef attributes even on incomplete types.
6796   // We also honor them straight for C++ class types, even as pointees;
6797   // there's an expressivity gap here.
6798   if (auto TT = T->getAs<TypedefType>()) {
6799     if (auto Align = TT->getDecl()->getMaxAlignment()) {
6800       if (BaseInfo)
6801         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6802       return getContext().toCharUnitsFromBits(Align);
6803     }
6804   }
6805 
6806   bool AlignForArray = T->isArrayType();
6807 
6808   // Analyze the base element type, so we don't get confused by incomplete
6809   // array types.
6810   T = getContext().getBaseElementType(T);
6811 
6812   if (T->isIncompleteType()) {
6813     // We could try to replicate the logic from
6814     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6815     // type is incomplete, so it's impossible to test. We could try to reuse
6816     // getTypeAlignIfKnown, but that doesn't return the information we need
6817     // to set BaseInfo.  So just ignore the possibility that the alignment is
6818     // greater than one.
6819     if (BaseInfo)
6820       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6821     return CharUnits::One();
6822   }
6823 
6824   if (BaseInfo)
6825     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6826 
6827   CharUnits Alignment;
6828   const CXXRecordDecl *RD;
6829   if (T.getQualifiers().hasUnaligned()) {
6830     Alignment = CharUnits::One();
6831   } else if (forPointeeType && !AlignForArray &&
6832              (RD = T->getAsCXXRecordDecl())) {
6833     // For C++ class pointees, we don't know whether we're pointing at a
6834     // base or a complete object, so we generally need to use the
6835     // non-virtual alignment.
6836     Alignment = getClassPointerAlignment(RD);
6837   } else {
6838     Alignment = getContext().getTypeAlignInChars(T);
6839   }
6840 
6841   // Cap to the global maximum type alignment unless the alignment
6842   // was somehow explicit on the type.
6843   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6844     if (Alignment.getQuantity() > MaxAlign &&
6845         !getContext().isAlignmentRequired(T))
6846       Alignment = CharUnits::fromQuantity(MaxAlign);
6847   }
6848   return Alignment;
6849 }
6850 
6851 bool CodeGenModule::stopAutoInit() {
6852   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6853   if (StopAfter) {
6854     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6855     // used
6856     if (NumAutoVarInit >= StopAfter) {
6857       return true;
6858     }
6859     if (!NumAutoVarInit) {
6860       unsigned DiagID = getDiags().getCustomDiagID(
6861           DiagnosticsEngine::Warning,
6862           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6863           "number of times ftrivial-auto-var-init=%1 gets applied.");
6864       getDiags().Report(DiagID)
6865           << StopAfter
6866           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6867                       LangOptions::TrivialAutoVarInitKind::Zero
6868                   ? "zero"
6869                   : "pattern");
6870     }
6871     ++NumAutoVarInit;
6872   }
6873   return false;
6874 }
6875 
6876 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
6877                                                     const Decl *D) const {
6878   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
6879   // postfix beginning with '.' since the symbol name can be demangled.
6880   if (LangOpts.HIP)
6881     OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
6882   else
6883     OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
6884 
6885   // If the CUID is not specified we try to generate a unique postfix.
6886   if (getLangOpts().CUID.empty()) {
6887     SourceManager &SM = getContext().getSourceManager();
6888     PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
6889     assert(PLoc.isValid() && "Source location is expected to be valid.");
6890 
6891     // Get the hash of the user defined macros.
6892     llvm::MD5 Hash;
6893     llvm::MD5::MD5Result Result;
6894     for (const auto &Arg : PreprocessorOpts.Macros)
6895       Hash.update(Arg.first);
6896     Hash.final(Result);
6897 
6898     // Get the UniqueID for the file containing the decl.
6899     llvm::sys::fs::UniqueID ID;
6900     if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
6901       PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
6902       assert(PLoc.isValid() && "Source location is expected to be valid.");
6903       if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
6904         SM.getDiagnostics().Report(diag::err_cannot_open_file)
6905             << PLoc.getFilename() << EC.message();
6906     }
6907     OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
6908        << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
6909   } else {
6910     OS << getContext().getCUIDHash();
6911   }
6912 }
6913