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