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