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