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