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