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