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