xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 8da70fed704c15d9656cbf2df190122acb975921)
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 we plan on emitting this inline builtin, we can't treat it as a builtin.
2140   if (FD->isInlineBuiltinDeclaration()) {
2141     const FunctionDecl *FDBody;
2142     bool HasBody = FD->hasBody(FDBody);
2143     (void)HasBody;
2144     assert(HasBody && "Inline builtin declarations should always have an "
2145                       "available body!");
2146     if (shouldEmitFunction(FDBody))
2147       F->addFnAttr(llvm::Attribute::NoBuiltin);
2148   }
2149 
2150   if (FD->isReplaceableGlobalAllocationFunction()) {
2151     // A replaceable global allocation function does not act like a builtin by
2152     // default, only if it is invoked by a new-expression or delete-expression.
2153     F->addFnAttr(llvm::Attribute::NoBuiltin);
2154   }
2155 
2156   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2157     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2158   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2159     if (MD->isVirtual())
2160       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2161 
2162   // Don't emit entries for function declarations in the cross-DSO mode. This
2163   // is handled with better precision by the receiving DSO. But if jump tables
2164   // are non-canonical then we need type metadata in order to produce the local
2165   // jump table.
2166   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2167       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2168     CreateFunctionTypeMetadataForIcall(FD, F);
2169 
2170   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2171     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2172 
2173   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2174     // Annotate the callback behavior as metadata:
2175     //  - The callback callee (as argument number).
2176     //  - The callback payloads (as argument numbers).
2177     llvm::LLVMContext &Ctx = F->getContext();
2178     llvm::MDBuilder MDB(Ctx);
2179 
2180     // The payload indices are all but the first one in the encoding. The first
2181     // identifies the callback callee.
2182     int CalleeIdx = *CB->encoding_begin();
2183     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2184     F->addMetadata(llvm::LLVMContext::MD_callback,
2185                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2186                                                CalleeIdx, PayloadIndices,
2187                                                /* VarArgsArePassed */ false)}));
2188   }
2189 }
2190 
2191 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2192   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2193          "Only globals with definition can force usage.");
2194   LLVMUsed.emplace_back(GV);
2195 }
2196 
2197 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2198   assert(!GV->isDeclaration() &&
2199          "Only globals with definition can force usage.");
2200   LLVMCompilerUsed.emplace_back(GV);
2201 }
2202 
2203 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2204   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2205          "Only globals with definition can force usage.");
2206   if (getTriple().isOSBinFormatELF())
2207     LLVMCompilerUsed.emplace_back(GV);
2208   else
2209     LLVMUsed.emplace_back(GV);
2210 }
2211 
2212 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2213                      std::vector<llvm::WeakTrackingVH> &List) {
2214   // Don't create llvm.used if there is no need.
2215   if (List.empty())
2216     return;
2217 
2218   // Convert List to what ConstantArray needs.
2219   SmallVector<llvm::Constant*, 8> UsedArray;
2220   UsedArray.resize(List.size());
2221   for (unsigned i = 0, e = List.size(); i != e; ++i) {
2222     UsedArray[i] =
2223         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2224             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2225   }
2226 
2227   if (UsedArray.empty())
2228     return;
2229   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2230 
2231   auto *GV = new llvm::GlobalVariable(
2232       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2233       llvm::ConstantArray::get(ATy, UsedArray), Name);
2234 
2235   GV->setSection("llvm.metadata");
2236 }
2237 
2238 void CodeGenModule::emitLLVMUsed() {
2239   emitUsed(*this, "llvm.used", LLVMUsed);
2240   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2241 }
2242 
2243 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2244   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2245   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2246 }
2247 
2248 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2249   llvm::SmallString<32> Opt;
2250   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2251   if (Opt.empty())
2252     return;
2253   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2254   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2255 }
2256 
2257 void CodeGenModule::AddDependentLib(StringRef Lib) {
2258   auto &C = getLLVMContext();
2259   if (getTarget().getTriple().isOSBinFormatELF()) {
2260       ELFDependentLibraries.push_back(
2261         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2262     return;
2263   }
2264 
2265   llvm::SmallString<24> Opt;
2266   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2267   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2268   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2269 }
2270 
2271 /// Add link options implied by the given module, including modules
2272 /// it depends on, using a postorder walk.
2273 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2274                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
2275                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
2276   // Import this module's parent.
2277   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2278     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2279   }
2280 
2281   // Import this module's dependencies.
2282   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
2283     if (Visited.insert(Mod->Imports[I - 1]).second)
2284       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
2285   }
2286 
2287   // Add linker options to link against the libraries/frameworks
2288   // described by this module.
2289   llvm::LLVMContext &Context = CGM.getLLVMContext();
2290   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2291 
2292   // For modules that use export_as for linking, use that module
2293   // name instead.
2294   if (Mod->UseExportAsModuleLinkName)
2295     return;
2296 
2297   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
2298     // Link against a framework.  Frameworks are currently Darwin only, so we
2299     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2300     if (Mod->LinkLibraries[I-1].IsFramework) {
2301       llvm::Metadata *Args[2] = {
2302           llvm::MDString::get(Context, "-framework"),
2303           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
2304 
2305       Metadata.push_back(llvm::MDNode::get(Context, Args));
2306       continue;
2307     }
2308 
2309     // Link against a library.
2310     if (IsELF) {
2311       llvm::Metadata *Args[2] = {
2312           llvm::MDString::get(Context, "lib"),
2313           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
2314       };
2315       Metadata.push_back(llvm::MDNode::get(Context, Args));
2316     } else {
2317       llvm::SmallString<24> Opt;
2318       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
2319           Mod->LinkLibraries[I - 1].Library, Opt);
2320       auto *OptString = llvm::MDString::get(Context, Opt);
2321       Metadata.push_back(llvm::MDNode::get(Context, OptString));
2322     }
2323   }
2324 }
2325 
2326 void CodeGenModule::EmitModuleLinkOptions() {
2327   // Collect the set of all of the modules we want to visit to emit link
2328   // options, which is essentially the imported modules and all of their
2329   // non-explicit child modules.
2330   llvm::SetVector<clang::Module *> LinkModules;
2331   llvm::SmallPtrSet<clang::Module *, 16> Visited;
2332   SmallVector<clang::Module *, 16> Stack;
2333 
2334   // Seed the stack with imported modules.
2335   for (Module *M : ImportedModules) {
2336     // Do not add any link flags when an implementation TU of a module imports
2337     // a header of that same module.
2338     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2339         !getLangOpts().isCompilingModule())
2340       continue;
2341     if (Visited.insert(M).second)
2342       Stack.push_back(M);
2343   }
2344 
2345   // Find all of the modules to import, making a little effort to prune
2346   // non-leaf modules.
2347   while (!Stack.empty()) {
2348     clang::Module *Mod = Stack.pop_back_val();
2349 
2350     bool AnyChildren = false;
2351 
2352     // Visit the submodules of this module.
2353     for (const auto &SM : Mod->submodules()) {
2354       // Skip explicit children; they need to be explicitly imported to be
2355       // linked against.
2356       if (SM->IsExplicit)
2357         continue;
2358 
2359       if (Visited.insert(SM).second) {
2360         Stack.push_back(SM);
2361         AnyChildren = true;
2362       }
2363     }
2364 
2365     // We didn't find any children, so add this module to the list of
2366     // modules to link against.
2367     if (!AnyChildren) {
2368       LinkModules.insert(Mod);
2369     }
2370   }
2371 
2372   // Add link options for all of the imported modules in reverse topological
2373   // order.  We don't do anything to try to order import link flags with respect
2374   // to linker options inserted by things like #pragma comment().
2375   SmallVector<llvm::MDNode *, 16> MetadataArgs;
2376   Visited.clear();
2377   for (Module *M : LinkModules)
2378     if (Visited.insert(M).second)
2379       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2380   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2381   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2382 
2383   // Add the linker options metadata flag.
2384   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2385   for (auto *MD : LinkerOptionsMetadata)
2386     NMD->addOperand(MD);
2387 }
2388 
2389 void CodeGenModule::EmitDeferred() {
2390   // Emit deferred declare target declarations.
2391   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2392     getOpenMPRuntime().emitDeferredTargetDecls();
2393 
2394   // Emit code for any potentially referenced deferred decls.  Since a
2395   // previously unused static decl may become used during the generation of code
2396   // for a static function, iterate until no changes are made.
2397 
2398   if (!DeferredVTables.empty()) {
2399     EmitDeferredVTables();
2400 
2401     // Emitting a vtable doesn't directly cause more vtables to
2402     // become deferred, although it can cause functions to be
2403     // emitted that then need those vtables.
2404     assert(DeferredVTables.empty());
2405   }
2406 
2407   // Emit CUDA/HIP static device variables referenced by host code only.
2408   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
2409   // needed for further handling.
2410   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2411     for (const auto *V : getContext().CUDADeviceVarODRUsedByHost)
2412       DeferredDeclsToEmit.push_back(V);
2413 
2414   // Stop if we're out of both deferred vtables and deferred declarations.
2415   if (DeferredDeclsToEmit.empty())
2416     return;
2417 
2418   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2419   // work, it will not interfere with this.
2420   std::vector<GlobalDecl> CurDeclsToEmit;
2421   CurDeclsToEmit.swap(DeferredDeclsToEmit);
2422 
2423   for (GlobalDecl &D : CurDeclsToEmit) {
2424     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2425     // to get GlobalValue with exactly the type we need, not something that
2426     // might had been created for another decl with the same mangled name but
2427     // different type.
2428     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2429         GetAddrOfGlobal(D, ForDefinition));
2430 
2431     // In case of different address spaces, we may still get a cast, even with
2432     // IsForDefinition equal to true. Query mangled names table to get
2433     // GlobalValue.
2434     if (!GV)
2435       GV = GetGlobalValue(getMangledName(D));
2436 
2437     // Make sure GetGlobalValue returned non-null.
2438     assert(GV);
2439 
2440     // Check to see if we've already emitted this.  This is necessary
2441     // for a couple of reasons: first, decls can end up in the
2442     // deferred-decls queue multiple times, and second, decls can end
2443     // up with definitions in unusual ways (e.g. by an extern inline
2444     // function acquiring a strong function redefinition).  Just
2445     // ignore these cases.
2446     if (!GV->isDeclaration())
2447       continue;
2448 
2449     // If this is OpenMP, check if it is legal to emit this global normally.
2450     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2451       continue;
2452 
2453     // Otherwise, emit the definition and move on to the next one.
2454     EmitGlobalDefinition(D, GV);
2455 
2456     // If we found out that we need to emit more decls, do that recursively.
2457     // This has the advantage that the decls are emitted in a DFS and related
2458     // ones are close together, which is convenient for testing.
2459     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2460       EmitDeferred();
2461       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2462     }
2463   }
2464 }
2465 
2466 void CodeGenModule::EmitVTablesOpportunistically() {
2467   // Try to emit external vtables as available_externally if they have emitted
2468   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
2469   // is not allowed to create new references to things that need to be emitted
2470   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2471 
2472   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2473          && "Only emit opportunistic vtables with optimizations");
2474 
2475   for (const CXXRecordDecl *RD : OpportunisticVTables) {
2476     assert(getVTables().isVTableExternal(RD) &&
2477            "This queue should only contain external vtables");
2478     if (getCXXABI().canSpeculativelyEmitVTable(RD))
2479       VTables.GenerateClassData(RD);
2480   }
2481   OpportunisticVTables.clear();
2482 }
2483 
2484 void CodeGenModule::EmitGlobalAnnotations() {
2485   if (Annotations.empty())
2486     return;
2487 
2488   // Create a new global variable for the ConstantStruct in the Module.
2489   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2490     Annotations[0]->getType(), Annotations.size()), Annotations);
2491   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2492                                       llvm::GlobalValue::AppendingLinkage,
2493                                       Array, "llvm.global.annotations");
2494   gv->setSection(AnnotationSection);
2495 }
2496 
2497 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2498   llvm::Constant *&AStr = AnnotationStrings[Str];
2499   if (AStr)
2500     return AStr;
2501 
2502   // Not found yet, create a new global.
2503   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2504   auto *gv =
2505       new llvm::GlobalVariable(getModule(), s->getType(), true,
2506                                llvm::GlobalValue::PrivateLinkage, s, ".str");
2507   gv->setSection(AnnotationSection);
2508   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2509   AStr = gv;
2510   return gv;
2511 }
2512 
2513 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2514   SourceManager &SM = getContext().getSourceManager();
2515   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2516   if (PLoc.isValid())
2517     return EmitAnnotationString(PLoc.getFilename());
2518   return EmitAnnotationString(SM.getBufferName(Loc));
2519 }
2520 
2521 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2522   SourceManager &SM = getContext().getSourceManager();
2523   PresumedLoc PLoc = SM.getPresumedLoc(L);
2524   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2525     SM.getExpansionLineNumber(L);
2526   return llvm::ConstantInt::get(Int32Ty, LineNo);
2527 }
2528 
2529 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2530   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2531   if (Exprs.empty())
2532     return llvm::ConstantPointerNull::get(Int8PtrTy);
2533 
2534   llvm::FoldingSetNodeID ID;
2535   for (Expr *E : Exprs) {
2536     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2537   }
2538   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2539   if (Lookup)
2540     return Lookup;
2541 
2542   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2543   LLVMArgs.reserve(Exprs.size());
2544   ConstantEmitter ConstEmiter(*this);
2545   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2546     const auto *CE = cast<clang::ConstantExpr>(E);
2547     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2548                                     CE->getType());
2549   });
2550   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2551   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2552                                       llvm::GlobalValue::PrivateLinkage, Struct,
2553                                       ".args");
2554   GV->setSection(AnnotationSection);
2555   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2556   auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
2557 
2558   Lookup = Bitcasted;
2559   return Bitcasted;
2560 }
2561 
2562 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2563                                                 const AnnotateAttr *AA,
2564                                                 SourceLocation L) {
2565   // Get the globals for file name, annotation, and the line number.
2566   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2567                  *UnitGV = EmitAnnotationUnit(L),
2568                  *LineNoCst = EmitAnnotationLineNo(L),
2569                  *Args = EmitAnnotationArgs(AA);
2570 
2571   llvm::Constant *ASZeroGV = GV;
2572   if (GV->getAddressSpace() != 0) {
2573     ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2574                    GV, GV->getValueType()->getPointerTo(0));
2575   }
2576 
2577   // Create the ConstantStruct for the global annotation.
2578   llvm::Constant *Fields[] = {
2579       llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
2580       llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2581       llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2582       LineNoCst,
2583       Args,
2584   };
2585   return llvm::ConstantStruct::getAnon(Fields);
2586 }
2587 
2588 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2589                                          llvm::GlobalValue *GV) {
2590   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2591   // Get the struct elements for these annotations.
2592   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2593     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2594 }
2595 
2596 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
2597                                        SourceLocation Loc) const {
2598   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2599   // NoSanitize by function name.
2600   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
2601     return true;
2602   // NoSanitize by location.
2603   if (Loc.isValid())
2604     return NoSanitizeL.containsLocation(Kind, Loc);
2605   // If location is unknown, this may be a compiler-generated function. Assume
2606   // it's located in the main file.
2607   auto &SM = Context.getSourceManager();
2608   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2609     return NoSanitizeL.containsFile(Kind, MainFile->getName());
2610   }
2611   return false;
2612 }
2613 
2614 bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV,
2615                                        SourceLocation Loc, QualType Ty,
2616                                        StringRef Category) const {
2617   // For now globals can be ignored only in ASan and KASan.
2618   const SanitizerMask EnabledAsanMask =
2619       LangOpts.Sanitize.Mask &
2620       (SanitizerKind::Address | SanitizerKind::KernelAddress |
2621        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2622        SanitizerKind::MemTag);
2623   if (!EnabledAsanMask)
2624     return false;
2625   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2626   if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category))
2627     return true;
2628   if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category))
2629     return true;
2630   // Check global type.
2631   if (!Ty.isNull()) {
2632     // Drill down the array types: if global variable of a fixed type is
2633     // not sanitized, we also don't instrument arrays of them.
2634     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2635       Ty = AT->getElementType();
2636     Ty = Ty.getCanonicalType().getUnqualifiedType();
2637     // Only record types (classes, structs etc.) are ignored.
2638     if (Ty->isRecordType()) {
2639       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2640       if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category))
2641         return true;
2642     }
2643   }
2644   return false;
2645 }
2646 
2647 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2648                                    StringRef Category) const {
2649   const auto &XRayFilter = getContext().getXRayFilter();
2650   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2651   auto Attr = ImbueAttr::NONE;
2652   if (Loc.isValid())
2653     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2654   if (Attr == ImbueAttr::NONE)
2655     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2656   switch (Attr) {
2657   case ImbueAttr::NONE:
2658     return false;
2659   case ImbueAttr::ALWAYS:
2660     Fn->addFnAttr("function-instrument", "xray-always");
2661     break;
2662   case ImbueAttr::ALWAYS_ARG1:
2663     Fn->addFnAttr("function-instrument", "xray-always");
2664     Fn->addFnAttr("xray-log-args", "1");
2665     break;
2666   case ImbueAttr::NEVER:
2667     Fn->addFnAttr("function-instrument", "xray-never");
2668     break;
2669   }
2670   return true;
2671 }
2672 
2673 bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
2674                                            SourceLocation Loc) const {
2675   const auto &ProfileList = getContext().getProfileList();
2676   // If the profile list is empty, then instrument everything.
2677   if (ProfileList.isEmpty())
2678     return false;
2679   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
2680   // First, check the function name.
2681   Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
2682   if (V.hasValue())
2683     return *V;
2684   // Next, check the source location.
2685   if (Loc.isValid()) {
2686     Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
2687     if (V.hasValue())
2688       return *V;
2689   }
2690   // If location is unknown, this may be a compiler-generated function. Assume
2691   // it's located in the main file.
2692   auto &SM = Context.getSourceManager();
2693   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2694     Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
2695     if (V.hasValue())
2696       return *V;
2697   }
2698   return ProfileList.getDefault();
2699 }
2700 
2701 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2702   // Never defer when EmitAllDecls is specified.
2703   if (LangOpts.EmitAllDecls)
2704     return true;
2705 
2706   if (CodeGenOpts.KeepStaticConsts) {
2707     const auto *VD = dyn_cast<VarDecl>(Global);
2708     if (VD && VD->getType().isConstQualified() &&
2709         VD->getStorageDuration() == SD_Static)
2710       return true;
2711   }
2712 
2713   return getContext().DeclMustBeEmitted(Global);
2714 }
2715 
2716 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2717   // In OpenMP 5.0 variables and function may be marked as
2718   // device_type(host/nohost) and we should not emit them eagerly unless we sure
2719   // that they must be emitted on the host/device. To be sure we need to have
2720   // seen a declare target with an explicit mentioning of the function, we know
2721   // we have if the level of the declare target attribute is -1. Note that we
2722   // check somewhere else if we should emit this at all.
2723   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
2724     llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
2725         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
2726     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
2727       return false;
2728   }
2729 
2730   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2731     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2732       // Implicit template instantiations may change linkage if they are later
2733       // explicitly instantiated, so they should not be emitted eagerly.
2734       return false;
2735   }
2736   if (const auto *VD = dyn_cast<VarDecl>(Global))
2737     if (Context.getInlineVariableDefinitionKind(VD) ==
2738         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2739       // A definition of an inline constexpr static data member may change
2740       // linkage later if it's redeclared outside the class.
2741       return false;
2742   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2743   // codegen for global variables, because they may be marked as threadprivate.
2744   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2745       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2746       !isTypeConstant(Global->getType(), false) &&
2747       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2748     return false;
2749 
2750   return true;
2751 }
2752 
2753 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2754   StringRef Name = getMangledName(GD);
2755 
2756   // The UUID descriptor should be pointer aligned.
2757   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2758 
2759   // Look for an existing global.
2760   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2761     return ConstantAddress(GV, Alignment);
2762 
2763   ConstantEmitter Emitter(*this);
2764   llvm::Constant *Init;
2765 
2766   APValue &V = GD->getAsAPValue();
2767   if (!V.isAbsent()) {
2768     // If possible, emit the APValue version of the initializer. In particular,
2769     // this gets the type of the constant right.
2770     Init = Emitter.emitForInitializer(
2771         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2772   } else {
2773     // As a fallback, directly construct the constant.
2774     // FIXME: This may get padding wrong under esoteric struct layout rules.
2775     // MSVC appears to create a complete type 'struct __s_GUID' that it
2776     // presumably uses to represent these constants.
2777     MSGuidDecl::Parts Parts = GD->getParts();
2778     llvm::Constant *Fields[4] = {
2779         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2780         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2781         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2782         llvm::ConstantDataArray::getRaw(
2783             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2784             Int8Ty)};
2785     Init = llvm::ConstantStruct::getAnon(Fields);
2786   }
2787 
2788   auto *GV = new llvm::GlobalVariable(
2789       getModule(), Init->getType(),
2790       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2791   if (supportsCOMDAT())
2792     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2793   setDSOLocal(GV);
2794 
2795   llvm::Constant *Addr = GV;
2796   if (!V.isAbsent()) {
2797     Emitter.finalize(GV);
2798   } else {
2799     llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2800     Addr = llvm::ConstantExpr::getBitCast(
2801         GV, Ty->getPointerTo(GV->getAddressSpace()));
2802   }
2803   return ConstantAddress(Addr, Alignment);
2804 }
2805 
2806 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
2807     const TemplateParamObjectDecl *TPO) {
2808   StringRef Name = getMangledName(TPO);
2809   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
2810 
2811   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2812     return ConstantAddress(GV, Alignment);
2813 
2814   ConstantEmitter Emitter(*this);
2815   llvm::Constant *Init = Emitter.emitForInitializer(
2816         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
2817 
2818   if (!Init) {
2819     ErrorUnsupported(TPO, "template parameter object");
2820     return ConstantAddress::invalid();
2821   }
2822 
2823   auto *GV = new llvm::GlobalVariable(
2824       getModule(), Init->getType(),
2825       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2826   if (supportsCOMDAT())
2827     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2828   Emitter.finalize(GV);
2829 
2830   return ConstantAddress(GV, Alignment);
2831 }
2832 
2833 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2834   const AliasAttr *AA = VD->getAttr<AliasAttr>();
2835   assert(AA && "No alias?");
2836 
2837   CharUnits Alignment = getContext().getDeclAlign(VD);
2838   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2839 
2840   // See if there is already something with the target's name in the module.
2841   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2842   if (Entry) {
2843     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2844     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2845     return ConstantAddress(Ptr, Alignment);
2846   }
2847 
2848   llvm::Constant *Aliasee;
2849   if (isa<llvm::FunctionType>(DeclTy))
2850     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2851                                       GlobalDecl(cast<FunctionDecl>(VD)),
2852                                       /*ForVTable=*/false);
2853   else
2854     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
2855                                     nullptr);
2856 
2857   auto *F = cast<llvm::GlobalValue>(Aliasee);
2858   F->setLinkage(llvm::Function::ExternalWeakLinkage);
2859   WeakRefReferences.insert(F);
2860 
2861   return ConstantAddress(Aliasee, Alignment);
2862 }
2863 
2864 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2865   const auto *Global = cast<ValueDecl>(GD.getDecl());
2866 
2867   // Weak references don't produce any output by themselves.
2868   if (Global->hasAttr<WeakRefAttr>())
2869     return;
2870 
2871   // If this is an alias definition (which otherwise looks like a declaration)
2872   // emit it now.
2873   if (Global->hasAttr<AliasAttr>())
2874     return EmitAliasDefinition(GD);
2875 
2876   // IFunc like an alias whose value is resolved at runtime by calling resolver.
2877   if (Global->hasAttr<IFuncAttr>())
2878     return emitIFuncDefinition(GD);
2879 
2880   // If this is a cpu_dispatch multiversion function, emit the resolver.
2881   if (Global->hasAttr<CPUDispatchAttr>())
2882     return emitCPUDispatchDefinition(GD);
2883 
2884   // If this is CUDA, be selective about which declarations we emit.
2885   if (LangOpts.CUDA) {
2886     if (LangOpts.CUDAIsDevice) {
2887       if (!Global->hasAttr<CUDADeviceAttr>() &&
2888           !Global->hasAttr<CUDAGlobalAttr>() &&
2889           !Global->hasAttr<CUDAConstantAttr>() &&
2890           !Global->hasAttr<CUDASharedAttr>() &&
2891           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
2892           !Global->getType()->isCUDADeviceBuiltinTextureType())
2893         return;
2894     } else {
2895       // We need to emit host-side 'shadows' for all global
2896       // device-side variables because the CUDA runtime needs their
2897       // size and host-side address in order to provide access to
2898       // their device-side incarnations.
2899 
2900       // So device-only functions are the only things we skip.
2901       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2902           Global->hasAttr<CUDADeviceAttr>())
2903         return;
2904 
2905       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2906              "Expected Variable or Function");
2907     }
2908   }
2909 
2910   if (LangOpts.OpenMP) {
2911     // If this is OpenMP, check if it is legal to emit this global normally.
2912     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2913       return;
2914     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2915       if (MustBeEmitted(Global))
2916         EmitOMPDeclareReduction(DRD);
2917       return;
2918     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2919       if (MustBeEmitted(Global))
2920         EmitOMPDeclareMapper(DMD);
2921       return;
2922     }
2923   }
2924 
2925   // Ignore declarations, they will be emitted on their first use.
2926   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2927     // Forward declarations are emitted lazily on first use.
2928     if (!FD->doesThisDeclarationHaveABody()) {
2929       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2930         return;
2931 
2932       StringRef MangledName = getMangledName(GD);
2933 
2934       // Compute the function info and LLVM type.
2935       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2936       llvm::Type *Ty = getTypes().GetFunctionType(FI);
2937 
2938       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2939                               /*DontDefer=*/false);
2940       return;
2941     }
2942   } else {
2943     const auto *VD = cast<VarDecl>(Global);
2944     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2945     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2946         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2947       if (LangOpts.OpenMP) {
2948         // Emit declaration of the must-be-emitted declare target variable.
2949         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2950                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2951           bool UnifiedMemoryEnabled =
2952               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2953           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2954               !UnifiedMemoryEnabled) {
2955             (void)GetAddrOfGlobalVar(VD);
2956           } else {
2957             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2958                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2959                      UnifiedMemoryEnabled)) &&
2960                    "Link clause or to clause with unified memory expected.");
2961             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2962           }
2963 
2964           return;
2965         }
2966       }
2967       // If this declaration may have caused an inline variable definition to
2968       // change linkage, make sure that it's emitted.
2969       if (Context.getInlineVariableDefinitionKind(VD) ==
2970           ASTContext::InlineVariableDefinitionKind::Strong)
2971         GetAddrOfGlobalVar(VD);
2972       return;
2973     }
2974   }
2975 
2976   // Defer code generation to first use when possible, e.g. if this is an inline
2977   // function. If the global must always be emitted, do it eagerly if possible
2978   // to benefit from cache locality.
2979   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2980     // Emit the definition if it can't be deferred.
2981     EmitGlobalDefinition(GD);
2982     return;
2983   }
2984 
2985   // If we're deferring emission of a C++ variable with an
2986   // initializer, remember the order in which it appeared in the file.
2987   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2988       cast<VarDecl>(Global)->hasInit()) {
2989     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2990     CXXGlobalInits.push_back(nullptr);
2991   }
2992 
2993   StringRef MangledName = getMangledName(GD);
2994   if (GetGlobalValue(MangledName) != nullptr) {
2995     // The value has already been used and should therefore be emitted.
2996     addDeferredDeclToEmit(GD);
2997   } else if (MustBeEmitted(Global)) {
2998     // The value must be emitted, but cannot be emitted eagerly.
2999     assert(!MayBeEmittedEagerly(Global));
3000     addDeferredDeclToEmit(GD);
3001   } else {
3002     // Otherwise, remember that we saw a deferred decl with this name.  The
3003     // first use of the mangled name will cause it to move into
3004     // DeferredDeclsToEmit.
3005     DeferredDecls[MangledName] = GD;
3006   }
3007 }
3008 
3009 // Check if T is a class type with a destructor that's not dllimport.
3010 static bool HasNonDllImportDtor(QualType T) {
3011   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3012     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3013       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3014         return true;
3015 
3016   return false;
3017 }
3018 
3019 namespace {
3020   struct FunctionIsDirectlyRecursive
3021       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3022     const StringRef Name;
3023     const Builtin::Context &BI;
3024     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3025         : Name(N), BI(C) {}
3026 
3027     bool VisitCallExpr(const CallExpr *E) {
3028       const FunctionDecl *FD = E->getDirectCallee();
3029       if (!FD)
3030         return false;
3031       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3032       if (Attr && Name == Attr->getLabel())
3033         return true;
3034       unsigned BuiltinID = FD->getBuiltinID();
3035       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3036         return false;
3037       StringRef BuiltinName = BI.getName(BuiltinID);
3038       if (BuiltinName.startswith("__builtin_") &&
3039           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3040         return true;
3041       }
3042       return false;
3043     }
3044 
3045     bool VisitStmt(const Stmt *S) {
3046       for (const Stmt *Child : S->children())
3047         if (Child && this->Visit(Child))
3048           return true;
3049       return false;
3050     }
3051   };
3052 
3053   // Make sure we're not referencing non-imported vars or functions.
3054   struct DLLImportFunctionVisitor
3055       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3056     bool SafeToInline = true;
3057 
3058     bool shouldVisitImplicitCode() const { return true; }
3059 
3060     bool VisitVarDecl(VarDecl *VD) {
3061       if (VD->getTLSKind()) {
3062         // A thread-local variable cannot be imported.
3063         SafeToInline = false;
3064         return SafeToInline;
3065       }
3066 
3067       // A variable definition might imply a destructor call.
3068       if (VD->isThisDeclarationADefinition())
3069         SafeToInline = !HasNonDllImportDtor(VD->getType());
3070 
3071       return SafeToInline;
3072     }
3073 
3074     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3075       if (const auto *D = E->getTemporary()->getDestructor())
3076         SafeToInline = D->hasAttr<DLLImportAttr>();
3077       return SafeToInline;
3078     }
3079 
3080     bool VisitDeclRefExpr(DeclRefExpr *E) {
3081       ValueDecl *VD = E->getDecl();
3082       if (isa<FunctionDecl>(VD))
3083         SafeToInline = VD->hasAttr<DLLImportAttr>();
3084       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3085         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3086       return SafeToInline;
3087     }
3088 
3089     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3090       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3091       return SafeToInline;
3092     }
3093 
3094     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3095       CXXMethodDecl *M = E->getMethodDecl();
3096       if (!M) {
3097         // Call through a pointer to member function. This is safe to inline.
3098         SafeToInline = true;
3099       } else {
3100         SafeToInline = M->hasAttr<DLLImportAttr>();
3101       }
3102       return SafeToInline;
3103     }
3104 
3105     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3106       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3107       return SafeToInline;
3108     }
3109 
3110     bool VisitCXXNewExpr(CXXNewExpr *E) {
3111       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3112       return SafeToInline;
3113     }
3114   };
3115 }
3116 
3117 // isTriviallyRecursive - Check if this function calls another
3118 // decl that, because of the asm attribute or the other decl being a builtin,
3119 // ends up pointing to itself.
3120 bool
3121 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3122   StringRef Name;
3123   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3124     // asm labels are a special kind of mangling we have to support.
3125     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3126     if (!Attr)
3127       return false;
3128     Name = Attr->getLabel();
3129   } else {
3130     Name = FD->getName();
3131   }
3132 
3133   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3134   const Stmt *Body = FD->getBody();
3135   return Body ? Walker.Visit(Body) : false;
3136 }
3137 
3138 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3139   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3140     return true;
3141   const auto *F = cast<FunctionDecl>(GD.getDecl());
3142   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3143     return false;
3144 
3145   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3146     // Check whether it would be safe to inline this dllimport function.
3147     DLLImportFunctionVisitor Visitor;
3148     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3149     if (!Visitor.SafeToInline)
3150       return false;
3151 
3152     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3153       // Implicit destructor invocations aren't captured in the AST, so the
3154       // check above can't see them. Check for them manually here.
3155       for (const Decl *Member : Dtor->getParent()->decls())
3156         if (isa<FieldDecl>(Member))
3157           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3158             return false;
3159       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3160         if (HasNonDllImportDtor(B.getType()))
3161           return false;
3162     }
3163   }
3164 
3165   // PR9614. Avoid cases where the source code is lying to us. An available
3166   // externally function should have an equivalent function somewhere else,
3167   // but a function that calls itself through asm label/`__builtin_` trickery is
3168   // clearly not equivalent to the real implementation.
3169   // This happens in glibc's btowc and in some configure checks.
3170   return !isTriviallyRecursive(F);
3171 }
3172 
3173 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3174   return CodeGenOpts.OptimizationLevel > 0;
3175 }
3176 
3177 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3178                                                        llvm::GlobalValue *GV) {
3179   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3180 
3181   if (FD->isCPUSpecificMultiVersion()) {
3182     auto *Spec = FD->getAttr<CPUSpecificAttr>();
3183     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3184       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3185     // Requires multiple emits.
3186   } else
3187     EmitGlobalFunctionDefinition(GD, GV);
3188 }
3189 
3190 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3191   const auto *D = cast<ValueDecl>(GD.getDecl());
3192 
3193   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3194                                  Context.getSourceManager(),
3195                                  "Generating code for declaration");
3196 
3197   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3198     // At -O0, don't generate IR for functions with available_externally
3199     // linkage.
3200     if (!shouldEmitFunction(GD))
3201       return;
3202 
3203     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3204       std::string Name;
3205       llvm::raw_string_ostream OS(Name);
3206       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3207                                /*Qualified=*/true);
3208       return Name;
3209     });
3210 
3211     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3212       // Make sure to emit the definition(s) before we emit the thunks.
3213       // This is necessary for the generation of certain thunks.
3214       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3215         ABI->emitCXXStructor(GD);
3216       else if (FD->isMultiVersion())
3217         EmitMultiVersionFunctionDefinition(GD, GV);
3218       else
3219         EmitGlobalFunctionDefinition(GD, GV);
3220 
3221       if (Method->isVirtual())
3222         getVTables().EmitThunks(GD);
3223 
3224       return;
3225     }
3226 
3227     if (FD->isMultiVersion())
3228       return EmitMultiVersionFunctionDefinition(GD, GV);
3229     return EmitGlobalFunctionDefinition(GD, GV);
3230   }
3231 
3232   if (const auto *VD = dyn_cast<VarDecl>(D))
3233     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3234 
3235   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
3236 }
3237 
3238 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3239                                                       llvm::Function *NewFn);
3240 
3241 static unsigned
3242 TargetMVPriority(const TargetInfo &TI,
3243                  const CodeGenFunction::MultiVersionResolverOption &RO) {
3244   unsigned Priority = 0;
3245   for (StringRef Feat : RO.Conditions.Features)
3246     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3247 
3248   if (!RO.Conditions.Architecture.empty())
3249     Priority = std::max(
3250         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3251   return Priority;
3252 }
3253 
3254 void CodeGenModule::emitMultiVersionFunctions() {
3255   std::vector<GlobalDecl> MVFuncsToEmit;
3256   MultiVersionFuncs.swap(MVFuncsToEmit);
3257   for (GlobalDecl GD : MVFuncsToEmit) {
3258     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3259     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3260     getContext().forEachMultiversionedFunctionVersion(
3261         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3262           GlobalDecl CurGD{
3263               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3264           StringRef MangledName = getMangledName(CurGD);
3265           llvm::Constant *Func = GetGlobalValue(MangledName);
3266           if (!Func) {
3267             if (CurFD->isDefined()) {
3268               EmitGlobalFunctionDefinition(CurGD, nullptr);
3269               Func = GetGlobalValue(MangledName);
3270             } else {
3271               const CGFunctionInfo &FI =
3272                   getTypes().arrangeGlobalDeclaration(GD);
3273               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3274               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3275                                        /*DontDefer=*/false, ForDefinition);
3276             }
3277             assert(Func && "This should have just been created");
3278           }
3279 
3280           const auto *TA = CurFD->getAttr<TargetAttr>();
3281           llvm::SmallVector<StringRef, 8> Feats;
3282           TA->getAddedFeatures(Feats);
3283 
3284           Options.emplace_back(cast<llvm::Function>(Func),
3285                                TA->getArchitecture(), Feats);
3286         });
3287 
3288     llvm::Function *ResolverFunc;
3289     const TargetInfo &TI = getTarget();
3290 
3291     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
3292       ResolverFunc = cast<llvm::Function>(
3293           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3294       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3295     } else {
3296       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3297     }
3298 
3299     if (supportsCOMDAT())
3300       ResolverFunc->setComdat(
3301           getModule().getOrInsertComdat(ResolverFunc->getName()));
3302 
3303     llvm::stable_sort(
3304         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3305                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
3306           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3307         });
3308     CodeGenFunction CGF(*this);
3309     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3310   }
3311 
3312   // Ensure that any additions to the deferred decls list caused by emitting a
3313   // variant are emitted.  This can happen when the variant itself is inline and
3314   // calls a function without linkage.
3315   if (!MVFuncsToEmit.empty())
3316     EmitDeferred();
3317 
3318   // Ensure that any additions to the multiversion funcs list from either the
3319   // deferred decls or the multiversion functions themselves are emitted.
3320   if (!MultiVersionFuncs.empty())
3321     emitMultiVersionFunctions();
3322 }
3323 
3324 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3325   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3326   assert(FD && "Not a FunctionDecl?");
3327   const auto *DD = FD->getAttr<CPUDispatchAttr>();
3328   assert(DD && "Not a cpu_dispatch Function?");
3329   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
3330 
3331   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
3332     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
3333     DeclTy = getTypes().GetFunctionType(FInfo);
3334   }
3335 
3336   StringRef ResolverName = getMangledName(GD);
3337 
3338   llvm::Type *ResolverType;
3339   GlobalDecl ResolverGD;
3340   if (getTarget().supportsIFunc())
3341     ResolverType = llvm::FunctionType::get(
3342         llvm::PointerType::get(DeclTy,
3343                                Context.getTargetAddressSpace(FD->getType())),
3344         false);
3345   else {
3346     ResolverType = DeclTy;
3347     ResolverGD = GD;
3348   }
3349 
3350   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3351       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3352   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3353   if (supportsCOMDAT())
3354     ResolverFunc->setComdat(
3355         getModule().getOrInsertComdat(ResolverFunc->getName()));
3356 
3357   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3358   const TargetInfo &Target = getTarget();
3359   unsigned Index = 0;
3360   for (const IdentifierInfo *II : DD->cpus()) {
3361     // Get the name of the target function so we can look it up/create it.
3362     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3363                               getCPUSpecificMangling(*this, II->getName());
3364 
3365     llvm::Constant *Func = GetGlobalValue(MangledName);
3366 
3367     if (!Func) {
3368       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3369       if (ExistingDecl.getDecl() &&
3370           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3371         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3372         Func = GetGlobalValue(MangledName);
3373       } else {
3374         if (!ExistingDecl.getDecl())
3375           ExistingDecl = GD.getWithMultiVersionIndex(Index);
3376 
3377       Func = GetOrCreateLLVMFunction(
3378           MangledName, DeclTy, ExistingDecl,
3379           /*ForVTable=*/false, /*DontDefer=*/true,
3380           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3381       }
3382     }
3383 
3384     llvm::SmallVector<StringRef, 32> Features;
3385     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3386     llvm::transform(Features, Features.begin(),
3387                     [](StringRef Str) { return Str.substr(1); });
3388     Features.erase(std::remove_if(
3389         Features.begin(), Features.end(), [&Target](StringRef Feat) {
3390           return !Target.validateCpuSupports(Feat);
3391         }), Features.end());
3392     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3393     ++Index;
3394   }
3395 
3396   llvm::stable_sort(
3397       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3398                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
3399         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3400                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3401       });
3402 
3403   // If the list contains multiple 'default' versions, such as when it contains
3404   // 'pentium' and 'generic', don't emit the call to the generic one (since we
3405   // always run on at least a 'pentium'). We do this by deleting the 'least
3406   // advanced' (read, lowest mangling letter).
3407   while (Options.size() > 1 &&
3408          CodeGenFunction::GetX86CpuSupportsMask(
3409              (Options.end() - 2)->Conditions.Features) == 0) {
3410     StringRef LHSName = (Options.end() - 2)->Function->getName();
3411     StringRef RHSName = (Options.end() - 1)->Function->getName();
3412     if (LHSName.compare(RHSName) < 0)
3413       Options.erase(Options.end() - 2);
3414     else
3415       Options.erase(Options.end() - 1);
3416   }
3417 
3418   CodeGenFunction CGF(*this);
3419   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3420 
3421   if (getTarget().supportsIFunc()) {
3422     std::string AliasName = getMangledNameImpl(
3423         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3424     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3425     if (!AliasFunc) {
3426       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3427           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3428           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3429       auto *GA = llvm::GlobalAlias::create(
3430          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3431       GA->setLinkage(llvm::Function::WeakODRLinkage);
3432       SetCommonAttributes(GD, GA);
3433     }
3434   }
3435 }
3436 
3437 /// If a dispatcher for the specified mangled name is not in the module, create
3438 /// and return an llvm Function with the specified type.
3439 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3440     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3441   std::string MangledName =
3442       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3443 
3444   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3445   // a separate resolver).
3446   std::string ResolverName = MangledName;
3447   if (getTarget().supportsIFunc())
3448     ResolverName += ".ifunc";
3449   else if (FD->isTargetMultiVersion())
3450     ResolverName += ".resolver";
3451 
3452   // If this already exists, just return that one.
3453   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3454     return ResolverGV;
3455 
3456   // Since this is the first time we've created this IFunc, make sure
3457   // that we put this multiversioned function into the list to be
3458   // replaced later if necessary (target multiversioning only).
3459   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3460     MultiVersionFuncs.push_back(GD);
3461 
3462   if (getTarget().supportsIFunc()) {
3463     llvm::Type *ResolverType = llvm::FunctionType::get(
3464         llvm::PointerType::get(
3465             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3466         false);
3467     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3468         MangledName + ".resolver", ResolverType, GlobalDecl{},
3469         /*ForVTable=*/false);
3470     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3471         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3472     GIF->setName(ResolverName);
3473     SetCommonAttributes(FD, GIF);
3474 
3475     return GIF;
3476   }
3477 
3478   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3479       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3480   assert(isa<llvm::GlobalValue>(Resolver) &&
3481          "Resolver should be created for the first time");
3482   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3483   return Resolver;
3484 }
3485 
3486 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3487 /// module, create and return an llvm Function with the specified type. If there
3488 /// is something in the module with the specified name, return it potentially
3489 /// bitcasted to the right type.
3490 ///
3491 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3492 /// to set the attributes on the function when it is first created.
3493 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3494     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3495     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3496     ForDefinition_t IsForDefinition) {
3497   const Decl *D = GD.getDecl();
3498 
3499   // Any attempts to use a MultiVersion function should result in retrieving
3500   // the iFunc instead. Name Mangling will handle the rest of the changes.
3501   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3502     // For the device mark the function as one that should be emitted.
3503     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3504         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3505         !DontDefer && !IsForDefinition) {
3506       if (const FunctionDecl *FDDef = FD->getDefinition()) {
3507         GlobalDecl GDDef;
3508         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3509           GDDef = GlobalDecl(CD, GD.getCtorType());
3510         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3511           GDDef = GlobalDecl(DD, GD.getDtorType());
3512         else
3513           GDDef = GlobalDecl(FDDef);
3514         EmitGlobal(GDDef);
3515       }
3516     }
3517 
3518     if (FD->isMultiVersion()) {
3519       if (FD->hasAttr<TargetAttr>())
3520         UpdateMultiVersionNames(GD, FD);
3521       if (!IsForDefinition)
3522         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3523     }
3524   }
3525 
3526   // Lookup the entry, lazily creating it if necessary.
3527   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3528   if (Entry) {
3529     if (WeakRefReferences.erase(Entry)) {
3530       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3531       if (FD && !FD->hasAttr<WeakAttr>())
3532         Entry->setLinkage(llvm::Function::ExternalLinkage);
3533     }
3534 
3535     // Handle dropped DLL attributes.
3536     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3537       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3538       setDSOLocal(Entry);
3539     }
3540 
3541     // If there are two attempts to define the same mangled name, issue an
3542     // error.
3543     if (IsForDefinition && !Entry->isDeclaration()) {
3544       GlobalDecl OtherGD;
3545       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3546       // to make sure that we issue an error only once.
3547       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3548           (GD.getCanonicalDecl().getDecl() !=
3549            OtherGD.getCanonicalDecl().getDecl()) &&
3550           DiagnosedConflictingDefinitions.insert(GD).second) {
3551         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3552             << MangledName;
3553         getDiags().Report(OtherGD.getDecl()->getLocation(),
3554                           diag::note_previous_definition);
3555       }
3556     }
3557 
3558     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3559         (Entry->getValueType() == Ty)) {
3560       return Entry;
3561     }
3562 
3563     // Make sure the result is of the correct type.
3564     // (If function is requested for a definition, we always need to create a new
3565     // function, not just return a bitcast.)
3566     if (!IsForDefinition)
3567       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3568   }
3569 
3570   // This function doesn't have a complete type (for example, the return
3571   // type is an incomplete struct). Use a fake type instead, and make
3572   // sure not to try to set attributes.
3573   bool IsIncompleteFunction = false;
3574 
3575   llvm::FunctionType *FTy;
3576   if (isa<llvm::FunctionType>(Ty)) {
3577     FTy = cast<llvm::FunctionType>(Ty);
3578   } else {
3579     FTy = llvm::FunctionType::get(VoidTy, false);
3580     IsIncompleteFunction = true;
3581   }
3582 
3583   llvm::Function *F =
3584       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3585                              Entry ? StringRef() : MangledName, &getModule());
3586 
3587   // If we already created a function with the same mangled name (but different
3588   // type) before, take its name and add it to the list of functions to be
3589   // replaced with F at the end of CodeGen.
3590   //
3591   // This happens if there is a prototype for a function (e.g. "int f()") and
3592   // then a definition of a different type (e.g. "int f(int x)").
3593   if (Entry) {
3594     F->takeName(Entry);
3595 
3596     // This might be an implementation of a function without a prototype, in
3597     // which case, try to do special replacement of calls which match the new
3598     // prototype.  The really key thing here is that we also potentially drop
3599     // arguments from the call site so as to make a direct call, which makes the
3600     // inliner happier and suppresses a number of optimizer warnings (!) about
3601     // dropping arguments.
3602     if (!Entry->use_empty()) {
3603       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3604       Entry->removeDeadConstantUsers();
3605     }
3606 
3607     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3608         F, Entry->getValueType()->getPointerTo());
3609     addGlobalValReplacement(Entry, BC);
3610   }
3611 
3612   assert(F->getName() == MangledName && "name was uniqued!");
3613   if (D)
3614     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3615   if (ExtraAttrs.hasFnAttrs()) {
3616     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3617     F->addFnAttrs(B);
3618   }
3619 
3620   if (!DontDefer) {
3621     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3622     // each other bottoming out with the base dtor.  Therefore we emit non-base
3623     // dtors on usage, even if there is no dtor definition in the TU.
3624     if (D && isa<CXXDestructorDecl>(D) &&
3625         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3626                                            GD.getDtorType()))
3627       addDeferredDeclToEmit(GD);
3628 
3629     // This is the first use or definition of a mangled name.  If there is a
3630     // deferred decl with this name, remember that we need to emit it at the end
3631     // of the file.
3632     auto DDI = DeferredDecls.find(MangledName);
3633     if (DDI != DeferredDecls.end()) {
3634       // Move the potentially referenced deferred decl to the
3635       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3636       // don't need it anymore).
3637       addDeferredDeclToEmit(DDI->second);
3638       DeferredDecls.erase(DDI);
3639 
3640       // Otherwise, there are cases we have to worry about where we're
3641       // using a declaration for which we must emit a definition but where
3642       // we might not find a top-level definition:
3643       //   - member functions defined inline in their classes
3644       //   - friend functions defined inline in some class
3645       //   - special member functions with implicit definitions
3646       // If we ever change our AST traversal to walk into class methods,
3647       // this will be unnecessary.
3648       //
3649       // We also don't emit a definition for a function if it's going to be an
3650       // entry in a vtable, unless it's already marked as used.
3651     } else if (getLangOpts().CPlusPlus && D) {
3652       // Look for a declaration that's lexically in a record.
3653       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3654            FD = FD->getPreviousDecl()) {
3655         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3656           if (FD->doesThisDeclarationHaveABody()) {
3657             addDeferredDeclToEmit(GD.getWithDecl(FD));
3658             break;
3659           }
3660         }
3661       }
3662     }
3663   }
3664 
3665   // Make sure the result is of the requested type.
3666   if (!IsIncompleteFunction) {
3667     assert(F->getFunctionType() == Ty);
3668     return F;
3669   }
3670 
3671   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3672   return llvm::ConstantExpr::getBitCast(F, PTy);
3673 }
3674 
3675 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
3676 /// non-null, then this function will use the specified type if it has to
3677 /// create it (this occurs when we see a definition of the function).
3678 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3679                                                  llvm::Type *Ty,
3680                                                  bool ForVTable,
3681                                                  bool DontDefer,
3682                                               ForDefinition_t IsForDefinition) {
3683   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
3684          "consteval function should never be emitted");
3685   // If there was no specific requested type, just convert it now.
3686   if (!Ty) {
3687     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3688     Ty = getTypes().ConvertType(FD->getType());
3689   }
3690 
3691   // Devirtualized destructor calls may come through here instead of via
3692   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3693   // of the complete destructor when necessary.
3694   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3695     if (getTarget().getCXXABI().isMicrosoft() &&
3696         GD.getDtorType() == Dtor_Complete &&
3697         DD->getParent()->getNumVBases() == 0)
3698       GD = GlobalDecl(DD, Dtor_Base);
3699   }
3700 
3701   StringRef MangledName = getMangledName(GD);
3702   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3703                                     /*IsThunk=*/false, llvm::AttributeList(),
3704                                     IsForDefinition);
3705   // Returns kernel handle for HIP kernel stub function.
3706   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
3707       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
3708     auto *Handle = getCUDARuntime().getKernelHandle(
3709         cast<llvm::Function>(F->stripPointerCasts()), GD);
3710     if (IsForDefinition)
3711       return F;
3712     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
3713   }
3714   return F;
3715 }
3716 
3717 static const FunctionDecl *
3718 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3719   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3720   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3721 
3722   IdentifierInfo &CII = C.Idents.get(Name);
3723   for (const auto *Result : DC->lookup(&CII))
3724     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3725       return FD;
3726 
3727   if (!C.getLangOpts().CPlusPlus)
3728     return nullptr;
3729 
3730   // Demangle the premangled name from getTerminateFn()
3731   IdentifierInfo &CXXII =
3732       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3733           ? C.Idents.get("terminate")
3734           : C.Idents.get(Name);
3735 
3736   for (const auto &N : {"__cxxabiv1", "std"}) {
3737     IdentifierInfo &NS = C.Idents.get(N);
3738     for (const auto *Result : DC->lookup(&NS)) {
3739       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3740       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
3741         for (const auto *Result : LSD->lookup(&NS))
3742           if ((ND = dyn_cast<NamespaceDecl>(Result)))
3743             break;
3744 
3745       if (ND)
3746         for (const auto *Result : ND->lookup(&CXXII))
3747           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3748             return FD;
3749     }
3750   }
3751 
3752   return nullptr;
3753 }
3754 
3755 /// CreateRuntimeFunction - Create a new runtime function with the specified
3756 /// type and name.
3757 llvm::FunctionCallee
3758 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3759                                      llvm::AttributeList ExtraAttrs, bool Local,
3760                                      bool AssumeConvergent) {
3761   if (AssumeConvergent) {
3762     ExtraAttrs =
3763         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
3764   }
3765 
3766   llvm::Constant *C =
3767       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3768                               /*DontDefer=*/false, /*IsThunk=*/false,
3769                               ExtraAttrs);
3770 
3771   if (auto *F = dyn_cast<llvm::Function>(C)) {
3772     if (F->empty()) {
3773       F->setCallingConv(getRuntimeCC());
3774 
3775       // In Windows Itanium environments, try to mark runtime functions
3776       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3777       // will link their standard library statically or dynamically. Marking
3778       // functions imported when they are not imported can cause linker errors
3779       // and warnings.
3780       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3781           !getCodeGenOpts().LTOVisibilityPublicStd) {
3782         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3783         if (!FD || FD->hasAttr<DLLImportAttr>()) {
3784           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3785           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3786         }
3787       }
3788       setDSOLocal(F);
3789     }
3790   }
3791 
3792   return {FTy, C};
3793 }
3794 
3795 /// isTypeConstant - Determine whether an object of this type can be emitted
3796 /// as a constant.
3797 ///
3798 /// If ExcludeCtor is true, the duration when the object's constructor runs
3799 /// will not be considered. The caller will need to verify that the object is
3800 /// not written to during its construction.
3801 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3802   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3803     return false;
3804 
3805   if (Context.getLangOpts().CPlusPlus) {
3806     if (const CXXRecordDecl *Record
3807           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3808       return ExcludeCtor && !Record->hasMutableFields() &&
3809              Record->hasTrivialDestructor();
3810   }
3811 
3812   return true;
3813 }
3814 
3815 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3816 /// create and return an llvm GlobalVariable with the specified type and address
3817 /// space. If there is something in the module with the specified name, return
3818 /// it potentially bitcasted to the right type.
3819 ///
3820 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3821 /// to set the attributes on the global when it is first created.
3822 ///
3823 /// If IsForDefinition is true, it is guaranteed that an actual global with
3824 /// type Ty will be returned, not conversion of a variable with the same
3825 /// mangled name but some other type.
3826 llvm::Constant *
3827 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
3828                                      LangAS AddrSpace, const VarDecl *D,
3829                                      ForDefinition_t IsForDefinition) {
3830   // Lookup the entry, lazily creating it if necessary.
3831   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3832   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
3833   if (Entry) {
3834     if (WeakRefReferences.erase(Entry)) {
3835       if (D && !D->hasAttr<WeakAttr>())
3836         Entry->setLinkage(llvm::Function::ExternalLinkage);
3837     }
3838 
3839     // Handle dropped DLL attributes.
3840     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3841       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3842 
3843     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3844       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3845 
3846     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
3847       return Entry;
3848 
3849     // If there are two attempts to define the same mangled name, issue an
3850     // error.
3851     if (IsForDefinition && !Entry->isDeclaration()) {
3852       GlobalDecl OtherGD;
3853       const VarDecl *OtherD;
3854 
3855       // Check that D is not yet in DiagnosedConflictingDefinitions is required
3856       // to make sure that we issue an error only once.
3857       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3858           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3859           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3860           OtherD->hasInit() &&
3861           DiagnosedConflictingDefinitions.insert(D).second) {
3862         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3863             << MangledName;
3864         getDiags().Report(OtherGD.getDecl()->getLocation(),
3865                           diag::note_previous_definition);
3866       }
3867     }
3868 
3869     // Make sure the result is of the correct type.
3870     if (Entry->getType()->getAddressSpace() != TargetAS) {
3871       return llvm::ConstantExpr::getAddrSpaceCast(Entry,
3872                                                   Ty->getPointerTo(TargetAS));
3873     }
3874 
3875     // (If global is requested for a definition, we always need to create a new
3876     // global, not just return a bitcast.)
3877     if (!IsForDefinition)
3878       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
3879   }
3880 
3881   auto DAddrSpace = GetGlobalVarAddressSpace(D);
3882 
3883   auto *GV = new llvm::GlobalVariable(
3884       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
3885       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
3886       getContext().getTargetAddressSpace(DAddrSpace));
3887 
3888   // If we already created a global with the same mangled name (but different
3889   // type) before, take its name and remove it from its parent.
3890   if (Entry) {
3891     GV->takeName(Entry);
3892 
3893     if (!Entry->use_empty()) {
3894       llvm::Constant *NewPtrForOldDecl =
3895           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3896       Entry->replaceAllUsesWith(NewPtrForOldDecl);
3897     }
3898 
3899     Entry->eraseFromParent();
3900   }
3901 
3902   // This is the first use or definition of a mangled name.  If there is a
3903   // deferred decl with this name, remember that we need to emit it at the end
3904   // of the file.
3905   auto DDI = DeferredDecls.find(MangledName);
3906   if (DDI != DeferredDecls.end()) {
3907     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3908     // list, and remove it from DeferredDecls (since we don't need it anymore).
3909     addDeferredDeclToEmit(DDI->second);
3910     DeferredDecls.erase(DDI);
3911   }
3912 
3913   // Handle things which are present even on external declarations.
3914   if (D) {
3915     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3916       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3917 
3918     // FIXME: This code is overly simple and should be merged with other global
3919     // handling.
3920     GV->setConstant(isTypeConstant(D->getType(), false));
3921 
3922     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3923 
3924     setLinkageForGV(GV, D);
3925 
3926     if (D->getTLSKind()) {
3927       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3928         CXXThreadLocals.push_back(D);
3929       setTLSMode(GV, *D);
3930     }
3931 
3932     setGVProperties(GV, D);
3933 
3934     // If required by the ABI, treat declarations of static data members with
3935     // inline initializers as definitions.
3936     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3937       EmitGlobalVarDefinition(D);
3938     }
3939 
3940     // Emit section information for extern variables.
3941     if (D->hasExternalStorage()) {
3942       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3943         GV->setSection(SA->getName());
3944     }
3945 
3946     // Handle XCore specific ABI requirements.
3947     if (getTriple().getArch() == llvm::Triple::xcore &&
3948         D->getLanguageLinkage() == CLanguageLinkage &&
3949         D->getType().isConstant(Context) &&
3950         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3951       GV->setSection(".cp.rodata");
3952 
3953     // Check if we a have a const declaration with an initializer, we may be
3954     // able to emit it as available_externally to expose it's value to the
3955     // optimizer.
3956     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3957         D->getType().isConstQualified() && !GV->hasInitializer() &&
3958         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3959       const auto *Record =
3960           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3961       bool HasMutableFields = Record && Record->hasMutableFields();
3962       if (!HasMutableFields) {
3963         const VarDecl *InitDecl;
3964         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3965         if (InitExpr) {
3966           ConstantEmitter emitter(*this);
3967           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3968           if (Init) {
3969             auto *InitType = Init->getType();
3970             if (GV->getValueType() != InitType) {
3971               // The type of the initializer does not match the definition.
3972               // This happens when an initializer has a different type from
3973               // the type of the global (because of padding at the end of a
3974               // structure for instance).
3975               GV->setName(StringRef());
3976               // Make a new global with the correct type, this is now guaranteed
3977               // to work.
3978               auto *NewGV = cast<llvm::GlobalVariable>(
3979                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3980                       ->stripPointerCasts());
3981 
3982               // Erase the old global, since it is no longer used.
3983               GV->eraseFromParent();
3984               GV = NewGV;
3985             } else {
3986               GV->setInitializer(Init);
3987               GV->setConstant(true);
3988               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3989             }
3990             emitter.finalize(GV);
3991           }
3992         }
3993       }
3994     }
3995   }
3996 
3997   if (GV->isDeclaration()) {
3998     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3999     // External HIP managed variables needed to be recorded for transformation
4000     // in both device and host compilations.
4001     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4002         D->hasExternalStorage())
4003       getCUDARuntime().handleVarRegistration(D, *GV);
4004   }
4005 
4006   LangAS ExpectedAS =
4007       D ? D->getType().getAddressSpace()
4008         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4009   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4010   if (DAddrSpace != ExpectedAS) {
4011     return getTargetCodeGenInfo().performAddrSpaceCast(
4012         *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
4013   }
4014 
4015   return GV;
4016 }
4017 
4018 llvm::Constant *
4019 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4020   const Decl *D = GD.getDecl();
4021 
4022   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4023     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4024                                 /*DontDefer=*/false, IsForDefinition);
4025 
4026   if (isa<CXXMethodDecl>(D)) {
4027     auto FInfo =
4028         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4029     auto Ty = getTypes().GetFunctionType(*FInfo);
4030     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4031                              IsForDefinition);
4032   }
4033 
4034   if (isa<FunctionDecl>(D)) {
4035     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4036     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4037     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4038                              IsForDefinition);
4039   }
4040 
4041   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4042 }
4043 
4044 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4045     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4046     unsigned Alignment) {
4047   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4048   llvm::GlobalVariable *OldGV = nullptr;
4049 
4050   if (GV) {
4051     // Check if the variable has the right type.
4052     if (GV->getValueType() == Ty)
4053       return GV;
4054 
4055     // Because C++ name mangling, the only way we can end up with an already
4056     // existing global with the same name is if it has been declared extern "C".
4057     assert(GV->isDeclaration() && "Declaration has wrong type!");
4058     OldGV = GV;
4059   }
4060 
4061   // Create a new variable.
4062   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4063                                 Linkage, nullptr, Name);
4064 
4065   if (OldGV) {
4066     // Replace occurrences of the old variable if needed.
4067     GV->takeName(OldGV);
4068 
4069     if (!OldGV->use_empty()) {
4070       llvm::Constant *NewPtrForOldDecl =
4071       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4072       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4073     }
4074 
4075     OldGV->eraseFromParent();
4076   }
4077 
4078   if (supportsCOMDAT() && GV->isWeakForLinker() &&
4079       !GV->hasAvailableExternallyLinkage())
4080     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4081 
4082   GV->setAlignment(llvm::MaybeAlign(Alignment));
4083 
4084   return GV;
4085 }
4086 
4087 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4088 /// given global variable.  If Ty is non-null and if the global doesn't exist,
4089 /// then it will be created with the specified type instead of whatever the
4090 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4091 /// that an actual global with type Ty will be returned, not conversion of a
4092 /// variable with the same mangled name but some other type.
4093 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4094                                                   llvm::Type *Ty,
4095                                            ForDefinition_t IsForDefinition) {
4096   assert(D->hasGlobalStorage() && "Not a global variable");
4097   QualType ASTTy = D->getType();
4098   if (!Ty)
4099     Ty = getTypes().ConvertTypeForMem(ASTTy);
4100 
4101   StringRef MangledName = getMangledName(D);
4102   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
4103                                IsForDefinition);
4104 }
4105 
4106 /// CreateRuntimeVariable - Create a new runtime global variable with the
4107 /// specified type and name.
4108 llvm::Constant *
4109 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4110                                      StringRef Name) {
4111   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
4112                                                        : LangAS::Default;
4113   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4114   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4115   return Ret;
4116 }
4117 
4118 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4119   assert(!D->getInit() && "Cannot emit definite definitions here!");
4120 
4121   StringRef MangledName = getMangledName(D);
4122   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4123 
4124   // We already have a definition, not declaration, with the same mangled name.
4125   // Emitting of declaration is not required (and actually overwrites emitted
4126   // definition).
4127   if (GV && !GV->isDeclaration())
4128     return;
4129 
4130   // If we have not seen a reference to this variable yet, place it into the
4131   // deferred declarations table to be emitted if needed later.
4132   if (!MustBeEmitted(D) && !GV) {
4133       DeferredDecls[MangledName] = D;
4134       return;
4135   }
4136 
4137   // The tentative definition is the only definition.
4138   EmitGlobalVarDefinition(D);
4139 }
4140 
4141 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4142   EmitExternalVarDeclaration(D);
4143 }
4144 
4145 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4146   return Context.toCharUnitsFromBits(
4147       getDataLayout().getTypeStoreSizeInBits(Ty));
4148 }
4149 
4150 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4151   if (LangOpts.OpenCL) {
4152     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4153     assert(AS == LangAS::opencl_global ||
4154            AS == LangAS::opencl_global_device ||
4155            AS == LangAS::opencl_global_host ||
4156            AS == LangAS::opencl_constant ||
4157            AS == LangAS::opencl_local ||
4158            AS >= LangAS::FirstTargetAddressSpace);
4159     return AS;
4160   }
4161 
4162   if (LangOpts.SYCLIsDevice &&
4163       (!D || D->getType().getAddressSpace() == LangAS::Default))
4164     return LangAS::sycl_global;
4165 
4166   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4167     if (D && D->hasAttr<CUDAConstantAttr>())
4168       return LangAS::cuda_constant;
4169     else if (D && D->hasAttr<CUDASharedAttr>())
4170       return LangAS::cuda_shared;
4171     else if (D && D->hasAttr<CUDADeviceAttr>())
4172       return LangAS::cuda_device;
4173     else if (D && D->getType().isConstQualified())
4174       return LangAS::cuda_constant;
4175     else
4176       return LangAS::cuda_device;
4177   }
4178 
4179   if (LangOpts.OpenMP) {
4180     LangAS AS;
4181     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4182       return AS;
4183   }
4184   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4185 }
4186 
4187 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4188   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4189   if (LangOpts.OpenCL)
4190     return LangAS::opencl_constant;
4191   if (LangOpts.SYCLIsDevice)
4192     return LangAS::sycl_global;
4193   if (auto AS = getTarget().getConstantAddressSpace())
4194     return AS.getValue();
4195   return LangAS::Default;
4196 }
4197 
4198 // In address space agnostic languages, string literals are in default address
4199 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4200 // emitted in constant address space in LLVM IR. To be consistent with other
4201 // parts of AST, string literal global variables in constant address space
4202 // need to be casted to default address space before being put into address
4203 // map and referenced by other part of CodeGen.
4204 // In OpenCL, string literals are in constant address space in AST, therefore
4205 // they should not be casted to default address space.
4206 static llvm::Constant *
4207 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4208                                        llvm::GlobalVariable *GV) {
4209   llvm::Constant *Cast = GV;
4210   if (!CGM.getLangOpts().OpenCL) {
4211     auto AS = CGM.GetGlobalConstantAddressSpace();
4212     if (AS != LangAS::Default)
4213       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4214           CGM, GV, AS, LangAS::Default,
4215           GV->getValueType()->getPointerTo(
4216               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4217   }
4218   return Cast;
4219 }
4220 
4221 template<typename SomeDecl>
4222 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4223                                                llvm::GlobalValue *GV) {
4224   if (!getLangOpts().CPlusPlus)
4225     return;
4226 
4227   // Must have 'used' attribute, or else inline assembly can't rely on
4228   // the name existing.
4229   if (!D->template hasAttr<UsedAttr>())
4230     return;
4231 
4232   // Must have internal linkage and an ordinary name.
4233   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4234     return;
4235 
4236   // Must be in an extern "C" context. Entities declared directly within
4237   // a record are not extern "C" even if the record is in such a context.
4238   const SomeDecl *First = D->getFirstDecl();
4239   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4240     return;
4241 
4242   // OK, this is an internal linkage entity inside an extern "C" linkage
4243   // specification. Make a note of that so we can give it the "expected"
4244   // mangled name if nothing else is using that name.
4245   std::pair<StaticExternCMap::iterator, bool> R =
4246       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4247 
4248   // If we have multiple internal linkage entities with the same name
4249   // in extern "C" regions, none of them gets that name.
4250   if (!R.second)
4251     R.first->second = nullptr;
4252 }
4253 
4254 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4255   if (!CGM.supportsCOMDAT())
4256     return false;
4257 
4258   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
4259   // them being "merged" by the COMDAT Folding linker optimization.
4260   if (D.hasAttr<CUDAGlobalAttr>())
4261     return false;
4262 
4263   if (D.hasAttr<SelectAnyAttr>())
4264     return true;
4265 
4266   GVALinkage Linkage;
4267   if (auto *VD = dyn_cast<VarDecl>(&D))
4268     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4269   else
4270     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4271 
4272   switch (Linkage) {
4273   case GVA_Internal:
4274   case GVA_AvailableExternally:
4275   case GVA_StrongExternal:
4276     return false;
4277   case GVA_DiscardableODR:
4278   case GVA_StrongODR:
4279     return true;
4280   }
4281   llvm_unreachable("No such linkage");
4282 }
4283 
4284 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4285                                           llvm::GlobalObject &GO) {
4286   if (!shouldBeInCOMDAT(*this, D))
4287     return;
4288   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4289 }
4290 
4291 /// Pass IsTentative as true if you want to create a tentative definition.
4292 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4293                                             bool IsTentative) {
4294   // OpenCL global variables of sampler type are translated to function calls,
4295   // therefore no need to be translated.
4296   QualType ASTTy = D->getType();
4297   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4298     return;
4299 
4300   // If this is OpenMP device, check if it is legal to emit this global
4301   // normally.
4302   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4303       OpenMPRuntime->emitTargetGlobalVariable(D))
4304     return;
4305 
4306   llvm::TrackingVH<llvm::Constant> Init;
4307   bool NeedsGlobalCtor = false;
4308   bool NeedsGlobalDtor =
4309       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4310 
4311   const VarDecl *InitDecl;
4312   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4313 
4314   Optional<ConstantEmitter> emitter;
4315 
4316   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4317   // as part of their declaration."  Sema has already checked for
4318   // error cases, so we just need to set Init to UndefValue.
4319   bool IsCUDASharedVar =
4320       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4321   // Shadows of initialized device-side global variables are also left
4322   // undefined.
4323   // Managed Variables should be initialized on both host side and device side.
4324   bool IsCUDAShadowVar =
4325       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4326       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4327        D->hasAttr<CUDASharedAttr>());
4328   bool IsCUDADeviceShadowVar =
4329       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4330       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4331        D->getType()->isCUDADeviceBuiltinTextureType());
4332   if (getLangOpts().CUDA &&
4333       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4334     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4335   else if (D->hasAttr<LoaderUninitializedAttr>())
4336     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4337   else if (!InitExpr) {
4338     // This is a tentative definition; tentative definitions are
4339     // implicitly initialized with { 0 }.
4340     //
4341     // Note that tentative definitions are only emitted at the end of
4342     // a translation unit, so they should never have incomplete
4343     // type. In addition, EmitTentativeDefinition makes sure that we
4344     // never attempt to emit a tentative definition if a real one
4345     // exists. A use may still exists, however, so we still may need
4346     // to do a RAUW.
4347     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4348     Init = EmitNullConstant(D->getType());
4349   } else {
4350     initializedGlobalDecl = GlobalDecl(D);
4351     emitter.emplace(*this);
4352     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
4353     if (!Initializer) {
4354       QualType T = InitExpr->getType();
4355       if (D->getType()->isReferenceType())
4356         T = D->getType();
4357 
4358       if (getLangOpts().CPlusPlus) {
4359         Init = EmitNullConstant(T);
4360         NeedsGlobalCtor = true;
4361       } else {
4362         ErrorUnsupported(D, "static initializer");
4363         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4364       }
4365     } else {
4366       Init = Initializer;
4367       // We don't need an initializer, so remove the entry for the delayed
4368       // initializer position (just in case this entry was delayed) if we
4369       // also don't need to register a destructor.
4370       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4371         DelayedCXXInitPosition.erase(D);
4372     }
4373   }
4374 
4375   llvm::Type* InitType = Init->getType();
4376   llvm::Constant *Entry =
4377       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4378 
4379   // Strip off pointer casts if we got them.
4380   Entry = Entry->stripPointerCasts();
4381 
4382   // Entry is now either a Function or GlobalVariable.
4383   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4384 
4385   // We have a definition after a declaration with the wrong type.
4386   // We must make a new GlobalVariable* and update everything that used OldGV
4387   // (a declaration or tentative definition) with the new GlobalVariable*
4388   // (which will be a definition).
4389   //
4390   // This happens if there is a prototype for a global (e.g.
4391   // "extern int x[];") and then a definition of a different type (e.g.
4392   // "int x[10];"). This also happens when an initializer has a different type
4393   // from the type of the global (this happens with unions).
4394   if (!GV || GV->getValueType() != InitType ||
4395       GV->getType()->getAddressSpace() !=
4396           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4397 
4398     // Move the old entry aside so that we'll create a new one.
4399     Entry->setName(StringRef());
4400 
4401     // Make a new global with the correct type, this is now guaranteed to work.
4402     GV = cast<llvm::GlobalVariable>(
4403         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4404             ->stripPointerCasts());
4405 
4406     // Replace all uses of the old global with the new global
4407     llvm::Constant *NewPtrForOldDecl =
4408         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4409                                                              Entry->getType());
4410     Entry->replaceAllUsesWith(NewPtrForOldDecl);
4411 
4412     // Erase the old global, since it is no longer used.
4413     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4414   }
4415 
4416   MaybeHandleStaticInExternC(D, GV);
4417 
4418   if (D->hasAttr<AnnotateAttr>())
4419     AddGlobalAnnotations(D, GV);
4420 
4421   // Set the llvm linkage type as appropriate.
4422   llvm::GlobalValue::LinkageTypes Linkage =
4423       getLLVMLinkageVarDefinition(D, GV->isConstant());
4424 
4425   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4426   // the device. [...]"
4427   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4428   // __device__, declares a variable that: [...]
4429   // Is accessible from all the threads within the grid and from the host
4430   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4431   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4432   if (GV && LangOpts.CUDA) {
4433     if (LangOpts.CUDAIsDevice) {
4434       if (Linkage != llvm::GlobalValue::InternalLinkage &&
4435           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
4436            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4437            D->getType()->isCUDADeviceBuiltinTextureType()))
4438         GV->setExternallyInitialized(true);
4439     } else {
4440       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4441     }
4442     getCUDARuntime().handleVarRegistration(D, *GV);
4443   }
4444 
4445   GV->setInitializer(Init);
4446   if (emitter)
4447     emitter->finalize(GV);
4448 
4449   // If it is safe to mark the global 'constant', do so now.
4450   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4451                   isTypeConstant(D->getType(), true));
4452 
4453   // If it is in a read-only section, mark it 'constant'.
4454   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4455     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4456     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4457       GV->setConstant(true);
4458   }
4459 
4460   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4461 
4462   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4463   // function is only defined alongside the variable, not also alongside
4464   // callers. Normally, all accesses to a thread_local go through the
4465   // thread-wrapper in order to ensure initialization has occurred, underlying
4466   // variable will never be used other than the thread-wrapper, so it can be
4467   // converted to internal linkage.
4468   //
4469   // However, if the variable has the 'constinit' attribute, it _can_ be
4470   // referenced directly, without calling the thread-wrapper, so the linkage
4471   // must not be changed.
4472   //
4473   // Additionally, if the variable isn't plain external linkage, e.g. if it's
4474   // weak or linkonce, the de-duplication semantics are important to preserve,
4475   // so we don't change the linkage.
4476   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4477       Linkage == llvm::GlobalValue::ExternalLinkage &&
4478       Context.getTargetInfo().getTriple().isOSDarwin() &&
4479       !D->hasAttr<ConstInitAttr>())
4480     Linkage = llvm::GlobalValue::InternalLinkage;
4481 
4482   GV->setLinkage(Linkage);
4483   if (D->hasAttr<DLLImportAttr>())
4484     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4485   else if (D->hasAttr<DLLExportAttr>())
4486     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4487   else
4488     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4489 
4490   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4491     // common vars aren't constant even if declared const.
4492     GV->setConstant(false);
4493     // Tentative definition of global variables may be initialized with
4494     // non-zero null pointers. In this case they should have weak linkage
4495     // since common linkage must have zero initializer and must not have
4496     // explicit section therefore cannot have non-zero initial value.
4497     if (!GV->getInitializer()->isNullValue())
4498       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4499   }
4500 
4501   setNonAliasAttributes(D, GV);
4502 
4503   if (D->getTLSKind() && !GV->isThreadLocal()) {
4504     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4505       CXXThreadLocals.push_back(D);
4506     setTLSMode(GV, *D);
4507   }
4508 
4509   maybeSetTrivialComdat(*D, *GV);
4510 
4511   // Emit the initializer function if necessary.
4512   if (NeedsGlobalCtor || NeedsGlobalDtor)
4513     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4514 
4515   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4516 
4517   // Emit global variable debug information.
4518   if (CGDebugInfo *DI = getModuleDebugInfo())
4519     if (getCodeGenOpts().hasReducedDebugInfo())
4520       DI->EmitGlobalVariable(GV, D);
4521 }
4522 
4523 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4524   if (CGDebugInfo *DI = getModuleDebugInfo())
4525     if (getCodeGenOpts().hasReducedDebugInfo()) {
4526       QualType ASTTy = D->getType();
4527       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4528       llvm::Constant *GV =
4529           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
4530       DI->EmitExternalVariable(
4531           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4532     }
4533 }
4534 
4535 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4536                                       CodeGenModule &CGM, const VarDecl *D,
4537                                       bool NoCommon) {
4538   // Don't give variables common linkage if -fno-common was specified unless it
4539   // was overridden by a NoCommon attribute.
4540   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4541     return true;
4542 
4543   // C11 6.9.2/2:
4544   //   A declaration of an identifier for an object that has file scope without
4545   //   an initializer, and without a storage-class specifier or with the
4546   //   storage-class specifier static, constitutes a tentative definition.
4547   if (D->getInit() || D->hasExternalStorage())
4548     return true;
4549 
4550   // A variable cannot be both common and exist in a section.
4551   if (D->hasAttr<SectionAttr>())
4552     return true;
4553 
4554   // A variable cannot be both common and exist in a section.
4555   // We don't try to determine which is the right section in the front-end.
4556   // If no specialized section name is applicable, it will resort to default.
4557   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4558       D->hasAttr<PragmaClangDataSectionAttr>() ||
4559       D->hasAttr<PragmaClangRelroSectionAttr>() ||
4560       D->hasAttr<PragmaClangRodataSectionAttr>())
4561     return true;
4562 
4563   // Thread local vars aren't considered common linkage.
4564   if (D->getTLSKind())
4565     return true;
4566 
4567   // Tentative definitions marked with WeakImportAttr are true definitions.
4568   if (D->hasAttr<WeakImportAttr>())
4569     return true;
4570 
4571   // A variable cannot be both common and exist in a comdat.
4572   if (shouldBeInCOMDAT(CGM, *D))
4573     return true;
4574 
4575   // Declarations with a required alignment do not have common linkage in MSVC
4576   // mode.
4577   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4578     if (D->hasAttr<AlignedAttr>())
4579       return true;
4580     QualType VarType = D->getType();
4581     if (Context.isAlignmentRequired(VarType))
4582       return true;
4583 
4584     if (const auto *RT = VarType->getAs<RecordType>()) {
4585       const RecordDecl *RD = RT->getDecl();
4586       for (const FieldDecl *FD : RD->fields()) {
4587         if (FD->isBitField())
4588           continue;
4589         if (FD->hasAttr<AlignedAttr>())
4590           return true;
4591         if (Context.isAlignmentRequired(FD->getType()))
4592           return true;
4593       }
4594     }
4595   }
4596 
4597   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4598   // common symbols, so symbols with greater alignment requirements cannot be
4599   // common.
4600   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4601   // alignments for common symbols via the aligncomm directive, so this
4602   // restriction only applies to MSVC environments.
4603   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4604       Context.getTypeAlignIfKnown(D->getType()) >
4605           Context.toBits(CharUnits::fromQuantity(32)))
4606     return true;
4607 
4608   return false;
4609 }
4610 
4611 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4612     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4613   if (Linkage == GVA_Internal)
4614     return llvm::Function::InternalLinkage;
4615 
4616   if (D->hasAttr<WeakAttr>()) {
4617     if (IsConstantVariable)
4618       return llvm::GlobalVariable::WeakODRLinkage;
4619     else
4620       return llvm::GlobalVariable::WeakAnyLinkage;
4621   }
4622 
4623   if (const auto *FD = D->getAsFunction())
4624     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4625       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4626 
4627   // We are guaranteed to have a strong definition somewhere else,
4628   // so we can use available_externally linkage.
4629   if (Linkage == GVA_AvailableExternally)
4630     return llvm::GlobalValue::AvailableExternallyLinkage;
4631 
4632   // Note that Apple's kernel linker doesn't support symbol
4633   // coalescing, so we need to avoid linkonce and weak linkages there.
4634   // Normally, this means we just map to internal, but for explicit
4635   // instantiations we'll map to external.
4636 
4637   // In C++, the compiler has to emit a definition in every translation unit
4638   // that references the function.  We should use linkonce_odr because
4639   // a) if all references in this translation unit are optimized away, we
4640   // don't need to codegen it.  b) if the function persists, it needs to be
4641   // merged with other definitions. c) C++ has the ODR, so we know the
4642   // definition is dependable.
4643   if (Linkage == GVA_DiscardableODR)
4644     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4645                                             : llvm::Function::InternalLinkage;
4646 
4647   // An explicit instantiation of a template has weak linkage, since
4648   // explicit instantiations can occur in multiple translation units
4649   // and must all be equivalent. However, we are not allowed to
4650   // throw away these explicit instantiations.
4651   //
4652   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
4653   // so say that CUDA templates are either external (for kernels) or internal.
4654   // This lets llvm perform aggressive inter-procedural optimizations. For
4655   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4656   // therefore we need to follow the normal linkage paradigm.
4657   if (Linkage == GVA_StrongODR) {
4658     if (getLangOpts().AppleKext)
4659       return llvm::Function::ExternalLinkage;
4660     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4661         !getLangOpts().GPURelocatableDeviceCode)
4662       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4663                                           : llvm::Function::InternalLinkage;
4664     return llvm::Function::WeakODRLinkage;
4665   }
4666 
4667   // C++ doesn't have tentative definitions and thus cannot have common
4668   // linkage.
4669   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4670       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4671                                  CodeGenOpts.NoCommon))
4672     return llvm::GlobalVariable::CommonLinkage;
4673 
4674   // selectany symbols are externally visible, so use weak instead of
4675   // linkonce.  MSVC optimizes away references to const selectany globals, so
4676   // all definitions should be the same and ODR linkage should be used.
4677   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4678   if (D->hasAttr<SelectAnyAttr>())
4679     return llvm::GlobalVariable::WeakODRLinkage;
4680 
4681   // Otherwise, we have strong external linkage.
4682   assert(Linkage == GVA_StrongExternal);
4683   return llvm::GlobalVariable::ExternalLinkage;
4684 }
4685 
4686 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4687     const VarDecl *VD, bool IsConstant) {
4688   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4689   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4690 }
4691 
4692 /// Replace the uses of a function that was declared with a non-proto type.
4693 /// We want to silently drop extra arguments from call sites
4694 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4695                                           llvm::Function *newFn) {
4696   // Fast path.
4697   if (old->use_empty()) return;
4698 
4699   llvm::Type *newRetTy = newFn->getReturnType();
4700   SmallVector<llvm::Value*, 4> newArgs;
4701 
4702   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4703          ui != ue; ) {
4704     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4705     llvm::User *user = use->getUser();
4706 
4707     // Recognize and replace uses of bitcasts.  Most calls to
4708     // unprototyped functions will use bitcasts.
4709     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4710       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4711         replaceUsesOfNonProtoConstant(bitcast, newFn);
4712       continue;
4713     }
4714 
4715     // Recognize calls to the function.
4716     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4717     if (!callSite) continue;
4718     if (!callSite->isCallee(&*use))
4719       continue;
4720 
4721     // If the return types don't match exactly, then we can't
4722     // transform this call unless it's dead.
4723     if (callSite->getType() != newRetTy && !callSite->use_empty())
4724       continue;
4725 
4726     // Get the call site's attribute list.
4727     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4728     llvm::AttributeList oldAttrs = callSite->getAttributes();
4729 
4730     // If the function was passed too few arguments, don't transform.
4731     unsigned newNumArgs = newFn->arg_size();
4732     if (callSite->arg_size() < newNumArgs)
4733       continue;
4734 
4735     // If extra arguments were passed, we silently drop them.
4736     // If any of the types mismatch, we don't transform.
4737     unsigned argNo = 0;
4738     bool dontTransform = false;
4739     for (llvm::Argument &A : newFn->args()) {
4740       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4741         dontTransform = true;
4742         break;
4743       }
4744 
4745       // Add any parameter attributes.
4746       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
4747       argNo++;
4748     }
4749     if (dontTransform)
4750       continue;
4751 
4752     // Okay, we can transform this.  Create the new call instruction and copy
4753     // over the required information.
4754     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4755 
4756     // Copy over any operand bundles.
4757     SmallVector<llvm::OperandBundleDef, 1> newBundles;
4758     callSite->getOperandBundlesAsDefs(newBundles);
4759 
4760     llvm::CallBase *newCall;
4761     if (dyn_cast<llvm::CallInst>(callSite)) {
4762       newCall =
4763           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4764     } else {
4765       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4766       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4767                                          oldInvoke->getUnwindDest(), newArgs,
4768                                          newBundles, "", callSite);
4769     }
4770     newArgs.clear(); // for the next iteration
4771 
4772     if (!newCall->getType()->isVoidTy())
4773       newCall->takeName(callSite);
4774     newCall->setAttributes(
4775         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
4776                                  oldAttrs.getRetAttrs(), newArgAttrs));
4777     newCall->setCallingConv(callSite->getCallingConv());
4778 
4779     // Finally, remove the old call, replacing any uses with the new one.
4780     if (!callSite->use_empty())
4781       callSite->replaceAllUsesWith(newCall);
4782 
4783     // Copy debug location attached to CI.
4784     if (callSite->getDebugLoc())
4785       newCall->setDebugLoc(callSite->getDebugLoc());
4786 
4787     callSite->eraseFromParent();
4788   }
4789 }
4790 
4791 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4792 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
4793 /// existing call uses of the old function in the module, this adjusts them to
4794 /// call the new function directly.
4795 ///
4796 /// This is not just a cleanup: the always_inline pass requires direct calls to
4797 /// functions to be able to inline them.  If there is a bitcast in the way, it
4798 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
4799 /// run at -O0.
4800 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4801                                                       llvm::Function *NewFn) {
4802   // If we're redefining a global as a function, don't transform it.
4803   if (!isa<llvm::Function>(Old)) return;
4804 
4805   replaceUsesOfNonProtoConstant(Old, NewFn);
4806 }
4807 
4808 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4809   auto DK = VD->isThisDeclarationADefinition();
4810   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4811     return;
4812 
4813   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4814   // If we have a definition, this might be a deferred decl. If the
4815   // instantiation is explicit, make sure we emit it at the end.
4816   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4817     GetAddrOfGlobalVar(VD);
4818 
4819   EmitTopLevelDecl(VD);
4820 }
4821 
4822 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4823                                                  llvm::GlobalValue *GV) {
4824   const auto *D = cast<FunctionDecl>(GD.getDecl());
4825 
4826   // Compute the function info and LLVM type.
4827   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4828   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4829 
4830   // Get or create the prototype for the function.
4831   if (!GV || (GV->getValueType() != Ty))
4832     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4833                                                    /*DontDefer=*/true,
4834                                                    ForDefinition));
4835 
4836   // Already emitted.
4837   if (!GV->isDeclaration())
4838     return;
4839 
4840   // We need to set linkage and visibility on the function before
4841   // generating code for it because various parts of IR generation
4842   // want to propagate this information down (e.g. to local static
4843   // declarations).
4844   auto *Fn = cast<llvm::Function>(GV);
4845   setFunctionLinkage(GD, Fn);
4846 
4847   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4848   setGVProperties(Fn, GD);
4849 
4850   MaybeHandleStaticInExternC(D, Fn);
4851 
4852   maybeSetTrivialComdat(*D, *Fn);
4853 
4854   // Set CodeGen attributes that represent floating point environment.
4855   setLLVMFunctionFEnvAttributes(D, Fn);
4856 
4857   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4858 
4859   setNonAliasAttributes(GD, Fn);
4860   SetLLVMFunctionAttributesForDefinition(D, Fn);
4861 
4862   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4863     AddGlobalCtor(Fn, CA->getPriority());
4864   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4865     AddGlobalDtor(Fn, DA->getPriority(), true);
4866   if (D->hasAttr<AnnotateAttr>())
4867     AddGlobalAnnotations(D, Fn);
4868 }
4869 
4870 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4871   const auto *D = cast<ValueDecl>(GD.getDecl());
4872   const AliasAttr *AA = D->getAttr<AliasAttr>();
4873   assert(AA && "Not an alias?");
4874 
4875   StringRef MangledName = getMangledName(GD);
4876 
4877   if (AA->getAliasee() == MangledName) {
4878     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4879     return;
4880   }
4881 
4882   // If there is a definition in the module, then it wins over the alias.
4883   // This is dubious, but allow it to be safe.  Just ignore the alias.
4884   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4885   if (Entry && !Entry->isDeclaration())
4886     return;
4887 
4888   Aliases.push_back(GD);
4889 
4890   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4891 
4892   // Create a reference to the named value.  This ensures that it is emitted
4893   // if a deferred decl.
4894   llvm::Constant *Aliasee;
4895   llvm::GlobalValue::LinkageTypes LT;
4896   if (isa<llvm::FunctionType>(DeclTy)) {
4897     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4898                                       /*ForVTable=*/false);
4899     LT = getFunctionLinkage(GD);
4900   } else {
4901     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
4902                                     /*D=*/nullptr);
4903     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
4904       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
4905     else
4906       LT = getFunctionLinkage(GD);
4907   }
4908 
4909   // Create the new alias itself, but don't set a name yet.
4910   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4911   auto *GA =
4912       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4913 
4914   if (Entry) {
4915     if (GA->getAliasee() == Entry) {
4916       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4917       return;
4918     }
4919 
4920     assert(Entry->isDeclaration());
4921 
4922     // If there is a declaration in the module, then we had an extern followed
4923     // by the alias, as in:
4924     //   extern int test6();
4925     //   ...
4926     //   int test6() __attribute__((alias("test7")));
4927     //
4928     // Remove it and replace uses of it with the alias.
4929     GA->takeName(Entry);
4930 
4931     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4932                                                           Entry->getType()));
4933     Entry->eraseFromParent();
4934   } else {
4935     GA->setName(MangledName);
4936   }
4937 
4938   // Set attributes which are particular to an alias; this is a
4939   // specialization of the attributes which may be set on a global
4940   // variable/function.
4941   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4942       D->isWeakImported()) {
4943     GA->setLinkage(llvm::Function::WeakAnyLinkage);
4944   }
4945 
4946   if (const auto *VD = dyn_cast<VarDecl>(D))
4947     if (VD->getTLSKind())
4948       setTLSMode(GA, *VD);
4949 
4950   SetCommonAttributes(GD, GA);
4951 }
4952 
4953 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4954   const auto *D = cast<ValueDecl>(GD.getDecl());
4955   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4956   assert(IFA && "Not an ifunc?");
4957 
4958   StringRef MangledName = getMangledName(GD);
4959 
4960   if (IFA->getResolver() == MangledName) {
4961     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4962     return;
4963   }
4964 
4965   // Report an error if some definition overrides ifunc.
4966   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4967   if (Entry && !Entry->isDeclaration()) {
4968     GlobalDecl OtherGD;
4969     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4970         DiagnosedConflictingDefinitions.insert(GD).second) {
4971       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4972           << MangledName;
4973       Diags.Report(OtherGD.getDecl()->getLocation(),
4974                    diag::note_previous_definition);
4975     }
4976     return;
4977   }
4978 
4979   Aliases.push_back(GD);
4980 
4981   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4982   llvm::Constant *Resolver =
4983       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4984                               /*ForVTable=*/false);
4985   llvm::GlobalIFunc *GIF =
4986       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4987                                 "", Resolver, &getModule());
4988   if (Entry) {
4989     if (GIF->getResolver() == Entry) {
4990       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4991       return;
4992     }
4993     assert(Entry->isDeclaration());
4994 
4995     // If there is a declaration in the module, then we had an extern followed
4996     // by the ifunc, as in:
4997     //   extern int test();
4998     //   ...
4999     //   int test() __attribute__((ifunc("resolver")));
5000     //
5001     // Remove it and replace uses of it with the ifunc.
5002     GIF->takeName(Entry);
5003 
5004     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
5005                                                           Entry->getType()));
5006     Entry->eraseFromParent();
5007   } else
5008     GIF->setName(MangledName);
5009 
5010   SetCommonAttributes(GD, GIF);
5011 }
5012 
5013 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
5014                                             ArrayRef<llvm::Type*> Tys) {
5015   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
5016                                          Tys);
5017 }
5018 
5019 static llvm::StringMapEntry<llvm::GlobalVariable *> &
5020 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5021                          const StringLiteral *Literal, bool TargetIsLSB,
5022                          bool &IsUTF16, unsigned &StringLength) {
5023   StringRef String = Literal->getString();
5024   unsigned NumBytes = String.size();
5025 
5026   // Check for simple case.
5027   if (!Literal->containsNonAsciiOrNull()) {
5028     StringLength = NumBytes;
5029     return *Map.insert(std::make_pair(String, nullptr)).first;
5030   }
5031 
5032   // Otherwise, convert the UTF8 literals into a string of shorts.
5033   IsUTF16 = true;
5034 
5035   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5036   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5037   llvm::UTF16 *ToPtr = &ToBuf[0];
5038 
5039   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5040                                  ToPtr + NumBytes, llvm::strictConversion);
5041 
5042   // ConvertUTF8toUTF16 returns the length in ToPtr.
5043   StringLength = ToPtr - &ToBuf[0];
5044 
5045   // Add an explicit null.
5046   *ToPtr = 0;
5047   return *Map.insert(std::make_pair(
5048                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5049                                    (StringLength + 1) * 2),
5050                          nullptr)).first;
5051 }
5052 
5053 ConstantAddress
5054 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5055   unsigned StringLength = 0;
5056   bool isUTF16 = false;
5057   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5058       GetConstantCFStringEntry(CFConstantStringMap, Literal,
5059                                getDataLayout().isLittleEndian(), isUTF16,
5060                                StringLength);
5061 
5062   if (auto *C = Entry.second)
5063     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
5064 
5065   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5066   llvm::Constant *Zeros[] = { Zero, Zero };
5067 
5068   const ASTContext &Context = getContext();
5069   const llvm::Triple &Triple = getTriple();
5070 
5071   const auto CFRuntime = getLangOpts().CFRuntime;
5072   const bool IsSwiftABI =
5073       static_cast<unsigned>(CFRuntime) >=
5074       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5075   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5076 
5077   // If we don't already have it, get __CFConstantStringClassReference.
5078   if (!CFConstantStringClassRef) {
5079     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5080     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5081     Ty = llvm::ArrayType::get(Ty, 0);
5082 
5083     switch (CFRuntime) {
5084     default: break;
5085     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
5086     case LangOptions::CoreFoundationABI::Swift5_0:
5087       CFConstantStringClassName =
5088           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5089                               : "$s10Foundation19_NSCFConstantStringCN";
5090       Ty = IntPtrTy;
5091       break;
5092     case LangOptions::CoreFoundationABI::Swift4_2:
5093       CFConstantStringClassName =
5094           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5095                               : "$S10Foundation19_NSCFConstantStringCN";
5096       Ty = IntPtrTy;
5097       break;
5098     case LangOptions::CoreFoundationABI::Swift4_1:
5099       CFConstantStringClassName =
5100           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5101                               : "__T010Foundation19_NSCFConstantStringCN";
5102       Ty = IntPtrTy;
5103       break;
5104     }
5105 
5106     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5107 
5108     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5109       llvm::GlobalValue *GV = nullptr;
5110 
5111       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5112         IdentifierInfo &II = Context.Idents.get(GV->getName());
5113         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5114         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5115 
5116         const VarDecl *VD = nullptr;
5117         for (const auto *Result : DC->lookup(&II))
5118           if ((VD = dyn_cast<VarDecl>(Result)))
5119             break;
5120 
5121         if (Triple.isOSBinFormatELF()) {
5122           if (!VD)
5123             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5124         } else {
5125           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5126           if (!VD || !VD->hasAttr<DLLExportAttr>())
5127             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5128           else
5129             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5130         }
5131 
5132         setDSOLocal(GV);
5133       }
5134     }
5135 
5136     // Decay array -> ptr
5137     CFConstantStringClassRef =
5138         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5139                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5140   }
5141 
5142   QualType CFTy = Context.getCFConstantStringType();
5143 
5144   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5145 
5146   ConstantInitBuilder Builder(*this);
5147   auto Fields = Builder.beginStruct(STy);
5148 
5149   // Class pointer.
5150   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
5151 
5152   // Flags.
5153   if (IsSwiftABI) {
5154     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5155     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5156   } else {
5157     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5158   }
5159 
5160   // String pointer.
5161   llvm::Constant *C = nullptr;
5162   if (isUTF16) {
5163     auto Arr = llvm::makeArrayRef(
5164         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5165         Entry.first().size() / 2);
5166     C = llvm::ConstantDataArray::get(VMContext, Arr);
5167   } else {
5168     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5169   }
5170 
5171   // Note: -fwritable-strings doesn't make the backing store strings of
5172   // CFStrings writable. (See <rdar://problem/10657500>)
5173   auto *GV =
5174       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5175                                llvm::GlobalValue::PrivateLinkage, C, ".str");
5176   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5177   // Don't enforce the target's minimum global alignment, since the only use
5178   // of the string is via this class initializer.
5179   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5180                             : Context.getTypeAlignInChars(Context.CharTy);
5181   GV->setAlignment(Align.getAsAlign());
5182 
5183   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5184   // Without it LLVM can merge the string with a non unnamed_addr one during
5185   // LTO.  Doing that changes the section it ends in, which surprises ld64.
5186   if (Triple.isOSBinFormatMachO())
5187     GV->setSection(isUTF16 ? "__TEXT,__ustring"
5188                            : "__TEXT,__cstring,cstring_literals");
5189   // Make sure the literal ends up in .rodata to allow for safe ICF and for
5190   // the static linker to adjust permissions to read-only later on.
5191   else if (Triple.isOSBinFormatELF())
5192     GV->setSection(".rodata");
5193 
5194   // String.
5195   llvm::Constant *Str =
5196       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5197 
5198   if (isUTF16)
5199     // Cast the UTF16 string to the correct type.
5200     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5201   Fields.add(Str);
5202 
5203   // String length.
5204   llvm::IntegerType *LengthTy =
5205       llvm::IntegerType::get(getModule().getContext(),
5206                              Context.getTargetInfo().getLongWidth());
5207   if (IsSwiftABI) {
5208     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5209         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5210       LengthTy = Int32Ty;
5211     else
5212       LengthTy = IntPtrTy;
5213   }
5214   Fields.addInt(LengthTy, StringLength);
5215 
5216   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5217   // properly aligned on 32-bit platforms.
5218   CharUnits Alignment =
5219       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5220 
5221   // The struct.
5222   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5223                                     /*isConstant=*/false,
5224                                     llvm::GlobalVariable::PrivateLinkage);
5225   GV->addAttribute("objc_arc_inert");
5226   switch (Triple.getObjectFormat()) {
5227   case llvm::Triple::UnknownObjectFormat:
5228     llvm_unreachable("unknown file format");
5229   case llvm::Triple::GOFF:
5230     llvm_unreachable("GOFF is not yet implemented");
5231   case llvm::Triple::XCOFF:
5232     llvm_unreachable("XCOFF is not yet implemented");
5233   case llvm::Triple::COFF:
5234   case llvm::Triple::ELF:
5235   case llvm::Triple::Wasm:
5236     GV->setSection("cfstring");
5237     break;
5238   case llvm::Triple::MachO:
5239     GV->setSection("__DATA,__cfstring");
5240     break;
5241   }
5242   Entry.second = GV;
5243 
5244   return ConstantAddress(GV, Alignment);
5245 }
5246 
5247 bool CodeGenModule::getExpressionLocationsEnabled() const {
5248   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5249 }
5250 
5251 QualType CodeGenModule::getObjCFastEnumerationStateType() {
5252   if (ObjCFastEnumerationStateType.isNull()) {
5253     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5254     D->startDefinition();
5255 
5256     QualType FieldTypes[] = {
5257       Context.UnsignedLongTy,
5258       Context.getPointerType(Context.getObjCIdType()),
5259       Context.getPointerType(Context.UnsignedLongTy),
5260       Context.getConstantArrayType(Context.UnsignedLongTy,
5261                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5262     };
5263 
5264     for (size_t i = 0; i < 4; ++i) {
5265       FieldDecl *Field = FieldDecl::Create(Context,
5266                                            D,
5267                                            SourceLocation(),
5268                                            SourceLocation(), nullptr,
5269                                            FieldTypes[i], /*TInfo=*/nullptr,
5270                                            /*BitWidth=*/nullptr,
5271                                            /*Mutable=*/false,
5272                                            ICIS_NoInit);
5273       Field->setAccess(AS_public);
5274       D->addDecl(Field);
5275     }
5276 
5277     D->completeDefinition();
5278     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5279   }
5280 
5281   return ObjCFastEnumerationStateType;
5282 }
5283 
5284 llvm::Constant *
5285 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5286   assert(!E->getType()->isPointerType() && "Strings are always arrays");
5287 
5288   // Don't emit it as the address of the string, emit the string data itself
5289   // as an inline array.
5290   if (E->getCharByteWidth() == 1) {
5291     SmallString<64> Str(E->getString());
5292 
5293     // Resize the string to the right size, which is indicated by its type.
5294     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5295     Str.resize(CAT->getSize().getZExtValue());
5296     return llvm::ConstantDataArray::getString(VMContext, Str, false);
5297   }
5298 
5299   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5300   llvm::Type *ElemTy = AType->getElementType();
5301   unsigned NumElements = AType->getNumElements();
5302 
5303   // Wide strings have either 2-byte or 4-byte elements.
5304   if (ElemTy->getPrimitiveSizeInBits() == 16) {
5305     SmallVector<uint16_t, 32> Elements;
5306     Elements.reserve(NumElements);
5307 
5308     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5309       Elements.push_back(E->getCodeUnit(i));
5310     Elements.resize(NumElements);
5311     return llvm::ConstantDataArray::get(VMContext, Elements);
5312   }
5313 
5314   assert(ElemTy->getPrimitiveSizeInBits() == 32);
5315   SmallVector<uint32_t, 32> Elements;
5316   Elements.reserve(NumElements);
5317 
5318   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5319     Elements.push_back(E->getCodeUnit(i));
5320   Elements.resize(NumElements);
5321   return llvm::ConstantDataArray::get(VMContext, Elements);
5322 }
5323 
5324 static llvm::GlobalVariable *
5325 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5326                       CodeGenModule &CGM, StringRef GlobalName,
5327                       CharUnits Alignment) {
5328   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5329       CGM.GetGlobalConstantAddressSpace());
5330 
5331   llvm::Module &M = CGM.getModule();
5332   // Create a global variable for this string
5333   auto *GV = new llvm::GlobalVariable(
5334       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5335       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5336   GV->setAlignment(Alignment.getAsAlign());
5337   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5338   if (GV->isWeakForLinker()) {
5339     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5340     GV->setComdat(M.getOrInsertComdat(GV->getName()));
5341   }
5342   CGM.setDSOLocal(GV);
5343 
5344   return GV;
5345 }
5346 
5347 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5348 /// constant array for the given string literal.
5349 ConstantAddress
5350 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5351                                                   StringRef Name) {
5352   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5353 
5354   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5355   llvm::GlobalVariable **Entry = nullptr;
5356   if (!LangOpts.WritableStrings) {
5357     Entry = &ConstantStringMap[C];
5358     if (auto GV = *Entry) {
5359       if (Alignment.getQuantity() > GV->getAlignment())
5360         GV->setAlignment(Alignment.getAsAlign());
5361       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5362                              Alignment);
5363     }
5364   }
5365 
5366   SmallString<256> MangledNameBuffer;
5367   StringRef GlobalVariableName;
5368   llvm::GlobalValue::LinkageTypes LT;
5369 
5370   // Mangle the string literal if that's how the ABI merges duplicate strings.
5371   // Don't do it if they are writable, since we don't want writes in one TU to
5372   // affect strings in another.
5373   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5374       !LangOpts.WritableStrings) {
5375     llvm::raw_svector_ostream Out(MangledNameBuffer);
5376     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5377     LT = llvm::GlobalValue::LinkOnceODRLinkage;
5378     GlobalVariableName = MangledNameBuffer;
5379   } else {
5380     LT = llvm::GlobalValue::PrivateLinkage;
5381     GlobalVariableName = Name;
5382   }
5383 
5384   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5385   if (Entry)
5386     *Entry = GV;
5387 
5388   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5389                                   QualType());
5390 
5391   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5392                          Alignment);
5393 }
5394 
5395 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5396 /// array for the given ObjCEncodeExpr node.
5397 ConstantAddress
5398 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5399   std::string Str;
5400   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5401 
5402   return GetAddrOfConstantCString(Str);
5403 }
5404 
5405 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5406 /// the literal and a terminating '\0' character.
5407 /// The result has pointer to array type.
5408 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5409     const std::string &Str, const char *GlobalName) {
5410   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5411   CharUnits Alignment =
5412     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5413 
5414   llvm::Constant *C =
5415       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5416 
5417   // Don't share any string literals if strings aren't constant.
5418   llvm::GlobalVariable **Entry = nullptr;
5419   if (!LangOpts.WritableStrings) {
5420     Entry = &ConstantStringMap[C];
5421     if (auto GV = *Entry) {
5422       if (Alignment.getQuantity() > GV->getAlignment())
5423         GV->setAlignment(Alignment.getAsAlign());
5424       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5425                              Alignment);
5426     }
5427   }
5428 
5429   // Get the default prefix if a name wasn't specified.
5430   if (!GlobalName)
5431     GlobalName = ".str";
5432   // Create a global variable for this.
5433   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5434                                   GlobalName, Alignment);
5435   if (Entry)
5436     *Entry = GV;
5437 
5438   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5439                          Alignment);
5440 }
5441 
5442 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5443     const MaterializeTemporaryExpr *E, const Expr *Init) {
5444   assert((E->getStorageDuration() == SD_Static ||
5445           E->getStorageDuration() == SD_Thread) && "not a global temporary");
5446   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5447 
5448   // If we're not materializing a subobject of the temporary, keep the
5449   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5450   QualType MaterializedType = Init->getType();
5451   if (Init == E->getSubExpr())
5452     MaterializedType = E->getType();
5453 
5454   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5455 
5456   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
5457   if (!InsertResult.second) {
5458     // We've seen this before: either we already created it or we're in the
5459     // process of doing so.
5460     if (!InsertResult.first->second) {
5461       // We recursively re-entered this function, probably during emission of
5462       // the initializer. Create a placeholder. We'll clean this up in the
5463       // outer call, at the end of this function.
5464       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
5465       InsertResult.first->second = new llvm::GlobalVariable(
5466           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
5467           nullptr);
5468     }
5469     return ConstantAddress(InsertResult.first->second, Align);
5470   }
5471 
5472   // FIXME: If an externally-visible declaration extends multiple temporaries,
5473   // we need to give each temporary the same name in every translation unit (and
5474   // we also need to make the temporaries externally-visible).
5475   SmallString<256> Name;
5476   llvm::raw_svector_ostream Out(Name);
5477   getCXXABI().getMangleContext().mangleReferenceTemporary(
5478       VD, E->getManglingNumber(), Out);
5479 
5480   APValue *Value = nullptr;
5481   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5482     // If the initializer of the extending declaration is a constant
5483     // initializer, we should have a cached constant initializer for this
5484     // temporary. Note that this might have a different value from the value
5485     // computed by evaluating the initializer if the surrounding constant
5486     // expression modifies the temporary.
5487     Value = E->getOrCreateValue(false);
5488   }
5489 
5490   // Try evaluating it now, it might have a constant initializer.
5491   Expr::EvalResult EvalResult;
5492   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5493       !EvalResult.hasSideEffects())
5494     Value = &EvalResult.Val;
5495 
5496   LangAS AddrSpace =
5497       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5498 
5499   Optional<ConstantEmitter> emitter;
5500   llvm::Constant *InitialValue = nullptr;
5501   bool Constant = false;
5502   llvm::Type *Type;
5503   if (Value) {
5504     // The temporary has a constant initializer, use it.
5505     emitter.emplace(*this);
5506     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5507                                                MaterializedType);
5508     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5509     Type = InitialValue->getType();
5510   } else {
5511     // No initializer, the initialization will be provided when we
5512     // initialize the declaration which performed lifetime extension.
5513     Type = getTypes().ConvertTypeForMem(MaterializedType);
5514   }
5515 
5516   // Create a global variable for this lifetime-extended temporary.
5517   llvm::GlobalValue::LinkageTypes Linkage =
5518       getLLVMLinkageVarDefinition(VD, Constant);
5519   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5520     const VarDecl *InitVD;
5521     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5522         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5523       // Temporaries defined inside a class get linkonce_odr linkage because the
5524       // class can be defined in multiple translation units.
5525       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5526     } else {
5527       // There is no need for this temporary to have external linkage if the
5528       // VarDecl has external linkage.
5529       Linkage = llvm::GlobalVariable::InternalLinkage;
5530     }
5531   }
5532   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5533   auto *GV = new llvm::GlobalVariable(
5534       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5535       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5536   if (emitter) emitter->finalize(GV);
5537   setGVProperties(GV, VD);
5538   GV->setAlignment(Align.getAsAlign());
5539   if (supportsCOMDAT() && GV->isWeakForLinker())
5540     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5541   if (VD->getTLSKind())
5542     setTLSMode(GV, *VD);
5543   llvm::Constant *CV = GV;
5544   if (AddrSpace != LangAS::Default)
5545     CV = getTargetCodeGenInfo().performAddrSpaceCast(
5546         *this, GV, AddrSpace, LangAS::Default,
5547         Type->getPointerTo(
5548             getContext().getTargetAddressSpace(LangAS::Default)));
5549 
5550   // Update the map with the new temporary. If we created a placeholder above,
5551   // replace it with the new global now.
5552   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
5553   if (Entry) {
5554     Entry->replaceAllUsesWith(
5555         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
5556     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
5557   }
5558   Entry = CV;
5559 
5560   return ConstantAddress(CV, Align);
5561 }
5562 
5563 /// EmitObjCPropertyImplementations - Emit information for synthesized
5564 /// properties for an implementation.
5565 void CodeGenModule::EmitObjCPropertyImplementations(const
5566                                                     ObjCImplementationDecl *D) {
5567   for (const auto *PID : D->property_impls()) {
5568     // Dynamic is just for type-checking.
5569     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5570       ObjCPropertyDecl *PD = PID->getPropertyDecl();
5571 
5572       // Determine which methods need to be implemented, some may have
5573       // been overridden. Note that ::isPropertyAccessor is not the method
5574       // we want, that just indicates if the decl came from a
5575       // property. What we want to know is if the method is defined in
5576       // this implementation.
5577       auto *Getter = PID->getGetterMethodDecl();
5578       if (!Getter || Getter->isSynthesizedAccessorStub())
5579         CodeGenFunction(*this).GenerateObjCGetter(
5580             const_cast<ObjCImplementationDecl *>(D), PID);
5581       auto *Setter = PID->getSetterMethodDecl();
5582       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5583         CodeGenFunction(*this).GenerateObjCSetter(
5584                                  const_cast<ObjCImplementationDecl *>(D), PID);
5585     }
5586   }
5587 }
5588 
5589 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5590   const ObjCInterfaceDecl *iface = impl->getClassInterface();
5591   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5592        ivar; ivar = ivar->getNextIvar())
5593     if (ivar->getType().isDestructedType())
5594       return true;
5595 
5596   return false;
5597 }
5598 
5599 static bool AllTrivialInitializers(CodeGenModule &CGM,
5600                                    ObjCImplementationDecl *D) {
5601   CodeGenFunction CGF(CGM);
5602   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5603        E = D->init_end(); B != E; ++B) {
5604     CXXCtorInitializer *CtorInitExp = *B;
5605     Expr *Init = CtorInitExp->getInit();
5606     if (!CGF.isTrivialInitializer(Init))
5607       return false;
5608   }
5609   return true;
5610 }
5611 
5612 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5613 /// for an implementation.
5614 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5615   // We might need a .cxx_destruct even if we don't have any ivar initializers.
5616   if (needsDestructMethod(D)) {
5617     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5618     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5619     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5620         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5621         getContext().VoidTy, nullptr, D,
5622         /*isInstance=*/true, /*isVariadic=*/false,
5623         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5624         /*isImplicitlyDeclared=*/true,
5625         /*isDefined=*/false, ObjCMethodDecl::Required);
5626     D->addInstanceMethod(DTORMethod);
5627     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5628     D->setHasDestructors(true);
5629   }
5630 
5631   // If the implementation doesn't have any ivar initializers, we don't need
5632   // a .cxx_construct.
5633   if (D->getNumIvarInitializers() == 0 ||
5634       AllTrivialInitializers(*this, D))
5635     return;
5636 
5637   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5638   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5639   // The constructor returns 'self'.
5640   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5641       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5642       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5643       /*isVariadic=*/false,
5644       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5645       /*isImplicitlyDeclared=*/true,
5646       /*isDefined=*/false, ObjCMethodDecl::Required);
5647   D->addInstanceMethod(CTORMethod);
5648   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5649   D->setHasNonZeroConstructors(true);
5650 }
5651 
5652 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5653 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5654   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5655       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5656     ErrorUnsupported(LSD, "linkage spec");
5657     return;
5658   }
5659 
5660   EmitDeclContext(LSD);
5661 }
5662 
5663 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5664   for (auto *I : DC->decls()) {
5665     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5666     // are themselves considered "top-level", so EmitTopLevelDecl on an
5667     // ObjCImplDecl does not recursively visit them. We need to do that in
5668     // case they're nested inside another construct (LinkageSpecDecl /
5669     // ExportDecl) that does stop them from being considered "top-level".
5670     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5671       for (auto *M : OID->methods())
5672         EmitTopLevelDecl(M);
5673     }
5674 
5675     EmitTopLevelDecl(I);
5676   }
5677 }
5678 
5679 /// EmitTopLevelDecl - Emit code for a single top level declaration.
5680 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5681   // Ignore dependent declarations.
5682   if (D->isTemplated())
5683     return;
5684 
5685   // Consteval function shouldn't be emitted.
5686   if (auto *FD = dyn_cast<FunctionDecl>(D))
5687     if (FD->isConsteval())
5688       return;
5689 
5690   switch (D->getKind()) {
5691   case Decl::CXXConversion:
5692   case Decl::CXXMethod:
5693   case Decl::Function:
5694     EmitGlobal(cast<FunctionDecl>(D));
5695     // Always provide some coverage mapping
5696     // even for the functions that aren't emitted.
5697     AddDeferredUnusedCoverageMapping(D);
5698     break;
5699 
5700   case Decl::CXXDeductionGuide:
5701     // Function-like, but does not result in code emission.
5702     break;
5703 
5704   case Decl::Var:
5705   case Decl::Decomposition:
5706   case Decl::VarTemplateSpecialization:
5707     EmitGlobal(cast<VarDecl>(D));
5708     if (auto *DD = dyn_cast<DecompositionDecl>(D))
5709       for (auto *B : DD->bindings())
5710         if (auto *HD = B->getHoldingVar())
5711           EmitGlobal(HD);
5712     break;
5713 
5714   // Indirect fields from global anonymous structs and unions can be
5715   // ignored; only the actual variable requires IR gen support.
5716   case Decl::IndirectField:
5717     break;
5718 
5719   // C++ Decls
5720   case Decl::Namespace:
5721     EmitDeclContext(cast<NamespaceDecl>(D));
5722     break;
5723   case Decl::ClassTemplateSpecialization: {
5724     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5725     if (CGDebugInfo *DI = getModuleDebugInfo())
5726       if (Spec->getSpecializationKind() ==
5727               TSK_ExplicitInstantiationDefinition &&
5728           Spec->hasDefinition())
5729         DI->completeTemplateDefinition(*Spec);
5730   } LLVM_FALLTHROUGH;
5731   case Decl::CXXRecord: {
5732     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5733     if (CGDebugInfo *DI = getModuleDebugInfo()) {
5734       if (CRD->hasDefinition())
5735         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5736       if (auto *ES = D->getASTContext().getExternalSource())
5737         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5738           DI->completeUnusedClass(*CRD);
5739     }
5740     // Emit any static data members, they may be definitions.
5741     for (auto *I : CRD->decls())
5742       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5743         EmitTopLevelDecl(I);
5744     break;
5745   }
5746     // No code generation needed.
5747   case Decl::UsingShadow:
5748   case Decl::ClassTemplate:
5749   case Decl::VarTemplate:
5750   case Decl::Concept:
5751   case Decl::VarTemplatePartialSpecialization:
5752   case Decl::FunctionTemplate:
5753   case Decl::TypeAliasTemplate:
5754   case Decl::Block:
5755   case Decl::Empty:
5756   case Decl::Binding:
5757     break;
5758   case Decl::Using:          // using X; [C++]
5759     if (CGDebugInfo *DI = getModuleDebugInfo())
5760         DI->EmitUsingDecl(cast<UsingDecl>(*D));
5761     break;
5762   case Decl::UsingEnum: // using enum X; [C++]
5763     if (CGDebugInfo *DI = getModuleDebugInfo())
5764       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
5765     break;
5766   case Decl::NamespaceAlias:
5767     if (CGDebugInfo *DI = getModuleDebugInfo())
5768         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5769     break;
5770   case Decl::UsingDirective: // using namespace X; [C++]
5771     if (CGDebugInfo *DI = getModuleDebugInfo())
5772       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5773     break;
5774   case Decl::CXXConstructor:
5775     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5776     break;
5777   case Decl::CXXDestructor:
5778     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5779     break;
5780 
5781   case Decl::StaticAssert:
5782     // Nothing to do.
5783     break;
5784 
5785   // Objective-C Decls
5786 
5787   // Forward declarations, no (immediate) code generation.
5788   case Decl::ObjCInterface:
5789   case Decl::ObjCCategory:
5790     break;
5791 
5792   case Decl::ObjCProtocol: {
5793     auto *Proto = cast<ObjCProtocolDecl>(D);
5794     if (Proto->isThisDeclarationADefinition())
5795       ObjCRuntime->GenerateProtocol(Proto);
5796     break;
5797   }
5798 
5799   case Decl::ObjCCategoryImpl:
5800     // Categories have properties but don't support synthesize so we
5801     // can ignore them here.
5802     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5803     break;
5804 
5805   case Decl::ObjCImplementation: {
5806     auto *OMD = cast<ObjCImplementationDecl>(D);
5807     EmitObjCPropertyImplementations(OMD);
5808     EmitObjCIvarInitializations(OMD);
5809     ObjCRuntime->GenerateClass(OMD);
5810     // Emit global variable debug information.
5811     if (CGDebugInfo *DI = getModuleDebugInfo())
5812       if (getCodeGenOpts().hasReducedDebugInfo())
5813         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5814             OMD->getClassInterface()), OMD->getLocation());
5815     break;
5816   }
5817   case Decl::ObjCMethod: {
5818     auto *OMD = cast<ObjCMethodDecl>(D);
5819     // If this is not a prototype, emit the body.
5820     if (OMD->getBody())
5821       CodeGenFunction(*this).GenerateObjCMethod(OMD);
5822     break;
5823   }
5824   case Decl::ObjCCompatibleAlias:
5825     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5826     break;
5827 
5828   case Decl::PragmaComment: {
5829     const auto *PCD = cast<PragmaCommentDecl>(D);
5830     switch (PCD->getCommentKind()) {
5831     case PCK_Unknown:
5832       llvm_unreachable("unexpected pragma comment kind");
5833     case PCK_Linker:
5834       AppendLinkerOptions(PCD->getArg());
5835       break;
5836     case PCK_Lib:
5837         AddDependentLib(PCD->getArg());
5838       break;
5839     case PCK_Compiler:
5840     case PCK_ExeStr:
5841     case PCK_User:
5842       break; // We ignore all of these.
5843     }
5844     break;
5845   }
5846 
5847   case Decl::PragmaDetectMismatch: {
5848     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5849     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5850     break;
5851   }
5852 
5853   case Decl::LinkageSpec:
5854     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5855     break;
5856 
5857   case Decl::FileScopeAsm: {
5858     // File-scope asm is ignored during device-side CUDA compilation.
5859     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5860       break;
5861     // File-scope asm is ignored during device-side OpenMP compilation.
5862     if (LangOpts.OpenMPIsDevice)
5863       break;
5864     // File-scope asm is ignored during device-side SYCL compilation.
5865     if (LangOpts.SYCLIsDevice)
5866       break;
5867     auto *AD = cast<FileScopeAsmDecl>(D);
5868     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5869     break;
5870   }
5871 
5872   case Decl::Import: {
5873     auto *Import = cast<ImportDecl>(D);
5874 
5875     // If we've already imported this module, we're done.
5876     if (!ImportedModules.insert(Import->getImportedModule()))
5877       break;
5878 
5879     // Emit debug information for direct imports.
5880     if (!Import->getImportedOwningModule()) {
5881       if (CGDebugInfo *DI = getModuleDebugInfo())
5882         DI->EmitImportDecl(*Import);
5883     }
5884 
5885     // Find all of the submodules and emit the module initializers.
5886     llvm::SmallPtrSet<clang::Module *, 16> Visited;
5887     SmallVector<clang::Module *, 16> Stack;
5888     Visited.insert(Import->getImportedModule());
5889     Stack.push_back(Import->getImportedModule());
5890 
5891     while (!Stack.empty()) {
5892       clang::Module *Mod = Stack.pop_back_val();
5893       if (!EmittedModuleInitializers.insert(Mod).second)
5894         continue;
5895 
5896       for (auto *D : Context.getModuleInitializers(Mod))
5897         EmitTopLevelDecl(D);
5898 
5899       // Visit the submodules of this module.
5900       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5901                                              SubEnd = Mod->submodule_end();
5902            Sub != SubEnd; ++Sub) {
5903         // Skip explicit children; they need to be explicitly imported to emit
5904         // the initializers.
5905         if ((*Sub)->IsExplicit)
5906           continue;
5907 
5908         if (Visited.insert(*Sub).second)
5909           Stack.push_back(*Sub);
5910       }
5911     }
5912     break;
5913   }
5914 
5915   case Decl::Export:
5916     EmitDeclContext(cast<ExportDecl>(D));
5917     break;
5918 
5919   case Decl::OMPThreadPrivate:
5920     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5921     break;
5922 
5923   case Decl::OMPAllocate:
5924     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
5925     break;
5926 
5927   case Decl::OMPDeclareReduction:
5928     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5929     break;
5930 
5931   case Decl::OMPDeclareMapper:
5932     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5933     break;
5934 
5935   case Decl::OMPRequires:
5936     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5937     break;
5938 
5939   case Decl::Typedef:
5940   case Decl::TypeAlias: // using foo = bar; [C++11]
5941     if (CGDebugInfo *DI = getModuleDebugInfo())
5942       DI->EmitAndRetainType(
5943           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
5944     break;
5945 
5946   case Decl::Record:
5947     if (CGDebugInfo *DI = getModuleDebugInfo())
5948       if (cast<RecordDecl>(D)->getDefinition())
5949         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5950     break;
5951 
5952   case Decl::Enum:
5953     if (CGDebugInfo *DI = getModuleDebugInfo())
5954       if (cast<EnumDecl>(D)->getDefinition())
5955         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
5956     break;
5957 
5958   default:
5959     // Make sure we handled everything we should, every other kind is a
5960     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
5961     // function. Need to recode Decl::Kind to do that easily.
5962     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5963     break;
5964   }
5965 }
5966 
5967 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5968   // Do we need to generate coverage mapping?
5969   if (!CodeGenOpts.CoverageMapping)
5970     return;
5971   switch (D->getKind()) {
5972   case Decl::CXXConversion:
5973   case Decl::CXXMethod:
5974   case Decl::Function:
5975   case Decl::ObjCMethod:
5976   case Decl::CXXConstructor:
5977   case Decl::CXXDestructor: {
5978     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5979       break;
5980     SourceManager &SM = getContext().getSourceManager();
5981     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5982       break;
5983     auto I = DeferredEmptyCoverageMappingDecls.find(D);
5984     if (I == DeferredEmptyCoverageMappingDecls.end())
5985       DeferredEmptyCoverageMappingDecls[D] = true;
5986     break;
5987   }
5988   default:
5989     break;
5990   };
5991 }
5992 
5993 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5994   // Do we need to generate coverage mapping?
5995   if (!CodeGenOpts.CoverageMapping)
5996     return;
5997   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5998     if (Fn->isTemplateInstantiation())
5999       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
6000   }
6001   auto I = DeferredEmptyCoverageMappingDecls.find(D);
6002   if (I == DeferredEmptyCoverageMappingDecls.end())
6003     DeferredEmptyCoverageMappingDecls[D] = false;
6004   else
6005     I->second = false;
6006 }
6007 
6008 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
6009   // We call takeVector() here to avoid use-after-free.
6010   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
6011   // we deserialize function bodies to emit coverage info for them, and that
6012   // deserializes more declarations. How should we handle that case?
6013   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
6014     if (!Entry.second)
6015       continue;
6016     const Decl *D = Entry.first;
6017     switch (D->getKind()) {
6018     case Decl::CXXConversion:
6019     case Decl::CXXMethod:
6020     case Decl::Function:
6021     case Decl::ObjCMethod: {
6022       CodeGenPGO PGO(*this);
6023       GlobalDecl GD(cast<FunctionDecl>(D));
6024       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6025                                   getFunctionLinkage(GD));
6026       break;
6027     }
6028     case Decl::CXXConstructor: {
6029       CodeGenPGO PGO(*this);
6030       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
6031       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6032                                   getFunctionLinkage(GD));
6033       break;
6034     }
6035     case Decl::CXXDestructor: {
6036       CodeGenPGO PGO(*this);
6037       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
6038       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6039                                   getFunctionLinkage(GD));
6040       break;
6041     }
6042     default:
6043       break;
6044     };
6045   }
6046 }
6047 
6048 void CodeGenModule::EmitMainVoidAlias() {
6049   // In order to transition away from "__original_main" gracefully, emit an
6050   // alias for "main" in the no-argument case so that libc can detect when
6051   // new-style no-argument main is in used.
6052   if (llvm::Function *F = getModule().getFunction("main")) {
6053     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6054         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
6055       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
6056   }
6057 }
6058 
6059 /// Turns the given pointer into a constant.
6060 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6061                                           const void *Ptr) {
6062   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6063   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6064   return llvm::ConstantInt::get(i64, PtrInt);
6065 }
6066 
6067 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6068                                    llvm::NamedMDNode *&GlobalMetadata,
6069                                    GlobalDecl D,
6070                                    llvm::GlobalValue *Addr) {
6071   if (!GlobalMetadata)
6072     GlobalMetadata =
6073       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6074 
6075   // TODO: should we report variant information for ctors/dtors?
6076   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6077                            llvm::ConstantAsMetadata::get(GetPointerConstant(
6078                                CGM.getLLVMContext(), D.getDecl()))};
6079   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6080 }
6081 
6082 /// For each function which is declared within an extern "C" region and marked
6083 /// as 'used', but has internal linkage, create an alias from the unmangled
6084 /// name to the mangled name if possible. People expect to be able to refer
6085 /// to such functions with an unmangled name from inline assembly within the
6086 /// same translation unit.
6087 void CodeGenModule::EmitStaticExternCAliases() {
6088   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
6089     return;
6090   for (auto &I : StaticExternCValues) {
6091     IdentifierInfo *Name = I.first;
6092     llvm::GlobalValue *Val = I.second;
6093     if (Val && !getModule().getNamedValue(Name->getName()))
6094       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
6095   }
6096 }
6097 
6098 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
6099                                              GlobalDecl &Result) const {
6100   auto Res = Manglings.find(MangledName);
6101   if (Res == Manglings.end())
6102     return false;
6103   Result = Res->getValue();
6104   return true;
6105 }
6106 
6107 /// Emits metadata nodes associating all the global values in the
6108 /// current module with the Decls they came from.  This is useful for
6109 /// projects using IR gen as a subroutine.
6110 ///
6111 /// Since there's currently no way to associate an MDNode directly
6112 /// with an llvm::GlobalValue, we create a global named metadata
6113 /// with the name 'clang.global.decl.ptrs'.
6114 void CodeGenModule::EmitDeclMetadata() {
6115   llvm::NamedMDNode *GlobalMetadata = nullptr;
6116 
6117   for (auto &I : MangledDeclNames) {
6118     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
6119     // Some mangled names don't necessarily have an associated GlobalValue
6120     // in this module, e.g. if we mangled it for DebugInfo.
6121     if (Addr)
6122       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
6123   }
6124 }
6125 
6126 /// Emits metadata nodes for all the local variables in the current
6127 /// function.
6128 void CodeGenFunction::EmitDeclMetadata() {
6129   if (LocalDeclMap.empty()) return;
6130 
6131   llvm::LLVMContext &Context = getLLVMContext();
6132 
6133   // Find the unique metadata ID for this name.
6134   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
6135 
6136   llvm::NamedMDNode *GlobalMetadata = nullptr;
6137 
6138   for (auto &I : LocalDeclMap) {
6139     const Decl *D = I.first;
6140     llvm::Value *Addr = I.second.getPointer();
6141     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
6142       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
6143       Alloca->setMetadata(
6144           DeclPtrKind, llvm::MDNode::get(
6145                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
6146     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
6147       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
6148       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
6149     }
6150   }
6151 }
6152 
6153 void CodeGenModule::EmitVersionIdentMetadata() {
6154   llvm::NamedMDNode *IdentMetadata =
6155     TheModule.getOrInsertNamedMetadata("llvm.ident");
6156   std::string Version = getClangFullVersion();
6157   llvm::LLVMContext &Ctx = TheModule.getContext();
6158 
6159   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
6160   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
6161 }
6162 
6163 void CodeGenModule::EmitCommandLineMetadata() {
6164   llvm::NamedMDNode *CommandLineMetadata =
6165     TheModule.getOrInsertNamedMetadata("llvm.commandline");
6166   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
6167   llvm::LLVMContext &Ctx = TheModule.getContext();
6168 
6169   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
6170   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
6171 }
6172 
6173 void CodeGenModule::EmitCoverageFile() {
6174   if (getCodeGenOpts().CoverageDataFile.empty() &&
6175       getCodeGenOpts().CoverageNotesFile.empty())
6176     return;
6177 
6178   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
6179   if (!CUNode)
6180     return;
6181 
6182   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
6183   llvm::LLVMContext &Ctx = TheModule.getContext();
6184   auto *CoverageDataFile =
6185       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
6186   auto *CoverageNotesFile =
6187       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
6188   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
6189     llvm::MDNode *CU = CUNode->getOperand(i);
6190     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
6191     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
6192   }
6193 }
6194 
6195 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
6196                                                        bool ForEH) {
6197   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
6198   // FIXME: should we even be calling this method if RTTI is disabled
6199   // and it's not for EH?
6200   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6201       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6202        getTriple().isNVPTX()))
6203     return llvm::Constant::getNullValue(Int8PtrTy);
6204 
6205   if (ForEH && Ty->isObjCObjectPointerType() &&
6206       LangOpts.ObjCRuntime.isGNUFamily())
6207     return ObjCRuntime->GetEHType(Ty);
6208 
6209   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
6210 }
6211 
6212 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
6213   // Do not emit threadprivates in simd-only mode.
6214   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
6215     return;
6216   for (auto RefExpr : D->varlists()) {
6217     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
6218     bool PerformInit =
6219         VD->getAnyInitializer() &&
6220         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
6221                                                         /*ForRef=*/false);
6222 
6223     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
6224     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
6225             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
6226       CXXGlobalInits.push_back(InitFunction);
6227   }
6228 }
6229 
6230 llvm::Metadata *
6231 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
6232                                             StringRef Suffix) {
6233   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
6234   if (InternalId)
6235     return InternalId;
6236 
6237   if (isExternallyVisible(T->getLinkage())) {
6238     std::string OutName;
6239     llvm::raw_string_ostream Out(OutName);
6240     getCXXABI().getMangleContext().mangleTypeName(T, Out);
6241     Out << Suffix;
6242 
6243     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
6244   } else {
6245     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
6246                                            llvm::ArrayRef<llvm::Metadata *>());
6247   }
6248 
6249   return InternalId;
6250 }
6251 
6252 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
6253   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
6254 }
6255 
6256 llvm::Metadata *
6257 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6258   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6259 }
6260 
6261 // Generalize pointer types to a void pointer with the qualifiers of the
6262 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
6263 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
6264 // 'void *'.
6265 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6266   if (!Ty->isPointerType())
6267     return Ty;
6268 
6269   return Ctx.getPointerType(
6270       QualType(Ctx.VoidTy).withCVRQualifiers(
6271           Ty->getPointeeType().getCVRQualifiers()));
6272 }
6273 
6274 // Apply type generalization to a FunctionType's return and argument types
6275 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6276   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6277     SmallVector<QualType, 8> GeneralizedParams;
6278     for (auto &Param : FnType->param_types())
6279       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
6280 
6281     return Ctx.getFunctionType(
6282         GeneralizeType(Ctx, FnType->getReturnType()),
6283         GeneralizedParams, FnType->getExtProtoInfo());
6284   }
6285 
6286   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
6287     return Ctx.getFunctionNoProtoType(
6288         GeneralizeType(Ctx, FnType->getReturnType()));
6289 
6290   llvm_unreachable("Encountered unknown FunctionType");
6291 }
6292 
6293 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
6294   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
6295                                       GeneralizedMetadataIdMap, ".generalized");
6296 }
6297 
6298 /// Returns whether this module needs the "all-vtables" type identifier.
6299 bool CodeGenModule::NeedAllVtablesTypeId() const {
6300   // Returns true if at least one of vtable-based CFI checkers is enabled and
6301   // is not in the trapping mode.
6302   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
6303            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
6304           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
6305            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
6306           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
6307            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
6308           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
6309            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
6310 }
6311 
6312 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
6313                                           CharUnits Offset,
6314                                           const CXXRecordDecl *RD) {
6315   llvm::Metadata *MD =
6316       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
6317   VTable->addTypeMetadata(Offset.getQuantity(), MD);
6318 
6319   if (CodeGenOpts.SanitizeCfiCrossDso)
6320     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
6321       VTable->addTypeMetadata(Offset.getQuantity(),
6322                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
6323 
6324   if (NeedAllVtablesTypeId()) {
6325     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
6326     VTable->addTypeMetadata(Offset.getQuantity(), MD);
6327   }
6328 }
6329 
6330 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
6331   if (!SanStats)
6332     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
6333 
6334   return *SanStats;
6335 }
6336 
6337 llvm::Value *
6338 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
6339                                                   CodeGenFunction &CGF) {
6340   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6341   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6342   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6343   auto *Call = CGF.EmitRuntimeCall(
6344       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6345   return Call;
6346 }
6347 
6348 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6349     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6350   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6351                                  /* forPointeeType= */ true);
6352 }
6353 
6354 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6355                                                  LValueBaseInfo *BaseInfo,
6356                                                  TBAAAccessInfo *TBAAInfo,
6357                                                  bool forPointeeType) {
6358   if (TBAAInfo)
6359     *TBAAInfo = getTBAAAccessInfo(T);
6360 
6361   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6362   // that doesn't return the information we need to compute BaseInfo.
6363 
6364   // Honor alignment typedef attributes even on incomplete types.
6365   // We also honor them straight for C++ class types, even as pointees;
6366   // there's an expressivity gap here.
6367   if (auto TT = T->getAs<TypedefType>()) {
6368     if (auto Align = TT->getDecl()->getMaxAlignment()) {
6369       if (BaseInfo)
6370         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6371       return getContext().toCharUnitsFromBits(Align);
6372     }
6373   }
6374 
6375   bool AlignForArray = T->isArrayType();
6376 
6377   // Analyze the base element type, so we don't get confused by incomplete
6378   // array types.
6379   T = getContext().getBaseElementType(T);
6380 
6381   if (T->isIncompleteType()) {
6382     // We could try to replicate the logic from
6383     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6384     // type is incomplete, so it's impossible to test. We could try to reuse
6385     // getTypeAlignIfKnown, but that doesn't return the information we need
6386     // to set BaseInfo.  So just ignore the possibility that the alignment is
6387     // greater than one.
6388     if (BaseInfo)
6389       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6390     return CharUnits::One();
6391   }
6392 
6393   if (BaseInfo)
6394     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6395 
6396   CharUnits Alignment;
6397   const CXXRecordDecl *RD;
6398   if (T.getQualifiers().hasUnaligned()) {
6399     Alignment = CharUnits::One();
6400   } else if (forPointeeType && !AlignForArray &&
6401              (RD = T->getAsCXXRecordDecl())) {
6402     // For C++ class pointees, we don't know whether we're pointing at a
6403     // base or a complete object, so we generally need to use the
6404     // non-virtual alignment.
6405     Alignment = getClassPointerAlignment(RD);
6406   } else {
6407     Alignment = getContext().getTypeAlignInChars(T);
6408   }
6409 
6410   // Cap to the global maximum type alignment unless the alignment
6411   // was somehow explicit on the type.
6412   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6413     if (Alignment.getQuantity() > MaxAlign &&
6414         !getContext().isAlignmentRequired(T))
6415       Alignment = CharUnits::fromQuantity(MaxAlign);
6416   }
6417   return Alignment;
6418 }
6419 
6420 bool CodeGenModule::stopAutoInit() {
6421   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6422   if (StopAfter) {
6423     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6424     // used
6425     if (NumAutoVarInit >= StopAfter) {
6426       return true;
6427     }
6428     if (!NumAutoVarInit) {
6429       unsigned DiagID = getDiags().getCustomDiagID(
6430           DiagnosticsEngine::Warning,
6431           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6432           "number of times ftrivial-auto-var-init=%1 gets applied.");
6433       getDiags().Report(DiagID)
6434           << StopAfter
6435           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6436                       LangOptions::TrivialAutoVarInitKind::Zero
6437                   ? "zero"
6438                   : "pattern");
6439     }
6440     ++NumAutoVarInit;
6441   }
6442   return false;
6443 }
6444 
6445 void CodeGenModule::printPostfixForExternalizedStaticVar(
6446     llvm::raw_ostream &OS) const {
6447   OS << ".static." << getContext().getCUIDHash();
6448 }
6449