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