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