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