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