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