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