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