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