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