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