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