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