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