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