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