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