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