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