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