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