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