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