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