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