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