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