xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 1a116db120e750cee60404867c3e79004aaeb668)
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, ForDefinition);
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                                           ForDefinition_t IsForDefinition) {
1152 
1153   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1154     // If this is an intrinsic function, set the function's attributes
1155     // to the intrinsic's attributes.
1156     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1157     return;
1158   }
1159 
1160   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1161 
1162   if (!IsIncompleteFunction) {
1163     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1164     // Setup target-specific attributes.
1165     if (!IsForDefinition)
1166       getTargetCodeGenInfo().setTargetAttributes(FD, F, *this,
1167                                                  NotForDefinition);
1168   }
1169 
1170   // Add the Returned attribute for "this", except for iOS 5 and earlier
1171   // where substantial code, including the libstdc++ dylib, was compiled with
1172   // GCC and does not actually return "this".
1173   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1174       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1175     assert(!F->arg_empty() &&
1176            F->arg_begin()->getType()
1177              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1178            "unexpected this return");
1179     F->addAttribute(1, llvm::Attribute::Returned);
1180   }
1181 
1182   // Only a few attributes are set on declarations; these may later be
1183   // overridden by a definition.
1184 
1185   setLinkageAndVisibilityForGV(F, FD);
1186 
1187   if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1188     F->addFnAttr("implicit-section-name");
1189   }
1190 
1191   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1192     F->setSection(SA->getName());
1193 
1194   if (FD->isReplaceableGlobalAllocationFunction()) {
1195     // A replaceable global allocation function does not act like a builtin by
1196     // default, only if it is invoked by a new-expression or delete-expression.
1197     F->addAttribute(llvm::AttributeList::FunctionIndex,
1198                     llvm::Attribute::NoBuiltin);
1199 
1200     // A sane operator new returns a non-aliasing pointer.
1201     // FIXME: Also add NonNull attribute to the return value
1202     // for the non-nothrow forms?
1203     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1204     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1205         (Kind == OO_New || Kind == OO_Array_New))
1206       F->addAttribute(llvm::AttributeList::ReturnIndex,
1207                       llvm::Attribute::NoAlias);
1208   }
1209 
1210   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1211     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1212   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1213     if (MD->isVirtual())
1214       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1215 
1216   // Don't emit entries for function declarations in the cross-DSO mode. This
1217   // is handled with better precision by the receiving DSO.
1218   if (!CodeGenOpts.SanitizeCfiCrossDso)
1219     CreateFunctionTypeMetadata(FD, F);
1220 }
1221 
1222 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1223   assert(!GV->isDeclaration() &&
1224          "Only globals with definition can force usage.");
1225   LLVMUsed.emplace_back(GV);
1226 }
1227 
1228 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1229   assert(!GV->isDeclaration() &&
1230          "Only globals with definition can force usage.");
1231   LLVMCompilerUsed.emplace_back(GV);
1232 }
1233 
1234 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1235                      std::vector<llvm::WeakTrackingVH> &List) {
1236   // Don't create llvm.used if there is no need.
1237   if (List.empty())
1238     return;
1239 
1240   // Convert List to what ConstantArray needs.
1241   SmallVector<llvm::Constant*, 8> UsedArray;
1242   UsedArray.resize(List.size());
1243   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1244     UsedArray[i] =
1245         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1246             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1247   }
1248 
1249   if (UsedArray.empty())
1250     return;
1251   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1252 
1253   auto *GV = new llvm::GlobalVariable(
1254       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1255       llvm::ConstantArray::get(ATy, UsedArray), Name);
1256 
1257   GV->setSection("llvm.metadata");
1258 }
1259 
1260 void CodeGenModule::emitLLVMUsed() {
1261   emitUsed(*this, "llvm.used", LLVMUsed);
1262   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1263 }
1264 
1265 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1266   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1267   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1268 }
1269 
1270 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1271   llvm::SmallString<32> Opt;
1272   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1273   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1274   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1275 }
1276 
1277 void CodeGenModule::AddDependentLib(StringRef Lib) {
1278   llvm::SmallString<24> Opt;
1279   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1280   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1281   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1282 }
1283 
1284 /// \brief Add link options implied by the given module, including modules
1285 /// it depends on, using a postorder walk.
1286 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1287                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
1288                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1289   // Import this module's parent.
1290   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1291     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1292   }
1293 
1294   // Import this module's dependencies.
1295   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1296     if (Visited.insert(Mod->Imports[I - 1]).second)
1297       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1298   }
1299 
1300   // Add linker options to link against the libraries/frameworks
1301   // described by this module.
1302   llvm::LLVMContext &Context = CGM.getLLVMContext();
1303   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1304     // Link against a framework.  Frameworks are currently Darwin only, so we
1305     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1306     if (Mod->LinkLibraries[I-1].IsFramework) {
1307       llvm::Metadata *Args[2] = {
1308           llvm::MDString::get(Context, "-framework"),
1309           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1310 
1311       Metadata.push_back(llvm::MDNode::get(Context, Args));
1312       continue;
1313     }
1314 
1315     // Link against a library.
1316     llvm::SmallString<24> Opt;
1317     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1318       Mod->LinkLibraries[I-1].Library, Opt);
1319     auto *OptString = llvm::MDString::get(Context, Opt);
1320     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1321   }
1322 }
1323 
1324 void CodeGenModule::EmitModuleLinkOptions() {
1325   // Collect the set of all of the modules we want to visit to emit link
1326   // options, which is essentially the imported modules and all of their
1327   // non-explicit child modules.
1328   llvm::SetVector<clang::Module *> LinkModules;
1329   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1330   SmallVector<clang::Module *, 16> Stack;
1331 
1332   // Seed the stack with imported modules.
1333   for (Module *M : ImportedModules) {
1334     // Do not add any link flags when an implementation TU of a module imports
1335     // a header of that same module.
1336     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1337         !getLangOpts().isCompilingModule())
1338       continue;
1339     if (Visited.insert(M).second)
1340       Stack.push_back(M);
1341   }
1342 
1343   // Find all of the modules to import, making a little effort to prune
1344   // non-leaf modules.
1345   while (!Stack.empty()) {
1346     clang::Module *Mod = Stack.pop_back_val();
1347 
1348     bool AnyChildren = false;
1349 
1350     // Visit the submodules of this module.
1351     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1352                                         SubEnd = Mod->submodule_end();
1353          Sub != SubEnd; ++Sub) {
1354       // Skip explicit children; they need to be explicitly imported to be
1355       // linked against.
1356       if ((*Sub)->IsExplicit)
1357         continue;
1358 
1359       if (Visited.insert(*Sub).second) {
1360         Stack.push_back(*Sub);
1361         AnyChildren = true;
1362       }
1363     }
1364 
1365     // We didn't find any children, so add this module to the list of
1366     // modules to link against.
1367     if (!AnyChildren) {
1368       LinkModules.insert(Mod);
1369     }
1370   }
1371 
1372   // Add link options for all of the imported modules in reverse topological
1373   // order.  We don't do anything to try to order import link flags with respect
1374   // to linker options inserted by things like #pragma comment().
1375   SmallVector<llvm::MDNode *, 16> MetadataArgs;
1376   Visited.clear();
1377   for (Module *M : LinkModules)
1378     if (Visited.insert(M).second)
1379       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1380   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1381   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1382 
1383   // Add the linker options metadata flag.
1384   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1385   for (auto *MD : LinkerOptionsMetadata)
1386     NMD->addOperand(MD);
1387 }
1388 
1389 void CodeGenModule::EmitDeferred() {
1390   // Emit code for any potentially referenced deferred decls.  Since a
1391   // previously unused static decl may become used during the generation of code
1392   // for a static function, iterate until no changes are made.
1393 
1394   if (!DeferredVTables.empty()) {
1395     EmitDeferredVTables();
1396 
1397     // Emitting a vtable doesn't directly cause more vtables to
1398     // become deferred, although it can cause functions to be
1399     // emitted that then need those vtables.
1400     assert(DeferredVTables.empty());
1401   }
1402 
1403   // Stop if we're out of both deferred vtables and deferred declarations.
1404   if (DeferredDeclsToEmit.empty())
1405     return;
1406 
1407   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1408   // work, it will not interfere with this.
1409   std::vector<GlobalDecl> CurDeclsToEmit;
1410   CurDeclsToEmit.swap(DeferredDeclsToEmit);
1411 
1412   for (GlobalDecl &D : CurDeclsToEmit) {
1413     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1414     // to get GlobalValue with exactly the type we need, not something that
1415     // might had been created for another decl with the same mangled name but
1416     // different type.
1417     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1418         GetAddrOfGlobal(D, ForDefinition));
1419 
1420     // In case of different address spaces, we may still get a cast, even with
1421     // IsForDefinition equal to true. Query mangled names table to get
1422     // GlobalValue.
1423     if (!GV)
1424       GV = GetGlobalValue(getMangledName(D));
1425 
1426     // Make sure GetGlobalValue returned non-null.
1427     assert(GV);
1428 
1429     // Check to see if we've already emitted this.  This is necessary
1430     // for a couple of reasons: first, decls can end up in the
1431     // deferred-decls queue multiple times, and second, decls can end
1432     // up with definitions in unusual ways (e.g. by an extern inline
1433     // function acquiring a strong function redefinition).  Just
1434     // ignore these cases.
1435     if (!GV->isDeclaration())
1436       continue;
1437 
1438     // Otherwise, emit the definition and move on to the next one.
1439     EmitGlobalDefinition(D, GV);
1440 
1441     // If we found out that we need to emit more decls, do that recursively.
1442     // This has the advantage that the decls are emitted in a DFS and related
1443     // ones are close together, which is convenient for testing.
1444     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1445       EmitDeferred();
1446       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1447     }
1448   }
1449 }
1450 
1451 void CodeGenModule::EmitVTablesOpportunistically() {
1452   // Try to emit external vtables as available_externally if they have emitted
1453   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
1454   // is not allowed to create new references to things that need to be emitted
1455   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1456 
1457   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1458          && "Only emit opportunistic vtables with optimizations");
1459 
1460   for (const CXXRecordDecl *RD : OpportunisticVTables) {
1461     assert(getVTables().isVTableExternal(RD) &&
1462            "This queue should only contain external vtables");
1463     if (getCXXABI().canSpeculativelyEmitVTable(RD))
1464       VTables.GenerateClassData(RD);
1465   }
1466   OpportunisticVTables.clear();
1467 }
1468 
1469 void CodeGenModule::EmitGlobalAnnotations() {
1470   if (Annotations.empty())
1471     return;
1472 
1473   // Create a new global variable for the ConstantStruct in the Module.
1474   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1475     Annotations[0]->getType(), Annotations.size()), Annotations);
1476   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1477                                       llvm::GlobalValue::AppendingLinkage,
1478                                       Array, "llvm.global.annotations");
1479   gv->setSection(AnnotationSection);
1480 }
1481 
1482 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1483   llvm::Constant *&AStr = AnnotationStrings[Str];
1484   if (AStr)
1485     return AStr;
1486 
1487   // Not found yet, create a new global.
1488   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1489   auto *gv =
1490       new llvm::GlobalVariable(getModule(), s->getType(), true,
1491                                llvm::GlobalValue::PrivateLinkage, s, ".str");
1492   gv->setSection(AnnotationSection);
1493   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1494   AStr = gv;
1495   return gv;
1496 }
1497 
1498 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1499   SourceManager &SM = getContext().getSourceManager();
1500   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1501   if (PLoc.isValid())
1502     return EmitAnnotationString(PLoc.getFilename());
1503   return EmitAnnotationString(SM.getBufferName(Loc));
1504 }
1505 
1506 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1507   SourceManager &SM = getContext().getSourceManager();
1508   PresumedLoc PLoc = SM.getPresumedLoc(L);
1509   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1510     SM.getExpansionLineNumber(L);
1511   return llvm::ConstantInt::get(Int32Ty, LineNo);
1512 }
1513 
1514 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1515                                                 const AnnotateAttr *AA,
1516                                                 SourceLocation L) {
1517   // Get the globals for file name, annotation, and the line number.
1518   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1519                  *UnitGV = EmitAnnotationUnit(L),
1520                  *LineNoCst = EmitAnnotationLineNo(L);
1521 
1522   // Create the ConstantStruct for the global annotation.
1523   llvm::Constant *Fields[4] = {
1524     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1525     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1526     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1527     LineNoCst
1528   };
1529   return llvm::ConstantStruct::getAnon(Fields);
1530 }
1531 
1532 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1533                                          llvm::GlobalValue *GV) {
1534   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1535   // Get the struct elements for these annotations.
1536   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1537     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1538 }
1539 
1540 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1541                                            SourceLocation Loc) const {
1542   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1543   // Blacklist by function name.
1544   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1545     return true;
1546   // Blacklist by location.
1547   if (Loc.isValid())
1548     return SanitizerBL.isBlacklistedLocation(Loc);
1549   // If location is unknown, this may be a compiler-generated function. Assume
1550   // it's located in the main file.
1551   auto &SM = Context.getSourceManager();
1552   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1553     return SanitizerBL.isBlacklistedFile(MainFile->getName());
1554   }
1555   return false;
1556 }
1557 
1558 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1559                                            SourceLocation Loc, QualType Ty,
1560                                            StringRef Category) const {
1561   // For now globals can be blacklisted only in ASan and KASan.
1562   if (!LangOpts.Sanitize.hasOneOf(
1563           SanitizerKind::Address | SanitizerKind::KernelAddress))
1564     return false;
1565   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1566   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1567     return true;
1568   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1569     return true;
1570   // Check global type.
1571   if (!Ty.isNull()) {
1572     // Drill down the array types: if global variable of a fixed type is
1573     // blacklisted, we also don't instrument arrays of them.
1574     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1575       Ty = AT->getElementType();
1576     Ty = Ty.getCanonicalType().getUnqualifiedType();
1577     // We allow to blacklist only record types (classes, structs etc.)
1578     if (Ty->isRecordType()) {
1579       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1580       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1581         return true;
1582     }
1583   }
1584   return false;
1585 }
1586 
1587 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1588                                    StringRef Category) const {
1589   if (!LangOpts.XRayInstrument)
1590     return false;
1591   const auto &XRayFilter = getContext().getXRayFilter();
1592   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1593   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1594   if (Loc.isValid())
1595     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1596   if (Attr == ImbueAttr::NONE)
1597     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1598   switch (Attr) {
1599   case ImbueAttr::NONE:
1600     return false;
1601   case ImbueAttr::ALWAYS:
1602     Fn->addFnAttr("function-instrument", "xray-always");
1603     break;
1604   case ImbueAttr::ALWAYS_ARG1:
1605     Fn->addFnAttr("function-instrument", "xray-always");
1606     Fn->addFnAttr("xray-log-args", "1");
1607     break;
1608   case ImbueAttr::NEVER:
1609     Fn->addFnAttr("function-instrument", "xray-never");
1610     break;
1611   }
1612   return true;
1613 }
1614 
1615 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1616   // Never defer when EmitAllDecls is specified.
1617   if (LangOpts.EmitAllDecls)
1618     return true;
1619 
1620   return getContext().DeclMustBeEmitted(Global);
1621 }
1622 
1623 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1624   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1625     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1626       // Implicit template instantiations may change linkage if they are later
1627       // explicitly instantiated, so they should not be emitted eagerly.
1628       return false;
1629   if (const auto *VD = dyn_cast<VarDecl>(Global))
1630     if (Context.getInlineVariableDefinitionKind(VD) ==
1631         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1632       // A definition of an inline constexpr static data member may change
1633       // linkage later if it's redeclared outside the class.
1634       return false;
1635   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1636   // codegen for global variables, because they may be marked as threadprivate.
1637   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1638       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1639     return false;
1640 
1641   return true;
1642 }
1643 
1644 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1645     const CXXUuidofExpr* E) {
1646   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1647   // well-formed.
1648   StringRef Uuid = E->getUuidStr();
1649   std::string Name = "_GUID_" + Uuid.lower();
1650   std::replace(Name.begin(), Name.end(), '-', '_');
1651 
1652   // The UUID descriptor should be pointer aligned.
1653   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1654 
1655   // Look for an existing global.
1656   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1657     return ConstantAddress(GV, Alignment);
1658 
1659   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1660   assert(Init && "failed to initialize as constant");
1661 
1662   auto *GV = new llvm::GlobalVariable(
1663       getModule(), Init->getType(),
1664       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1665   if (supportsCOMDAT())
1666     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1667   return ConstantAddress(GV, Alignment);
1668 }
1669 
1670 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1671   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1672   assert(AA && "No alias?");
1673 
1674   CharUnits Alignment = getContext().getDeclAlign(VD);
1675   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1676 
1677   // See if there is already something with the target's name in the module.
1678   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1679   if (Entry) {
1680     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1681     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1682     return ConstantAddress(Ptr, Alignment);
1683   }
1684 
1685   llvm::Constant *Aliasee;
1686   if (isa<llvm::FunctionType>(DeclTy))
1687     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1688                                       GlobalDecl(cast<FunctionDecl>(VD)),
1689                                       /*ForVTable=*/false);
1690   else
1691     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1692                                     llvm::PointerType::getUnqual(DeclTy),
1693                                     nullptr);
1694 
1695   auto *F = cast<llvm::GlobalValue>(Aliasee);
1696   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1697   WeakRefReferences.insert(F);
1698 
1699   return ConstantAddress(Aliasee, Alignment);
1700 }
1701 
1702 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1703   const auto *Global = cast<ValueDecl>(GD.getDecl());
1704 
1705   // Weak references don't produce any output by themselves.
1706   if (Global->hasAttr<WeakRefAttr>())
1707     return;
1708 
1709   // If this is an alias definition (which otherwise looks like a declaration)
1710   // emit it now.
1711   if (Global->hasAttr<AliasAttr>())
1712     return EmitAliasDefinition(GD);
1713 
1714   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1715   if (Global->hasAttr<IFuncAttr>())
1716     return emitIFuncDefinition(GD);
1717 
1718   // If this is CUDA, be selective about which declarations we emit.
1719   if (LangOpts.CUDA) {
1720     if (LangOpts.CUDAIsDevice) {
1721       if (!Global->hasAttr<CUDADeviceAttr>() &&
1722           !Global->hasAttr<CUDAGlobalAttr>() &&
1723           !Global->hasAttr<CUDAConstantAttr>() &&
1724           !Global->hasAttr<CUDASharedAttr>())
1725         return;
1726     } else {
1727       // We need to emit host-side 'shadows' for all global
1728       // device-side variables because the CUDA runtime needs their
1729       // size and host-side address in order to provide access to
1730       // their device-side incarnations.
1731 
1732       // So device-only functions are the only things we skip.
1733       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1734           Global->hasAttr<CUDADeviceAttr>())
1735         return;
1736 
1737       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1738              "Expected Variable or Function");
1739     }
1740   }
1741 
1742   if (LangOpts.OpenMP) {
1743     // If this is OpenMP device, check if it is legal to emit this global
1744     // normally.
1745     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1746       return;
1747     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1748       if (MustBeEmitted(Global))
1749         EmitOMPDeclareReduction(DRD);
1750       return;
1751     }
1752   }
1753 
1754   // Ignore declarations, they will be emitted on their first use.
1755   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1756     // Forward declarations are emitted lazily on first use.
1757     if (!FD->doesThisDeclarationHaveABody()) {
1758       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1759         return;
1760 
1761       StringRef MangledName = getMangledName(GD);
1762 
1763       // Compute the function info and LLVM type.
1764       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1765       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1766 
1767       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1768                               /*DontDefer=*/false);
1769       return;
1770     }
1771   } else {
1772     const auto *VD = cast<VarDecl>(Global);
1773     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1774     // We need to emit device-side global CUDA variables even if a
1775     // variable does not have a definition -- we still need to define
1776     // host-side shadow for it.
1777     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1778                            !VD->hasDefinition() &&
1779                            (VD->hasAttr<CUDAConstantAttr>() ||
1780                             VD->hasAttr<CUDADeviceAttr>());
1781     if (!MustEmitForCuda &&
1782         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1783         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1784       // If this declaration may have caused an inline variable definition to
1785       // change linkage, make sure that it's emitted.
1786       if (Context.getInlineVariableDefinitionKind(VD) ==
1787           ASTContext::InlineVariableDefinitionKind::Strong)
1788         GetAddrOfGlobalVar(VD);
1789       return;
1790     }
1791   }
1792 
1793   // Defer code generation to first use when possible, e.g. if this is an inline
1794   // function. If the global must always be emitted, do it eagerly if possible
1795   // to benefit from cache locality.
1796   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1797     // Emit the definition if it can't be deferred.
1798     EmitGlobalDefinition(GD);
1799     return;
1800   }
1801 
1802   // If we're deferring emission of a C++ variable with an
1803   // initializer, remember the order in which it appeared in the file.
1804   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1805       cast<VarDecl>(Global)->hasInit()) {
1806     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1807     CXXGlobalInits.push_back(nullptr);
1808   }
1809 
1810   StringRef MangledName = getMangledName(GD);
1811   if (GetGlobalValue(MangledName) != nullptr) {
1812     // The value has already been used and should therefore be emitted.
1813     addDeferredDeclToEmit(GD);
1814   } else if (MustBeEmitted(Global)) {
1815     // The value must be emitted, but cannot be emitted eagerly.
1816     assert(!MayBeEmittedEagerly(Global));
1817     addDeferredDeclToEmit(GD);
1818   } else {
1819     // Otherwise, remember that we saw a deferred decl with this name.  The
1820     // first use of the mangled name will cause it to move into
1821     // DeferredDeclsToEmit.
1822     DeferredDecls[MangledName] = GD;
1823   }
1824 }
1825 
1826 // Check if T is a class type with a destructor that's not dllimport.
1827 static bool HasNonDllImportDtor(QualType T) {
1828   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1829     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1830       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1831         return true;
1832 
1833   return false;
1834 }
1835 
1836 namespace {
1837   struct FunctionIsDirectlyRecursive :
1838     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1839     const StringRef Name;
1840     const Builtin::Context &BI;
1841     bool Result;
1842     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1843       Name(N), BI(C), Result(false) {
1844     }
1845     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1846 
1847     bool TraverseCallExpr(CallExpr *E) {
1848       const FunctionDecl *FD = E->getDirectCallee();
1849       if (!FD)
1850         return true;
1851       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1852       if (Attr && Name == Attr->getLabel()) {
1853         Result = true;
1854         return false;
1855       }
1856       unsigned BuiltinID = FD->getBuiltinID();
1857       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1858         return true;
1859       StringRef BuiltinName = BI.getName(BuiltinID);
1860       if (BuiltinName.startswith("__builtin_") &&
1861           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1862         Result = true;
1863         return false;
1864       }
1865       return true;
1866     }
1867   };
1868 
1869   // Make sure we're not referencing non-imported vars or functions.
1870   struct DLLImportFunctionVisitor
1871       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1872     bool SafeToInline = true;
1873 
1874     bool shouldVisitImplicitCode() const { return true; }
1875 
1876     bool VisitVarDecl(VarDecl *VD) {
1877       if (VD->getTLSKind()) {
1878         // A thread-local variable cannot be imported.
1879         SafeToInline = false;
1880         return SafeToInline;
1881       }
1882 
1883       // A variable definition might imply a destructor call.
1884       if (VD->isThisDeclarationADefinition())
1885         SafeToInline = !HasNonDllImportDtor(VD->getType());
1886 
1887       return SafeToInline;
1888     }
1889 
1890     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1891       if (const auto *D = E->getTemporary()->getDestructor())
1892         SafeToInline = D->hasAttr<DLLImportAttr>();
1893       return SafeToInline;
1894     }
1895 
1896     bool VisitDeclRefExpr(DeclRefExpr *E) {
1897       ValueDecl *VD = E->getDecl();
1898       if (isa<FunctionDecl>(VD))
1899         SafeToInline = VD->hasAttr<DLLImportAttr>();
1900       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1901         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1902       return SafeToInline;
1903     }
1904 
1905     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1906       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1907       return SafeToInline;
1908     }
1909 
1910     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1911       CXXMethodDecl *M = E->getMethodDecl();
1912       if (!M) {
1913         // Call through a pointer to member function. This is safe to inline.
1914         SafeToInline = true;
1915       } else {
1916         SafeToInline = M->hasAttr<DLLImportAttr>();
1917       }
1918       return SafeToInline;
1919     }
1920 
1921     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1922       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1923       return SafeToInline;
1924     }
1925 
1926     bool VisitCXXNewExpr(CXXNewExpr *E) {
1927       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1928       return SafeToInline;
1929     }
1930   };
1931 }
1932 
1933 // isTriviallyRecursive - Check if this function calls another
1934 // decl that, because of the asm attribute or the other decl being a builtin,
1935 // ends up pointing to itself.
1936 bool
1937 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1938   StringRef Name;
1939   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1940     // asm labels are a special kind of mangling we have to support.
1941     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1942     if (!Attr)
1943       return false;
1944     Name = Attr->getLabel();
1945   } else {
1946     Name = FD->getName();
1947   }
1948 
1949   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1950   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1951   return Walker.Result;
1952 }
1953 
1954 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1955   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1956     return true;
1957   const auto *F = cast<FunctionDecl>(GD.getDecl());
1958   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1959     return false;
1960 
1961   if (F->hasAttr<DLLImportAttr>()) {
1962     // Check whether it would be safe to inline this dllimport function.
1963     DLLImportFunctionVisitor Visitor;
1964     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1965     if (!Visitor.SafeToInline)
1966       return false;
1967 
1968     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1969       // Implicit destructor invocations aren't captured in the AST, so the
1970       // check above can't see them. Check for them manually here.
1971       for (const Decl *Member : Dtor->getParent()->decls())
1972         if (isa<FieldDecl>(Member))
1973           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1974             return false;
1975       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1976         if (HasNonDllImportDtor(B.getType()))
1977           return false;
1978     }
1979   }
1980 
1981   // PR9614. Avoid cases where the source code is lying to us. An available
1982   // externally function should have an equivalent function somewhere else,
1983   // but a function that calls itself is clearly not equivalent to the real
1984   // implementation.
1985   // This happens in glibc's btowc and in some configure checks.
1986   return !isTriviallyRecursive(F);
1987 }
1988 
1989 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
1990   return CodeGenOpts.OptimizationLevel > 0;
1991 }
1992 
1993 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1994   const auto *D = cast<ValueDecl>(GD.getDecl());
1995 
1996   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1997                                  Context.getSourceManager(),
1998                                  "Generating code for declaration");
1999 
2000   if (isa<FunctionDecl>(D)) {
2001     // At -O0, don't generate IR for functions with available_externally
2002     // linkage.
2003     if (!shouldEmitFunction(GD))
2004       return;
2005 
2006     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2007       // Make sure to emit the definition(s) before we emit the thunks.
2008       // This is necessary for the generation of certain thunks.
2009       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2010         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
2011       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2012         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2013       else
2014         EmitGlobalFunctionDefinition(GD, GV);
2015 
2016       if (Method->isVirtual())
2017         getVTables().EmitThunks(GD);
2018 
2019       return;
2020     }
2021 
2022     return EmitGlobalFunctionDefinition(GD, GV);
2023   }
2024 
2025   if (const auto *VD = dyn_cast<VarDecl>(D))
2026     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2027 
2028   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2029 }
2030 
2031 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2032                                                       llvm::Function *NewFn);
2033 
2034 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2035 /// module, create and return an llvm Function with the specified type. If there
2036 /// is something in the module with the specified name, return it potentially
2037 /// bitcasted to the right type.
2038 ///
2039 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2040 /// to set the attributes on the function when it is first created.
2041 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2042     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2043     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2044     ForDefinition_t IsForDefinition) {
2045   const Decl *D = GD.getDecl();
2046 
2047   // Lookup the entry, lazily creating it if necessary.
2048   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2049   if (Entry) {
2050     if (WeakRefReferences.erase(Entry)) {
2051       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2052       if (FD && !FD->hasAttr<WeakAttr>())
2053         Entry->setLinkage(llvm::Function::ExternalLinkage);
2054     }
2055 
2056     // Handle dropped DLL attributes.
2057     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2058       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2059 
2060     // If there are two attempts to define the same mangled name, issue an
2061     // error.
2062     if (IsForDefinition && !Entry->isDeclaration()) {
2063       GlobalDecl OtherGD;
2064       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2065       // to make sure that we issue an error only once.
2066       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2067           (GD.getCanonicalDecl().getDecl() !=
2068            OtherGD.getCanonicalDecl().getDecl()) &&
2069           DiagnosedConflictingDefinitions.insert(GD).second) {
2070         getDiags().Report(D->getLocation(),
2071                           diag::err_duplicate_mangled_name);
2072         getDiags().Report(OtherGD.getDecl()->getLocation(),
2073                           diag::note_previous_definition);
2074       }
2075     }
2076 
2077     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2078         (Entry->getType()->getElementType() == Ty)) {
2079       return Entry;
2080     }
2081 
2082     // Make sure the result is of the correct type.
2083     // (If function is requested for a definition, we always need to create a new
2084     // function, not just return a bitcast.)
2085     if (!IsForDefinition)
2086       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2087   }
2088 
2089   // This function doesn't have a complete type (for example, the return
2090   // type is an incomplete struct). Use a fake type instead, and make
2091   // sure not to try to set attributes.
2092   bool IsIncompleteFunction = false;
2093 
2094   llvm::FunctionType *FTy;
2095   if (isa<llvm::FunctionType>(Ty)) {
2096     FTy = cast<llvm::FunctionType>(Ty);
2097   } else {
2098     FTy = llvm::FunctionType::get(VoidTy, false);
2099     IsIncompleteFunction = true;
2100   }
2101 
2102   llvm::Function *F =
2103       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2104                              Entry ? StringRef() : MangledName, &getModule());
2105 
2106   // If we already created a function with the same mangled name (but different
2107   // type) before, take its name and add it to the list of functions to be
2108   // replaced with F at the end of CodeGen.
2109   //
2110   // This happens if there is a prototype for a function (e.g. "int f()") and
2111   // then a definition of a different type (e.g. "int f(int x)").
2112   if (Entry) {
2113     F->takeName(Entry);
2114 
2115     // This might be an implementation of a function without a prototype, in
2116     // which case, try to do special replacement of calls which match the new
2117     // prototype.  The really key thing here is that we also potentially drop
2118     // arguments from the call site so as to make a direct call, which makes the
2119     // inliner happier and suppresses a number of optimizer warnings (!) about
2120     // dropping arguments.
2121     if (!Entry->use_empty()) {
2122       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2123       Entry->removeDeadConstantUsers();
2124     }
2125 
2126     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2127         F, Entry->getType()->getElementType()->getPointerTo());
2128     addGlobalValReplacement(Entry, BC);
2129   }
2130 
2131   assert(F->getName() == MangledName && "name was uniqued!");
2132   if (D)
2133     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk,
2134                           IsForDefinition);
2135   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2136     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2137     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2138   }
2139 
2140   if (!DontDefer) {
2141     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2142     // each other bottoming out with the base dtor.  Therefore we emit non-base
2143     // dtors on usage, even if there is no dtor definition in the TU.
2144     if (D && isa<CXXDestructorDecl>(D) &&
2145         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2146                                            GD.getDtorType()))
2147       addDeferredDeclToEmit(GD);
2148 
2149     // This is the first use or definition of a mangled name.  If there is a
2150     // deferred decl with this name, remember that we need to emit it at the end
2151     // of the file.
2152     auto DDI = DeferredDecls.find(MangledName);
2153     if (DDI != DeferredDecls.end()) {
2154       // Move the potentially referenced deferred decl to the
2155       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2156       // don't need it anymore).
2157       addDeferredDeclToEmit(DDI->second);
2158       DeferredDecls.erase(DDI);
2159 
2160       // Otherwise, there are cases we have to worry about where we're
2161       // using a declaration for which we must emit a definition but where
2162       // we might not find a top-level definition:
2163       //   - member functions defined inline in their classes
2164       //   - friend functions defined inline in some class
2165       //   - special member functions with implicit definitions
2166       // If we ever change our AST traversal to walk into class methods,
2167       // this will be unnecessary.
2168       //
2169       // We also don't emit a definition for a function if it's going to be an
2170       // entry in a vtable, unless it's already marked as used.
2171     } else if (getLangOpts().CPlusPlus && D) {
2172       // Look for a declaration that's lexically in a record.
2173       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2174            FD = FD->getPreviousDecl()) {
2175         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2176           if (FD->doesThisDeclarationHaveABody()) {
2177             addDeferredDeclToEmit(GD.getWithDecl(FD));
2178             break;
2179           }
2180         }
2181       }
2182     }
2183   }
2184 
2185   // Make sure the result is of the requested type.
2186   if (!IsIncompleteFunction) {
2187     assert(F->getType()->getElementType() == Ty);
2188     return F;
2189   }
2190 
2191   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2192   return llvm::ConstantExpr::getBitCast(F, PTy);
2193 }
2194 
2195 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2196 /// non-null, then this function will use the specified type if it has to
2197 /// create it (this occurs when we see a definition of the function).
2198 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2199                                                  llvm::Type *Ty,
2200                                                  bool ForVTable,
2201                                                  bool DontDefer,
2202                                               ForDefinition_t IsForDefinition) {
2203   // If there was no specific requested type, just convert it now.
2204   if (!Ty) {
2205     const auto *FD = cast<FunctionDecl>(GD.getDecl());
2206     auto CanonTy = Context.getCanonicalType(FD->getType());
2207     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2208   }
2209 
2210   StringRef MangledName = getMangledName(GD);
2211   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2212                                  /*IsThunk=*/false, llvm::AttributeList(),
2213                                  IsForDefinition);
2214 }
2215 
2216 static const FunctionDecl *
2217 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2218   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2219   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2220 
2221   IdentifierInfo &CII = C.Idents.get(Name);
2222   for (const auto &Result : DC->lookup(&CII))
2223     if (const auto FD = dyn_cast<FunctionDecl>(Result))
2224       return FD;
2225 
2226   if (!C.getLangOpts().CPlusPlus)
2227     return nullptr;
2228 
2229   // Demangle the premangled name from getTerminateFn()
2230   IdentifierInfo &CXXII =
2231       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2232           ? C.Idents.get("terminate")
2233           : C.Idents.get(Name);
2234 
2235   for (const auto &N : {"__cxxabiv1", "std"}) {
2236     IdentifierInfo &NS = C.Idents.get(N);
2237     for (const auto &Result : DC->lookup(&NS)) {
2238       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2239       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2240         for (const auto &Result : LSD->lookup(&NS))
2241           if ((ND = dyn_cast<NamespaceDecl>(Result)))
2242             break;
2243 
2244       if (ND)
2245         for (const auto &Result : ND->lookup(&CXXII))
2246           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2247             return FD;
2248     }
2249   }
2250 
2251   return nullptr;
2252 }
2253 
2254 /// CreateRuntimeFunction - Create a new runtime function with the specified
2255 /// type and name.
2256 llvm::Constant *
2257 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2258                                      llvm::AttributeList ExtraAttrs,
2259                                      bool Local) {
2260   llvm::Constant *C =
2261       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2262                               /*DontDefer=*/false, /*IsThunk=*/false,
2263                               ExtraAttrs);
2264 
2265   if (auto *F = dyn_cast<llvm::Function>(C)) {
2266     if (F->empty()) {
2267       F->setCallingConv(getRuntimeCC());
2268 
2269       if (!Local && getTriple().isOSBinFormatCOFF() &&
2270           !getCodeGenOpts().LTOVisibilityPublicStd) {
2271         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2272         if (!FD || FD->hasAttr<DLLImportAttr>()) {
2273           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2274           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2275         }
2276       }
2277     }
2278   }
2279 
2280   return C;
2281 }
2282 
2283 /// CreateBuiltinFunction - Create a new builtin function with the specified
2284 /// type and name.
2285 llvm::Constant *
2286 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2287                                      llvm::AttributeList ExtraAttrs) {
2288   llvm::Constant *C =
2289       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2290                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2291   if (auto *F = dyn_cast<llvm::Function>(C))
2292     if (F->empty())
2293       F->setCallingConv(getBuiltinCC());
2294   return C;
2295 }
2296 
2297 /// isTypeConstant - Determine whether an object of this type can be emitted
2298 /// as a constant.
2299 ///
2300 /// If ExcludeCtor is true, the duration when the object's constructor runs
2301 /// will not be considered. The caller will need to verify that the object is
2302 /// not written to during its construction.
2303 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2304   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2305     return false;
2306 
2307   if (Context.getLangOpts().CPlusPlus) {
2308     if (const CXXRecordDecl *Record
2309           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2310       return ExcludeCtor && !Record->hasMutableFields() &&
2311              Record->hasTrivialDestructor();
2312   }
2313 
2314   return true;
2315 }
2316 
2317 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2318 /// create and return an llvm GlobalVariable with the specified type.  If there
2319 /// is something in the module with the specified name, return it potentially
2320 /// bitcasted to the right type.
2321 ///
2322 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2323 /// to set the attributes on the global when it is first created.
2324 ///
2325 /// If IsForDefinition is true, it is guranteed that an actual global with
2326 /// type Ty will be returned, not conversion of a variable with the same
2327 /// mangled name but some other type.
2328 llvm::Constant *
2329 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2330                                      llvm::PointerType *Ty,
2331                                      const VarDecl *D,
2332                                      ForDefinition_t IsForDefinition) {
2333   // Lookup the entry, lazily creating it if necessary.
2334   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2335   if (Entry) {
2336     if (WeakRefReferences.erase(Entry)) {
2337       if (D && !D->hasAttr<WeakAttr>())
2338         Entry->setLinkage(llvm::Function::ExternalLinkage);
2339     }
2340 
2341     // Handle dropped DLL attributes.
2342     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2343       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2344 
2345     if (Entry->getType() == Ty)
2346       return Entry;
2347 
2348     // If there are two attempts to define the same mangled name, issue an
2349     // error.
2350     if (IsForDefinition && !Entry->isDeclaration()) {
2351       GlobalDecl OtherGD;
2352       const VarDecl *OtherD;
2353 
2354       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2355       // to make sure that we issue an error only once.
2356       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2357           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2358           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2359           OtherD->hasInit() &&
2360           DiagnosedConflictingDefinitions.insert(D).second) {
2361         getDiags().Report(D->getLocation(),
2362                           diag::err_duplicate_mangled_name);
2363         getDiags().Report(OtherGD.getDecl()->getLocation(),
2364                           diag::note_previous_definition);
2365       }
2366     }
2367 
2368     // Make sure the result is of the correct type.
2369     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2370       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2371 
2372     // (If global is requested for a definition, we always need to create a new
2373     // global, not just return a bitcast.)
2374     if (!IsForDefinition)
2375       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2376   }
2377 
2378   auto AddrSpace = GetGlobalVarAddressSpace(D);
2379   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2380 
2381   auto *GV = new llvm::GlobalVariable(
2382       getModule(), Ty->getElementType(), false,
2383       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2384       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2385 
2386   // If we already created a global with the same mangled name (but different
2387   // type) before, take its name and remove it from its parent.
2388   if (Entry) {
2389     GV->takeName(Entry);
2390 
2391     if (!Entry->use_empty()) {
2392       llvm::Constant *NewPtrForOldDecl =
2393           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2394       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2395     }
2396 
2397     Entry->eraseFromParent();
2398   }
2399 
2400   // This is the first use or definition of a mangled name.  If there is a
2401   // deferred decl with this name, remember that we need to emit it at the end
2402   // of the file.
2403   auto DDI = DeferredDecls.find(MangledName);
2404   if (DDI != DeferredDecls.end()) {
2405     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2406     // list, and remove it from DeferredDecls (since we don't need it anymore).
2407     addDeferredDeclToEmit(DDI->second);
2408     DeferredDecls.erase(DDI);
2409   }
2410 
2411   // Handle things which are present even on external declarations.
2412   if (D) {
2413     // FIXME: This code is overly simple and should be merged with other global
2414     // handling.
2415     GV->setConstant(isTypeConstant(D->getType(), false));
2416 
2417     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2418 
2419     setLinkageAndVisibilityForGV(GV, D);
2420 
2421     if (D->getTLSKind()) {
2422       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2423         CXXThreadLocals.push_back(D);
2424       setTLSMode(GV, *D);
2425     }
2426 
2427     // If required by the ABI, treat declarations of static data members with
2428     // inline initializers as definitions.
2429     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2430       EmitGlobalVarDefinition(D);
2431     }
2432 
2433     // Handle XCore specific ABI requirements.
2434     if (getTriple().getArch() == llvm::Triple::xcore &&
2435         D->getLanguageLinkage() == CLanguageLinkage &&
2436         D->getType().isConstant(Context) &&
2437         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2438       GV->setSection(".cp.rodata");
2439   }
2440 
2441   auto ExpectedAS =
2442       D ? D->getType().getAddressSpace()
2443         : static_cast<unsigned>(LangOpts.OpenCL ? LangAS::opencl_global
2444                                                 : LangAS::Default);
2445   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2446          Ty->getPointerAddressSpace());
2447   if (AddrSpace != ExpectedAS)
2448     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2449                                                        ExpectedAS, Ty);
2450 
2451   return GV;
2452 }
2453 
2454 llvm::Constant *
2455 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2456                                ForDefinition_t IsForDefinition) {
2457   const Decl *D = GD.getDecl();
2458   if (isa<CXXConstructorDecl>(D))
2459     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2460                                 getFromCtorType(GD.getCtorType()),
2461                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2462                                 /*DontDefer=*/false, IsForDefinition);
2463   else if (isa<CXXDestructorDecl>(D))
2464     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2465                                 getFromDtorType(GD.getDtorType()),
2466                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2467                                 /*DontDefer=*/false, IsForDefinition);
2468   else if (isa<CXXMethodDecl>(D)) {
2469     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2470         cast<CXXMethodDecl>(D));
2471     auto Ty = getTypes().GetFunctionType(*FInfo);
2472     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2473                              IsForDefinition);
2474   } else if (isa<FunctionDecl>(D)) {
2475     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2476     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2477     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2478                              IsForDefinition);
2479   } else
2480     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2481                               IsForDefinition);
2482 }
2483 
2484 llvm::GlobalVariable *
2485 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2486                                       llvm::Type *Ty,
2487                                       llvm::GlobalValue::LinkageTypes Linkage) {
2488   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2489   llvm::GlobalVariable *OldGV = nullptr;
2490 
2491   if (GV) {
2492     // Check if the variable has the right type.
2493     if (GV->getType()->getElementType() == Ty)
2494       return GV;
2495 
2496     // Because C++ name mangling, the only way we can end up with an already
2497     // existing global with the same name is if it has been declared extern "C".
2498     assert(GV->isDeclaration() && "Declaration has wrong type!");
2499     OldGV = GV;
2500   }
2501 
2502   // Create a new variable.
2503   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2504                                 Linkage, nullptr, Name);
2505 
2506   if (OldGV) {
2507     // Replace occurrences of the old variable if needed.
2508     GV->takeName(OldGV);
2509 
2510     if (!OldGV->use_empty()) {
2511       llvm::Constant *NewPtrForOldDecl =
2512       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2513       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2514     }
2515 
2516     OldGV->eraseFromParent();
2517   }
2518 
2519   if (supportsCOMDAT() && GV->isWeakForLinker() &&
2520       !GV->hasAvailableExternallyLinkage())
2521     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2522 
2523   return GV;
2524 }
2525 
2526 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2527 /// given global variable.  If Ty is non-null and if the global doesn't exist,
2528 /// then it will be created with the specified type instead of whatever the
2529 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2530 /// that an actual global with type Ty will be returned, not conversion of a
2531 /// variable with the same mangled name but some other type.
2532 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2533                                                   llvm::Type *Ty,
2534                                            ForDefinition_t IsForDefinition) {
2535   assert(D->hasGlobalStorage() && "Not a global variable");
2536   QualType ASTTy = D->getType();
2537   if (!Ty)
2538     Ty = getTypes().ConvertTypeForMem(ASTTy);
2539 
2540   llvm::PointerType *PTy =
2541     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2542 
2543   StringRef MangledName = getMangledName(D);
2544   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2545 }
2546 
2547 /// CreateRuntimeVariable - Create a new runtime global variable with the
2548 /// specified type and name.
2549 llvm::Constant *
2550 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2551                                      StringRef Name) {
2552   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2553 }
2554 
2555 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2556   assert(!D->getInit() && "Cannot emit definite definitions here!");
2557 
2558   StringRef MangledName = getMangledName(D);
2559   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2560 
2561   // We already have a definition, not declaration, with the same mangled name.
2562   // Emitting of declaration is not required (and actually overwrites emitted
2563   // definition).
2564   if (GV && !GV->isDeclaration())
2565     return;
2566 
2567   // If we have not seen a reference to this variable yet, place it into the
2568   // deferred declarations table to be emitted if needed later.
2569   if (!MustBeEmitted(D) && !GV) {
2570       DeferredDecls[MangledName] = D;
2571       return;
2572   }
2573 
2574   // The tentative definition is the only definition.
2575   EmitGlobalVarDefinition(D);
2576 }
2577 
2578 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2579   return Context.toCharUnitsFromBits(
2580       getDataLayout().getTypeStoreSizeInBits(Ty));
2581 }
2582 
2583 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
2584   unsigned AddrSpace;
2585   if (LangOpts.OpenCL) {
2586     AddrSpace = D ? D->getType().getAddressSpace()
2587                   : static_cast<unsigned>(LangAS::opencl_global);
2588     assert(AddrSpace == LangAS::opencl_global ||
2589            AddrSpace == LangAS::opencl_constant ||
2590            AddrSpace == LangAS::opencl_local ||
2591            AddrSpace >= LangAS::FirstTargetAddressSpace);
2592     return AddrSpace;
2593   }
2594 
2595   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2596     if (D && D->hasAttr<CUDAConstantAttr>())
2597       return LangAS::cuda_constant;
2598     else if (D && D->hasAttr<CUDASharedAttr>())
2599       return LangAS::cuda_shared;
2600     else
2601       return LangAS::cuda_device;
2602   }
2603 
2604   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
2605 }
2606 
2607 template<typename SomeDecl>
2608 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2609                                                llvm::GlobalValue *GV) {
2610   if (!getLangOpts().CPlusPlus)
2611     return;
2612 
2613   // Must have 'used' attribute, or else inline assembly can't rely on
2614   // the name existing.
2615   if (!D->template hasAttr<UsedAttr>())
2616     return;
2617 
2618   // Must have internal linkage and an ordinary name.
2619   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2620     return;
2621 
2622   // Must be in an extern "C" context. Entities declared directly within
2623   // a record are not extern "C" even if the record is in such a context.
2624   const SomeDecl *First = D->getFirstDecl();
2625   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2626     return;
2627 
2628   // OK, this is an internal linkage entity inside an extern "C" linkage
2629   // specification. Make a note of that so we can give it the "expected"
2630   // mangled name if nothing else is using that name.
2631   std::pair<StaticExternCMap::iterator, bool> R =
2632       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2633 
2634   // If we have multiple internal linkage entities with the same name
2635   // in extern "C" regions, none of them gets that name.
2636   if (!R.second)
2637     R.first->second = nullptr;
2638 }
2639 
2640 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2641   if (!CGM.supportsCOMDAT())
2642     return false;
2643 
2644   if (D.hasAttr<SelectAnyAttr>())
2645     return true;
2646 
2647   GVALinkage Linkage;
2648   if (auto *VD = dyn_cast<VarDecl>(&D))
2649     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2650   else
2651     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2652 
2653   switch (Linkage) {
2654   case GVA_Internal:
2655   case GVA_AvailableExternally:
2656   case GVA_StrongExternal:
2657     return false;
2658   case GVA_DiscardableODR:
2659   case GVA_StrongODR:
2660     return true;
2661   }
2662   llvm_unreachable("No such linkage");
2663 }
2664 
2665 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2666                                           llvm::GlobalObject &GO) {
2667   if (!shouldBeInCOMDAT(*this, D))
2668     return;
2669   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2670 }
2671 
2672 /// Pass IsTentative as true if you want to create a tentative definition.
2673 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2674                                             bool IsTentative) {
2675   // OpenCL global variables of sampler type are translated to function calls,
2676   // therefore no need to be translated.
2677   QualType ASTTy = D->getType();
2678   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2679     return;
2680 
2681   llvm::Constant *Init = nullptr;
2682   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2683   bool NeedsGlobalCtor = false;
2684   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2685 
2686   const VarDecl *InitDecl;
2687   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2688 
2689   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2690   // as part of their declaration."  Sema has already checked for
2691   // error cases, so we just need to set Init to UndefValue.
2692   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2693       D->hasAttr<CUDASharedAttr>())
2694     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2695   else if (!InitExpr) {
2696     // This is a tentative definition; tentative definitions are
2697     // implicitly initialized with { 0 }.
2698     //
2699     // Note that tentative definitions are only emitted at the end of
2700     // a translation unit, so they should never have incomplete
2701     // type. In addition, EmitTentativeDefinition makes sure that we
2702     // never attempt to emit a tentative definition if a real one
2703     // exists. A use may still exists, however, so we still may need
2704     // to do a RAUW.
2705     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2706     Init = EmitNullConstant(D->getType());
2707   } else {
2708     initializedGlobalDecl = GlobalDecl(D);
2709     Init = EmitConstantInit(*InitDecl);
2710 
2711     if (!Init) {
2712       QualType T = InitExpr->getType();
2713       if (D->getType()->isReferenceType())
2714         T = D->getType();
2715 
2716       if (getLangOpts().CPlusPlus) {
2717         Init = EmitNullConstant(T);
2718         NeedsGlobalCtor = true;
2719       } else {
2720         ErrorUnsupported(D, "static initializer");
2721         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2722       }
2723     } else {
2724       // We don't need an initializer, so remove the entry for the delayed
2725       // initializer position (just in case this entry was delayed) if we
2726       // also don't need to register a destructor.
2727       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2728         DelayedCXXInitPosition.erase(D);
2729     }
2730   }
2731 
2732   llvm::Type* InitType = Init->getType();
2733   llvm::Constant *Entry =
2734       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2735 
2736   // Strip off a bitcast if we got one back.
2737   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2738     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2739            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2740            // All zero index gep.
2741            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2742     Entry = CE->getOperand(0);
2743   }
2744 
2745   // Entry is now either a Function or GlobalVariable.
2746   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2747 
2748   // We have a definition after a declaration with the wrong type.
2749   // We must make a new GlobalVariable* and update everything that used OldGV
2750   // (a declaration or tentative definition) with the new GlobalVariable*
2751   // (which will be a definition).
2752   //
2753   // This happens if there is a prototype for a global (e.g.
2754   // "extern int x[];") and then a definition of a different type (e.g.
2755   // "int x[10];"). This also happens when an initializer has a different type
2756   // from the type of the global (this happens with unions).
2757   if (!GV || GV->getType()->getElementType() != InitType ||
2758       GV->getType()->getAddressSpace() !=
2759           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
2760 
2761     // Move the old entry aside so that we'll create a new one.
2762     Entry->setName(StringRef());
2763 
2764     // Make a new global with the correct type, this is now guaranteed to work.
2765     GV = cast<llvm::GlobalVariable>(
2766         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2767 
2768     // Replace all uses of the old global with the new global
2769     llvm::Constant *NewPtrForOldDecl =
2770         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2771     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2772 
2773     // Erase the old global, since it is no longer used.
2774     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2775   }
2776 
2777   MaybeHandleStaticInExternC(D, GV);
2778 
2779   if (D->hasAttr<AnnotateAttr>())
2780     AddGlobalAnnotations(D, GV);
2781 
2782   // Set the llvm linkage type as appropriate.
2783   llvm::GlobalValue::LinkageTypes Linkage =
2784       getLLVMLinkageVarDefinition(D, GV->isConstant());
2785 
2786   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2787   // the device. [...]"
2788   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2789   // __device__, declares a variable that: [...]
2790   // Is accessible from all the threads within the grid and from the host
2791   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2792   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2793   if (GV && LangOpts.CUDA) {
2794     if (LangOpts.CUDAIsDevice) {
2795       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2796         GV->setExternallyInitialized(true);
2797     } else {
2798       // Host-side shadows of external declarations of device-side
2799       // global variables become internal definitions. These have to
2800       // be internal in order to prevent name conflicts with global
2801       // host variables with the same name in a different TUs.
2802       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2803         Linkage = llvm::GlobalValue::InternalLinkage;
2804 
2805         // Shadow variables and their properties must be registered
2806         // with CUDA runtime.
2807         unsigned Flags = 0;
2808         if (!D->hasDefinition())
2809           Flags |= CGCUDARuntime::ExternDeviceVar;
2810         if (D->hasAttr<CUDAConstantAttr>())
2811           Flags |= CGCUDARuntime::ConstantDeviceVar;
2812         getCUDARuntime().registerDeviceVar(*GV, Flags);
2813       } else if (D->hasAttr<CUDASharedAttr>())
2814         // __shared__ variables are odd. Shadows do get created, but
2815         // they are not registered with the CUDA runtime, so they
2816         // can't really be used to access their device-side
2817         // counterparts. It's not clear yet whether it's nvcc's bug or
2818         // a feature, but we've got to do the same for compatibility.
2819         Linkage = llvm::GlobalValue::InternalLinkage;
2820     }
2821   }
2822   GV->setInitializer(Init);
2823 
2824   // If it is safe to mark the global 'constant', do so now.
2825   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2826                   isTypeConstant(D->getType(), true));
2827 
2828   // If it is in a read-only section, mark it 'constant'.
2829   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2830     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2831     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2832       GV->setConstant(true);
2833   }
2834 
2835   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2836 
2837 
2838   // On Darwin, if the normal linkage of a C++ thread_local variable is
2839   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2840   // copies within a linkage unit; otherwise, the backing variable has
2841   // internal linkage and all accesses should just be calls to the
2842   // Itanium-specified entry point, which has the normal linkage of the
2843   // variable. This is to preserve the ability to change the implementation
2844   // behind the scenes.
2845   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2846       Context.getTargetInfo().getTriple().isOSDarwin() &&
2847       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2848       !llvm::GlobalVariable::isWeakLinkage(Linkage))
2849     Linkage = llvm::GlobalValue::InternalLinkage;
2850 
2851   GV->setLinkage(Linkage);
2852   if (D->hasAttr<DLLImportAttr>())
2853     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2854   else if (D->hasAttr<DLLExportAttr>())
2855     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2856   else
2857     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2858 
2859   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2860     // common vars aren't constant even if declared const.
2861     GV->setConstant(false);
2862     // Tentative definition of global variables may be initialized with
2863     // non-zero null pointers. In this case they should have weak linkage
2864     // since common linkage must have zero initializer and must not have
2865     // explicit section therefore cannot have non-zero initial value.
2866     if (!GV->getInitializer()->isNullValue())
2867       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2868   }
2869 
2870   setNonAliasAttributes(D, GV);
2871 
2872   if (D->getTLSKind() && !GV->isThreadLocal()) {
2873     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2874       CXXThreadLocals.push_back(D);
2875     setTLSMode(GV, *D);
2876   }
2877 
2878   maybeSetTrivialComdat(*D, *GV);
2879 
2880   // Emit the initializer function if necessary.
2881   if (NeedsGlobalCtor || NeedsGlobalDtor)
2882     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2883 
2884   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2885 
2886   // Emit global variable debug information.
2887   if (CGDebugInfo *DI = getModuleDebugInfo())
2888     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2889       DI->EmitGlobalVariable(GV, D);
2890 }
2891 
2892 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2893                                       CodeGenModule &CGM, const VarDecl *D,
2894                                       bool NoCommon) {
2895   // Don't give variables common linkage if -fno-common was specified unless it
2896   // was overridden by a NoCommon attribute.
2897   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2898     return true;
2899 
2900   // C11 6.9.2/2:
2901   //   A declaration of an identifier for an object that has file scope without
2902   //   an initializer, and without a storage-class specifier or with the
2903   //   storage-class specifier static, constitutes a tentative definition.
2904   if (D->getInit() || D->hasExternalStorage())
2905     return true;
2906 
2907   // A variable cannot be both common and exist in a section.
2908   if (D->hasAttr<SectionAttr>())
2909     return true;
2910 
2911   // A variable cannot be both common and exist in a section.
2912   // We dont try to determine which is the right section in the front-end.
2913   // If no specialized section name is applicable, it will resort to default.
2914   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
2915       D->hasAttr<PragmaClangDataSectionAttr>() ||
2916       D->hasAttr<PragmaClangRodataSectionAttr>())
2917     return true;
2918 
2919   // Thread local vars aren't considered common linkage.
2920   if (D->getTLSKind())
2921     return true;
2922 
2923   // Tentative definitions marked with WeakImportAttr are true definitions.
2924   if (D->hasAttr<WeakImportAttr>())
2925     return true;
2926 
2927   // A variable cannot be both common and exist in a comdat.
2928   if (shouldBeInCOMDAT(CGM, *D))
2929     return true;
2930 
2931   // Declarations with a required alignment do not have common linkage in MSVC
2932   // mode.
2933   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2934     if (D->hasAttr<AlignedAttr>())
2935       return true;
2936     QualType VarType = D->getType();
2937     if (Context.isAlignmentRequired(VarType))
2938       return true;
2939 
2940     if (const auto *RT = VarType->getAs<RecordType>()) {
2941       const RecordDecl *RD = RT->getDecl();
2942       for (const FieldDecl *FD : RD->fields()) {
2943         if (FD->isBitField())
2944           continue;
2945         if (FD->hasAttr<AlignedAttr>())
2946           return true;
2947         if (Context.isAlignmentRequired(FD->getType()))
2948           return true;
2949       }
2950     }
2951   }
2952 
2953   return false;
2954 }
2955 
2956 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2957     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2958   if (Linkage == GVA_Internal)
2959     return llvm::Function::InternalLinkage;
2960 
2961   if (D->hasAttr<WeakAttr>()) {
2962     if (IsConstantVariable)
2963       return llvm::GlobalVariable::WeakODRLinkage;
2964     else
2965       return llvm::GlobalVariable::WeakAnyLinkage;
2966   }
2967 
2968   // We are guaranteed to have a strong definition somewhere else,
2969   // so we can use available_externally linkage.
2970   if (Linkage == GVA_AvailableExternally)
2971     return llvm::GlobalValue::AvailableExternallyLinkage;
2972 
2973   // Note that Apple's kernel linker doesn't support symbol
2974   // coalescing, so we need to avoid linkonce and weak linkages there.
2975   // Normally, this means we just map to internal, but for explicit
2976   // instantiations we'll map to external.
2977 
2978   // In C++, the compiler has to emit a definition in every translation unit
2979   // that references the function.  We should use linkonce_odr because
2980   // a) if all references in this translation unit are optimized away, we
2981   // don't need to codegen it.  b) if the function persists, it needs to be
2982   // merged with other definitions. c) C++ has the ODR, so we know the
2983   // definition is dependable.
2984   if (Linkage == GVA_DiscardableODR)
2985     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2986                                             : llvm::Function::InternalLinkage;
2987 
2988   // An explicit instantiation of a template has weak linkage, since
2989   // explicit instantiations can occur in multiple translation units
2990   // and must all be equivalent. However, we are not allowed to
2991   // throw away these explicit instantiations.
2992   //
2993   // We don't currently support CUDA device code spread out across multiple TUs,
2994   // so say that CUDA templates are either external (for kernels) or internal.
2995   // This lets llvm perform aggressive inter-procedural optimizations.
2996   if (Linkage == GVA_StrongODR) {
2997     if (Context.getLangOpts().AppleKext)
2998       return llvm::Function::ExternalLinkage;
2999     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3000       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3001                                           : llvm::Function::InternalLinkage;
3002     return llvm::Function::WeakODRLinkage;
3003   }
3004 
3005   // C++ doesn't have tentative definitions and thus cannot have common
3006   // linkage.
3007   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3008       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
3009                                  CodeGenOpts.NoCommon))
3010     return llvm::GlobalVariable::CommonLinkage;
3011 
3012   // selectany symbols are externally visible, so use weak instead of
3013   // linkonce.  MSVC optimizes away references to const selectany globals, so
3014   // all definitions should be the same and ODR linkage should be used.
3015   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3016   if (D->hasAttr<SelectAnyAttr>())
3017     return llvm::GlobalVariable::WeakODRLinkage;
3018 
3019   // Otherwise, we have strong external linkage.
3020   assert(Linkage == GVA_StrongExternal);
3021   return llvm::GlobalVariable::ExternalLinkage;
3022 }
3023 
3024 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3025     const VarDecl *VD, bool IsConstant) {
3026   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
3027   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
3028 }
3029 
3030 /// Replace the uses of a function that was declared with a non-proto type.
3031 /// We want to silently drop extra arguments from call sites
3032 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3033                                           llvm::Function *newFn) {
3034   // Fast path.
3035   if (old->use_empty()) return;
3036 
3037   llvm::Type *newRetTy = newFn->getReturnType();
3038   SmallVector<llvm::Value*, 4> newArgs;
3039   SmallVector<llvm::OperandBundleDef, 1> newBundles;
3040 
3041   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3042          ui != ue; ) {
3043     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
3044     llvm::User *user = use->getUser();
3045 
3046     // Recognize and replace uses of bitcasts.  Most calls to
3047     // unprototyped functions will use bitcasts.
3048     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3049       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3050         replaceUsesOfNonProtoConstant(bitcast, newFn);
3051       continue;
3052     }
3053 
3054     // Recognize calls to the function.
3055     llvm::CallSite callSite(user);
3056     if (!callSite) continue;
3057     if (!callSite.isCallee(&*use)) continue;
3058 
3059     // If the return types don't match exactly, then we can't
3060     // transform this call unless it's dead.
3061     if (callSite->getType() != newRetTy && !callSite->use_empty())
3062       continue;
3063 
3064     // Get the call site's attribute list.
3065     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
3066     llvm::AttributeList oldAttrs = callSite.getAttributes();
3067 
3068     // If the function was passed too few arguments, don't transform.
3069     unsigned newNumArgs = newFn->arg_size();
3070     if (callSite.arg_size() < newNumArgs) continue;
3071 
3072     // If extra arguments were passed, we silently drop them.
3073     // If any of the types mismatch, we don't transform.
3074     unsigned argNo = 0;
3075     bool dontTransform = false;
3076     for (llvm::Argument &A : newFn->args()) {
3077       if (callSite.getArgument(argNo)->getType() != A.getType()) {
3078         dontTransform = true;
3079         break;
3080       }
3081 
3082       // Add any parameter attributes.
3083       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3084       argNo++;
3085     }
3086     if (dontTransform)
3087       continue;
3088 
3089     // Okay, we can transform this.  Create the new call instruction and copy
3090     // over the required information.
3091     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3092 
3093     // Copy over any operand bundles.
3094     callSite.getOperandBundlesAsDefs(newBundles);
3095 
3096     llvm::CallSite newCall;
3097     if (callSite.isCall()) {
3098       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3099                                        callSite.getInstruction());
3100     } else {
3101       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3102       newCall = llvm::InvokeInst::Create(newFn,
3103                                          oldInvoke->getNormalDest(),
3104                                          oldInvoke->getUnwindDest(),
3105                                          newArgs, newBundles, "",
3106                                          callSite.getInstruction());
3107     }
3108     newArgs.clear(); // for the next iteration
3109 
3110     if (!newCall->getType()->isVoidTy())
3111       newCall->takeName(callSite.getInstruction());
3112     newCall.setAttributes(llvm::AttributeList::get(
3113         newFn->getContext(), oldAttrs.getFnAttributes(),
3114         oldAttrs.getRetAttributes(), newArgAttrs));
3115     newCall.setCallingConv(callSite.getCallingConv());
3116 
3117     // Finally, remove the old call, replacing any uses with the new one.
3118     if (!callSite->use_empty())
3119       callSite->replaceAllUsesWith(newCall.getInstruction());
3120 
3121     // Copy debug location attached to CI.
3122     if (callSite->getDebugLoc())
3123       newCall->setDebugLoc(callSite->getDebugLoc());
3124 
3125     callSite->eraseFromParent();
3126   }
3127 }
3128 
3129 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3130 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3131 /// existing call uses of the old function in the module, this adjusts them to
3132 /// call the new function directly.
3133 ///
3134 /// This is not just a cleanup: the always_inline pass requires direct calls to
3135 /// functions to be able to inline them.  If there is a bitcast in the way, it
3136 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3137 /// run at -O0.
3138 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3139                                                       llvm::Function *NewFn) {
3140   // If we're redefining a global as a function, don't transform it.
3141   if (!isa<llvm::Function>(Old)) return;
3142 
3143   replaceUsesOfNonProtoConstant(Old, NewFn);
3144 }
3145 
3146 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3147   auto DK = VD->isThisDeclarationADefinition();
3148   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3149     return;
3150 
3151   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3152   // If we have a definition, this might be a deferred decl. If the
3153   // instantiation is explicit, make sure we emit it at the end.
3154   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3155     GetAddrOfGlobalVar(VD);
3156 
3157   EmitTopLevelDecl(VD);
3158 }
3159 
3160 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3161                                                  llvm::GlobalValue *GV) {
3162   const auto *D = cast<FunctionDecl>(GD.getDecl());
3163 
3164   // Compute the function info and LLVM type.
3165   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3166   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3167 
3168   // Get or create the prototype for the function.
3169   if (!GV || (GV->getType()->getElementType() != Ty))
3170     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3171                                                    /*DontDefer=*/true,
3172                                                    ForDefinition));
3173 
3174   // Already emitted.
3175   if (!GV->isDeclaration())
3176     return;
3177 
3178   // We need to set linkage and visibility on the function before
3179   // generating code for it because various parts of IR generation
3180   // want to propagate this information down (e.g. to local static
3181   // declarations).
3182   auto *Fn = cast<llvm::Function>(GV);
3183   setFunctionLinkage(GD, Fn);
3184   setFunctionDLLStorageClass(GD, Fn);
3185 
3186   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3187   setGlobalVisibility(Fn, D);
3188 
3189   MaybeHandleStaticInExternC(D, Fn);
3190 
3191   maybeSetTrivialComdat(*D, *Fn);
3192 
3193   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3194 
3195   setFunctionDefinitionAttributes(D, Fn);
3196   SetLLVMFunctionAttributesForDefinition(D, Fn);
3197 
3198   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3199     AddGlobalCtor(Fn, CA->getPriority());
3200   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3201     AddGlobalDtor(Fn, DA->getPriority());
3202   if (D->hasAttr<AnnotateAttr>())
3203     AddGlobalAnnotations(D, Fn);
3204 }
3205 
3206 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3207   const auto *D = cast<ValueDecl>(GD.getDecl());
3208   const AliasAttr *AA = D->getAttr<AliasAttr>();
3209   assert(AA && "Not an alias?");
3210 
3211   StringRef MangledName = getMangledName(GD);
3212 
3213   if (AA->getAliasee() == MangledName) {
3214     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3215     return;
3216   }
3217 
3218   // If there is a definition in the module, then it wins over the alias.
3219   // This is dubious, but allow it to be safe.  Just ignore the alias.
3220   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3221   if (Entry && !Entry->isDeclaration())
3222     return;
3223 
3224   Aliases.push_back(GD);
3225 
3226   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3227 
3228   // Create a reference to the named value.  This ensures that it is emitted
3229   // if a deferred decl.
3230   llvm::Constant *Aliasee;
3231   if (isa<llvm::FunctionType>(DeclTy))
3232     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3233                                       /*ForVTable=*/false);
3234   else
3235     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3236                                     llvm::PointerType::getUnqual(DeclTy),
3237                                     /*D=*/nullptr);
3238 
3239   // Create the new alias itself, but don't set a name yet.
3240   auto *GA = llvm::GlobalAlias::create(
3241       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3242 
3243   if (Entry) {
3244     if (GA->getAliasee() == Entry) {
3245       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3246       return;
3247     }
3248 
3249     assert(Entry->isDeclaration());
3250 
3251     // If there is a declaration in the module, then we had an extern followed
3252     // by the alias, as in:
3253     //   extern int test6();
3254     //   ...
3255     //   int test6() __attribute__((alias("test7")));
3256     //
3257     // Remove it and replace uses of it with the alias.
3258     GA->takeName(Entry);
3259 
3260     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3261                                                           Entry->getType()));
3262     Entry->eraseFromParent();
3263   } else {
3264     GA->setName(MangledName);
3265   }
3266 
3267   // Set attributes which are particular to an alias; this is a
3268   // specialization of the attributes which may be set on a global
3269   // variable/function.
3270   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3271       D->isWeakImported()) {
3272     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3273   }
3274 
3275   if (const auto *VD = dyn_cast<VarDecl>(D))
3276     if (VD->getTLSKind())
3277       setTLSMode(GA, *VD);
3278 
3279   setAliasAttributes(D, GA);
3280 }
3281 
3282 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3283   const auto *D = cast<ValueDecl>(GD.getDecl());
3284   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3285   assert(IFA && "Not an ifunc?");
3286 
3287   StringRef MangledName = getMangledName(GD);
3288 
3289   if (IFA->getResolver() == MangledName) {
3290     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3291     return;
3292   }
3293 
3294   // Report an error if some definition overrides ifunc.
3295   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3296   if (Entry && !Entry->isDeclaration()) {
3297     GlobalDecl OtherGD;
3298     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3299         DiagnosedConflictingDefinitions.insert(GD).second) {
3300       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3301       Diags.Report(OtherGD.getDecl()->getLocation(),
3302                    diag::note_previous_definition);
3303     }
3304     return;
3305   }
3306 
3307   Aliases.push_back(GD);
3308 
3309   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3310   llvm::Constant *Resolver =
3311       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3312                               /*ForVTable=*/false);
3313   llvm::GlobalIFunc *GIF =
3314       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3315                                 "", Resolver, &getModule());
3316   if (Entry) {
3317     if (GIF->getResolver() == Entry) {
3318       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3319       return;
3320     }
3321     assert(Entry->isDeclaration());
3322 
3323     // If there is a declaration in the module, then we had an extern followed
3324     // by the ifunc, as in:
3325     //   extern int test();
3326     //   ...
3327     //   int test() __attribute__((ifunc("resolver")));
3328     //
3329     // Remove it and replace uses of it with the ifunc.
3330     GIF->takeName(Entry);
3331 
3332     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3333                                                           Entry->getType()));
3334     Entry->eraseFromParent();
3335   } else
3336     GIF->setName(MangledName);
3337 
3338   SetCommonAttributes(D, GIF);
3339 }
3340 
3341 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3342                                             ArrayRef<llvm::Type*> Tys) {
3343   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3344                                          Tys);
3345 }
3346 
3347 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3348 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3349                          const StringLiteral *Literal, bool TargetIsLSB,
3350                          bool &IsUTF16, unsigned &StringLength) {
3351   StringRef String = Literal->getString();
3352   unsigned NumBytes = String.size();
3353 
3354   // Check for simple case.
3355   if (!Literal->containsNonAsciiOrNull()) {
3356     StringLength = NumBytes;
3357     return *Map.insert(std::make_pair(String, nullptr)).first;
3358   }
3359 
3360   // Otherwise, convert the UTF8 literals into a string of shorts.
3361   IsUTF16 = true;
3362 
3363   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3364   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3365   llvm::UTF16 *ToPtr = &ToBuf[0];
3366 
3367   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3368                                  ToPtr + NumBytes, llvm::strictConversion);
3369 
3370   // ConvertUTF8toUTF16 returns the length in ToPtr.
3371   StringLength = ToPtr - &ToBuf[0];
3372 
3373   // Add an explicit null.
3374   *ToPtr = 0;
3375   return *Map.insert(std::make_pair(
3376                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3377                                    (StringLength + 1) * 2),
3378                          nullptr)).first;
3379 }
3380 
3381 ConstantAddress
3382 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3383   unsigned StringLength = 0;
3384   bool isUTF16 = false;
3385   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3386       GetConstantCFStringEntry(CFConstantStringMap, Literal,
3387                                getDataLayout().isLittleEndian(), isUTF16,
3388                                StringLength);
3389 
3390   if (auto *C = Entry.second)
3391     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3392 
3393   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3394   llvm::Constant *Zeros[] = { Zero, Zero };
3395 
3396   // If we don't already have it, get __CFConstantStringClassReference.
3397   if (!CFConstantStringClassRef) {
3398     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3399     Ty = llvm::ArrayType::get(Ty, 0);
3400     llvm::Constant *GV =
3401         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3402 
3403     if (getTriple().isOSBinFormatCOFF()) {
3404       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3405       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3406       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3407       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3408 
3409       const VarDecl *VD = nullptr;
3410       for (const auto &Result : DC->lookup(&II))
3411         if ((VD = dyn_cast<VarDecl>(Result)))
3412           break;
3413 
3414       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3415         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3416         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3417       } else {
3418         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3419         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3420       }
3421     }
3422 
3423     // Decay array -> ptr
3424     CFConstantStringClassRef =
3425         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3426   }
3427 
3428   QualType CFTy = getContext().getCFConstantStringType();
3429 
3430   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3431 
3432   ConstantInitBuilder Builder(*this);
3433   auto Fields = Builder.beginStruct(STy);
3434 
3435   // Class pointer.
3436   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3437 
3438   // Flags.
3439   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3440 
3441   // String pointer.
3442   llvm::Constant *C = nullptr;
3443   if (isUTF16) {
3444     auto Arr = llvm::makeArrayRef(
3445         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3446         Entry.first().size() / 2);
3447     C = llvm::ConstantDataArray::get(VMContext, Arr);
3448   } else {
3449     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3450   }
3451 
3452   // Note: -fwritable-strings doesn't make the backing store strings of
3453   // CFStrings writable. (See <rdar://problem/10657500>)
3454   auto *GV =
3455       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3456                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3457   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3458   // Don't enforce the target's minimum global alignment, since the only use
3459   // of the string is via this class initializer.
3460   CharUnits Align = isUTF16
3461                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3462                         : getContext().getTypeAlignInChars(getContext().CharTy);
3463   GV->setAlignment(Align.getQuantity());
3464 
3465   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3466   // Without it LLVM can merge the string with a non unnamed_addr one during
3467   // LTO.  Doing that changes the section it ends in, which surprises ld64.
3468   if (getTriple().isOSBinFormatMachO())
3469     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3470                            : "__TEXT,__cstring,cstring_literals");
3471 
3472   // String.
3473   llvm::Constant *Str =
3474       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3475 
3476   if (isUTF16)
3477     // Cast the UTF16 string to the correct type.
3478     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3479   Fields.add(Str);
3480 
3481   // String length.
3482   auto Ty = getTypes().ConvertType(getContext().LongTy);
3483   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3484 
3485   CharUnits Alignment = getPointerAlign();
3486 
3487   // The struct.
3488   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3489                                     /*isConstant=*/false,
3490                                     llvm::GlobalVariable::PrivateLinkage);
3491   switch (getTriple().getObjectFormat()) {
3492   case llvm::Triple::UnknownObjectFormat:
3493     llvm_unreachable("unknown file format");
3494   case llvm::Triple::COFF:
3495   case llvm::Triple::ELF:
3496   case llvm::Triple::Wasm:
3497     GV->setSection("cfstring");
3498     break;
3499   case llvm::Triple::MachO:
3500     GV->setSection("__DATA,__cfstring");
3501     break;
3502   }
3503   Entry.second = GV;
3504 
3505   return ConstantAddress(GV, Alignment);
3506 }
3507 
3508 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3509   if (ObjCFastEnumerationStateType.isNull()) {
3510     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3511     D->startDefinition();
3512 
3513     QualType FieldTypes[] = {
3514       Context.UnsignedLongTy,
3515       Context.getPointerType(Context.getObjCIdType()),
3516       Context.getPointerType(Context.UnsignedLongTy),
3517       Context.getConstantArrayType(Context.UnsignedLongTy,
3518                            llvm::APInt(32, 5), ArrayType::Normal, 0)
3519     };
3520 
3521     for (size_t i = 0; i < 4; ++i) {
3522       FieldDecl *Field = FieldDecl::Create(Context,
3523                                            D,
3524                                            SourceLocation(),
3525                                            SourceLocation(), nullptr,
3526                                            FieldTypes[i], /*TInfo=*/nullptr,
3527                                            /*BitWidth=*/nullptr,
3528                                            /*Mutable=*/false,
3529                                            ICIS_NoInit);
3530       Field->setAccess(AS_public);
3531       D->addDecl(Field);
3532     }
3533 
3534     D->completeDefinition();
3535     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3536   }
3537 
3538   return ObjCFastEnumerationStateType;
3539 }
3540 
3541 llvm::Constant *
3542 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3543   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3544 
3545   // Don't emit it as the address of the string, emit the string data itself
3546   // as an inline array.
3547   if (E->getCharByteWidth() == 1) {
3548     SmallString<64> Str(E->getString());
3549 
3550     // Resize the string to the right size, which is indicated by its type.
3551     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3552     Str.resize(CAT->getSize().getZExtValue());
3553     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3554   }
3555 
3556   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3557   llvm::Type *ElemTy = AType->getElementType();
3558   unsigned NumElements = AType->getNumElements();
3559 
3560   // Wide strings have either 2-byte or 4-byte elements.
3561   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3562     SmallVector<uint16_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   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3572   SmallVector<uint32_t, 32> Elements;
3573   Elements.reserve(NumElements);
3574 
3575   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3576     Elements.push_back(E->getCodeUnit(i));
3577   Elements.resize(NumElements);
3578   return llvm::ConstantDataArray::get(VMContext, Elements);
3579 }
3580 
3581 static llvm::GlobalVariable *
3582 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3583                       CodeGenModule &CGM, StringRef GlobalName,
3584                       CharUnits Alignment) {
3585   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3586   unsigned AddrSpace = 0;
3587   if (CGM.getLangOpts().OpenCL)
3588     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3589 
3590   llvm::Module &M = CGM.getModule();
3591   // Create a global variable for this string
3592   auto *GV = new llvm::GlobalVariable(
3593       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3594       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3595   GV->setAlignment(Alignment.getQuantity());
3596   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3597   if (GV->isWeakForLinker()) {
3598     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3599     GV->setComdat(M.getOrInsertComdat(GV->getName()));
3600   }
3601 
3602   return GV;
3603 }
3604 
3605 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3606 /// constant array for the given string literal.
3607 ConstantAddress
3608 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3609                                                   StringRef Name) {
3610   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3611 
3612   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3613   llvm::GlobalVariable **Entry = nullptr;
3614   if (!LangOpts.WritableStrings) {
3615     Entry = &ConstantStringMap[C];
3616     if (auto GV = *Entry) {
3617       if (Alignment.getQuantity() > GV->getAlignment())
3618         GV->setAlignment(Alignment.getQuantity());
3619       return ConstantAddress(GV, Alignment);
3620     }
3621   }
3622 
3623   SmallString<256> MangledNameBuffer;
3624   StringRef GlobalVariableName;
3625   llvm::GlobalValue::LinkageTypes LT;
3626 
3627   // Mangle the string literal if the ABI allows for it.  However, we cannot
3628   // do this if  we are compiling with ASan or -fwritable-strings because they
3629   // rely on strings having normal linkage.
3630   if (!LangOpts.WritableStrings &&
3631       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3632       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3633     llvm::raw_svector_ostream Out(MangledNameBuffer);
3634     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3635 
3636     LT = llvm::GlobalValue::LinkOnceODRLinkage;
3637     GlobalVariableName = MangledNameBuffer;
3638   } else {
3639     LT = llvm::GlobalValue::PrivateLinkage;
3640     GlobalVariableName = Name;
3641   }
3642 
3643   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3644   if (Entry)
3645     *Entry = GV;
3646 
3647   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3648                                   QualType());
3649   return ConstantAddress(GV, Alignment);
3650 }
3651 
3652 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3653 /// array for the given ObjCEncodeExpr node.
3654 ConstantAddress
3655 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3656   std::string Str;
3657   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3658 
3659   return GetAddrOfConstantCString(Str);
3660 }
3661 
3662 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3663 /// the literal and a terminating '\0' character.
3664 /// The result has pointer to array type.
3665 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3666     const std::string &Str, const char *GlobalName) {
3667   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3668   CharUnits Alignment =
3669     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3670 
3671   llvm::Constant *C =
3672       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3673 
3674   // Don't share any string literals if strings aren't constant.
3675   llvm::GlobalVariable **Entry = nullptr;
3676   if (!LangOpts.WritableStrings) {
3677     Entry = &ConstantStringMap[C];
3678     if (auto GV = *Entry) {
3679       if (Alignment.getQuantity() > GV->getAlignment())
3680         GV->setAlignment(Alignment.getQuantity());
3681       return ConstantAddress(GV, Alignment);
3682     }
3683   }
3684 
3685   // Get the default prefix if a name wasn't specified.
3686   if (!GlobalName)
3687     GlobalName = ".str";
3688   // Create a global variable for this.
3689   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3690                                   GlobalName, Alignment);
3691   if (Entry)
3692     *Entry = GV;
3693   return ConstantAddress(GV, Alignment);
3694 }
3695 
3696 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3697     const MaterializeTemporaryExpr *E, const Expr *Init) {
3698   assert((E->getStorageDuration() == SD_Static ||
3699           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3700   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3701 
3702   // If we're not materializing a subobject of the temporary, keep the
3703   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3704   QualType MaterializedType = Init->getType();
3705   if (Init == E->GetTemporaryExpr())
3706     MaterializedType = E->getType();
3707 
3708   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3709 
3710   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3711     return ConstantAddress(Slot, Align);
3712 
3713   // FIXME: If an externally-visible declaration extends multiple temporaries,
3714   // we need to give each temporary the same name in every translation unit (and
3715   // we also need to make the temporaries externally-visible).
3716   SmallString<256> Name;
3717   llvm::raw_svector_ostream Out(Name);
3718   getCXXABI().getMangleContext().mangleReferenceTemporary(
3719       VD, E->getManglingNumber(), Out);
3720 
3721   APValue *Value = nullptr;
3722   if (E->getStorageDuration() == SD_Static) {
3723     // We might have a cached constant initializer for this temporary. Note
3724     // that this might have a different value from the value computed by
3725     // evaluating the initializer if the surrounding constant expression
3726     // modifies the temporary.
3727     Value = getContext().getMaterializedTemporaryValue(E, false);
3728     if (Value && Value->isUninit())
3729       Value = nullptr;
3730   }
3731 
3732   // Try evaluating it now, it might have a constant initializer.
3733   Expr::EvalResult EvalResult;
3734   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3735       !EvalResult.hasSideEffects())
3736     Value = &EvalResult.Val;
3737 
3738   llvm::Constant *InitialValue = nullptr;
3739   bool Constant = false;
3740   llvm::Type *Type;
3741   if (Value) {
3742     // The temporary has a constant initializer, use it.
3743     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3744     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3745     Type = InitialValue->getType();
3746   } else {
3747     // No initializer, the initialization will be provided when we
3748     // initialize the declaration which performed lifetime extension.
3749     Type = getTypes().ConvertTypeForMem(MaterializedType);
3750   }
3751 
3752   // Create a global variable for this lifetime-extended temporary.
3753   llvm::GlobalValue::LinkageTypes Linkage =
3754       getLLVMLinkageVarDefinition(VD, Constant);
3755   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3756     const VarDecl *InitVD;
3757     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3758         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3759       // Temporaries defined inside a class get linkonce_odr linkage because the
3760       // class can be defined in multipe translation units.
3761       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3762     } else {
3763       // There is no need for this temporary to have external linkage if the
3764       // VarDecl has external linkage.
3765       Linkage = llvm::GlobalVariable::InternalLinkage;
3766     }
3767   }
3768   unsigned AddrSpace =
3769       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
3770   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
3771   auto *GV = new llvm::GlobalVariable(
3772       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3773       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
3774   setGlobalVisibility(GV, VD);
3775   GV->setAlignment(Align.getQuantity());
3776   if (supportsCOMDAT() && GV->isWeakForLinker())
3777     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3778   if (VD->getTLSKind())
3779     setTLSMode(GV, *VD);
3780   llvm::Constant *CV = GV;
3781   if (AddrSpace != LangAS::Default)
3782     CV = getTargetCodeGenInfo().performAddrSpaceCast(
3783         *this, GV, AddrSpace, LangAS::Default,
3784         Type->getPointerTo(
3785             getContext().getTargetAddressSpace(LangAS::Default)));
3786   MaterializedGlobalTemporaryMap[E] = CV;
3787   return ConstantAddress(CV, Align);
3788 }
3789 
3790 /// EmitObjCPropertyImplementations - Emit information for synthesized
3791 /// properties for an implementation.
3792 void CodeGenModule::EmitObjCPropertyImplementations(const
3793                                                     ObjCImplementationDecl *D) {
3794   for (const auto *PID : D->property_impls()) {
3795     // Dynamic is just for type-checking.
3796     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3797       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3798 
3799       // Determine which methods need to be implemented, some may have
3800       // been overridden. Note that ::isPropertyAccessor is not the method
3801       // we want, that just indicates if the decl came from a
3802       // property. What we want to know is if the method is defined in
3803       // this implementation.
3804       if (!D->getInstanceMethod(PD->getGetterName()))
3805         CodeGenFunction(*this).GenerateObjCGetter(
3806                                  const_cast<ObjCImplementationDecl *>(D), PID);
3807       if (!PD->isReadOnly() &&
3808           !D->getInstanceMethod(PD->getSetterName()))
3809         CodeGenFunction(*this).GenerateObjCSetter(
3810                                  const_cast<ObjCImplementationDecl *>(D), PID);
3811     }
3812   }
3813 }
3814 
3815 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3816   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3817   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3818        ivar; ivar = ivar->getNextIvar())
3819     if (ivar->getType().isDestructedType())
3820       return true;
3821 
3822   return false;
3823 }
3824 
3825 static bool AllTrivialInitializers(CodeGenModule &CGM,
3826                                    ObjCImplementationDecl *D) {
3827   CodeGenFunction CGF(CGM);
3828   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3829        E = D->init_end(); B != E; ++B) {
3830     CXXCtorInitializer *CtorInitExp = *B;
3831     Expr *Init = CtorInitExp->getInit();
3832     if (!CGF.isTrivialInitializer(Init))
3833       return false;
3834   }
3835   return true;
3836 }
3837 
3838 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3839 /// for an implementation.
3840 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3841   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3842   if (needsDestructMethod(D)) {
3843     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3844     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3845     ObjCMethodDecl *DTORMethod =
3846       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3847                              cxxSelector, getContext().VoidTy, nullptr, D,
3848                              /*isInstance=*/true, /*isVariadic=*/false,
3849                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3850                              /*isDefined=*/false, ObjCMethodDecl::Required);
3851     D->addInstanceMethod(DTORMethod);
3852     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3853     D->setHasDestructors(true);
3854   }
3855 
3856   // If the implementation doesn't have any ivar initializers, we don't need
3857   // a .cxx_construct.
3858   if (D->getNumIvarInitializers() == 0 ||
3859       AllTrivialInitializers(*this, D))
3860     return;
3861 
3862   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3863   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3864   // The constructor returns 'self'.
3865   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3866                                                 D->getLocation(),
3867                                                 D->getLocation(),
3868                                                 cxxSelector,
3869                                                 getContext().getObjCIdType(),
3870                                                 nullptr, D, /*isInstance=*/true,
3871                                                 /*isVariadic=*/false,
3872                                                 /*isPropertyAccessor=*/true,
3873                                                 /*isImplicitlyDeclared=*/true,
3874                                                 /*isDefined=*/false,
3875                                                 ObjCMethodDecl::Required);
3876   D->addInstanceMethod(CTORMethod);
3877   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3878   D->setHasNonZeroConstructors(true);
3879 }
3880 
3881 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3882 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3883   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3884       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3885     ErrorUnsupported(LSD, "linkage spec");
3886     return;
3887   }
3888 
3889   EmitDeclContext(LSD);
3890 }
3891 
3892 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3893   for (auto *I : DC->decls()) {
3894     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3895     // are themselves considered "top-level", so EmitTopLevelDecl on an
3896     // ObjCImplDecl does not recursively visit them. We need to do that in
3897     // case they're nested inside another construct (LinkageSpecDecl /
3898     // ExportDecl) that does stop them from being considered "top-level".
3899     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3900       for (auto *M : OID->methods())
3901         EmitTopLevelDecl(M);
3902     }
3903 
3904     EmitTopLevelDecl(I);
3905   }
3906 }
3907 
3908 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3909 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3910   // Ignore dependent declarations.
3911   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3912     return;
3913 
3914   switch (D->getKind()) {
3915   case Decl::CXXConversion:
3916   case Decl::CXXMethod:
3917   case Decl::Function:
3918     // Skip function templates
3919     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3920         cast<FunctionDecl>(D)->isLateTemplateParsed())
3921       return;
3922 
3923     EmitGlobal(cast<FunctionDecl>(D));
3924     // Always provide some coverage mapping
3925     // even for the functions that aren't emitted.
3926     AddDeferredUnusedCoverageMapping(D);
3927     break;
3928 
3929   case Decl::CXXDeductionGuide:
3930     // Function-like, but does not result in code emission.
3931     break;
3932 
3933   case Decl::Var:
3934   case Decl::Decomposition:
3935     // Skip variable templates
3936     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3937       return;
3938     LLVM_FALLTHROUGH;
3939   case Decl::VarTemplateSpecialization:
3940     EmitGlobal(cast<VarDecl>(D));
3941     if (auto *DD = dyn_cast<DecompositionDecl>(D))
3942       for (auto *B : DD->bindings())
3943         if (auto *HD = B->getHoldingVar())
3944           EmitGlobal(HD);
3945     break;
3946 
3947   // Indirect fields from global anonymous structs and unions can be
3948   // ignored; only the actual variable requires IR gen support.
3949   case Decl::IndirectField:
3950     break;
3951 
3952   // C++ Decls
3953   case Decl::Namespace:
3954     EmitDeclContext(cast<NamespaceDecl>(D));
3955     break;
3956   case Decl::CXXRecord:
3957     if (DebugInfo) {
3958       if (auto *ES = D->getASTContext().getExternalSource())
3959         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3960           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3961     }
3962     // Emit any static data members, they may be definitions.
3963     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3964       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3965         EmitTopLevelDecl(I);
3966     break;
3967     // No code generation needed.
3968   case Decl::UsingShadow:
3969   case Decl::ClassTemplate:
3970   case Decl::VarTemplate:
3971   case Decl::VarTemplatePartialSpecialization:
3972   case Decl::FunctionTemplate:
3973   case Decl::TypeAliasTemplate:
3974   case Decl::Block:
3975   case Decl::Empty:
3976     break;
3977   case Decl::Using:          // using X; [C++]
3978     if (CGDebugInfo *DI = getModuleDebugInfo())
3979         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3980     return;
3981   case Decl::NamespaceAlias:
3982     if (CGDebugInfo *DI = getModuleDebugInfo())
3983         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3984     return;
3985   case Decl::UsingDirective: // using namespace X; [C++]
3986     if (CGDebugInfo *DI = getModuleDebugInfo())
3987       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3988     return;
3989   case Decl::CXXConstructor:
3990     // Skip function templates
3991     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3992         cast<FunctionDecl>(D)->isLateTemplateParsed())
3993       return;
3994 
3995     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3996     break;
3997   case Decl::CXXDestructor:
3998     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3999       return;
4000     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4001     break;
4002 
4003   case Decl::StaticAssert:
4004     // Nothing to do.
4005     break;
4006 
4007   // Objective-C Decls
4008 
4009   // Forward declarations, no (immediate) code generation.
4010   case Decl::ObjCInterface:
4011   case Decl::ObjCCategory:
4012     break;
4013 
4014   case Decl::ObjCProtocol: {
4015     auto *Proto = cast<ObjCProtocolDecl>(D);
4016     if (Proto->isThisDeclarationADefinition())
4017       ObjCRuntime->GenerateProtocol(Proto);
4018     break;
4019   }
4020 
4021   case Decl::ObjCCategoryImpl:
4022     // Categories have properties but don't support synthesize so we
4023     // can ignore them here.
4024     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4025     break;
4026 
4027   case Decl::ObjCImplementation: {
4028     auto *OMD = cast<ObjCImplementationDecl>(D);
4029     EmitObjCPropertyImplementations(OMD);
4030     EmitObjCIvarInitializations(OMD);
4031     ObjCRuntime->GenerateClass(OMD);
4032     // Emit global variable debug information.
4033     if (CGDebugInfo *DI = getModuleDebugInfo())
4034       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4035         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4036             OMD->getClassInterface()), OMD->getLocation());
4037     break;
4038   }
4039   case Decl::ObjCMethod: {
4040     auto *OMD = cast<ObjCMethodDecl>(D);
4041     // If this is not a prototype, emit the body.
4042     if (OMD->getBody())
4043       CodeGenFunction(*this).GenerateObjCMethod(OMD);
4044     break;
4045   }
4046   case Decl::ObjCCompatibleAlias:
4047     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4048     break;
4049 
4050   case Decl::PragmaComment: {
4051     const auto *PCD = cast<PragmaCommentDecl>(D);
4052     switch (PCD->getCommentKind()) {
4053     case PCK_Unknown:
4054       llvm_unreachable("unexpected pragma comment kind");
4055     case PCK_Linker:
4056       AppendLinkerOptions(PCD->getArg());
4057       break;
4058     case PCK_Lib:
4059       AddDependentLib(PCD->getArg());
4060       break;
4061     case PCK_Compiler:
4062     case PCK_ExeStr:
4063     case PCK_User:
4064       break; // We ignore all of these.
4065     }
4066     break;
4067   }
4068 
4069   case Decl::PragmaDetectMismatch: {
4070     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4071     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4072     break;
4073   }
4074 
4075   case Decl::LinkageSpec:
4076     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4077     break;
4078 
4079   case Decl::FileScopeAsm: {
4080     // File-scope asm is ignored during device-side CUDA compilation.
4081     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4082       break;
4083     // File-scope asm is ignored during device-side OpenMP compilation.
4084     if (LangOpts.OpenMPIsDevice)
4085       break;
4086     auto *AD = cast<FileScopeAsmDecl>(D);
4087     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4088     break;
4089   }
4090 
4091   case Decl::Import: {
4092     auto *Import = cast<ImportDecl>(D);
4093 
4094     // If we've already imported this module, we're done.
4095     if (!ImportedModules.insert(Import->getImportedModule()))
4096       break;
4097 
4098     // Emit debug information for direct imports.
4099     if (!Import->getImportedOwningModule()) {
4100       if (CGDebugInfo *DI = getModuleDebugInfo())
4101         DI->EmitImportDecl(*Import);
4102     }
4103 
4104     // Find all of the submodules and emit the module initializers.
4105     llvm::SmallPtrSet<clang::Module *, 16> Visited;
4106     SmallVector<clang::Module *, 16> Stack;
4107     Visited.insert(Import->getImportedModule());
4108     Stack.push_back(Import->getImportedModule());
4109 
4110     while (!Stack.empty()) {
4111       clang::Module *Mod = Stack.pop_back_val();
4112       if (!EmittedModuleInitializers.insert(Mod).second)
4113         continue;
4114 
4115       for (auto *D : Context.getModuleInitializers(Mod))
4116         EmitTopLevelDecl(D);
4117 
4118       // Visit the submodules of this module.
4119       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4120                                              SubEnd = Mod->submodule_end();
4121            Sub != SubEnd; ++Sub) {
4122         // Skip explicit children; they need to be explicitly imported to emit
4123         // the initializers.
4124         if ((*Sub)->IsExplicit)
4125           continue;
4126 
4127         if (Visited.insert(*Sub).second)
4128           Stack.push_back(*Sub);
4129       }
4130     }
4131     break;
4132   }
4133 
4134   case Decl::Export:
4135     EmitDeclContext(cast<ExportDecl>(D));
4136     break;
4137 
4138   case Decl::OMPThreadPrivate:
4139     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4140     break;
4141 
4142   case Decl::ClassTemplateSpecialization: {
4143     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4144     if (DebugInfo &&
4145         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4146         Spec->hasDefinition())
4147       DebugInfo->completeTemplateDefinition(*Spec);
4148     break;
4149   }
4150 
4151   case Decl::OMPDeclareReduction:
4152     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4153     break;
4154 
4155   default:
4156     // Make sure we handled everything we should, every other kind is a
4157     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4158     // function. Need to recode Decl::Kind to do that easily.
4159     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4160     break;
4161   }
4162 }
4163 
4164 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4165   // Do we need to generate coverage mapping?
4166   if (!CodeGenOpts.CoverageMapping)
4167     return;
4168   switch (D->getKind()) {
4169   case Decl::CXXConversion:
4170   case Decl::CXXMethod:
4171   case Decl::Function:
4172   case Decl::ObjCMethod:
4173   case Decl::CXXConstructor:
4174   case Decl::CXXDestructor: {
4175     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4176       return;
4177     auto I = DeferredEmptyCoverageMappingDecls.find(D);
4178     if (I == DeferredEmptyCoverageMappingDecls.end())
4179       DeferredEmptyCoverageMappingDecls[D] = true;
4180     break;
4181   }
4182   default:
4183     break;
4184   };
4185 }
4186 
4187 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4188   // Do we need to generate coverage mapping?
4189   if (!CodeGenOpts.CoverageMapping)
4190     return;
4191   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4192     if (Fn->isTemplateInstantiation())
4193       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4194   }
4195   auto I = DeferredEmptyCoverageMappingDecls.find(D);
4196   if (I == DeferredEmptyCoverageMappingDecls.end())
4197     DeferredEmptyCoverageMappingDecls[D] = false;
4198   else
4199     I->second = false;
4200 }
4201 
4202 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4203   std::vector<const Decl *> DeferredDecls;
4204   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4205     if (!I.second)
4206       continue;
4207     DeferredDecls.push_back(I.first);
4208   }
4209   // Sort the declarations by their location to make sure that the tests get a
4210   // predictable order for the coverage mapping for the unused declarations.
4211   if (CodeGenOpts.DumpCoverageMapping)
4212     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4213               [] (const Decl *LHS, const Decl *RHS) {
4214       return LHS->getLocStart() < RHS->getLocStart();
4215     });
4216   for (const auto *D : DeferredDecls) {
4217     switch (D->getKind()) {
4218     case Decl::CXXConversion:
4219     case Decl::CXXMethod:
4220     case Decl::Function:
4221     case Decl::ObjCMethod: {
4222       CodeGenPGO PGO(*this);
4223       GlobalDecl GD(cast<FunctionDecl>(D));
4224       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4225                                   getFunctionLinkage(GD));
4226       break;
4227     }
4228     case Decl::CXXConstructor: {
4229       CodeGenPGO PGO(*this);
4230       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4231       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4232                                   getFunctionLinkage(GD));
4233       break;
4234     }
4235     case Decl::CXXDestructor: {
4236       CodeGenPGO PGO(*this);
4237       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4238       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4239                                   getFunctionLinkage(GD));
4240       break;
4241     }
4242     default:
4243       break;
4244     };
4245   }
4246 }
4247 
4248 /// Turns the given pointer into a constant.
4249 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4250                                           const void *Ptr) {
4251   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4252   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4253   return llvm::ConstantInt::get(i64, PtrInt);
4254 }
4255 
4256 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4257                                    llvm::NamedMDNode *&GlobalMetadata,
4258                                    GlobalDecl D,
4259                                    llvm::GlobalValue *Addr) {
4260   if (!GlobalMetadata)
4261     GlobalMetadata =
4262       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4263 
4264   // TODO: should we report variant information for ctors/dtors?
4265   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4266                            llvm::ConstantAsMetadata::get(GetPointerConstant(
4267                                CGM.getLLVMContext(), D.getDecl()))};
4268   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4269 }
4270 
4271 /// For each function which is declared within an extern "C" region and marked
4272 /// as 'used', but has internal linkage, create an alias from the unmangled
4273 /// name to the mangled name if possible. People expect to be able to refer
4274 /// to such functions with an unmangled name from inline assembly within the
4275 /// same translation unit.
4276 void CodeGenModule::EmitStaticExternCAliases() {
4277   // Don't do anything if we're generating CUDA device code -- the NVPTX
4278   // assembly target doesn't support aliases.
4279   if (Context.getTargetInfo().getTriple().isNVPTX())
4280     return;
4281   for (auto &I : StaticExternCValues) {
4282     IdentifierInfo *Name = I.first;
4283     llvm::GlobalValue *Val = I.second;
4284     if (Val && !getModule().getNamedValue(Name->getName()))
4285       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4286   }
4287 }
4288 
4289 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4290                                              GlobalDecl &Result) const {
4291   auto Res = Manglings.find(MangledName);
4292   if (Res == Manglings.end())
4293     return false;
4294   Result = Res->getValue();
4295   return true;
4296 }
4297 
4298 /// Emits metadata nodes associating all the global values in the
4299 /// current module with the Decls they came from.  This is useful for
4300 /// projects using IR gen as a subroutine.
4301 ///
4302 /// Since there's currently no way to associate an MDNode directly
4303 /// with an llvm::GlobalValue, we create a global named metadata
4304 /// with the name 'clang.global.decl.ptrs'.
4305 void CodeGenModule::EmitDeclMetadata() {
4306   llvm::NamedMDNode *GlobalMetadata = nullptr;
4307 
4308   for (auto &I : MangledDeclNames) {
4309     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4310     // Some mangled names don't necessarily have an associated GlobalValue
4311     // in this module, e.g. if we mangled it for DebugInfo.
4312     if (Addr)
4313       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4314   }
4315 }
4316 
4317 /// Emits metadata nodes for all the local variables in the current
4318 /// function.
4319 void CodeGenFunction::EmitDeclMetadata() {
4320   if (LocalDeclMap.empty()) return;
4321 
4322   llvm::LLVMContext &Context = getLLVMContext();
4323 
4324   // Find the unique metadata ID for this name.
4325   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4326 
4327   llvm::NamedMDNode *GlobalMetadata = nullptr;
4328 
4329   for (auto &I : LocalDeclMap) {
4330     const Decl *D = I.first;
4331     llvm::Value *Addr = I.second.getPointer();
4332     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4333       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4334       Alloca->setMetadata(
4335           DeclPtrKind, llvm::MDNode::get(
4336                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4337     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4338       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4339       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4340     }
4341   }
4342 }
4343 
4344 void CodeGenModule::EmitVersionIdentMetadata() {
4345   llvm::NamedMDNode *IdentMetadata =
4346     TheModule.getOrInsertNamedMetadata("llvm.ident");
4347   std::string Version = getClangFullVersion();
4348   llvm::LLVMContext &Ctx = TheModule.getContext();
4349 
4350   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4351   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4352 }
4353 
4354 void CodeGenModule::EmitTargetMetadata() {
4355   // Warning, new MangledDeclNames may be appended within this loop.
4356   // We rely on MapVector insertions adding new elements to the end
4357   // of the container.
4358   // FIXME: Move this loop into the one target that needs it, and only
4359   // loop over those declarations for which we couldn't emit the target
4360   // metadata when we emitted the declaration.
4361   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4362     auto Val = *(MangledDeclNames.begin() + I);
4363     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4364     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4365     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4366   }
4367 }
4368 
4369 void CodeGenModule::EmitCoverageFile() {
4370   if (getCodeGenOpts().CoverageDataFile.empty() &&
4371       getCodeGenOpts().CoverageNotesFile.empty())
4372     return;
4373 
4374   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4375   if (!CUNode)
4376     return;
4377 
4378   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4379   llvm::LLVMContext &Ctx = TheModule.getContext();
4380   auto *CoverageDataFile =
4381       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4382   auto *CoverageNotesFile =
4383       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4384   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4385     llvm::MDNode *CU = CUNode->getOperand(i);
4386     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4387     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4388   }
4389 }
4390 
4391 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4392   // Sema has checked that all uuid strings are of the form
4393   // "12345678-1234-1234-1234-1234567890ab".
4394   assert(Uuid.size() == 36);
4395   for (unsigned i = 0; i < 36; ++i) {
4396     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4397     else                                         assert(isHexDigit(Uuid[i]));
4398   }
4399 
4400   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4401   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4402 
4403   llvm::Constant *Field3[8];
4404   for (unsigned Idx = 0; Idx < 8; ++Idx)
4405     Field3[Idx] = llvm::ConstantInt::get(
4406         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4407 
4408   llvm::Constant *Fields[4] = {
4409     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4410     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4411     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4412     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4413   };
4414 
4415   return llvm::ConstantStruct::getAnon(Fields);
4416 }
4417 
4418 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4419                                                        bool ForEH) {
4420   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4421   // FIXME: should we even be calling this method if RTTI is disabled
4422   // and it's not for EH?
4423   if (!ForEH && !getLangOpts().RTTI)
4424     return llvm::Constant::getNullValue(Int8PtrTy);
4425 
4426   if (ForEH && Ty->isObjCObjectPointerType() &&
4427       LangOpts.ObjCRuntime.isGNUFamily())
4428     return ObjCRuntime->GetEHType(Ty);
4429 
4430   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4431 }
4432 
4433 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4434   for (auto RefExpr : D->varlists()) {
4435     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4436     bool PerformInit =
4437         VD->getAnyInitializer() &&
4438         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4439                                                         /*ForRef=*/false);
4440 
4441     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4442     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4443             VD, Addr, RefExpr->getLocStart(), PerformInit))
4444       CXXGlobalInits.push_back(InitFunction);
4445   }
4446 }
4447 
4448 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4449   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4450   if (InternalId)
4451     return InternalId;
4452 
4453   if (isExternallyVisible(T->getLinkage())) {
4454     std::string OutName;
4455     llvm::raw_string_ostream Out(OutName);
4456     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4457 
4458     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4459   } else {
4460     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4461                                            llvm::ArrayRef<llvm::Metadata *>());
4462   }
4463 
4464   return InternalId;
4465 }
4466 
4467 /// Returns whether this module needs the "all-vtables" type identifier.
4468 bool CodeGenModule::NeedAllVtablesTypeId() const {
4469   // Returns true if at least one of vtable-based CFI checkers is enabled and
4470   // is not in the trapping mode.
4471   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4472            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4473           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4474            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4475           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4476            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4477           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4478            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4479 }
4480 
4481 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4482                                           CharUnits Offset,
4483                                           const CXXRecordDecl *RD) {
4484   llvm::Metadata *MD =
4485       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4486   VTable->addTypeMetadata(Offset.getQuantity(), MD);
4487 
4488   if (CodeGenOpts.SanitizeCfiCrossDso)
4489     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4490       VTable->addTypeMetadata(Offset.getQuantity(),
4491                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4492 
4493   if (NeedAllVtablesTypeId()) {
4494     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4495     VTable->addTypeMetadata(Offset.getQuantity(), MD);
4496   }
4497 }
4498 
4499 // Fills in the supplied string map with the set of target features for the
4500 // passed in function.
4501 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4502                                           const FunctionDecl *FD) {
4503   StringRef TargetCPU = Target.getTargetOpts().CPU;
4504   if (const auto *TD = FD->getAttr<TargetAttr>()) {
4505     // If we have a TargetAttr build up the feature map based on that.
4506     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4507 
4508     // Make a copy of the features as passed on the command line into the
4509     // beginning of the additional features from the function to override.
4510     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
4511                             Target.getTargetOpts().FeaturesAsWritten.begin(),
4512                             Target.getTargetOpts().FeaturesAsWritten.end());
4513 
4514     if (ParsedAttr.Architecture != "")
4515       TargetCPU = ParsedAttr.Architecture ;
4516 
4517     // Now populate the feature map, first with the TargetCPU which is either
4518     // the default or a new one from the target attribute string. Then we'll use
4519     // the passed in features (FeaturesAsWritten) along with the new ones from
4520     // the attribute.
4521     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4522                           ParsedAttr.Features);
4523   } else {
4524     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4525                           Target.getTargetOpts().Features);
4526   }
4527 }
4528 
4529 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4530   if (!SanStats)
4531     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4532 
4533   return *SanStats;
4534 }
4535 llvm::Value *
4536 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4537                                                   CodeGenFunction &CGF) {
4538   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4539   auto SamplerT = getOpenCLRuntime().getSamplerType();
4540   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4541   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4542                                 "__translate_sampler_initializer"),
4543                                 {C});
4544 }
4545