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