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