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