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