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