xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 3c9be62d24bf8de495dc6c707c8dbd3cedc86eef)
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   setDSOLocal(GV);
1925   return ConstantAddress(GV, Alignment);
1926 }
1927 
1928 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1929   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1930   assert(AA && "No alias?");
1931 
1932   CharUnits Alignment = getContext().getDeclAlign(VD);
1933   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1934 
1935   // See if there is already something with the target's name in the module.
1936   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1937   if (Entry) {
1938     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1939     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1940     return ConstantAddress(Ptr, Alignment);
1941   }
1942 
1943   llvm::Constant *Aliasee;
1944   if (isa<llvm::FunctionType>(DeclTy))
1945     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1946                                       GlobalDecl(cast<FunctionDecl>(VD)),
1947                                       /*ForVTable=*/false);
1948   else
1949     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1950                                     llvm::PointerType::getUnqual(DeclTy),
1951                                     nullptr);
1952 
1953   auto *F = cast<llvm::GlobalValue>(Aliasee);
1954   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1955   WeakRefReferences.insert(F);
1956 
1957   return ConstantAddress(Aliasee, Alignment);
1958 }
1959 
1960 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1961   const auto *Global = cast<ValueDecl>(GD.getDecl());
1962 
1963   // Weak references don't produce any output by themselves.
1964   if (Global->hasAttr<WeakRefAttr>())
1965     return;
1966 
1967   // If this is an alias definition (which otherwise looks like a declaration)
1968   // emit it now.
1969   if (Global->hasAttr<AliasAttr>())
1970     return EmitAliasDefinition(GD);
1971 
1972   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1973   if (Global->hasAttr<IFuncAttr>())
1974     return emitIFuncDefinition(GD);
1975 
1976   // If this is CUDA, be selective about which declarations we emit.
1977   if (LangOpts.CUDA) {
1978     if (LangOpts.CUDAIsDevice) {
1979       if (!Global->hasAttr<CUDADeviceAttr>() &&
1980           !Global->hasAttr<CUDAGlobalAttr>() &&
1981           !Global->hasAttr<CUDAConstantAttr>() &&
1982           !Global->hasAttr<CUDASharedAttr>())
1983         return;
1984     } else {
1985       // We need to emit host-side 'shadows' for all global
1986       // device-side variables because the CUDA runtime needs their
1987       // size and host-side address in order to provide access to
1988       // their device-side incarnations.
1989 
1990       // So device-only functions are the only things we skip.
1991       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1992           Global->hasAttr<CUDADeviceAttr>())
1993         return;
1994 
1995       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1996              "Expected Variable or Function");
1997     }
1998   }
1999 
2000   if (LangOpts.OpenMP) {
2001     // If this is OpenMP device, check if it is legal to emit this global
2002     // normally.
2003     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2004       return;
2005     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2006       if (MustBeEmitted(Global))
2007         EmitOMPDeclareReduction(DRD);
2008       return;
2009     }
2010   }
2011 
2012   // Ignore declarations, they will be emitted on their first use.
2013   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2014     // Forward declarations are emitted lazily on first use.
2015     if (!FD->doesThisDeclarationHaveABody()) {
2016       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2017         return;
2018 
2019       StringRef MangledName = getMangledName(GD);
2020 
2021       // Compute the function info and LLVM type.
2022       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2023       llvm::Type *Ty = getTypes().GetFunctionType(FI);
2024 
2025       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2026                               /*DontDefer=*/false);
2027       return;
2028     }
2029   } else {
2030     const auto *VD = cast<VarDecl>(Global);
2031     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2032     // We need to emit device-side global CUDA variables even if a
2033     // variable does not have a definition -- we still need to define
2034     // host-side shadow for it.
2035     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2036                            !VD->hasDefinition() &&
2037                            (VD->hasAttr<CUDAConstantAttr>() ||
2038                             VD->hasAttr<CUDADeviceAttr>());
2039     if (!MustEmitForCuda &&
2040         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2041         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2042       // If this declaration may have caused an inline variable definition to
2043       // change linkage, make sure that it's emitted.
2044       if (Context.getInlineVariableDefinitionKind(VD) ==
2045           ASTContext::InlineVariableDefinitionKind::Strong)
2046         GetAddrOfGlobalVar(VD);
2047       return;
2048     }
2049   }
2050 
2051   // Defer code generation to first use when possible, e.g. if this is an inline
2052   // function. If the global must always be emitted, do it eagerly if possible
2053   // to benefit from cache locality.
2054   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2055     // Emit the definition if it can't be deferred.
2056     EmitGlobalDefinition(GD);
2057     return;
2058   }
2059 
2060   // If we're deferring emission of a C++ variable with an
2061   // initializer, remember the order in which it appeared in the file.
2062   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2063       cast<VarDecl>(Global)->hasInit()) {
2064     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2065     CXXGlobalInits.push_back(nullptr);
2066   }
2067 
2068   StringRef MangledName = getMangledName(GD);
2069   if (GetGlobalValue(MangledName) != nullptr) {
2070     // The value has already been used and should therefore be emitted.
2071     addDeferredDeclToEmit(GD);
2072   } else if (MustBeEmitted(Global)) {
2073     // The value must be emitted, but cannot be emitted eagerly.
2074     assert(!MayBeEmittedEagerly(Global));
2075     addDeferredDeclToEmit(GD);
2076   } else {
2077     // Otherwise, remember that we saw a deferred decl with this name.  The
2078     // first use of the mangled name will cause it to move into
2079     // DeferredDeclsToEmit.
2080     DeferredDecls[MangledName] = GD;
2081   }
2082 }
2083 
2084 // Check if T is a class type with a destructor that's not dllimport.
2085 static bool HasNonDllImportDtor(QualType T) {
2086   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2087     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2088       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2089         return true;
2090 
2091   return false;
2092 }
2093 
2094 namespace {
2095   struct FunctionIsDirectlyRecursive :
2096     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2097     const StringRef Name;
2098     const Builtin::Context &BI;
2099     bool Result;
2100     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2101       Name(N), BI(C), Result(false) {
2102     }
2103     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2104 
2105     bool TraverseCallExpr(CallExpr *E) {
2106       const FunctionDecl *FD = E->getDirectCallee();
2107       if (!FD)
2108         return true;
2109       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2110       if (Attr && Name == Attr->getLabel()) {
2111         Result = true;
2112         return false;
2113       }
2114       unsigned BuiltinID = FD->getBuiltinID();
2115       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2116         return true;
2117       StringRef BuiltinName = BI.getName(BuiltinID);
2118       if (BuiltinName.startswith("__builtin_") &&
2119           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2120         Result = true;
2121         return false;
2122       }
2123       return true;
2124     }
2125   };
2126 
2127   // Make sure we're not referencing non-imported vars or functions.
2128   struct DLLImportFunctionVisitor
2129       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2130     bool SafeToInline = true;
2131 
2132     bool shouldVisitImplicitCode() const { return true; }
2133 
2134     bool VisitVarDecl(VarDecl *VD) {
2135       if (VD->getTLSKind()) {
2136         // A thread-local variable cannot be imported.
2137         SafeToInline = false;
2138         return SafeToInline;
2139       }
2140 
2141       // A variable definition might imply a destructor call.
2142       if (VD->isThisDeclarationADefinition())
2143         SafeToInline = !HasNonDllImportDtor(VD->getType());
2144 
2145       return SafeToInline;
2146     }
2147 
2148     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2149       if (const auto *D = E->getTemporary()->getDestructor())
2150         SafeToInline = D->hasAttr<DLLImportAttr>();
2151       return SafeToInline;
2152     }
2153 
2154     bool VisitDeclRefExpr(DeclRefExpr *E) {
2155       ValueDecl *VD = E->getDecl();
2156       if (isa<FunctionDecl>(VD))
2157         SafeToInline = VD->hasAttr<DLLImportAttr>();
2158       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2159         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2160       return SafeToInline;
2161     }
2162 
2163     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2164       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2165       return SafeToInline;
2166     }
2167 
2168     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2169       CXXMethodDecl *M = E->getMethodDecl();
2170       if (!M) {
2171         // Call through a pointer to member function. This is safe to inline.
2172         SafeToInline = true;
2173       } else {
2174         SafeToInline = M->hasAttr<DLLImportAttr>();
2175       }
2176       return SafeToInline;
2177     }
2178 
2179     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2180       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2181       return SafeToInline;
2182     }
2183 
2184     bool VisitCXXNewExpr(CXXNewExpr *E) {
2185       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2186       return SafeToInline;
2187     }
2188   };
2189 }
2190 
2191 // isTriviallyRecursive - Check if this function calls another
2192 // decl that, because of the asm attribute or the other decl being a builtin,
2193 // ends up pointing to itself.
2194 bool
2195 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2196   StringRef Name;
2197   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2198     // asm labels are a special kind of mangling we have to support.
2199     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2200     if (!Attr)
2201       return false;
2202     Name = Attr->getLabel();
2203   } else {
2204     Name = FD->getName();
2205   }
2206 
2207   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2208   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2209   return Walker.Result;
2210 }
2211 
2212 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2213   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2214     return true;
2215   const auto *F = cast<FunctionDecl>(GD.getDecl());
2216   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2217     return false;
2218 
2219   if (F->hasAttr<DLLImportAttr>()) {
2220     // Check whether it would be safe to inline this dllimport function.
2221     DLLImportFunctionVisitor Visitor;
2222     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2223     if (!Visitor.SafeToInline)
2224       return false;
2225 
2226     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2227       // Implicit destructor invocations aren't captured in the AST, so the
2228       // check above can't see them. Check for them manually here.
2229       for (const Decl *Member : Dtor->getParent()->decls())
2230         if (isa<FieldDecl>(Member))
2231           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2232             return false;
2233       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2234         if (HasNonDllImportDtor(B.getType()))
2235           return false;
2236     }
2237   }
2238 
2239   // PR9614. Avoid cases where the source code is lying to us. An available
2240   // externally function should have an equivalent function somewhere else,
2241   // but a function that calls itself is clearly not equivalent to the real
2242   // implementation.
2243   // This happens in glibc's btowc and in some configure checks.
2244   return !isTriviallyRecursive(F);
2245 }
2246 
2247 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2248   return CodeGenOpts.OptimizationLevel > 0;
2249 }
2250 
2251 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2252   const auto *D = cast<ValueDecl>(GD.getDecl());
2253 
2254   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2255                                  Context.getSourceManager(),
2256                                  "Generating code for declaration");
2257 
2258   if (isa<FunctionDecl>(D)) {
2259     // At -O0, don't generate IR for functions with available_externally
2260     // linkage.
2261     if (!shouldEmitFunction(GD))
2262       return;
2263 
2264     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2265       // Make sure to emit the definition(s) before we emit the thunks.
2266       // This is necessary for the generation of certain thunks.
2267       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2268         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
2269       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2270         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2271       else
2272         EmitGlobalFunctionDefinition(GD, GV);
2273 
2274       if (Method->isVirtual())
2275         getVTables().EmitThunks(GD);
2276 
2277       return;
2278     }
2279 
2280     return EmitGlobalFunctionDefinition(GD, GV);
2281   }
2282 
2283   if (const auto *VD = dyn_cast<VarDecl>(D))
2284     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2285 
2286   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2287 }
2288 
2289 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2290                                                       llvm::Function *NewFn);
2291 
2292 void CodeGenModule::emitMultiVersionFunctions() {
2293   for (GlobalDecl GD : MultiVersionFuncs) {
2294     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2295     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2296     getContext().forEachMultiversionedFunctionVersion(
2297         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2298           GlobalDecl CurGD{
2299               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2300           StringRef MangledName = getMangledName(CurGD);
2301           llvm::Constant *Func = GetGlobalValue(MangledName);
2302           if (!Func) {
2303             if (CurFD->isDefined()) {
2304               EmitGlobalFunctionDefinition(CurGD, nullptr);
2305               Func = GetGlobalValue(MangledName);
2306             } else {
2307               const CGFunctionInfo &FI =
2308                   getTypes().arrangeGlobalDeclaration(GD);
2309               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2310               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2311                                        /*DontDefer=*/false, ForDefinition);
2312             }
2313             assert(Func && "This should have just been created");
2314           }
2315           Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
2316                                CurFD->getAttr<TargetAttr>()->parse());
2317         });
2318 
2319     llvm::Function *ResolverFunc = cast<llvm::Function>(
2320         GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2321     if (supportsCOMDAT())
2322       ResolverFunc->setComdat(
2323           getModule().getOrInsertComdat(ResolverFunc->getName()));
2324     std::stable_sort(
2325         Options.begin(), Options.end(),
2326         std::greater<CodeGenFunction::MultiVersionResolverOption>());
2327     CodeGenFunction CGF(*this);
2328     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2329   }
2330 }
2331 
2332 /// If an ifunc for the specified mangled name is not in the module, create and
2333 /// return an llvm IFunc Function with the specified type.
2334 llvm::Constant *
2335 CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
2336                                             StringRef MangledName,
2337                                             const FunctionDecl *FD) {
2338   std::string IFuncName = (MangledName + ".ifunc").str();
2339   if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2340     return IFuncGV;
2341 
2342   // Since this is the first time we've created this IFunc, make sure
2343   // that we put this multiversioned function into the list to be
2344   // replaced later.
2345   MultiVersionFuncs.push_back(GD);
2346 
2347   std::string ResolverName = (MangledName + ".resolver").str();
2348   llvm::Type *ResolverType = llvm::FunctionType::get(
2349       llvm::PointerType::get(DeclTy,
2350                              Context.getTargetAddressSpace(FD->getType())),
2351       false);
2352   llvm::Constant *Resolver =
2353       GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2354                               /*ForVTable=*/false);
2355   llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2356       DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2357   GIF->setName(IFuncName);
2358   SetCommonAttributes(FD, GIF);
2359 
2360   return GIF;
2361 }
2362 
2363 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2364 /// module, create and return an llvm Function with the specified type. If there
2365 /// is something in the module with the specified name, return it potentially
2366 /// bitcasted to the right type.
2367 ///
2368 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2369 /// to set the attributes on the function when it is first created.
2370 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2371     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2372     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2373     ForDefinition_t IsForDefinition) {
2374   const Decl *D = GD.getDecl();
2375 
2376   // Any attempts to use a MultiVersion function should result in retrieving
2377   // the iFunc instead. Name Mangling will handle the rest of the changes.
2378   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2379     // For the device mark the function as one that should be emitted.
2380     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2381         !OpenMPRuntime->markAsGlobalTarget(FD) && FD->isDefined() &&
2382         !DontDefer && !IsForDefinition)
2383       addDeferredDeclToEmit(GD);
2384 
2385     if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) {
2386       UpdateMultiVersionNames(GD, FD);
2387       if (!IsForDefinition)
2388         return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD);
2389     }
2390   }
2391 
2392   // Lookup the entry, lazily creating it if necessary.
2393   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2394   if (Entry) {
2395     if (WeakRefReferences.erase(Entry)) {
2396       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2397       if (FD && !FD->hasAttr<WeakAttr>())
2398         Entry->setLinkage(llvm::Function::ExternalLinkage);
2399     }
2400 
2401     // Handle dropped DLL attributes.
2402     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2403       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2404 
2405     // If there are two attempts to define the same mangled name, issue an
2406     // error.
2407     if (IsForDefinition && !Entry->isDeclaration()) {
2408       GlobalDecl OtherGD;
2409       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2410       // to make sure that we issue an error only once.
2411       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2412           (GD.getCanonicalDecl().getDecl() !=
2413            OtherGD.getCanonicalDecl().getDecl()) &&
2414           DiagnosedConflictingDefinitions.insert(GD).second) {
2415         getDiags().Report(D->getLocation(),
2416                           diag::err_duplicate_mangled_name);
2417         getDiags().Report(OtherGD.getDecl()->getLocation(),
2418                           diag::note_previous_definition);
2419       }
2420     }
2421 
2422     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2423         (Entry->getType()->getElementType() == Ty)) {
2424       return Entry;
2425     }
2426 
2427     // Make sure the result is of the correct type.
2428     // (If function is requested for a definition, we always need to create a new
2429     // function, not just return a bitcast.)
2430     if (!IsForDefinition)
2431       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2432   }
2433 
2434   // This function doesn't have a complete type (for example, the return
2435   // type is an incomplete struct). Use a fake type instead, and make
2436   // sure not to try to set attributes.
2437   bool IsIncompleteFunction = false;
2438 
2439   llvm::FunctionType *FTy;
2440   if (isa<llvm::FunctionType>(Ty)) {
2441     FTy = cast<llvm::FunctionType>(Ty);
2442   } else {
2443     FTy = llvm::FunctionType::get(VoidTy, false);
2444     IsIncompleteFunction = true;
2445   }
2446 
2447   llvm::Function *F =
2448       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2449                              Entry ? StringRef() : MangledName, &getModule());
2450 
2451   // If we already created a function with the same mangled name (but different
2452   // type) before, take its name and add it to the list of functions to be
2453   // replaced with F at the end of CodeGen.
2454   //
2455   // This happens if there is a prototype for a function (e.g. "int f()") and
2456   // then a definition of a different type (e.g. "int f(int x)").
2457   if (Entry) {
2458     F->takeName(Entry);
2459 
2460     // This might be an implementation of a function without a prototype, in
2461     // which case, try to do special replacement of calls which match the new
2462     // prototype.  The really key thing here is that we also potentially drop
2463     // arguments from the call site so as to make a direct call, which makes the
2464     // inliner happier and suppresses a number of optimizer warnings (!) about
2465     // dropping arguments.
2466     if (!Entry->use_empty()) {
2467       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2468       Entry->removeDeadConstantUsers();
2469     }
2470 
2471     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2472         F, Entry->getType()->getElementType()->getPointerTo());
2473     addGlobalValReplacement(Entry, BC);
2474   }
2475 
2476   assert(F->getName() == MangledName && "name was uniqued!");
2477   if (D)
2478     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2479   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2480     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2481     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2482   }
2483 
2484   if (!DontDefer) {
2485     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2486     // each other bottoming out with the base dtor.  Therefore we emit non-base
2487     // dtors on usage, even if there is no dtor definition in the TU.
2488     if (D && isa<CXXDestructorDecl>(D) &&
2489         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2490                                            GD.getDtorType()))
2491       addDeferredDeclToEmit(GD);
2492 
2493     // This is the first use or definition of a mangled name.  If there is a
2494     // deferred decl with this name, remember that we need to emit it at the end
2495     // of the file.
2496     auto DDI = DeferredDecls.find(MangledName);
2497     if (DDI != DeferredDecls.end()) {
2498       // Move the potentially referenced deferred decl to the
2499       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2500       // don't need it anymore).
2501       addDeferredDeclToEmit(DDI->second);
2502       DeferredDecls.erase(DDI);
2503 
2504       // Otherwise, there are cases we have to worry about where we're
2505       // using a declaration for which we must emit a definition but where
2506       // we might not find a top-level definition:
2507       //   - member functions defined inline in their classes
2508       //   - friend functions defined inline in some class
2509       //   - special member functions with implicit definitions
2510       // If we ever change our AST traversal to walk into class methods,
2511       // this will be unnecessary.
2512       //
2513       // We also don't emit a definition for a function if it's going to be an
2514       // entry in a vtable, unless it's already marked as used.
2515     } else if (getLangOpts().CPlusPlus && D) {
2516       // Look for a declaration that's lexically in a record.
2517       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2518            FD = FD->getPreviousDecl()) {
2519         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2520           if (FD->doesThisDeclarationHaveABody()) {
2521             addDeferredDeclToEmit(GD.getWithDecl(FD));
2522             break;
2523           }
2524         }
2525       }
2526     }
2527   }
2528 
2529   // Make sure the result is of the requested type.
2530   if (!IsIncompleteFunction) {
2531     assert(F->getType()->getElementType() == Ty);
2532     return F;
2533   }
2534 
2535   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2536   return llvm::ConstantExpr::getBitCast(F, PTy);
2537 }
2538 
2539 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2540 /// non-null, then this function will use the specified type if it has to
2541 /// create it (this occurs when we see a definition of the function).
2542 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2543                                                  llvm::Type *Ty,
2544                                                  bool ForVTable,
2545                                                  bool DontDefer,
2546                                               ForDefinition_t IsForDefinition) {
2547   // If there was no specific requested type, just convert it now.
2548   if (!Ty) {
2549     const auto *FD = cast<FunctionDecl>(GD.getDecl());
2550     auto CanonTy = Context.getCanonicalType(FD->getType());
2551     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2552   }
2553 
2554   // Devirtualized destructor calls may come through here instead of via
2555   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2556   // of the complete destructor when necessary.
2557   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2558     if (getTarget().getCXXABI().isMicrosoft() &&
2559         GD.getDtorType() == Dtor_Complete &&
2560         DD->getParent()->getNumVBases() == 0)
2561       GD = GlobalDecl(DD, Dtor_Base);
2562   }
2563 
2564   StringRef MangledName = getMangledName(GD);
2565   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2566                                  /*IsThunk=*/false, llvm::AttributeList(),
2567                                  IsForDefinition);
2568 }
2569 
2570 static const FunctionDecl *
2571 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2572   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2573   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2574 
2575   IdentifierInfo &CII = C.Idents.get(Name);
2576   for (const auto &Result : DC->lookup(&CII))
2577     if (const auto FD = dyn_cast<FunctionDecl>(Result))
2578       return FD;
2579 
2580   if (!C.getLangOpts().CPlusPlus)
2581     return nullptr;
2582 
2583   // Demangle the premangled name from getTerminateFn()
2584   IdentifierInfo &CXXII =
2585       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
2586           ? C.Idents.get("terminate")
2587           : C.Idents.get(Name);
2588 
2589   for (const auto &N : {"__cxxabiv1", "std"}) {
2590     IdentifierInfo &NS = C.Idents.get(N);
2591     for (const auto &Result : DC->lookup(&NS)) {
2592       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2593       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2594         for (const auto &Result : LSD->lookup(&NS))
2595           if ((ND = dyn_cast<NamespaceDecl>(Result)))
2596             break;
2597 
2598       if (ND)
2599         for (const auto &Result : ND->lookup(&CXXII))
2600           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2601             return FD;
2602     }
2603   }
2604 
2605   return nullptr;
2606 }
2607 
2608 /// CreateRuntimeFunction - Create a new runtime function with the specified
2609 /// type and name.
2610 llvm::Constant *
2611 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2612                                      llvm::AttributeList ExtraAttrs,
2613                                      bool Local) {
2614   llvm::Constant *C =
2615       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2616                               /*DontDefer=*/false, /*IsThunk=*/false,
2617                               ExtraAttrs);
2618 
2619   if (auto *F = dyn_cast<llvm::Function>(C)) {
2620     if (F->empty()) {
2621       F->setCallingConv(getRuntimeCC());
2622 
2623       if (!Local && getTriple().isOSBinFormatCOFF() &&
2624           !getCodeGenOpts().LTOVisibilityPublicStd &&
2625           !getTriple().isWindowsGNUEnvironment()) {
2626         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2627         if (!FD || FD->hasAttr<DLLImportAttr>()) {
2628           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2629           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2630         }
2631       }
2632       setDSOLocal(F);
2633     }
2634   }
2635 
2636   return C;
2637 }
2638 
2639 /// CreateBuiltinFunction - Create a new builtin function with the specified
2640 /// type and name.
2641 llvm::Constant *
2642 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2643                                      llvm::AttributeList ExtraAttrs) {
2644   llvm::Constant *C =
2645       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2646                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2647   if (auto *F = dyn_cast<llvm::Function>(C))
2648     if (F->empty())
2649       F->setCallingConv(getBuiltinCC());
2650   return C;
2651 }
2652 
2653 /// isTypeConstant - Determine whether an object of this type can be emitted
2654 /// as a constant.
2655 ///
2656 /// If ExcludeCtor is true, the duration when the object's constructor runs
2657 /// will not be considered. The caller will need to verify that the object is
2658 /// not written to during its construction.
2659 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2660   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2661     return false;
2662 
2663   if (Context.getLangOpts().CPlusPlus) {
2664     if (const CXXRecordDecl *Record
2665           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2666       return ExcludeCtor && !Record->hasMutableFields() &&
2667              Record->hasTrivialDestructor();
2668   }
2669 
2670   return true;
2671 }
2672 
2673 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2674 /// create and return an llvm GlobalVariable with the specified type.  If there
2675 /// is something in the module with the specified name, return it potentially
2676 /// bitcasted to the right type.
2677 ///
2678 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2679 /// to set the attributes on the global when it is first created.
2680 ///
2681 /// If IsForDefinition is true, it is guranteed that an actual global with
2682 /// type Ty will be returned, not conversion of a variable with the same
2683 /// mangled name but some other type.
2684 llvm::Constant *
2685 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2686                                      llvm::PointerType *Ty,
2687                                      const VarDecl *D,
2688                                      ForDefinition_t IsForDefinition) {
2689   // Lookup the entry, lazily creating it if necessary.
2690   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2691   if (Entry) {
2692     if (WeakRefReferences.erase(Entry)) {
2693       if (D && !D->hasAttr<WeakAttr>())
2694         Entry->setLinkage(llvm::Function::ExternalLinkage);
2695     }
2696 
2697     // Handle dropped DLL attributes.
2698     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2699       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2700 
2701     if (Entry->getType() == Ty)
2702       return Entry;
2703 
2704     // If there are two attempts to define the same mangled name, issue an
2705     // error.
2706     if (IsForDefinition && !Entry->isDeclaration()) {
2707       GlobalDecl OtherGD;
2708       const VarDecl *OtherD;
2709 
2710       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2711       // to make sure that we issue an error only once.
2712       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2713           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2714           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2715           OtherD->hasInit() &&
2716           DiagnosedConflictingDefinitions.insert(D).second) {
2717         getDiags().Report(D->getLocation(),
2718                           diag::err_duplicate_mangled_name);
2719         getDiags().Report(OtherGD.getDecl()->getLocation(),
2720                           diag::note_previous_definition);
2721       }
2722     }
2723 
2724     // Make sure the result is of the correct type.
2725     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2726       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2727 
2728     // (If global is requested for a definition, we always need to create a new
2729     // global, not just return a bitcast.)
2730     if (!IsForDefinition)
2731       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2732   }
2733 
2734   auto AddrSpace = GetGlobalVarAddressSpace(D);
2735   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2736 
2737   auto *GV = new llvm::GlobalVariable(
2738       getModule(), Ty->getElementType(), false,
2739       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2740       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2741 
2742   // If we already created a global with the same mangled name (but different
2743   // type) before, take its name and remove it from its parent.
2744   if (Entry) {
2745     GV->takeName(Entry);
2746 
2747     if (!Entry->use_empty()) {
2748       llvm::Constant *NewPtrForOldDecl =
2749           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2750       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2751     }
2752 
2753     Entry->eraseFromParent();
2754   }
2755 
2756   // This is the first use or definition of a mangled name.  If there is a
2757   // deferred decl with this name, remember that we need to emit it at the end
2758   // of the file.
2759   auto DDI = DeferredDecls.find(MangledName);
2760   if (DDI != DeferredDecls.end()) {
2761     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2762     // list, and remove it from DeferredDecls (since we don't need it anymore).
2763     addDeferredDeclToEmit(DDI->second);
2764     DeferredDecls.erase(DDI);
2765   }
2766 
2767   // Handle things which are present even on external declarations.
2768   if (D) {
2769     // FIXME: This code is overly simple and should be merged with other global
2770     // handling.
2771     GV->setConstant(isTypeConstant(D->getType(), false));
2772 
2773     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2774 
2775     setLinkageForGV(GV, D);
2776 
2777     if (D->getTLSKind()) {
2778       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2779         CXXThreadLocals.push_back(D);
2780       setTLSMode(GV, *D);
2781     }
2782 
2783     setGVProperties(GV, D);
2784 
2785     // If required by the ABI, treat declarations of static data members with
2786     // inline initializers as definitions.
2787     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2788       EmitGlobalVarDefinition(D);
2789     }
2790 
2791     // Emit section information for extern variables.
2792     if (D->hasExternalStorage()) {
2793       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
2794         GV->setSection(SA->getName());
2795     }
2796 
2797     // Handle XCore specific ABI requirements.
2798     if (getTriple().getArch() == llvm::Triple::xcore &&
2799         D->getLanguageLinkage() == CLanguageLinkage &&
2800         D->getType().isConstant(Context) &&
2801         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2802       GV->setSection(".cp.rodata");
2803 
2804     // Check if we a have a const declaration with an initializer, we may be
2805     // able to emit it as available_externally to expose it's value to the
2806     // optimizer.
2807     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2808         D->getType().isConstQualified() && !GV->hasInitializer() &&
2809         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
2810       const auto *Record =
2811           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
2812       bool HasMutableFields = Record && Record->hasMutableFields();
2813       if (!HasMutableFields) {
2814         const VarDecl *InitDecl;
2815         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2816         if (InitExpr) {
2817           ConstantEmitter emitter(*this);
2818           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
2819           if (Init) {
2820             auto *InitType = Init->getType();
2821             if (GV->getType()->getElementType() != InitType) {
2822               // The type of the initializer does not match the definition.
2823               // This happens when an initializer has a different type from
2824               // the type of the global (because of padding at the end of a
2825               // structure for instance).
2826               GV->setName(StringRef());
2827               // Make a new global with the correct type, this is now guaranteed
2828               // to work.
2829               auto *NewGV = cast<llvm::GlobalVariable>(
2830                   GetAddrOfGlobalVar(D, InitType, IsForDefinition));
2831 
2832               // Erase the old global, since it is no longer used.
2833               GV->eraseFromParent();
2834               GV = NewGV;
2835             } else {
2836               GV->setInitializer(Init);
2837               GV->setConstant(true);
2838               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2839             }
2840             emitter.finalize(GV);
2841           }
2842         }
2843       }
2844     }
2845   }
2846 
2847   LangAS ExpectedAS =
2848       D ? D->getType().getAddressSpace()
2849         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
2850   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2851          Ty->getPointerAddressSpace());
2852   if (AddrSpace != ExpectedAS)
2853     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2854                                                        ExpectedAS, Ty);
2855 
2856   return GV;
2857 }
2858 
2859 llvm::Constant *
2860 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2861                                ForDefinition_t IsForDefinition) {
2862   const Decl *D = GD.getDecl();
2863   if (isa<CXXConstructorDecl>(D))
2864     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2865                                 getFromCtorType(GD.getCtorType()),
2866                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2867                                 /*DontDefer=*/false, IsForDefinition);
2868   else if (isa<CXXDestructorDecl>(D))
2869     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2870                                 getFromDtorType(GD.getDtorType()),
2871                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2872                                 /*DontDefer=*/false, IsForDefinition);
2873   else if (isa<CXXMethodDecl>(D)) {
2874     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2875         cast<CXXMethodDecl>(D));
2876     auto Ty = getTypes().GetFunctionType(*FInfo);
2877     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2878                              IsForDefinition);
2879   } else if (isa<FunctionDecl>(D)) {
2880     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2881     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2882     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2883                              IsForDefinition);
2884   } else
2885     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2886                               IsForDefinition);
2887 }
2888 
2889 llvm::GlobalVariable *
2890 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2891                                       llvm::Type *Ty,
2892                                       llvm::GlobalValue::LinkageTypes Linkage) {
2893   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2894   llvm::GlobalVariable *OldGV = nullptr;
2895 
2896   if (GV) {
2897     // Check if the variable has the right type.
2898     if (GV->getType()->getElementType() == Ty)
2899       return GV;
2900 
2901     // Because C++ name mangling, the only way we can end up with an already
2902     // existing global with the same name is if it has been declared extern "C".
2903     assert(GV->isDeclaration() && "Declaration has wrong type!");
2904     OldGV = GV;
2905   }
2906 
2907   // Create a new variable.
2908   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2909                                 Linkage, nullptr, Name);
2910 
2911   if (OldGV) {
2912     // Replace occurrences of the old variable if needed.
2913     GV->takeName(OldGV);
2914 
2915     if (!OldGV->use_empty()) {
2916       llvm::Constant *NewPtrForOldDecl =
2917       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2918       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2919     }
2920 
2921     OldGV->eraseFromParent();
2922   }
2923 
2924   if (supportsCOMDAT() && GV->isWeakForLinker() &&
2925       !GV->hasAvailableExternallyLinkage())
2926     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2927 
2928   return GV;
2929 }
2930 
2931 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2932 /// given global variable.  If Ty is non-null and if the global doesn't exist,
2933 /// then it will be created with the specified type instead of whatever the
2934 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2935 /// that an actual global with type Ty will be returned, not conversion of a
2936 /// variable with the same mangled name but some other type.
2937 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2938                                                   llvm::Type *Ty,
2939                                            ForDefinition_t IsForDefinition) {
2940   assert(D->hasGlobalStorage() && "Not a global variable");
2941   QualType ASTTy = D->getType();
2942   if (!Ty)
2943     Ty = getTypes().ConvertTypeForMem(ASTTy);
2944 
2945   llvm::PointerType *PTy =
2946     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2947 
2948   StringRef MangledName = getMangledName(D);
2949   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2950 }
2951 
2952 /// CreateRuntimeVariable - Create a new runtime global variable with the
2953 /// specified type and name.
2954 llvm::Constant *
2955 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2956                                      StringRef Name) {
2957   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2958 }
2959 
2960 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2961   assert(!D->getInit() && "Cannot emit definite definitions here!");
2962 
2963   StringRef MangledName = getMangledName(D);
2964   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2965 
2966   // We already have a definition, not declaration, with the same mangled name.
2967   // Emitting of declaration is not required (and actually overwrites emitted
2968   // definition).
2969   if (GV && !GV->isDeclaration())
2970     return;
2971 
2972   // If we have not seen a reference to this variable yet, place it into the
2973   // deferred declarations table to be emitted if needed later.
2974   if (!MustBeEmitted(D) && !GV) {
2975       DeferredDecls[MangledName] = D;
2976       return;
2977   }
2978 
2979   // The tentative definition is the only definition.
2980   EmitGlobalVarDefinition(D);
2981 }
2982 
2983 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2984   return Context.toCharUnitsFromBits(
2985       getDataLayout().getTypeStoreSizeInBits(Ty));
2986 }
2987 
2988 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
2989   LangAS AddrSpace = LangAS::Default;
2990   if (LangOpts.OpenCL) {
2991     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
2992     assert(AddrSpace == LangAS::opencl_global ||
2993            AddrSpace == LangAS::opencl_constant ||
2994            AddrSpace == LangAS::opencl_local ||
2995            AddrSpace >= LangAS::FirstTargetAddressSpace);
2996     return AddrSpace;
2997   }
2998 
2999   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3000     if (D && D->hasAttr<CUDAConstantAttr>())
3001       return LangAS::cuda_constant;
3002     else if (D && D->hasAttr<CUDASharedAttr>())
3003       return LangAS::cuda_shared;
3004     else
3005       return LangAS::cuda_device;
3006   }
3007 
3008   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3009 }
3010 
3011 template<typename SomeDecl>
3012 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3013                                                llvm::GlobalValue *GV) {
3014   if (!getLangOpts().CPlusPlus)
3015     return;
3016 
3017   // Must have 'used' attribute, or else inline assembly can't rely on
3018   // the name existing.
3019   if (!D->template hasAttr<UsedAttr>())
3020     return;
3021 
3022   // Must have internal linkage and an ordinary name.
3023   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3024     return;
3025 
3026   // Must be in an extern "C" context. Entities declared directly within
3027   // a record are not extern "C" even if the record is in such a context.
3028   const SomeDecl *First = D->getFirstDecl();
3029   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3030     return;
3031 
3032   // OK, this is an internal linkage entity inside an extern "C" linkage
3033   // specification. Make a note of that so we can give it the "expected"
3034   // mangled name if nothing else is using that name.
3035   std::pair<StaticExternCMap::iterator, bool> R =
3036       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3037 
3038   // If we have multiple internal linkage entities with the same name
3039   // in extern "C" regions, none of them gets that name.
3040   if (!R.second)
3041     R.first->second = nullptr;
3042 }
3043 
3044 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3045   if (!CGM.supportsCOMDAT())
3046     return false;
3047 
3048   if (D.hasAttr<SelectAnyAttr>())
3049     return true;
3050 
3051   GVALinkage Linkage;
3052   if (auto *VD = dyn_cast<VarDecl>(&D))
3053     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3054   else
3055     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3056 
3057   switch (Linkage) {
3058   case GVA_Internal:
3059   case GVA_AvailableExternally:
3060   case GVA_StrongExternal:
3061     return false;
3062   case GVA_DiscardableODR:
3063   case GVA_StrongODR:
3064     return true;
3065   }
3066   llvm_unreachable("No such linkage");
3067 }
3068 
3069 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3070                                           llvm::GlobalObject &GO) {
3071   if (!shouldBeInCOMDAT(*this, D))
3072     return;
3073   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3074 }
3075 
3076 /// Pass IsTentative as true if you want to create a tentative definition.
3077 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3078                                             bool IsTentative) {
3079   // OpenCL global variables of sampler type are translated to function calls,
3080   // therefore no need to be translated.
3081   QualType ASTTy = D->getType();
3082   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3083     return;
3084 
3085   // If this is OpenMP device, check if it is legal to emit this global
3086   // normally.
3087   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3088       OpenMPRuntime->emitTargetGlobalVariable(D))
3089     return;
3090 
3091   llvm::Constant *Init = nullptr;
3092   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3093   bool NeedsGlobalCtor = false;
3094   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
3095 
3096   const VarDecl *InitDecl;
3097   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3098 
3099   Optional<ConstantEmitter> emitter;
3100 
3101   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3102   // as part of their declaration."  Sema has already checked for
3103   // error cases, so we just need to set Init to UndefValue.
3104   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3105       D->hasAttr<CUDASharedAttr>())
3106     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3107   else if (!InitExpr) {
3108     // This is a tentative definition; tentative definitions are
3109     // implicitly initialized with { 0 }.
3110     //
3111     // Note that tentative definitions are only emitted at the end of
3112     // a translation unit, so they should never have incomplete
3113     // type. In addition, EmitTentativeDefinition makes sure that we
3114     // never attempt to emit a tentative definition if a real one
3115     // exists. A use may still exists, however, so we still may need
3116     // to do a RAUW.
3117     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3118     Init = EmitNullConstant(D->getType());
3119   } else {
3120     initializedGlobalDecl = GlobalDecl(D);
3121     emitter.emplace(*this);
3122     Init = emitter->tryEmitForInitializer(*InitDecl);
3123 
3124     if (!Init) {
3125       QualType T = InitExpr->getType();
3126       if (D->getType()->isReferenceType())
3127         T = D->getType();
3128 
3129       if (getLangOpts().CPlusPlus) {
3130         Init = EmitNullConstant(T);
3131         NeedsGlobalCtor = true;
3132       } else {
3133         ErrorUnsupported(D, "static initializer");
3134         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3135       }
3136     } else {
3137       // We don't need an initializer, so remove the entry for the delayed
3138       // initializer position (just in case this entry was delayed) if we
3139       // also don't need to register a destructor.
3140       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3141         DelayedCXXInitPosition.erase(D);
3142     }
3143   }
3144 
3145   llvm::Type* InitType = Init->getType();
3146   llvm::Constant *Entry =
3147       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3148 
3149   // Strip off a bitcast if we got one back.
3150   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3151     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3152            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3153            // All zero index gep.
3154            CE->getOpcode() == llvm::Instruction::GetElementPtr);
3155     Entry = CE->getOperand(0);
3156   }
3157 
3158   // Entry is now either a Function or GlobalVariable.
3159   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3160 
3161   // We have a definition after a declaration with the wrong type.
3162   // We must make a new GlobalVariable* and update everything that used OldGV
3163   // (a declaration or tentative definition) with the new GlobalVariable*
3164   // (which will be a definition).
3165   //
3166   // This happens if there is a prototype for a global (e.g.
3167   // "extern int x[];") and then a definition of a different type (e.g.
3168   // "int x[10];"). This also happens when an initializer has a different type
3169   // from the type of the global (this happens with unions).
3170   if (!GV || GV->getType()->getElementType() != InitType ||
3171       GV->getType()->getAddressSpace() !=
3172           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3173 
3174     // Move the old entry aside so that we'll create a new one.
3175     Entry->setName(StringRef());
3176 
3177     // Make a new global with the correct type, this is now guaranteed to work.
3178     GV = cast<llvm::GlobalVariable>(
3179         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
3180 
3181     // Replace all uses of the old global with the new global
3182     llvm::Constant *NewPtrForOldDecl =
3183         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3184     Entry->replaceAllUsesWith(NewPtrForOldDecl);
3185 
3186     // Erase the old global, since it is no longer used.
3187     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3188   }
3189 
3190   MaybeHandleStaticInExternC(D, GV);
3191 
3192   if (D->hasAttr<AnnotateAttr>())
3193     AddGlobalAnnotations(D, GV);
3194 
3195   // Set the llvm linkage type as appropriate.
3196   llvm::GlobalValue::LinkageTypes Linkage =
3197       getLLVMLinkageVarDefinition(D, GV->isConstant());
3198 
3199   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3200   // the device. [...]"
3201   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3202   // __device__, declares a variable that: [...]
3203   // Is accessible from all the threads within the grid and from the host
3204   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3205   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3206   if (GV && LangOpts.CUDA) {
3207     if (LangOpts.CUDAIsDevice) {
3208       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3209         GV->setExternallyInitialized(true);
3210     } else {
3211       // Host-side shadows of external declarations of device-side
3212       // global variables become internal definitions. These have to
3213       // be internal in order to prevent name conflicts with global
3214       // host variables with the same name in a different TUs.
3215       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3216         Linkage = llvm::GlobalValue::InternalLinkage;
3217 
3218         // Shadow variables and their properties must be registered
3219         // with CUDA runtime.
3220         unsigned Flags = 0;
3221         if (!D->hasDefinition())
3222           Flags |= CGCUDARuntime::ExternDeviceVar;
3223         if (D->hasAttr<CUDAConstantAttr>())
3224           Flags |= CGCUDARuntime::ConstantDeviceVar;
3225         getCUDARuntime().registerDeviceVar(*GV, Flags);
3226       } else if (D->hasAttr<CUDASharedAttr>())
3227         // __shared__ variables are odd. Shadows do get created, but
3228         // they are not registered with the CUDA runtime, so they
3229         // can't really be used to access their device-side
3230         // counterparts. It's not clear yet whether it's nvcc's bug or
3231         // a feature, but we've got to do the same for compatibility.
3232         Linkage = llvm::GlobalValue::InternalLinkage;
3233     }
3234   }
3235 
3236   GV->setInitializer(Init);
3237   if (emitter) emitter->finalize(GV);
3238 
3239   // If it is safe to mark the global 'constant', do so now.
3240   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3241                   isTypeConstant(D->getType(), true));
3242 
3243   // If it is in a read-only section, mark it 'constant'.
3244   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3245     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3246     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3247       GV->setConstant(true);
3248   }
3249 
3250   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3251 
3252 
3253   // On Darwin, if the normal linkage of a C++ thread_local variable is
3254   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3255   // copies within a linkage unit; otherwise, the backing variable has
3256   // internal linkage and all accesses should just be calls to the
3257   // Itanium-specified entry point, which has the normal linkage of the
3258   // variable. This is to preserve the ability to change the implementation
3259   // behind the scenes.
3260   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
3261       Context.getTargetInfo().getTriple().isOSDarwin() &&
3262       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3263       !llvm::GlobalVariable::isWeakLinkage(Linkage))
3264     Linkage = llvm::GlobalValue::InternalLinkage;
3265 
3266   GV->setLinkage(Linkage);
3267   if (D->hasAttr<DLLImportAttr>())
3268     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3269   else if (D->hasAttr<DLLExportAttr>())
3270     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3271   else
3272     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3273 
3274   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3275     // common vars aren't constant even if declared const.
3276     GV->setConstant(false);
3277     // Tentative definition of global variables may be initialized with
3278     // non-zero null pointers. In this case they should have weak linkage
3279     // since common linkage must have zero initializer and must not have
3280     // explicit section therefore cannot have non-zero initial value.
3281     if (!GV->getInitializer()->isNullValue())
3282       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3283   }
3284 
3285   setNonAliasAttributes(D, GV);
3286 
3287   if (D->getTLSKind() && !GV->isThreadLocal()) {
3288     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3289       CXXThreadLocals.push_back(D);
3290     setTLSMode(GV, *D);
3291   }
3292 
3293   maybeSetTrivialComdat(*D, *GV);
3294 
3295   // Emit the initializer function if necessary.
3296   if (NeedsGlobalCtor || NeedsGlobalDtor)
3297     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3298 
3299   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3300 
3301   // Emit global variable debug information.
3302   if (CGDebugInfo *DI = getModuleDebugInfo())
3303     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3304       DI->EmitGlobalVariable(GV, D);
3305 }
3306 
3307 static bool isVarDeclStrongDefinition(const ASTContext &Context,
3308                                       CodeGenModule &CGM, const VarDecl *D,
3309                                       bool NoCommon) {
3310   // Don't give variables common linkage if -fno-common was specified unless it
3311   // was overridden by a NoCommon attribute.
3312   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3313     return true;
3314 
3315   // C11 6.9.2/2:
3316   //   A declaration of an identifier for an object that has file scope without
3317   //   an initializer, and without a storage-class specifier or with the
3318   //   storage-class specifier static, constitutes a tentative definition.
3319   if (D->getInit() || D->hasExternalStorage())
3320     return true;
3321 
3322   // A variable cannot be both common and exist in a section.
3323   if (D->hasAttr<SectionAttr>())
3324     return true;
3325 
3326   // A variable cannot be both common and exist in a section.
3327   // We dont try to determine which is the right section in the front-end.
3328   // If no specialized section name is applicable, it will resort to default.
3329   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3330       D->hasAttr<PragmaClangDataSectionAttr>() ||
3331       D->hasAttr<PragmaClangRodataSectionAttr>())
3332     return true;
3333 
3334   // Thread local vars aren't considered common linkage.
3335   if (D->getTLSKind())
3336     return true;
3337 
3338   // Tentative definitions marked with WeakImportAttr are true definitions.
3339   if (D->hasAttr<WeakImportAttr>())
3340     return true;
3341 
3342   // A variable cannot be both common and exist in a comdat.
3343   if (shouldBeInCOMDAT(CGM, *D))
3344     return true;
3345 
3346   // Declarations with a required alignment do not have common linkage in MSVC
3347   // mode.
3348   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3349     if (D->hasAttr<AlignedAttr>())
3350       return true;
3351     QualType VarType = D->getType();
3352     if (Context.isAlignmentRequired(VarType))
3353       return true;
3354 
3355     if (const auto *RT = VarType->getAs<RecordType>()) {
3356       const RecordDecl *RD = RT->getDecl();
3357       for (const FieldDecl *FD : RD->fields()) {
3358         if (FD->isBitField())
3359           continue;
3360         if (FD->hasAttr<AlignedAttr>())
3361           return true;
3362         if (Context.isAlignmentRequired(FD->getType()))
3363           return true;
3364       }
3365     }
3366   }
3367 
3368   return false;
3369 }
3370 
3371 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
3372     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
3373   if (Linkage == GVA_Internal)
3374     return llvm::Function::InternalLinkage;
3375 
3376   if (D->hasAttr<WeakAttr>()) {
3377     if (IsConstantVariable)
3378       return llvm::GlobalVariable::WeakODRLinkage;
3379     else
3380       return llvm::GlobalVariable::WeakAnyLinkage;
3381   }
3382 
3383   // We are guaranteed to have a strong definition somewhere else,
3384   // so we can use available_externally linkage.
3385   if (Linkage == GVA_AvailableExternally)
3386     return llvm::GlobalValue::AvailableExternallyLinkage;
3387 
3388   // Note that Apple's kernel linker doesn't support symbol
3389   // coalescing, so we need to avoid linkonce and weak linkages there.
3390   // Normally, this means we just map to internal, but for explicit
3391   // instantiations we'll map to external.
3392 
3393   // In C++, the compiler has to emit a definition in every translation unit
3394   // that references the function.  We should use linkonce_odr because
3395   // a) if all references in this translation unit are optimized away, we
3396   // don't need to codegen it.  b) if the function persists, it needs to be
3397   // merged with other definitions. c) C++ has the ODR, so we know the
3398   // definition is dependable.
3399   if (Linkage == GVA_DiscardableODR)
3400     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3401                                             : llvm::Function::InternalLinkage;
3402 
3403   // An explicit instantiation of a template has weak linkage, since
3404   // explicit instantiations can occur in multiple translation units
3405   // and must all be equivalent. However, we are not allowed to
3406   // throw away these explicit instantiations.
3407   //
3408   // We don't currently support CUDA device code spread out across multiple TUs,
3409   // so say that CUDA templates are either external (for kernels) or internal.
3410   // This lets llvm perform aggressive inter-procedural optimizations.
3411   if (Linkage == GVA_StrongODR) {
3412     if (Context.getLangOpts().AppleKext)
3413       return llvm::Function::ExternalLinkage;
3414     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3415       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3416                                           : llvm::Function::InternalLinkage;
3417     return llvm::Function::WeakODRLinkage;
3418   }
3419 
3420   // C++ doesn't have tentative definitions and thus cannot have common
3421   // linkage.
3422   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3423       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
3424                                  CodeGenOpts.NoCommon))
3425     return llvm::GlobalVariable::CommonLinkage;
3426 
3427   // selectany symbols are externally visible, so use weak instead of
3428   // linkonce.  MSVC optimizes away references to const selectany globals, so
3429   // all definitions should be the same and ODR linkage should be used.
3430   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3431   if (D->hasAttr<SelectAnyAttr>())
3432     return llvm::GlobalVariable::WeakODRLinkage;
3433 
3434   // Otherwise, we have strong external linkage.
3435   assert(Linkage == GVA_StrongExternal);
3436   return llvm::GlobalVariable::ExternalLinkage;
3437 }
3438 
3439 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3440     const VarDecl *VD, bool IsConstant) {
3441   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
3442   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
3443 }
3444 
3445 /// Replace the uses of a function that was declared with a non-proto type.
3446 /// We want to silently drop extra arguments from call sites
3447 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3448                                           llvm::Function *newFn) {
3449   // Fast path.
3450   if (old->use_empty()) return;
3451 
3452   llvm::Type *newRetTy = newFn->getReturnType();
3453   SmallVector<llvm::Value*, 4> newArgs;
3454   SmallVector<llvm::OperandBundleDef, 1> newBundles;
3455 
3456   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3457          ui != ue; ) {
3458     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
3459     llvm::User *user = use->getUser();
3460 
3461     // Recognize and replace uses of bitcasts.  Most calls to
3462     // unprototyped functions will use bitcasts.
3463     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3464       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3465         replaceUsesOfNonProtoConstant(bitcast, newFn);
3466       continue;
3467     }
3468 
3469     // Recognize calls to the function.
3470     llvm::CallSite callSite(user);
3471     if (!callSite) continue;
3472     if (!callSite.isCallee(&*use)) continue;
3473 
3474     // If the return types don't match exactly, then we can't
3475     // transform this call unless it's dead.
3476     if (callSite->getType() != newRetTy && !callSite->use_empty())
3477       continue;
3478 
3479     // Get the call site's attribute list.
3480     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
3481     llvm::AttributeList oldAttrs = callSite.getAttributes();
3482 
3483     // If the function was passed too few arguments, don't transform.
3484     unsigned newNumArgs = newFn->arg_size();
3485     if (callSite.arg_size() < newNumArgs) continue;
3486 
3487     // If extra arguments were passed, we silently drop them.
3488     // If any of the types mismatch, we don't transform.
3489     unsigned argNo = 0;
3490     bool dontTransform = false;
3491     for (llvm::Argument &A : newFn->args()) {
3492       if (callSite.getArgument(argNo)->getType() != A.getType()) {
3493         dontTransform = true;
3494         break;
3495       }
3496 
3497       // Add any parameter attributes.
3498       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3499       argNo++;
3500     }
3501     if (dontTransform)
3502       continue;
3503 
3504     // Okay, we can transform this.  Create the new call instruction and copy
3505     // over the required information.
3506     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3507 
3508     // Copy over any operand bundles.
3509     callSite.getOperandBundlesAsDefs(newBundles);
3510 
3511     llvm::CallSite newCall;
3512     if (callSite.isCall()) {
3513       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3514                                        callSite.getInstruction());
3515     } else {
3516       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3517       newCall = llvm::InvokeInst::Create(newFn,
3518                                          oldInvoke->getNormalDest(),
3519                                          oldInvoke->getUnwindDest(),
3520                                          newArgs, newBundles, "",
3521                                          callSite.getInstruction());
3522     }
3523     newArgs.clear(); // for the next iteration
3524 
3525     if (!newCall->getType()->isVoidTy())
3526       newCall->takeName(callSite.getInstruction());
3527     newCall.setAttributes(llvm::AttributeList::get(
3528         newFn->getContext(), oldAttrs.getFnAttributes(),
3529         oldAttrs.getRetAttributes(), newArgAttrs));
3530     newCall.setCallingConv(callSite.getCallingConv());
3531 
3532     // Finally, remove the old call, replacing any uses with the new one.
3533     if (!callSite->use_empty())
3534       callSite->replaceAllUsesWith(newCall.getInstruction());
3535 
3536     // Copy debug location attached to CI.
3537     if (callSite->getDebugLoc())
3538       newCall->setDebugLoc(callSite->getDebugLoc());
3539 
3540     callSite->eraseFromParent();
3541   }
3542 }
3543 
3544 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3545 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3546 /// existing call uses of the old function in the module, this adjusts them to
3547 /// call the new function directly.
3548 ///
3549 /// This is not just a cleanup: the always_inline pass requires direct calls to
3550 /// functions to be able to inline them.  If there is a bitcast in the way, it
3551 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3552 /// run at -O0.
3553 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3554                                                       llvm::Function *NewFn) {
3555   // If we're redefining a global as a function, don't transform it.
3556   if (!isa<llvm::Function>(Old)) return;
3557 
3558   replaceUsesOfNonProtoConstant(Old, NewFn);
3559 }
3560 
3561 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3562   auto DK = VD->isThisDeclarationADefinition();
3563   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3564     return;
3565 
3566   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3567   // If we have a definition, this might be a deferred decl. If the
3568   // instantiation is explicit, make sure we emit it at the end.
3569   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3570     GetAddrOfGlobalVar(VD);
3571 
3572   EmitTopLevelDecl(VD);
3573 }
3574 
3575 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3576                                                  llvm::GlobalValue *GV) {
3577   const auto *D = cast<FunctionDecl>(GD.getDecl());
3578 
3579   // Compute the function info and LLVM type.
3580   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3581   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3582 
3583   // Get or create the prototype for the function.
3584   if (!GV || (GV->getType()->getElementType() != Ty))
3585     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3586                                                    /*DontDefer=*/true,
3587                                                    ForDefinition));
3588 
3589   // Already emitted.
3590   if (!GV->isDeclaration())
3591     return;
3592 
3593   // We need to set linkage and visibility on the function before
3594   // generating code for it because various parts of IR generation
3595   // want to propagate this information down (e.g. to local static
3596   // declarations).
3597   auto *Fn = cast<llvm::Function>(GV);
3598   setFunctionLinkage(GD, Fn);
3599 
3600   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3601   setGVProperties(Fn, GD);
3602 
3603   MaybeHandleStaticInExternC(D, Fn);
3604 
3605   maybeSetTrivialComdat(*D, *Fn);
3606 
3607   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3608 
3609   setNonAliasAttributes(GD, Fn);
3610   SetLLVMFunctionAttributesForDefinition(D, Fn);
3611 
3612   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3613     AddGlobalCtor(Fn, CA->getPriority());
3614   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3615     AddGlobalDtor(Fn, DA->getPriority());
3616   if (D->hasAttr<AnnotateAttr>())
3617     AddGlobalAnnotations(D, Fn);
3618 }
3619 
3620 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3621   const auto *D = cast<ValueDecl>(GD.getDecl());
3622   const AliasAttr *AA = D->getAttr<AliasAttr>();
3623   assert(AA && "Not an alias?");
3624 
3625   StringRef MangledName = getMangledName(GD);
3626 
3627   if (AA->getAliasee() == MangledName) {
3628     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3629     return;
3630   }
3631 
3632   // If there is a definition in the module, then it wins over the alias.
3633   // This is dubious, but allow it to be safe.  Just ignore the alias.
3634   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3635   if (Entry && !Entry->isDeclaration())
3636     return;
3637 
3638   Aliases.push_back(GD);
3639 
3640   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3641 
3642   // Create a reference to the named value.  This ensures that it is emitted
3643   // if a deferred decl.
3644   llvm::Constant *Aliasee;
3645   if (isa<llvm::FunctionType>(DeclTy))
3646     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3647                                       /*ForVTable=*/false);
3648   else
3649     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3650                                     llvm::PointerType::getUnqual(DeclTy),
3651                                     /*D=*/nullptr);
3652 
3653   // Create the new alias itself, but don't set a name yet.
3654   auto *GA = llvm::GlobalAlias::create(
3655       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3656 
3657   if (Entry) {
3658     if (GA->getAliasee() == Entry) {
3659       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3660       return;
3661     }
3662 
3663     assert(Entry->isDeclaration());
3664 
3665     // If there is a declaration in the module, then we had an extern followed
3666     // by the alias, as in:
3667     //   extern int test6();
3668     //   ...
3669     //   int test6() __attribute__((alias("test7")));
3670     //
3671     // Remove it and replace uses of it with the alias.
3672     GA->takeName(Entry);
3673 
3674     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3675                                                           Entry->getType()));
3676     Entry->eraseFromParent();
3677   } else {
3678     GA->setName(MangledName);
3679   }
3680 
3681   // Set attributes which are particular to an alias; this is a
3682   // specialization of the attributes which may be set on a global
3683   // variable/function.
3684   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3685       D->isWeakImported()) {
3686     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3687   }
3688 
3689   if (const auto *VD = dyn_cast<VarDecl>(D))
3690     if (VD->getTLSKind())
3691       setTLSMode(GA, *VD);
3692 
3693   SetCommonAttributes(GD, GA);
3694 }
3695 
3696 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3697   const auto *D = cast<ValueDecl>(GD.getDecl());
3698   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3699   assert(IFA && "Not an ifunc?");
3700 
3701   StringRef MangledName = getMangledName(GD);
3702 
3703   if (IFA->getResolver() == MangledName) {
3704     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3705     return;
3706   }
3707 
3708   // Report an error if some definition overrides ifunc.
3709   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3710   if (Entry && !Entry->isDeclaration()) {
3711     GlobalDecl OtherGD;
3712     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3713         DiagnosedConflictingDefinitions.insert(GD).second) {
3714       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3715       Diags.Report(OtherGD.getDecl()->getLocation(),
3716                    diag::note_previous_definition);
3717     }
3718     return;
3719   }
3720 
3721   Aliases.push_back(GD);
3722 
3723   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3724   llvm::Constant *Resolver =
3725       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3726                               /*ForVTable=*/false);
3727   llvm::GlobalIFunc *GIF =
3728       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3729                                 "", Resolver, &getModule());
3730   if (Entry) {
3731     if (GIF->getResolver() == Entry) {
3732       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3733       return;
3734     }
3735     assert(Entry->isDeclaration());
3736 
3737     // If there is a declaration in the module, then we had an extern followed
3738     // by the ifunc, as in:
3739     //   extern int test();
3740     //   ...
3741     //   int test() __attribute__((ifunc("resolver")));
3742     //
3743     // Remove it and replace uses of it with the ifunc.
3744     GIF->takeName(Entry);
3745 
3746     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3747                                                           Entry->getType()));
3748     Entry->eraseFromParent();
3749   } else
3750     GIF->setName(MangledName);
3751 
3752   SetCommonAttributes(GD, GIF);
3753 }
3754 
3755 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3756                                             ArrayRef<llvm::Type*> Tys) {
3757   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3758                                          Tys);
3759 }
3760 
3761 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3762 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3763                          const StringLiteral *Literal, bool TargetIsLSB,
3764                          bool &IsUTF16, unsigned &StringLength) {
3765   StringRef String = Literal->getString();
3766   unsigned NumBytes = String.size();
3767 
3768   // Check for simple case.
3769   if (!Literal->containsNonAsciiOrNull()) {
3770     StringLength = NumBytes;
3771     return *Map.insert(std::make_pair(String, nullptr)).first;
3772   }
3773 
3774   // Otherwise, convert the UTF8 literals into a string of shorts.
3775   IsUTF16 = true;
3776 
3777   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3778   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3779   llvm::UTF16 *ToPtr = &ToBuf[0];
3780 
3781   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3782                                  ToPtr + NumBytes, llvm::strictConversion);
3783 
3784   // ConvertUTF8toUTF16 returns the length in ToPtr.
3785   StringLength = ToPtr - &ToBuf[0];
3786 
3787   // Add an explicit null.
3788   *ToPtr = 0;
3789   return *Map.insert(std::make_pair(
3790                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3791                                    (StringLength + 1) * 2),
3792                          nullptr)).first;
3793 }
3794 
3795 ConstantAddress
3796 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3797   unsigned StringLength = 0;
3798   bool isUTF16 = false;
3799   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3800       GetConstantCFStringEntry(CFConstantStringMap, Literal,
3801                                getDataLayout().isLittleEndian(), isUTF16,
3802                                StringLength);
3803 
3804   if (auto *C = Entry.second)
3805     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3806 
3807   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3808   llvm::Constant *Zeros[] = { Zero, Zero };
3809 
3810   // If we don't already have it, get __CFConstantStringClassReference.
3811   if (!CFConstantStringClassRef) {
3812     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3813     Ty = llvm::ArrayType::get(Ty, 0);
3814     llvm::GlobalValue *GV = cast<llvm::GlobalValue>(
3815         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"));
3816 
3817     if (getTriple().isOSBinFormatCOFF()) {
3818       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3819       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3820       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3821 
3822       const VarDecl *VD = nullptr;
3823       for (const auto &Result : DC->lookup(&II))
3824         if ((VD = dyn_cast<VarDecl>(Result)))
3825           break;
3826 
3827       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3828         GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3829         GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3830       } else {
3831         GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3832         GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3833       }
3834     }
3835     setDSOLocal(GV);
3836 
3837     // Decay array -> ptr
3838     CFConstantStringClassRef =
3839         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3840   }
3841 
3842   QualType CFTy = getContext().getCFConstantStringType();
3843 
3844   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3845 
3846   ConstantInitBuilder Builder(*this);
3847   auto Fields = Builder.beginStruct(STy);
3848 
3849   // Class pointer.
3850   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3851 
3852   // Flags.
3853   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3854 
3855   // String pointer.
3856   llvm::Constant *C = nullptr;
3857   if (isUTF16) {
3858     auto Arr = llvm::makeArrayRef(
3859         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3860         Entry.first().size() / 2);
3861     C = llvm::ConstantDataArray::get(VMContext, Arr);
3862   } else {
3863     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3864   }
3865 
3866   // Note: -fwritable-strings doesn't make the backing store strings of
3867   // CFStrings writable. (See <rdar://problem/10657500>)
3868   auto *GV =
3869       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3870                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3871   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3872   // Don't enforce the target's minimum global alignment, since the only use
3873   // of the string is via this class initializer.
3874   CharUnits Align = isUTF16
3875                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3876                         : getContext().getTypeAlignInChars(getContext().CharTy);
3877   GV->setAlignment(Align.getQuantity());
3878 
3879   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3880   // Without it LLVM can merge the string with a non unnamed_addr one during
3881   // LTO.  Doing that changes the section it ends in, which surprises ld64.
3882   if (getTriple().isOSBinFormatMachO())
3883     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3884                            : "__TEXT,__cstring,cstring_literals");
3885 
3886   // String.
3887   llvm::Constant *Str =
3888       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3889 
3890   if (isUTF16)
3891     // Cast the UTF16 string to the correct type.
3892     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3893   Fields.add(Str);
3894 
3895   // String length.
3896   auto Ty = getTypes().ConvertType(getContext().LongTy);
3897   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3898 
3899   CharUnits Alignment = getPointerAlign();
3900 
3901   // The struct.
3902   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3903                                     /*isConstant=*/false,
3904                                     llvm::GlobalVariable::PrivateLinkage);
3905   switch (getTriple().getObjectFormat()) {
3906   case llvm::Triple::UnknownObjectFormat:
3907     llvm_unreachable("unknown file format");
3908   case llvm::Triple::COFF:
3909   case llvm::Triple::ELF:
3910   case llvm::Triple::Wasm:
3911     GV->setSection("cfstring");
3912     break;
3913   case llvm::Triple::MachO:
3914     GV->setSection("__DATA,__cfstring");
3915     break;
3916   }
3917   Entry.second = GV;
3918 
3919   return ConstantAddress(GV, Alignment);
3920 }
3921 
3922 bool CodeGenModule::getExpressionLocationsEnabled() const {
3923   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
3924 }
3925 
3926 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3927   if (ObjCFastEnumerationStateType.isNull()) {
3928     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3929     D->startDefinition();
3930 
3931     QualType FieldTypes[] = {
3932       Context.UnsignedLongTy,
3933       Context.getPointerType(Context.getObjCIdType()),
3934       Context.getPointerType(Context.UnsignedLongTy),
3935       Context.getConstantArrayType(Context.UnsignedLongTy,
3936                            llvm::APInt(32, 5), ArrayType::Normal, 0)
3937     };
3938 
3939     for (size_t i = 0; i < 4; ++i) {
3940       FieldDecl *Field = FieldDecl::Create(Context,
3941                                            D,
3942                                            SourceLocation(),
3943                                            SourceLocation(), nullptr,
3944                                            FieldTypes[i], /*TInfo=*/nullptr,
3945                                            /*BitWidth=*/nullptr,
3946                                            /*Mutable=*/false,
3947                                            ICIS_NoInit);
3948       Field->setAccess(AS_public);
3949       D->addDecl(Field);
3950     }
3951 
3952     D->completeDefinition();
3953     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3954   }
3955 
3956   return ObjCFastEnumerationStateType;
3957 }
3958 
3959 llvm::Constant *
3960 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3961   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3962 
3963   // Don't emit it as the address of the string, emit the string data itself
3964   // as an inline array.
3965   if (E->getCharByteWidth() == 1) {
3966     SmallString<64> Str(E->getString());
3967 
3968     // Resize the string to the right size, which is indicated by its type.
3969     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3970     Str.resize(CAT->getSize().getZExtValue());
3971     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3972   }
3973 
3974   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3975   llvm::Type *ElemTy = AType->getElementType();
3976   unsigned NumElements = AType->getNumElements();
3977 
3978   // Wide strings have either 2-byte or 4-byte elements.
3979   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3980     SmallVector<uint16_t, 32> Elements;
3981     Elements.reserve(NumElements);
3982 
3983     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3984       Elements.push_back(E->getCodeUnit(i));
3985     Elements.resize(NumElements);
3986     return llvm::ConstantDataArray::get(VMContext, Elements);
3987   }
3988 
3989   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3990   SmallVector<uint32_t, 32> Elements;
3991   Elements.reserve(NumElements);
3992 
3993   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3994     Elements.push_back(E->getCodeUnit(i));
3995   Elements.resize(NumElements);
3996   return llvm::ConstantDataArray::get(VMContext, Elements);
3997 }
3998 
3999 static llvm::GlobalVariable *
4000 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4001                       CodeGenModule &CGM, StringRef GlobalName,
4002                       CharUnits Alignment) {
4003   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4004   unsigned AddrSpace = 0;
4005   if (CGM.getLangOpts().OpenCL)
4006     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
4007 
4008   llvm::Module &M = CGM.getModule();
4009   // Create a global variable for this string
4010   auto *GV = new llvm::GlobalVariable(
4011       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4012       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4013   GV->setAlignment(Alignment.getQuantity());
4014   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4015   if (GV->isWeakForLinker()) {
4016     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4017     GV->setComdat(M.getOrInsertComdat(GV->getName()));
4018   }
4019 
4020   return GV;
4021 }
4022 
4023 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4024 /// constant array for the given string literal.
4025 ConstantAddress
4026 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4027                                                   StringRef Name) {
4028   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4029 
4030   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4031   llvm::GlobalVariable **Entry = nullptr;
4032   if (!LangOpts.WritableStrings) {
4033     Entry = &ConstantStringMap[C];
4034     if (auto GV = *Entry) {
4035       if (Alignment.getQuantity() > GV->getAlignment())
4036         GV->setAlignment(Alignment.getQuantity());
4037       return ConstantAddress(GV, Alignment);
4038     }
4039   }
4040 
4041   SmallString<256> MangledNameBuffer;
4042   StringRef GlobalVariableName;
4043   llvm::GlobalValue::LinkageTypes LT;
4044 
4045   // Mangle the string literal if the ABI allows for it.  However, we cannot
4046   // do this if  we are compiling with ASan or -fwritable-strings because they
4047   // rely on strings having normal linkage.
4048   if (!LangOpts.WritableStrings &&
4049       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4050       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
4051     llvm::raw_svector_ostream Out(MangledNameBuffer);
4052     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
4053 
4054     LT = llvm::GlobalValue::LinkOnceODRLinkage;
4055     GlobalVariableName = MangledNameBuffer;
4056   } else {
4057     LT = llvm::GlobalValue::PrivateLinkage;
4058     GlobalVariableName = Name;
4059   }
4060 
4061   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4062   if (Entry)
4063     *Entry = GV;
4064 
4065   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4066                                   QualType());
4067   return ConstantAddress(GV, Alignment);
4068 }
4069 
4070 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4071 /// array for the given ObjCEncodeExpr node.
4072 ConstantAddress
4073 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4074   std::string Str;
4075   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
4076 
4077   return GetAddrOfConstantCString(Str);
4078 }
4079 
4080 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
4081 /// the literal and a terminating '\0' character.
4082 /// The result has pointer to array type.
4083 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4084     const std::string &Str, const char *GlobalName) {
4085   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4086   CharUnits Alignment =
4087     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
4088 
4089   llvm::Constant *C =
4090       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4091 
4092   // Don't share any string literals if strings aren't constant.
4093   llvm::GlobalVariable **Entry = nullptr;
4094   if (!LangOpts.WritableStrings) {
4095     Entry = &ConstantStringMap[C];
4096     if (auto GV = *Entry) {
4097       if (Alignment.getQuantity() > GV->getAlignment())
4098         GV->setAlignment(Alignment.getQuantity());
4099       return ConstantAddress(GV, Alignment);
4100     }
4101   }
4102 
4103   // Get the default prefix if a name wasn't specified.
4104   if (!GlobalName)
4105     GlobalName = ".str";
4106   // Create a global variable for this.
4107   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4108                                   GlobalName, Alignment);
4109   if (Entry)
4110     *Entry = GV;
4111   return ConstantAddress(GV, Alignment);
4112 }
4113 
4114 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
4115     const MaterializeTemporaryExpr *E, const Expr *Init) {
4116   assert((E->getStorageDuration() == SD_Static ||
4117           E->getStorageDuration() == SD_Thread) && "not a global temporary");
4118   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
4119 
4120   // If we're not materializing a subobject of the temporary, keep the
4121   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
4122   QualType MaterializedType = Init->getType();
4123   if (Init == E->GetTemporaryExpr())
4124     MaterializedType = E->getType();
4125 
4126   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4127 
4128   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4129     return ConstantAddress(Slot, Align);
4130 
4131   // FIXME: If an externally-visible declaration extends multiple temporaries,
4132   // we need to give each temporary the same name in every translation unit (and
4133   // we also need to make the temporaries externally-visible).
4134   SmallString<256> Name;
4135   llvm::raw_svector_ostream Out(Name);
4136   getCXXABI().getMangleContext().mangleReferenceTemporary(
4137       VD, E->getManglingNumber(), Out);
4138 
4139   APValue *Value = nullptr;
4140   if (E->getStorageDuration() == SD_Static) {
4141     // We might have a cached constant initializer for this temporary. Note
4142     // that this might have a different value from the value computed by
4143     // evaluating the initializer if the surrounding constant expression
4144     // modifies the temporary.
4145     Value = getContext().getMaterializedTemporaryValue(E, false);
4146     if (Value && Value->isUninit())
4147       Value = nullptr;
4148   }
4149 
4150   // Try evaluating it now, it might have a constant initializer.
4151   Expr::EvalResult EvalResult;
4152   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4153       !EvalResult.hasSideEffects())
4154     Value = &EvalResult.Val;
4155 
4156   LangAS AddrSpace =
4157       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4158 
4159   Optional<ConstantEmitter> emitter;
4160   llvm::Constant *InitialValue = nullptr;
4161   bool Constant = false;
4162   llvm::Type *Type;
4163   if (Value) {
4164     // The temporary has a constant initializer, use it.
4165     emitter.emplace(*this);
4166     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4167                                                MaterializedType);
4168     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4169     Type = InitialValue->getType();
4170   } else {
4171     // No initializer, the initialization will be provided when we
4172     // initialize the declaration which performed lifetime extension.
4173     Type = getTypes().ConvertTypeForMem(MaterializedType);
4174   }
4175 
4176   // Create a global variable for this lifetime-extended temporary.
4177   llvm::GlobalValue::LinkageTypes Linkage =
4178       getLLVMLinkageVarDefinition(VD, Constant);
4179   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4180     const VarDecl *InitVD;
4181     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4182         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4183       // Temporaries defined inside a class get linkonce_odr linkage because the
4184       // class can be defined in multipe translation units.
4185       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4186     } else {
4187       // There is no need for this temporary to have external linkage if the
4188       // VarDecl has external linkage.
4189       Linkage = llvm::GlobalVariable::InternalLinkage;
4190     }
4191   }
4192   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4193   auto *GV = new llvm::GlobalVariable(
4194       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4195       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4196   if (emitter) emitter->finalize(GV);
4197   setGVProperties(GV, VD);
4198   GV->setAlignment(Align.getQuantity());
4199   if (supportsCOMDAT() && GV->isWeakForLinker())
4200     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4201   if (VD->getTLSKind())
4202     setTLSMode(GV, *VD);
4203   llvm::Constant *CV = GV;
4204   if (AddrSpace != LangAS::Default)
4205     CV = getTargetCodeGenInfo().performAddrSpaceCast(
4206         *this, GV, AddrSpace, LangAS::Default,
4207         Type->getPointerTo(
4208             getContext().getTargetAddressSpace(LangAS::Default)));
4209   MaterializedGlobalTemporaryMap[E] = CV;
4210   return ConstantAddress(CV, Align);
4211 }
4212 
4213 /// EmitObjCPropertyImplementations - Emit information for synthesized
4214 /// properties for an implementation.
4215 void CodeGenModule::EmitObjCPropertyImplementations(const
4216                                                     ObjCImplementationDecl *D) {
4217   for (const auto *PID : D->property_impls()) {
4218     // Dynamic is just for type-checking.
4219     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4220       ObjCPropertyDecl *PD = PID->getPropertyDecl();
4221 
4222       // Determine which methods need to be implemented, some may have
4223       // been overridden. Note that ::isPropertyAccessor is not the method
4224       // we want, that just indicates if the decl came from a
4225       // property. What we want to know is if the method is defined in
4226       // this implementation.
4227       if (!D->getInstanceMethod(PD->getGetterName()))
4228         CodeGenFunction(*this).GenerateObjCGetter(
4229                                  const_cast<ObjCImplementationDecl *>(D), PID);
4230       if (!PD->isReadOnly() &&
4231           !D->getInstanceMethod(PD->getSetterName()))
4232         CodeGenFunction(*this).GenerateObjCSetter(
4233                                  const_cast<ObjCImplementationDecl *>(D), PID);
4234     }
4235   }
4236 }
4237 
4238 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
4239   const ObjCInterfaceDecl *iface = impl->getClassInterface();
4240   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
4241        ivar; ivar = ivar->getNextIvar())
4242     if (ivar->getType().isDestructedType())
4243       return true;
4244 
4245   return false;
4246 }
4247 
4248 static bool AllTrivialInitializers(CodeGenModule &CGM,
4249                                    ObjCImplementationDecl *D) {
4250   CodeGenFunction CGF(CGM);
4251   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4252        E = D->init_end(); B != E; ++B) {
4253     CXXCtorInitializer *CtorInitExp = *B;
4254     Expr *Init = CtorInitExp->getInit();
4255     if (!CGF.isTrivialInitializer(Init))
4256       return false;
4257   }
4258   return true;
4259 }
4260 
4261 /// EmitObjCIvarInitializations - Emit information for ivar initialization
4262 /// for an implementation.
4263 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
4264   // We might need a .cxx_destruct even if we don't have any ivar initializers.
4265   if (needsDestructMethod(D)) {
4266     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4267     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4268     ObjCMethodDecl *DTORMethod =
4269       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
4270                              cxxSelector, getContext().VoidTy, nullptr, D,
4271                              /*isInstance=*/true, /*isVariadic=*/false,
4272                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
4273                              /*isDefined=*/false, ObjCMethodDecl::Required);
4274     D->addInstanceMethod(DTORMethod);
4275     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
4276     D->setHasDestructors(true);
4277   }
4278 
4279   // If the implementation doesn't have any ivar initializers, we don't need
4280   // a .cxx_construct.
4281   if (D->getNumIvarInitializers() == 0 ||
4282       AllTrivialInitializers(*this, D))
4283     return;
4284 
4285   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4286   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4287   // The constructor returns 'self'.
4288   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
4289                                                 D->getLocation(),
4290                                                 D->getLocation(),
4291                                                 cxxSelector,
4292                                                 getContext().getObjCIdType(),
4293                                                 nullptr, D, /*isInstance=*/true,
4294                                                 /*isVariadic=*/false,
4295                                                 /*isPropertyAccessor=*/true,
4296                                                 /*isImplicitlyDeclared=*/true,
4297                                                 /*isDefined=*/false,
4298                                                 ObjCMethodDecl::Required);
4299   D->addInstanceMethod(CTORMethod);
4300   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
4301   D->setHasNonZeroConstructors(true);
4302 }
4303 
4304 // EmitLinkageSpec - Emit all declarations in a linkage spec.
4305 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
4306   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4307       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
4308     ErrorUnsupported(LSD, "linkage spec");
4309     return;
4310   }
4311 
4312   EmitDeclContext(LSD);
4313 }
4314 
4315 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4316   for (auto *I : DC->decls()) {
4317     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4318     // are themselves considered "top-level", so EmitTopLevelDecl on an
4319     // ObjCImplDecl does not recursively visit them. We need to do that in
4320     // case they're nested inside another construct (LinkageSpecDecl /
4321     // ExportDecl) that does stop them from being considered "top-level".
4322     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
4323       for (auto *M : OID->methods())
4324         EmitTopLevelDecl(M);
4325     }
4326 
4327     EmitTopLevelDecl(I);
4328   }
4329 }
4330 
4331 /// EmitTopLevelDecl - Emit code for a single top level declaration.
4332 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
4333   // Ignore dependent declarations.
4334   if (D->isTemplated())
4335     return;
4336 
4337   switch (D->getKind()) {
4338   case Decl::CXXConversion:
4339   case Decl::CXXMethod:
4340   case Decl::Function:
4341     EmitGlobal(cast<FunctionDecl>(D));
4342     // Always provide some coverage mapping
4343     // even for the functions that aren't emitted.
4344     AddDeferredUnusedCoverageMapping(D);
4345     break;
4346 
4347   case Decl::CXXDeductionGuide:
4348     // Function-like, but does not result in code emission.
4349     break;
4350 
4351   case Decl::Var:
4352   case Decl::Decomposition:
4353   case Decl::VarTemplateSpecialization:
4354     EmitGlobal(cast<VarDecl>(D));
4355     if (auto *DD = dyn_cast<DecompositionDecl>(D))
4356       for (auto *B : DD->bindings())
4357         if (auto *HD = B->getHoldingVar())
4358           EmitGlobal(HD);
4359     break;
4360 
4361   // Indirect fields from global anonymous structs and unions can be
4362   // ignored; only the actual variable requires IR gen support.
4363   case Decl::IndirectField:
4364     break;
4365 
4366   // C++ Decls
4367   case Decl::Namespace:
4368     EmitDeclContext(cast<NamespaceDecl>(D));
4369     break;
4370   case Decl::ClassTemplateSpecialization: {
4371     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4372     if (DebugInfo &&
4373         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4374         Spec->hasDefinition())
4375       DebugInfo->completeTemplateDefinition(*Spec);
4376   } LLVM_FALLTHROUGH;
4377   case Decl::CXXRecord:
4378     if (DebugInfo) {
4379       if (auto *ES = D->getASTContext().getExternalSource())
4380         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4381           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4382     }
4383     // Emit any static data members, they may be definitions.
4384     for (auto *I : cast<CXXRecordDecl>(D)->decls())
4385       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4386         EmitTopLevelDecl(I);
4387     break;
4388     // No code generation needed.
4389   case Decl::UsingShadow:
4390   case Decl::ClassTemplate:
4391   case Decl::VarTemplate:
4392   case Decl::VarTemplatePartialSpecialization:
4393   case Decl::FunctionTemplate:
4394   case Decl::TypeAliasTemplate:
4395   case Decl::Block:
4396   case Decl::Empty:
4397     break;
4398   case Decl::Using:          // using X; [C++]
4399     if (CGDebugInfo *DI = getModuleDebugInfo())
4400         DI->EmitUsingDecl(cast<UsingDecl>(*D));
4401     return;
4402   case Decl::NamespaceAlias:
4403     if (CGDebugInfo *DI = getModuleDebugInfo())
4404         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4405     return;
4406   case Decl::UsingDirective: // using namespace X; [C++]
4407     if (CGDebugInfo *DI = getModuleDebugInfo())
4408       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4409     return;
4410   case Decl::CXXConstructor:
4411     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4412     break;
4413   case Decl::CXXDestructor:
4414     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4415     break;
4416 
4417   case Decl::StaticAssert:
4418     // Nothing to do.
4419     break;
4420 
4421   // Objective-C Decls
4422 
4423   // Forward declarations, no (immediate) code generation.
4424   case Decl::ObjCInterface:
4425   case Decl::ObjCCategory:
4426     break;
4427 
4428   case Decl::ObjCProtocol: {
4429     auto *Proto = cast<ObjCProtocolDecl>(D);
4430     if (Proto->isThisDeclarationADefinition())
4431       ObjCRuntime->GenerateProtocol(Proto);
4432     break;
4433   }
4434 
4435   case Decl::ObjCCategoryImpl:
4436     // Categories have properties but don't support synthesize so we
4437     // can ignore them here.
4438     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4439     break;
4440 
4441   case Decl::ObjCImplementation: {
4442     auto *OMD = cast<ObjCImplementationDecl>(D);
4443     EmitObjCPropertyImplementations(OMD);
4444     EmitObjCIvarInitializations(OMD);
4445     ObjCRuntime->GenerateClass(OMD);
4446     // Emit global variable debug information.
4447     if (CGDebugInfo *DI = getModuleDebugInfo())
4448       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4449         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4450             OMD->getClassInterface()), OMD->getLocation());
4451     break;
4452   }
4453   case Decl::ObjCMethod: {
4454     auto *OMD = cast<ObjCMethodDecl>(D);
4455     // If this is not a prototype, emit the body.
4456     if (OMD->getBody())
4457       CodeGenFunction(*this).GenerateObjCMethod(OMD);
4458     break;
4459   }
4460   case Decl::ObjCCompatibleAlias:
4461     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4462     break;
4463 
4464   case Decl::PragmaComment: {
4465     const auto *PCD = cast<PragmaCommentDecl>(D);
4466     switch (PCD->getCommentKind()) {
4467     case PCK_Unknown:
4468       llvm_unreachable("unexpected pragma comment kind");
4469     case PCK_Linker:
4470       AppendLinkerOptions(PCD->getArg());
4471       break;
4472     case PCK_Lib:
4473       if (getTarget().getTriple().isOSBinFormatELF() &&
4474           !getTarget().getTriple().isPS4())
4475         AddELFLibDirective(PCD->getArg());
4476       else
4477         AddDependentLib(PCD->getArg());
4478       break;
4479     case PCK_Compiler:
4480     case PCK_ExeStr:
4481     case PCK_User:
4482       break; // We ignore all of these.
4483     }
4484     break;
4485   }
4486 
4487   case Decl::PragmaDetectMismatch: {
4488     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4489     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4490     break;
4491   }
4492 
4493   case Decl::LinkageSpec:
4494     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4495     break;
4496 
4497   case Decl::FileScopeAsm: {
4498     // File-scope asm is ignored during device-side CUDA compilation.
4499     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4500       break;
4501     // File-scope asm is ignored during device-side OpenMP compilation.
4502     if (LangOpts.OpenMPIsDevice)
4503       break;
4504     auto *AD = cast<FileScopeAsmDecl>(D);
4505     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4506     break;
4507   }
4508 
4509   case Decl::Import: {
4510     auto *Import = cast<ImportDecl>(D);
4511 
4512     // If we've already imported this module, we're done.
4513     if (!ImportedModules.insert(Import->getImportedModule()))
4514       break;
4515 
4516     // Emit debug information for direct imports.
4517     if (!Import->getImportedOwningModule()) {
4518       if (CGDebugInfo *DI = getModuleDebugInfo())
4519         DI->EmitImportDecl(*Import);
4520     }
4521 
4522     // Find all of the submodules and emit the module initializers.
4523     llvm::SmallPtrSet<clang::Module *, 16> Visited;
4524     SmallVector<clang::Module *, 16> Stack;
4525     Visited.insert(Import->getImportedModule());
4526     Stack.push_back(Import->getImportedModule());
4527 
4528     while (!Stack.empty()) {
4529       clang::Module *Mod = Stack.pop_back_val();
4530       if (!EmittedModuleInitializers.insert(Mod).second)
4531         continue;
4532 
4533       for (auto *D : Context.getModuleInitializers(Mod))
4534         EmitTopLevelDecl(D);
4535 
4536       // Visit the submodules of this module.
4537       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4538                                              SubEnd = Mod->submodule_end();
4539            Sub != SubEnd; ++Sub) {
4540         // Skip explicit children; they need to be explicitly imported to emit
4541         // the initializers.
4542         if ((*Sub)->IsExplicit)
4543           continue;
4544 
4545         if (Visited.insert(*Sub).second)
4546           Stack.push_back(*Sub);
4547       }
4548     }
4549     break;
4550   }
4551 
4552   case Decl::Export:
4553     EmitDeclContext(cast<ExportDecl>(D));
4554     break;
4555 
4556   case Decl::OMPThreadPrivate:
4557     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4558     break;
4559 
4560   case Decl::OMPDeclareReduction:
4561     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4562     break;
4563 
4564   default:
4565     // Make sure we handled everything we should, every other kind is a
4566     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4567     // function. Need to recode Decl::Kind to do that easily.
4568     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4569     break;
4570   }
4571 }
4572 
4573 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4574   // Do we need to generate coverage mapping?
4575   if (!CodeGenOpts.CoverageMapping)
4576     return;
4577   switch (D->getKind()) {
4578   case Decl::CXXConversion:
4579   case Decl::CXXMethod:
4580   case Decl::Function:
4581   case Decl::ObjCMethod:
4582   case Decl::CXXConstructor:
4583   case Decl::CXXDestructor: {
4584     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4585       return;
4586     SourceManager &SM = getContext().getSourceManager();
4587     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4588       return;
4589     auto I = DeferredEmptyCoverageMappingDecls.find(D);
4590     if (I == DeferredEmptyCoverageMappingDecls.end())
4591       DeferredEmptyCoverageMappingDecls[D] = true;
4592     break;
4593   }
4594   default:
4595     break;
4596   };
4597 }
4598 
4599 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4600   // Do we need to generate coverage mapping?
4601   if (!CodeGenOpts.CoverageMapping)
4602     return;
4603   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4604     if (Fn->isTemplateInstantiation())
4605       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4606   }
4607   auto I = DeferredEmptyCoverageMappingDecls.find(D);
4608   if (I == DeferredEmptyCoverageMappingDecls.end())
4609     DeferredEmptyCoverageMappingDecls[D] = false;
4610   else
4611     I->second = false;
4612 }
4613 
4614 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4615   // We call takeVector() here to avoid use-after-free.
4616   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4617   // we deserialize function bodies to emit coverage info for them, and that
4618   // deserializes more declarations. How should we handle that case?
4619   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
4620     if (!Entry.second)
4621       continue;
4622     const Decl *D = Entry.first;
4623     switch (D->getKind()) {
4624     case Decl::CXXConversion:
4625     case Decl::CXXMethod:
4626     case Decl::Function:
4627     case Decl::ObjCMethod: {
4628       CodeGenPGO PGO(*this);
4629       GlobalDecl GD(cast<FunctionDecl>(D));
4630       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4631                                   getFunctionLinkage(GD));
4632       break;
4633     }
4634     case Decl::CXXConstructor: {
4635       CodeGenPGO PGO(*this);
4636       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4637       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4638                                   getFunctionLinkage(GD));
4639       break;
4640     }
4641     case Decl::CXXDestructor: {
4642       CodeGenPGO PGO(*this);
4643       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4644       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4645                                   getFunctionLinkage(GD));
4646       break;
4647     }
4648     default:
4649       break;
4650     };
4651   }
4652 }
4653 
4654 /// Turns the given pointer into a constant.
4655 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4656                                           const void *Ptr) {
4657   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4658   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4659   return llvm::ConstantInt::get(i64, PtrInt);
4660 }
4661 
4662 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4663                                    llvm::NamedMDNode *&GlobalMetadata,
4664                                    GlobalDecl D,
4665                                    llvm::GlobalValue *Addr) {
4666   if (!GlobalMetadata)
4667     GlobalMetadata =
4668       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4669 
4670   // TODO: should we report variant information for ctors/dtors?
4671   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4672                            llvm::ConstantAsMetadata::get(GetPointerConstant(
4673                                CGM.getLLVMContext(), D.getDecl()))};
4674   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4675 }
4676 
4677 /// For each function which is declared within an extern "C" region and marked
4678 /// as 'used', but has internal linkage, create an alias from the unmangled
4679 /// name to the mangled name if possible. People expect to be able to refer
4680 /// to such functions with an unmangled name from inline assembly within the
4681 /// same translation unit.
4682 void CodeGenModule::EmitStaticExternCAliases() {
4683   // Don't do anything if we're generating CUDA device code -- the NVPTX
4684   // assembly target doesn't support aliases.
4685   if (Context.getTargetInfo().getTriple().isNVPTX())
4686     return;
4687   for (auto &I : StaticExternCValues) {
4688     IdentifierInfo *Name = I.first;
4689     llvm::GlobalValue *Val = I.second;
4690     if (Val && !getModule().getNamedValue(Name->getName()))
4691       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4692   }
4693 }
4694 
4695 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4696                                              GlobalDecl &Result) const {
4697   auto Res = Manglings.find(MangledName);
4698   if (Res == Manglings.end())
4699     return false;
4700   Result = Res->getValue();
4701   return true;
4702 }
4703 
4704 /// Emits metadata nodes associating all the global values in the
4705 /// current module with the Decls they came from.  This is useful for
4706 /// projects using IR gen as a subroutine.
4707 ///
4708 /// Since there's currently no way to associate an MDNode directly
4709 /// with an llvm::GlobalValue, we create a global named metadata
4710 /// with the name 'clang.global.decl.ptrs'.
4711 void CodeGenModule::EmitDeclMetadata() {
4712   llvm::NamedMDNode *GlobalMetadata = nullptr;
4713 
4714   for (auto &I : MangledDeclNames) {
4715     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4716     // Some mangled names don't necessarily have an associated GlobalValue
4717     // in this module, e.g. if we mangled it for DebugInfo.
4718     if (Addr)
4719       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4720   }
4721 }
4722 
4723 /// Emits metadata nodes for all the local variables in the current
4724 /// function.
4725 void CodeGenFunction::EmitDeclMetadata() {
4726   if (LocalDeclMap.empty()) return;
4727 
4728   llvm::LLVMContext &Context = getLLVMContext();
4729 
4730   // Find the unique metadata ID for this name.
4731   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4732 
4733   llvm::NamedMDNode *GlobalMetadata = nullptr;
4734 
4735   for (auto &I : LocalDeclMap) {
4736     const Decl *D = I.first;
4737     llvm::Value *Addr = I.second.getPointer();
4738     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4739       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4740       Alloca->setMetadata(
4741           DeclPtrKind, llvm::MDNode::get(
4742                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4743     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4744       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4745       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4746     }
4747   }
4748 }
4749 
4750 void CodeGenModule::EmitVersionIdentMetadata() {
4751   llvm::NamedMDNode *IdentMetadata =
4752     TheModule.getOrInsertNamedMetadata("llvm.ident");
4753   std::string Version = getClangFullVersion();
4754   llvm::LLVMContext &Ctx = TheModule.getContext();
4755 
4756   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4757   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4758 }
4759 
4760 void CodeGenModule::EmitTargetMetadata() {
4761   // Warning, new MangledDeclNames may be appended within this loop.
4762   // We rely on MapVector insertions adding new elements to the end
4763   // of the container.
4764   // FIXME: Move this loop into the one target that needs it, and only
4765   // loop over those declarations for which we couldn't emit the target
4766   // metadata when we emitted the declaration.
4767   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4768     auto Val = *(MangledDeclNames.begin() + I);
4769     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4770     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4771     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4772   }
4773 }
4774 
4775 void CodeGenModule::EmitCoverageFile() {
4776   if (getCodeGenOpts().CoverageDataFile.empty() &&
4777       getCodeGenOpts().CoverageNotesFile.empty())
4778     return;
4779 
4780   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4781   if (!CUNode)
4782     return;
4783 
4784   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4785   llvm::LLVMContext &Ctx = TheModule.getContext();
4786   auto *CoverageDataFile =
4787       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4788   auto *CoverageNotesFile =
4789       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4790   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4791     llvm::MDNode *CU = CUNode->getOperand(i);
4792     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4793     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4794   }
4795 }
4796 
4797 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4798   // Sema has checked that all uuid strings are of the form
4799   // "12345678-1234-1234-1234-1234567890ab".
4800   assert(Uuid.size() == 36);
4801   for (unsigned i = 0; i < 36; ++i) {
4802     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4803     else                                         assert(isHexDigit(Uuid[i]));
4804   }
4805 
4806   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4807   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4808 
4809   llvm::Constant *Field3[8];
4810   for (unsigned Idx = 0; Idx < 8; ++Idx)
4811     Field3[Idx] = llvm::ConstantInt::get(
4812         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4813 
4814   llvm::Constant *Fields[4] = {
4815     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4816     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4817     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4818     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4819   };
4820 
4821   return llvm::ConstantStruct::getAnon(Fields);
4822 }
4823 
4824 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4825                                                        bool ForEH) {
4826   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4827   // FIXME: should we even be calling this method if RTTI is disabled
4828   // and it's not for EH?
4829   if (!ForEH && !getLangOpts().RTTI)
4830     return llvm::Constant::getNullValue(Int8PtrTy);
4831 
4832   if (ForEH && Ty->isObjCObjectPointerType() &&
4833       LangOpts.ObjCRuntime.isGNUFamily())
4834     return ObjCRuntime->GetEHType(Ty);
4835 
4836   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4837 }
4838 
4839 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4840   // Do not emit threadprivates in simd-only mode.
4841   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
4842     return;
4843   for (auto RefExpr : D->varlists()) {
4844     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4845     bool PerformInit =
4846         VD->getAnyInitializer() &&
4847         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4848                                                         /*ForRef=*/false);
4849 
4850     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4851     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4852             VD, Addr, RefExpr->getLocStart(), PerformInit))
4853       CXXGlobalInits.push_back(InitFunction);
4854   }
4855 }
4856 
4857 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4858   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4859   if (InternalId)
4860     return InternalId;
4861 
4862   if (isExternallyVisible(T->getLinkage())) {
4863     std::string OutName;
4864     llvm::raw_string_ostream Out(OutName);
4865     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4866 
4867     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4868   } else {
4869     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4870                                            llvm::ArrayRef<llvm::Metadata *>());
4871   }
4872 
4873   return InternalId;
4874 }
4875 
4876 // Generalize pointer types to a void pointer with the qualifiers of the
4877 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
4878 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
4879 // 'void *'.
4880 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
4881   if (!Ty->isPointerType())
4882     return Ty;
4883 
4884   return Ctx.getPointerType(
4885       QualType(Ctx.VoidTy).withCVRQualifiers(
4886           Ty->getPointeeType().getCVRQualifiers()));
4887 }
4888 
4889 // Apply type generalization to a FunctionType's return and argument types
4890 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
4891   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
4892     SmallVector<QualType, 8> GeneralizedParams;
4893     for (auto &Param : FnType->param_types())
4894       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
4895 
4896     return Ctx.getFunctionType(
4897         GeneralizeType(Ctx, FnType->getReturnType()),
4898         GeneralizedParams, FnType->getExtProtoInfo());
4899   }
4900 
4901   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
4902     return Ctx.getFunctionNoProtoType(
4903         GeneralizeType(Ctx, FnType->getReturnType()));
4904 
4905   llvm_unreachable("Encountered unknown FunctionType");
4906 }
4907 
4908 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
4909   T = GeneralizeFunctionType(getContext(), T);
4910 
4911   llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
4912   if (InternalId)
4913     return InternalId;
4914 
4915   if (isExternallyVisible(T->getLinkage())) {
4916     std::string OutName;
4917     llvm::raw_string_ostream Out(OutName);
4918     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4919     Out << ".generalized";
4920 
4921     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4922   } else {
4923     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4924                                            llvm::ArrayRef<llvm::Metadata *>());
4925   }
4926 
4927   return InternalId;
4928 }
4929 
4930 /// Returns whether this module needs the "all-vtables" type identifier.
4931 bool CodeGenModule::NeedAllVtablesTypeId() const {
4932   // Returns true if at least one of vtable-based CFI checkers is enabled and
4933   // is not in the trapping mode.
4934   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4935            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4936           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4937            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4938           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4939            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4940           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4941            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4942 }
4943 
4944 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4945                                           CharUnits Offset,
4946                                           const CXXRecordDecl *RD) {
4947   llvm::Metadata *MD =
4948       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4949   VTable->addTypeMetadata(Offset.getQuantity(), MD);
4950 
4951   if (CodeGenOpts.SanitizeCfiCrossDso)
4952     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4953       VTable->addTypeMetadata(Offset.getQuantity(),
4954                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4955 
4956   if (NeedAllVtablesTypeId()) {
4957     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4958     VTable->addTypeMetadata(Offset.getQuantity(), MD);
4959   }
4960 }
4961 
4962 // Fills in the supplied string map with the set of target features for the
4963 // passed in function.
4964 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4965                                           const FunctionDecl *FD) {
4966   StringRef TargetCPU = Target.getTargetOpts().CPU;
4967   if (const auto *TD = FD->getAttr<TargetAttr>()) {
4968     // If we have a TargetAttr build up the feature map based on that.
4969     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4970 
4971     ParsedAttr.Features.erase(
4972         llvm::remove_if(ParsedAttr.Features,
4973                         [&](const std::string &Feat) {
4974                           return !Target.isValidFeatureName(
4975                               StringRef{Feat}.substr(1));
4976                         }),
4977         ParsedAttr.Features.end());
4978 
4979     // Make a copy of the features as passed on the command line into the
4980     // beginning of the additional features from the function to override.
4981     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
4982                             Target.getTargetOpts().FeaturesAsWritten.begin(),
4983                             Target.getTargetOpts().FeaturesAsWritten.end());
4984 
4985     if (ParsedAttr.Architecture != "" &&
4986         Target.isValidCPUName(ParsedAttr.Architecture))
4987       TargetCPU = ParsedAttr.Architecture;
4988 
4989     // Now populate the feature map, first with the TargetCPU which is either
4990     // the default or a new one from the target attribute string. Then we'll use
4991     // the passed in features (FeaturesAsWritten) along with the new ones from
4992     // the attribute.
4993     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4994                           ParsedAttr.Features);
4995   } else {
4996     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4997                           Target.getTargetOpts().Features);
4998   }
4999 }
5000 
5001 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5002   if (!SanStats)
5003     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5004 
5005   return *SanStats;
5006 }
5007 llvm::Value *
5008 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5009                                                   CodeGenFunction &CGF) {
5010   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5011   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5012   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5013   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5014                                 "__translate_sampler_initializer"),
5015                                 {C});
5016 }
5017