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