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