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