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