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