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