xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 284ebe237ff277625caa23192f159a1be7d0a6d4)
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   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization as part
1994   // of their declaration."
1995   if (getLangOpts().CPlusPlus && getLangOpts().CUDAIsDevice
1996       && D->hasAttr<CUDASharedAttr>()) {
1997     if (InitExpr) {
1998       Error(D->getLocation(),
1999             "__shared__ variable cannot have an initialization.");
2000     }
2001     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2002   } else if (!InitExpr) {
2003     // This is a tentative definition; tentative definitions are
2004     // implicitly initialized with { 0 }.
2005     //
2006     // Note that tentative definitions are only emitted at the end of
2007     // a translation unit, so they should never have incomplete
2008     // type. In addition, EmitTentativeDefinition makes sure that we
2009     // never attempt to emit a tentative definition if a real one
2010     // exists. A use may still exists, however, so we still may need
2011     // to do a RAUW.
2012     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2013     Init = EmitNullConstant(D->getType());
2014   } else {
2015     initializedGlobalDecl = GlobalDecl(D);
2016     Init = EmitConstantInit(*InitDecl);
2017 
2018     if (!Init) {
2019       QualType T = InitExpr->getType();
2020       if (D->getType()->isReferenceType())
2021         T = D->getType();
2022 
2023       if (getLangOpts().CPlusPlus) {
2024         Init = EmitNullConstant(T);
2025         NeedsGlobalCtor = true;
2026       } else {
2027         ErrorUnsupported(D, "static initializer");
2028         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2029       }
2030     } else {
2031       // We don't need an initializer, so remove the entry for the delayed
2032       // initializer position (just in case this entry was delayed) if we
2033       // also don't need to register a destructor.
2034       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2035         DelayedCXXInitPosition.erase(D);
2036     }
2037   }
2038 
2039   llvm::Type* InitType = Init->getType();
2040   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
2041 
2042   // Strip off a bitcast if we got one back.
2043   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2044     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2045            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2046            // All zero index gep.
2047            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2048     Entry = CE->getOperand(0);
2049   }
2050 
2051   // Entry is now either a Function or GlobalVariable.
2052   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2053 
2054   // We have a definition after a declaration with the wrong type.
2055   // We must make a new GlobalVariable* and update everything that used OldGV
2056   // (a declaration or tentative definition) with the new GlobalVariable*
2057   // (which will be a definition).
2058   //
2059   // This happens if there is a prototype for a global (e.g.
2060   // "extern int x[];") and then a definition of a different type (e.g.
2061   // "int x[10];"). This also happens when an initializer has a different type
2062   // from the type of the global (this happens with unions).
2063   if (!GV ||
2064       GV->getType()->getElementType() != InitType ||
2065       GV->getType()->getAddressSpace() !=
2066        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2067 
2068     // Move the old entry aside so that we'll create a new one.
2069     Entry->setName(StringRef());
2070 
2071     // Make a new global with the correct type, this is now guaranteed to work.
2072     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
2073 
2074     // Replace all uses of the old global with the new global
2075     llvm::Constant *NewPtrForOldDecl =
2076         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2077     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2078 
2079     // Erase the old global, since it is no longer used.
2080     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2081   }
2082 
2083   MaybeHandleStaticInExternC(D, GV);
2084 
2085   if (D->hasAttr<AnnotateAttr>())
2086     AddGlobalAnnotations(D, GV);
2087 
2088   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2089   // the device. [...]"
2090   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2091   // __device__, declares a variable that: [...]
2092   // Is accessible from all the threads within the grid and from the host
2093   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2094   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2095   if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice &&
2096       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) {
2097     GV->setExternallyInitialized(true);
2098   }
2099   GV->setInitializer(Init);
2100 
2101   // If it is safe to mark the global 'constant', do so now.
2102   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2103                   isTypeConstant(D->getType(), true));
2104 
2105   // If it is in a read-only section, mark it 'constant'.
2106   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2107     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2108     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2109       GV->setConstant(true);
2110   }
2111 
2112   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2113 
2114   // Set the llvm linkage type as appropriate.
2115   llvm::GlobalValue::LinkageTypes Linkage =
2116       getLLVMLinkageVarDefinition(D, GV->isConstant());
2117 
2118   // On Darwin, the backing variable for a C++11 thread_local variable always
2119   // has internal linkage; all accesses should just be calls to the
2120   // Itanium-specified entry point, which has the normal linkage of the
2121   // variable.
2122   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2123       Context.getTargetInfo().getTriple().isMacOSX())
2124     Linkage = llvm::GlobalValue::InternalLinkage;
2125 
2126   GV->setLinkage(Linkage);
2127   if (D->hasAttr<DLLImportAttr>())
2128     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2129   else if (D->hasAttr<DLLExportAttr>())
2130     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2131   else
2132     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2133 
2134   if (Linkage == llvm::GlobalVariable::CommonLinkage)
2135     // common vars aren't constant even if declared const.
2136     GV->setConstant(false);
2137 
2138   setNonAliasAttributes(D, GV);
2139 
2140   if (D->getTLSKind() && !GV->isThreadLocal()) {
2141     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2142       CXXThreadLocals.push_back(std::make_pair(D, GV));
2143     setTLSMode(GV, *D);
2144   }
2145 
2146   maybeSetTrivialComdat(*D, *GV);
2147 
2148   // Emit the initializer function if necessary.
2149   if (NeedsGlobalCtor || NeedsGlobalDtor)
2150     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2151 
2152   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2153 
2154   // Emit global variable debug information.
2155   if (CGDebugInfo *DI = getModuleDebugInfo())
2156     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2157       DI->EmitGlobalVariable(GV, D);
2158 }
2159 
2160 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2161                                       CodeGenModule &CGM, const VarDecl *D,
2162                                       bool NoCommon) {
2163   // Don't give variables common linkage if -fno-common was specified unless it
2164   // was overridden by a NoCommon attribute.
2165   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2166     return true;
2167 
2168   // C11 6.9.2/2:
2169   //   A declaration of an identifier for an object that has file scope without
2170   //   an initializer, and without a storage-class specifier or with the
2171   //   storage-class specifier static, constitutes a tentative definition.
2172   if (D->getInit() || D->hasExternalStorage())
2173     return true;
2174 
2175   // A variable cannot be both common and exist in a section.
2176   if (D->hasAttr<SectionAttr>())
2177     return true;
2178 
2179   // Thread local vars aren't considered common linkage.
2180   if (D->getTLSKind())
2181     return true;
2182 
2183   // Tentative definitions marked with WeakImportAttr are true definitions.
2184   if (D->hasAttr<WeakImportAttr>())
2185     return true;
2186 
2187   // A variable cannot be both common and exist in a comdat.
2188   if (shouldBeInCOMDAT(CGM, *D))
2189     return true;
2190 
2191   // Declarations with a required alignment do not have common linakge in MSVC
2192   // mode.
2193   if (Context.getLangOpts().MSVCCompat) {
2194     if (D->hasAttr<AlignedAttr>())
2195       return true;
2196     QualType VarType = D->getType();
2197     if (Context.isAlignmentRequired(VarType))
2198       return true;
2199 
2200     if (const auto *RT = VarType->getAs<RecordType>()) {
2201       const RecordDecl *RD = RT->getDecl();
2202       for (const FieldDecl *FD : RD->fields()) {
2203         if (FD->isBitField())
2204           continue;
2205         if (FD->hasAttr<AlignedAttr>())
2206           return true;
2207         if (Context.isAlignmentRequired(FD->getType()))
2208           return true;
2209       }
2210     }
2211   }
2212 
2213   return false;
2214 }
2215 
2216 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2217     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2218   if (Linkage == GVA_Internal)
2219     return llvm::Function::InternalLinkage;
2220 
2221   if (D->hasAttr<WeakAttr>()) {
2222     if (IsConstantVariable)
2223       return llvm::GlobalVariable::WeakODRLinkage;
2224     else
2225       return llvm::GlobalVariable::WeakAnyLinkage;
2226   }
2227 
2228   // We are guaranteed to have a strong definition somewhere else,
2229   // so we can use available_externally linkage.
2230   if (Linkage == GVA_AvailableExternally)
2231     return llvm::Function::AvailableExternallyLinkage;
2232 
2233   // Note that Apple's kernel linker doesn't support symbol
2234   // coalescing, so we need to avoid linkonce and weak linkages there.
2235   // Normally, this means we just map to internal, but for explicit
2236   // instantiations we'll map to external.
2237 
2238   // In C++, the compiler has to emit a definition in every translation unit
2239   // that references the function.  We should use linkonce_odr because
2240   // a) if all references in this translation unit are optimized away, we
2241   // don't need to codegen it.  b) if the function persists, it needs to be
2242   // merged with other definitions. c) C++ has the ODR, so we know the
2243   // definition is dependable.
2244   if (Linkage == GVA_DiscardableODR)
2245     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2246                                             : llvm::Function::InternalLinkage;
2247 
2248   // An explicit instantiation of a template has weak linkage, since
2249   // explicit instantiations can occur in multiple translation units
2250   // and must all be equivalent. However, we are not allowed to
2251   // throw away these explicit instantiations.
2252   if (Linkage == GVA_StrongODR)
2253     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2254                                             : llvm::Function::ExternalLinkage;
2255 
2256   // C++ doesn't have tentative definitions and thus cannot have common
2257   // linkage.
2258   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2259       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2260                                  CodeGenOpts.NoCommon))
2261     return llvm::GlobalVariable::CommonLinkage;
2262 
2263   // selectany symbols are externally visible, so use weak instead of
2264   // linkonce.  MSVC optimizes away references to const selectany globals, so
2265   // all definitions should be the same and ODR linkage should be used.
2266   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2267   if (D->hasAttr<SelectAnyAttr>())
2268     return llvm::GlobalVariable::WeakODRLinkage;
2269 
2270   // Otherwise, we have strong external linkage.
2271   assert(Linkage == GVA_StrongExternal);
2272   return llvm::GlobalVariable::ExternalLinkage;
2273 }
2274 
2275 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2276     const VarDecl *VD, bool IsConstant) {
2277   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2278   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2279 }
2280 
2281 /// Replace the uses of a function that was declared with a non-proto type.
2282 /// We want to silently drop extra arguments from call sites
2283 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2284                                           llvm::Function *newFn) {
2285   // Fast path.
2286   if (old->use_empty()) return;
2287 
2288   llvm::Type *newRetTy = newFn->getReturnType();
2289   SmallVector<llvm::Value*, 4> newArgs;
2290 
2291   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2292          ui != ue; ) {
2293     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2294     llvm::User *user = use->getUser();
2295 
2296     // Recognize and replace uses of bitcasts.  Most calls to
2297     // unprototyped functions will use bitcasts.
2298     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2299       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2300         replaceUsesOfNonProtoConstant(bitcast, newFn);
2301       continue;
2302     }
2303 
2304     // Recognize calls to the function.
2305     llvm::CallSite callSite(user);
2306     if (!callSite) continue;
2307     if (!callSite.isCallee(&*use)) continue;
2308 
2309     // If the return types don't match exactly, then we can't
2310     // transform this call unless it's dead.
2311     if (callSite->getType() != newRetTy && !callSite->use_empty())
2312       continue;
2313 
2314     // Get the call site's attribute list.
2315     SmallVector<llvm::AttributeSet, 8> newAttrs;
2316     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2317 
2318     // Collect any return attributes from the call.
2319     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2320       newAttrs.push_back(
2321         llvm::AttributeSet::get(newFn->getContext(),
2322                                 oldAttrs.getRetAttributes()));
2323 
2324     // If the function was passed too few arguments, don't transform.
2325     unsigned newNumArgs = newFn->arg_size();
2326     if (callSite.arg_size() < newNumArgs) continue;
2327 
2328     // If extra arguments were passed, we silently drop them.
2329     // If any of the types mismatch, we don't transform.
2330     unsigned argNo = 0;
2331     bool dontTransform = false;
2332     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2333            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2334       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2335         dontTransform = true;
2336         break;
2337       }
2338 
2339       // Add any parameter attributes.
2340       if (oldAttrs.hasAttributes(argNo + 1))
2341         newAttrs.
2342           push_back(llvm::
2343                     AttributeSet::get(newFn->getContext(),
2344                                       oldAttrs.getParamAttributes(argNo + 1)));
2345     }
2346     if (dontTransform)
2347       continue;
2348 
2349     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2350       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2351                                                  oldAttrs.getFnAttributes()));
2352 
2353     // Okay, we can transform this.  Create the new call instruction and copy
2354     // over the required information.
2355     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2356 
2357     llvm::CallSite newCall;
2358     if (callSite.isCall()) {
2359       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2360                                        callSite.getInstruction());
2361     } else {
2362       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2363       newCall = llvm::InvokeInst::Create(newFn,
2364                                          oldInvoke->getNormalDest(),
2365                                          oldInvoke->getUnwindDest(),
2366                                          newArgs, "",
2367                                          callSite.getInstruction());
2368     }
2369     newArgs.clear(); // for the next iteration
2370 
2371     if (!newCall->getType()->isVoidTy())
2372       newCall->takeName(callSite.getInstruction());
2373     newCall.setAttributes(
2374                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2375     newCall.setCallingConv(callSite.getCallingConv());
2376 
2377     // Finally, remove the old call, replacing any uses with the new one.
2378     if (!callSite->use_empty())
2379       callSite->replaceAllUsesWith(newCall.getInstruction());
2380 
2381     // Copy debug location attached to CI.
2382     if (callSite->getDebugLoc())
2383       newCall->setDebugLoc(callSite->getDebugLoc());
2384     callSite->eraseFromParent();
2385   }
2386 }
2387 
2388 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2389 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2390 /// existing call uses of the old function in the module, this adjusts them to
2391 /// call the new function directly.
2392 ///
2393 /// This is not just a cleanup: the always_inline pass requires direct calls to
2394 /// functions to be able to inline them.  If there is a bitcast in the way, it
2395 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2396 /// run at -O0.
2397 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2398                                                       llvm::Function *NewFn) {
2399   // If we're redefining a global as a function, don't transform it.
2400   if (!isa<llvm::Function>(Old)) return;
2401 
2402   replaceUsesOfNonProtoConstant(Old, NewFn);
2403 }
2404 
2405 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2406   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2407   // If we have a definition, this might be a deferred decl. If the
2408   // instantiation is explicit, make sure we emit it at the end.
2409   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2410     GetAddrOfGlobalVar(VD);
2411 
2412   EmitTopLevelDecl(VD);
2413 }
2414 
2415 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2416                                                  llvm::GlobalValue *GV) {
2417   const auto *D = cast<FunctionDecl>(GD.getDecl());
2418 
2419   // Compute the function info and LLVM type.
2420   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2421   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2422 
2423   // Get or create the prototype for the function.
2424   if (!GV) {
2425     llvm::Constant *C =
2426         GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
2427 
2428     // Strip off a bitcast if we got one back.
2429     if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2430       assert(CE->getOpcode() == llvm::Instruction::BitCast);
2431       GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2432     } else {
2433       GV = cast<llvm::GlobalValue>(C);
2434     }
2435   }
2436 
2437   if (!GV->isDeclaration()) {
2438     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2439     GlobalDecl OldGD = Manglings.lookup(GV->getName());
2440     if (auto *Prev = OldGD.getDecl())
2441       getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
2442     return;
2443   }
2444 
2445   if (GV->getType()->getElementType() != Ty) {
2446     // If the types mismatch then we have to rewrite the definition.
2447     assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
2448 
2449     // F is the Function* for the one with the wrong type, we must make a new
2450     // Function* and update everything that used F (a declaration) with the new
2451     // Function* (which will be a definition).
2452     //
2453     // This happens if there is a prototype for a function
2454     // (e.g. "int f()") and then a definition of a different type
2455     // (e.g. "int f(int x)").  Move the old function aside so that it
2456     // doesn't interfere with GetAddrOfFunction.
2457     GV->setName(StringRef());
2458     auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2459 
2460     // This might be an implementation of a function without a
2461     // prototype, in which case, try to do special replacement of
2462     // calls which match the new prototype.  The really key thing here
2463     // is that we also potentially drop arguments from the call site
2464     // so as to make a direct call, which makes the inliner happier
2465     // and suppresses a number of optimizer warnings (!) about
2466     // dropping arguments.
2467     if (!GV->use_empty()) {
2468       ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2469       GV->removeDeadConstantUsers();
2470     }
2471 
2472     // Replace uses of F with the Function we will endow with a body.
2473     if (!GV->use_empty()) {
2474       llvm::Constant *NewPtrForOldDecl =
2475           llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2476       GV->replaceAllUsesWith(NewPtrForOldDecl);
2477     }
2478 
2479     // Ok, delete the old function now, which is dead.
2480     GV->eraseFromParent();
2481 
2482     GV = NewFn;
2483   }
2484 
2485   // We need to set linkage and visibility on the function before
2486   // generating code for it because various parts of IR generation
2487   // want to propagate this information down (e.g. to local static
2488   // declarations).
2489   auto *Fn = cast<llvm::Function>(GV);
2490   setFunctionLinkage(GD, Fn);
2491   setFunctionDLLStorageClass(GD, Fn);
2492 
2493   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2494   setGlobalVisibility(Fn, D);
2495 
2496   MaybeHandleStaticInExternC(D, Fn);
2497 
2498   maybeSetTrivialComdat(*D, *Fn);
2499 
2500   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2501 
2502   setFunctionDefinitionAttributes(D, Fn);
2503   SetLLVMFunctionAttributesForDefinition(D, Fn);
2504 
2505   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2506     AddGlobalCtor(Fn, CA->getPriority());
2507   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2508     AddGlobalDtor(Fn, DA->getPriority());
2509   if (D->hasAttr<AnnotateAttr>())
2510     AddGlobalAnnotations(D, Fn);
2511 }
2512 
2513 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2514   const auto *D = cast<ValueDecl>(GD.getDecl());
2515   const AliasAttr *AA = D->getAttr<AliasAttr>();
2516   assert(AA && "Not an alias?");
2517 
2518   StringRef MangledName = getMangledName(GD);
2519 
2520   // If there is a definition in the module, then it wins over the alias.
2521   // This is dubious, but allow it to be safe.  Just ignore the alias.
2522   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2523   if (Entry && !Entry->isDeclaration())
2524     return;
2525 
2526   Aliases.push_back(GD);
2527 
2528   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2529 
2530   // Create a reference to the named value.  This ensures that it is emitted
2531   // if a deferred decl.
2532   llvm::Constant *Aliasee;
2533   if (isa<llvm::FunctionType>(DeclTy))
2534     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2535                                       /*ForVTable=*/false);
2536   else
2537     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2538                                     llvm::PointerType::getUnqual(DeclTy),
2539                                     /*D=*/nullptr);
2540 
2541   // Create the new alias itself, but don't set a name yet.
2542   auto *GA = llvm::GlobalAlias::create(
2543       cast<llvm::PointerType>(Aliasee->getType()),
2544       llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2545 
2546   if (Entry) {
2547     if (GA->getAliasee() == Entry) {
2548       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2549       return;
2550     }
2551 
2552     assert(Entry->isDeclaration());
2553 
2554     // If there is a declaration in the module, then we had an extern followed
2555     // by the alias, as in:
2556     //   extern int test6();
2557     //   ...
2558     //   int test6() __attribute__((alias("test7")));
2559     //
2560     // Remove it and replace uses of it with the alias.
2561     GA->takeName(Entry);
2562 
2563     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2564                                                           Entry->getType()));
2565     Entry->eraseFromParent();
2566   } else {
2567     GA->setName(MangledName);
2568   }
2569 
2570   // Set attributes which are particular to an alias; this is a
2571   // specialization of the attributes which may be set on a global
2572   // variable/function.
2573   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2574       D->isWeakImported()) {
2575     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2576   }
2577 
2578   if (const auto *VD = dyn_cast<VarDecl>(D))
2579     if (VD->getTLSKind())
2580       setTLSMode(GA, *VD);
2581 
2582   setAliasAttributes(D, GA);
2583 }
2584 
2585 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2586                                             ArrayRef<llvm::Type*> Tys) {
2587   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2588                                          Tys);
2589 }
2590 
2591 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2592 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2593                          const StringLiteral *Literal, bool TargetIsLSB,
2594                          bool &IsUTF16, unsigned &StringLength) {
2595   StringRef String = Literal->getString();
2596   unsigned NumBytes = String.size();
2597 
2598   // Check for simple case.
2599   if (!Literal->containsNonAsciiOrNull()) {
2600     StringLength = NumBytes;
2601     return *Map.insert(std::make_pair(String, nullptr)).first;
2602   }
2603 
2604   // Otherwise, convert the UTF8 literals into a string of shorts.
2605   IsUTF16 = true;
2606 
2607   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2608   const UTF8 *FromPtr = (const UTF8 *)String.data();
2609   UTF16 *ToPtr = &ToBuf[0];
2610 
2611   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2612                            &ToPtr, ToPtr + NumBytes,
2613                            strictConversion);
2614 
2615   // ConvertUTF8toUTF16 returns the length in ToPtr.
2616   StringLength = ToPtr - &ToBuf[0];
2617 
2618   // Add an explicit null.
2619   *ToPtr = 0;
2620   return *Map.insert(std::make_pair(
2621                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2622                                    (StringLength + 1) * 2),
2623                          nullptr)).first;
2624 }
2625 
2626 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2627 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2628                        const StringLiteral *Literal, unsigned &StringLength) {
2629   StringRef String = Literal->getString();
2630   StringLength = String.size();
2631   return *Map.insert(std::make_pair(String, nullptr)).first;
2632 }
2633 
2634 llvm::Constant *
2635 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2636   unsigned StringLength = 0;
2637   bool isUTF16 = false;
2638   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2639       GetConstantCFStringEntry(CFConstantStringMap, Literal,
2640                                getDataLayout().isLittleEndian(), isUTF16,
2641                                StringLength);
2642 
2643   if (auto *C = Entry.second)
2644     return C;
2645 
2646   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2647   llvm::Constant *Zeros[] = { Zero, Zero };
2648   llvm::Value *V;
2649 
2650   // If we don't already have it, get __CFConstantStringClassReference.
2651   if (!CFConstantStringClassRef) {
2652     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2653     Ty = llvm::ArrayType::get(Ty, 0);
2654     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2655                                            "__CFConstantStringClassReference");
2656     // Decay array -> ptr
2657     V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2658     CFConstantStringClassRef = V;
2659   }
2660   else
2661     V = CFConstantStringClassRef;
2662 
2663   QualType CFTy = getContext().getCFConstantStringType();
2664 
2665   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2666 
2667   llvm::Constant *Fields[4];
2668 
2669   // Class pointer.
2670   Fields[0] = cast<llvm::ConstantExpr>(V);
2671 
2672   // Flags.
2673   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2674   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2675     llvm::ConstantInt::get(Ty, 0x07C8);
2676 
2677   // String pointer.
2678   llvm::Constant *C = nullptr;
2679   if (isUTF16) {
2680     ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2681         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2682         Entry.first().size() / 2);
2683     C = llvm::ConstantDataArray::get(VMContext, Arr);
2684   } else {
2685     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2686   }
2687 
2688   // Note: -fwritable-strings doesn't make the backing store strings of
2689   // CFStrings writable. (See <rdar://problem/10657500>)
2690   auto *GV =
2691       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2692                                llvm::GlobalValue::PrivateLinkage, C, ".str");
2693   GV->setUnnamedAddr(true);
2694   // Don't enforce the target's minimum global alignment, since the only use
2695   // of the string is via this class initializer.
2696   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2697   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2698   // that changes the section it ends in, which surprises ld64.
2699   if (isUTF16) {
2700     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2701     GV->setAlignment(Align.getQuantity());
2702     GV->setSection("__TEXT,__ustring");
2703   } else {
2704     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2705     GV->setAlignment(Align.getQuantity());
2706     GV->setSection("__TEXT,__cstring,cstring_literals");
2707   }
2708 
2709   // String.
2710   Fields[2] =
2711       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2712 
2713   if (isUTF16)
2714     // Cast the UTF16 string to the correct type.
2715     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2716 
2717   // String length.
2718   Ty = getTypes().ConvertType(getContext().LongTy);
2719   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2720 
2721   // The struct.
2722   C = llvm::ConstantStruct::get(STy, Fields);
2723   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2724                                 llvm::GlobalVariable::PrivateLinkage, C,
2725                                 "_unnamed_cfstring_");
2726   GV->setSection("__DATA,__cfstring");
2727   Entry.second = GV;
2728 
2729   return GV;
2730 }
2731 
2732 llvm::GlobalVariable *
2733 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2734   unsigned StringLength = 0;
2735   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2736       GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2737 
2738   if (auto *C = Entry.second)
2739     return C;
2740 
2741   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2742   llvm::Constant *Zeros[] = { Zero, Zero };
2743   llvm::Value *V;
2744   // If we don't already have it, get _NSConstantStringClassReference.
2745   if (!ConstantStringClassRef) {
2746     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2747     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2748     llvm::Constant *GV;
2749     if (LangOpts.ObjCRuntime.isNonFragile()) {
2750       std::string str =
2751         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2752                             : "OBJC_CLASS_$_" + StringClass;
2753       GV = getObjCRuntime().GetClassGlobal(str);
2754       // Make sure the result is of the correct type.
2755       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2756       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2757       ConstantStringClassRef = V;
2758     } else {
2759       std::string str =
2760         StringClass.empty() ? "_NSConstantStringClassReference"
2761                             : "_" + StringClass + "ClassReference";
2762       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2763       GV = CreateRuntimeVariable(PTy, str);
2764       // Decay array -> ptr
2765       V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
2766       ConstantStringClassRef = V;
2767     }
2768   } else
2769     V = ConstantStringClassRef;
2770 
2771   if (!NSConstantStringType) {
2772     // Construct the type for a constant NSString.
2773     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2774     D->startDefinition();
2775 
2776     QualType FieldTypes[3];
2777 
2778     // const int *isa;
2779     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2780     // const char *str;
2781     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2782     // unsigned int length;
2783     FieldTypes[2] = Context.UnsignedIntTy;
2784 
2785     // Create fields
2786     for (unsigned i = 0; i < 3; ++i) {
2787       FieldDecl *Field = FieldDecl::Create(Context, D,
2788                                            SourceLocation(),
2789                                            SourceLocation(), nullptr,
2790                                            FieldTypes[i], /*TInfo=*/nullptr,
2791                                            /*BitWidth=*/nullptr,
2792                                            /*Mutable=*/false,
2793                                            ICIS_NoInit);
2794       Field->setAccess(AS_public);
2795       D->addDecl(Field);
2796     }
2797 
2798     D->completeDefinition();
2799     QualType NSTy = Context.getTagDeclType(D);
2800     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2801   }
2802 
2803   llvm::Constant *Fields[3];
2804 
2805   // Class pointer.
2806   Fields[0] = cast<llvm::ConstantExpr>(V);
2807 
2808   // String pointer.
2809   llvm::Constant *C =
2810       llvm::ConstantDataArray::getString(VMContext, Entry.first());
2811 
2812   llvm::GlobalValue::LinkageTypes Linkage;
2813   bool isConstant;
2814   Linkage = llvm::GlobalValue::PrivateLinkage;
2815   isConstant = !LangOpts.WritableStrings;
2816 
2817   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2818                                       Linkage, C, ".str");
2819   GV->setUnnamedAddr(true);
2820   // Don't enforce the target's minimum global alignment, since the only use
2821   // of the string is via this class initializer.
2822   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2823   GV->setAlignment(Align.getQuantity());
2824   Fields[1] =
2825       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2826 
2827   // String length.
2828   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2829   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2830 
2831   // The struct.
2832   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2833   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2834                                 llvm::GlobalVariable::PrivateLinkage, C,
2835                                 "_unnamed_nsstring_");
2836   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2837   const char *NSStringNonFragileABISection =
2838       "__DATA,__objc_stringobj,regular,no_dead_strip";
2839   // FIXME. Fix section.
2840   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2841                      ? NSStringNonFragileABISection
2842                      : NSStringSection);
2843   Entry.second = GV;
2844 
2845   return GV;
2846 }
2847 
2848 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2849   if (ObjCFastEnumerationStateType.isNull()) {
2850     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2851     D->startDefinition();
2852 
2853     QualType FieldTypes[] = {
2854       Context.UnsignedLongTy,
2855       Context.getPointerType(Context.getObjCIdType()),
2856       Context.getPointerType(Context.UnsignedLongTy),
2857       Context.getConstantArrayType(Context.UnsignedLongTy,
2858                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2859     };
2860 
2861     for (size_t i = 0; i < 4; ++i) {
2862       FieldDecl *Field = FieldDecl::Create(Context,
2863                                            D,
2864                                            SourceLocation(),
2865                                            SourceLocation(), nullptr,
2866                                            FieldTypes[i], /*TInfo=*/nullptr,
2867                                            /*BitWidth=*/nullptr,
2868                                            /*Mutable=*/false,
2869                                            ICIS_NoInit);
2870       Field->setAccess(AS_public);
2871       D->addDecl(Field);
2872     }
2873 
2874     D->completeDefinition();
2875     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2876   }
2877 
2878   return ObjCFastEnumerationStateType;
2879 }
2880 
2881 llvm::Constant *
2882 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2883   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2884 
2885   // Don't emit it as the address of the string, emit the string data itself
2886   // as an inline array.
2887   if (E->getCharByteWidth() == 1) {
2888     SmallString<64> Str(E->getString());
2889 
2890     // Resize the string to the right size, which is indicated by its type.
2891     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2892     Str.resize(CAT->getSize().getZExtValue());
2893     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2894   }
2895 
2896   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2897   llvm::Type *ElemTy = AType->getElementType();
2898   unsigned NumElements = AType->getNumElements();
2899 
2900   // Wide strings have either 2-byte or 4-byte elements.
2901   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2902     SmallVector<uint16_t, 32> Elements;
2903     Elements.reserve(NumElements);
2904 
2905     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2906       Elements.push_back(E->getCodeUnit(i));
2907     Elements.resize(NumElements);
2908     return llvm::ConstantDataArray::get(VMContext, Elements);
2909   }
2910 
2911   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2912   SmallVector<uint32_t, 32> Elements;
2913   Elements.reserve(NumElements);
2914 
2915   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2916     Elements.push_back(E->getCodeUnit(i));
2917   Elements.resize(NumElements);
2918   return llvm::ConstantDataArray::get(VMContext, Elements);
2919 }
2920 
2921 static llvm::GlobalVariable *
2922 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
2923                       CodeGenModule &CGM, StringRef GlobalName,
2924                       unsigned Alignment) {
2925   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2926   unsigned AddrSpace = 0;
2927   if (CGM.getLangOpts().OpenCL)
2928     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2929 
2930   llvm::Module &M = CGM.getModule();
2931   // Create a global variable for this string
2932   auto *GV = new llvm::GlobalVariable(
2933       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
2934       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2935   GV->setAlignment(Alignment);
2936   GV->setUnnamedAddr(true);
2937   if (GV->isWeakForLinker()) {
2938     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
2939     GV->setComdat(M.getOrInsertComdat(GV->getName()));
2940   }
2941 
2942   return GV;
2943 }
2944 
2945 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2946 /// constant array for the given string literal.
2947 llvm::GlobalVariable *
2948 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
2949                                                   StringRef Name) {
2950   auto Alignment =
2951       getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
2952 
2953   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2954   llvm::GlobalVariable **Entry = nullptr;
2955   if (!LangOpts.WritableStrings) {
2956     Entry = &ConstantStringMap[C];
2957     if (auto GV = *Entry) {
2958       if (Alignment > GV->getAlignment())
2959         GV->setAlignment(Alignment);
2960       return GV;
2961     }
2962   }
2963 
2964   SmallString<256> MangledNameBuffer;
2965   StringRef GlobalVariableName;
2966   llvm::GlobalValue::LinkageTypes LT;
2967 
2968   // Mangle the string literal if the ABI allows for it.  However, we cannot
2969   // do this if  we are compiling with ASan or -fwritable-strings because they
2970   // rely on strings having normal linkage.
2971   if (!LangOpts.WritableStrings &&
2972       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
2973       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2974     llvm::raw_svector_ostream Out(MangledNameBuffer);
2975     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2976 
2977     LT = llvm::GlobalValue::LinkOnceODRLinkage;
2978     GlobalVariableName = MangledNameBuffer;
2979   } else {
2980     LT = llvm::GlobalValue::PrivateLinkage;
2981     GlobalVariableName = Name;
2982   }
2983 
2984   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
2985   if (Entry)
2986     *Entry = GV;
2987 
2988   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
2989                                   QualType());
2990   return GV;
2991 }
2992 
2993 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2994 /// array for the given ObjCEncodeExpr node.
2995 llvm::GlobalVariable *
2996 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2997   std::string Str;
2998   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2999 
3000   return GetAddrOfConstantCString(Str);
3001 }
3002 
3003 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3004 /// the literal and a terminating '\0' character.
3005 /// The result has pointer to array type.
3006 llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
3007     const std::string &Str, const char *GlobalName, unsigned Alignment) {
3008   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3009   if (Alignment == 0) {
3010     Alignment = getContext()
3011                     .getAlignOfGlobalVarInChars(getContext().CharTy)
3012                     .getQuantity();
3013   }
3014 
3015   llvm::Constant *C =
3016       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3017 
3018   // Don't share any string literals if strings aren't constant.
3019   llvm::GlobalVariable **Entry = nullptr;
3020   if (!LangOpts.WritableStrings) {
3021     Entry = &ConstantStringMap[C];
3022     if (auto GV = *Entry) {
3023       if (Alignment > GV->getAlignment())
3024         GV->setAlignment(Alignment);
3025       return GV;
3026     }
3027   }
3028 
3029   // Get the default prefix if a name wasn't specified.
3030   if (!GlobalName)
3031     GlobalName = ".str";
3032   // Create a global variable for this.
3033   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3034                                   GlobalName, Alignment);
3035   if (Entry)
3036     *Entry = GV;
3037   return GV;
3038 }
3039 
3040 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
3041     const MaterializeTemporaryExpr *E, const Expr *Init) {
3042   assert((E->getStorageDuration() == SD_Static ||
3043           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3044   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3045 
3046   // If we're not materializing a subobject of the temporary, keep the
3047   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3048   QualType MaterializedType = Init->getType();
3049   if (Init == E->GetTemporaryExpr())
3050     MaterializedType = E->getType();
3051 
3052   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3053     return Slot;
3054 
3055   // FIXME: If an externally-visible declaration extends multiple temporaries,
3056   // we need to give each temporary the same name in every translation unit (and
3057   // we also need to make the temporaries externally-visible).
3058   SmallString<256> Name;
3059   llvm::raw_svector_ostream Out(Name);
3060   getCXXABI().getMangleContext().mangleReferenceTemporary(
3061       VD, E->getManglingNumber(), Out);
3062 
3063   APValue *Value = nullptr;
3064   if (E->getStorageDuration() == SD_Static) {
3065     // We might have a cached constant initializer for this temporary. Note
3066     // that this might have a different value from the value computed by
3067     // evaluating the initializer if the surrounding constant expression
3068     // modifies the temporary.
3069     Value = getContext().getMaterializedTemporaryValue(E, false);
3070     if (Value && Value->isUninit())
3071       Value = nullptr;
3072   }
3073 
3074   // Try evaluating it now, it might have a constant initializer.
3075   Expr::EvalResult EvalResult;
3076   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3077       !EvalResult.hasSideEffects())
3078     Value = &EvalResult.Val;
3079 
3080   llvm::Constant *InitialValue = nullptr;
3081   bool Constant = false;
3082   llvm::Type *Type;
3083   if (Value) {
3084     // The temporary has a constant initializer, use it.
3085     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3086     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3087     Type = InitialValue->getType();
3088   } else {
3089     // No initializer, the initialization will be provided when we
3090     // initialize the declaration which performed lifetime extension.
3091     Type = getTypes().ConvertTypeForMem(MaterializedType);
3092   }
3093 
3094   // Create a global variable for this lifetime-extended temporary.
3095   llvm::GlobalValue::LinkageTypes Linkage =
3096       getLLVMLinkageVarDefinition(VD, Constant);
3097   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3098     const VarDecl *InitVD;
3099     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3100         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3101       // Temporaries defined inside a class get linkonce_odr linkage because the
3102       // class can be defined in multipe translation units.
3103       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3104     } else {
3105       // There is no need for this temporary to have external linkage if the
3106       // VarDecl has external linkage.
3107       Linkage = llvm::GlobalVariable::InternalLinkage;
3108     }
3109   }
3110   unsigned AddrSpace = GetGlobalVarAddressSpace(
3111       VD, getContext().getTargetAddressSpace(MaterializedType));
3112   auto *GV = new llvm::GlobalVariable(
3113       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3114       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3115       AddrSpace);
3116   setGlobalVisibility(GV, VD);
3117   GV->setAlignment(
3118       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
3119   if (supportsCOMDAT() && GV->isWeakForLinker())
3120     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3121   if (VD->getTLSKind())
3122     setTLSMode(GV, *VD);
3123   MaterializedGlobalTemporaryMap[E] = GV;
3124   return GV;
3125 }
3126 
3127 /// EmitObjCPropertyImplementations - Emit information for synthesized
3128 /// properties for an implementation.
3129 void CodeGenModule::EmitObjCPropertyImplementations(const
3130                                                     ObjCImplementationDecl *D) {
3131   for (const auto *PID : D->property_impls()) {
3132     // Dynamic is just for type-checking.
3133     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3134       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3135 
3136       // Determine which methods need to be implemented, some may have
3137       // been overridden. Note that ::isPropertyAccessor is not the method
3138       // we want, that just indicates if the decl came from a
3139       // property. What we want to know is if the method is defined in
3140       // this implementation.
3141       if (!D->getInstanceMethod(PD->getGetterName()))
3142         CodeGenFunction(*this).GenerateObjCGetter(
3143                                  const_cast<ObjCImplementationDecl *>(D), PID);
3144       if (!PD->isReadOnly() &&
3145           !D->getInstanceMethod(PD->getSetterName()))
3146         CodeGenFunction(*this).GenerateObjCSetter(
3147                                  const_cast<ObjCImplementationDecl *>(D), PID);
3148     }
3149   }
3150 }
3151 
3152 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3153   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3154   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3155        ivar; ivar = ivar->getNextIvar())
3156     if (ivar->getType().isDestructedType())
3157       return true;
3158 
3159   return false;
3160 }
3161 
3162 static bool AllTrivialInitializers(CodeGenModule &CGM,
3163                                    ObjCImplementationDecl *D) {
3164   CodeGenFunction CGF(CGM);
3165   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3166        E = D->init_end(); B != E; ++B) {
3167     CXXCtorInitializer *CtorInitExp = *B;
3168     Expr *Init = CtorInitExp->getInit();
3169     if (!CGF.isTrivialInitializer(Init))
3170       return false;
3171   }
3172   return true;
3173 }
3174 
3175 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3176 /// for an implementation.
3177 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3178   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3179   if (needsDestructMethod(D)) {
3180     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3181     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3182     ObjCMethodDecl *DTORMethod =
3183       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3184                              cxxSelector, getContext().VoidTy, nullptr, D,
3185                              /*isInstance=*/true, /*isVariadic=*/false,
3186                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3187                              /*isDefined=*/false, ObjCMethodDecl::Required);
3188     D->addInstanceMethod(DTORMethod);
3189     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3190     D->setHasDestructors(true);
3191   }
3192 
3193   // If the implementation doesn't have any ivar initializers, we don't need
3194   // a .cxx_construct.
3195   if (D->getNumIvarInitializers() == 0 ||
3196       AllTrivialInitializers(*this, D))
3197     return;
3198 
3199   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3200   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3201   // The constructor returns 'self'.
3202   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3203                                                 D->getLocation(),
3204                                                 D->getLocation(),
3205                                                 cxxSelector,
3206                                                 getContext().getObjCIdType(),
3207                                                 nullptr, D, /*isInstance=*/true,
3208                                                 /*isVariadic=*/false,
3209                                                 /*isPropertyAccessor=*/true,
3210                                                 /*isImplicitlyDeclared=*/true,
3211                                                 /*isDefined=*/false,
3212                                                 ObjCMethodDecl::Required);
3213   D->addInstanceMethod(CTORMethod);
3214   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3215   D->setHasNonZeroConstructors(true);
3216 }
3217 
3218 /// EmitNamespace - Emit all declarations in a namespace.
3219 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3220   for (auto *I : ND->decls()) {
3221     if (const auto *VD = dyn_cast<VarDecl>(I))
3222       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3223           VD->getTemplateSpecializationKind() != TSK_Undeclared)
3224         continue;
3225     EmitTopLevelDecl(I);
3226   }
3227 }
3228 
3229 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3230 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3231   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3232       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3233     ErrorUnsupported(LSD, "linkage spec");
3234     return;
3235   }
3236 
3237   for (auto *I : LSD->decls()) {
3238     // Meta-data for ObjC class includes references to implemented methods.
3239     // Generate class's method definitions first.
3240     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3241       for (auto *M : OID->methods())
3242         EmitTopLevelDecl(M);
3243     }
3244     EmitTopLevelDecl(I);
3245   }
3246 }
3247 
3248 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3249 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3250   // Ignore dependent declarations.
3251   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3252     return;
3253 
3254   switch (D->getKind()) {
3255   case Decl::CXXConversion:
3256   case Decl::CXXMethod:
3257   case Decl::Function:
3258     // Skip function templates
3259     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3260         cast<FunctionDecl>(D)->isLateTemplateParsed())
3261       return;
3262 
3263     EmitGlobal(cast<FunctionDecl>(D));
3264     // Always provide some coverage mapping
3265     // even for the functions that aren't emitted.
3266     AddDeferredUnusedCoverageMapping(D);
3267     break;
3268 
3269   case Decl::Var:
3270     // Skip variable templates
3271     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3272       return;
3273   case Decl::VarTemplateSpecialization:
3274     EmitGlobal(cast<VarDecl>(D));
3275     break;
3276 
3277   // Indirect fields from global anonymous structs and unions can be
3278   // ignored; only the actual variable requires IR gen support.
3279   case Decl::IndirectField:
3280     break;
3281 
3282   // C++ Decls
3283   case Decl::Namespace:
3284     EmitNamespace(cast<NamespaceDecl>(D));
3285     break;
3286     // No code generation needed.
3287   case Decl::UsingShadow:
3288   case Decl::ClassTemplate:
3289   case Decl::VarTemplate:
3290   case Decl::VarTemplatePartialSpecialization:
3291   case Decl::FunctionTemplate:
3292   case Decl::TypeAliasTemplate:
3293   case Decl::Block:
3294   case Decl::Empty:
3295     break;
3296   case Decl::Using:          // using X; [C++]
3297     if (CGDebugInfo *DI = getModuleDebugInfo())
3298         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3299     return;
3300   case Decl::NamespaceAlias:
3301     if (CGDebugInfo *DI = getModuleDebugInfo())
3302         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3303     return;
3304   case Decl::UsingDirective: // using namespace X; [C++]
3305     if (CGDebugInfo *DI = getModuleDebugInfo())
3306       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3307     return;
3308   case Decl::CXXConstructor:
3309     // Skip function templates
3310     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3311         cast<FunctionDecl>(D)->isLateTemplateParsed())
3312       return;
3313 
3314     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3315     break;
3316   case Decl::CXXDestructor:
3317     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3318       return;
3319     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3320     break;
3321 
3322   case Decl::StaticAssert:
3323     // Nothing to do.
3324     break;
3325 
3326   // Objective-C Decls
3327 
3328   // Forward declarations, no (immediate) code generation.
3329   case Decl::ObjCInterface:
3330   case Decl::ObjCCategory:
3331     break;
3332 
3333   case Decl::ObjCProtocol: {
3334     auto *Proto = cast<ObjCProtocolDecl>(D);
3335     if (Proto->isThisDeclarationADefinition())
3336       ObjCRuntime->GenerateProtocol(Proto);
3337     break;
3338   }
3339 
3340   case Decl::ObjCCategoryImpl:
3341     // Categories have properties but don't support synthesize so we
3342     // can ignore them here.
3343     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3344     break;
3345 
3346   case Decl::ObjCImplementation: {
3347     auto *OMD = cast<ObjCImplementationDecl>(D);
3348     EmitObjCPropertyImplementations(OMD);
3349     EmitObjCIvarInitializations(OMD);
3350     ObjCRuntime->GenerateClass(OMD);
3351     // Emit global variable debug information.
3352     if (CGDebugInfo *DI = getModuleDebugInfo())
3353       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3354         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3355             OMD->getClassInterface()), OMD->getLocation());
3356     break;
3357   }
3358   case Decl::ObjCMethod: {
3359     auto *OMD = cast<ObjCMethodDecl>(D);
3360     // If this is not a prototype, emit the body.
3361     if (OMD->getBody())
3362       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3363     break;
3364   }
3365   case Decl::ObjCCompatibleAlias:
3366     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3367     break;
3368 
3369   case Decl::LinkageSpec:
3370     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3371     break;
3372 
3373   case Decl::FileScopeAsm: {
3374     // File-scope asm is ignored during device-side CUDA compilation.
3375     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3376       break;
3377     auto *AD = cast<FileScopeAsmDecl>(D);
3378     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3379     break;
3380   }
3381 
3382   case Decl::Import: {
3383     auto *Import = cast<ImportDecl>(D);
3384 
3385     // Ignore import declarations that come from imported modules.
3386     if (Import->getImportedOwningModule())
3387       break;
3388     if (CGDebugInfo *DI = getModuleDebugInfo())
3389       DI->EmitImportDecl(*Import);
3390 
3391     ImportedModules.insert(Import->getImportedModule());
3392     break;
3393   }
3394 
3395   case Decl::OMPThreadPrivate:
3396     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3397     break;
3398 
3399   case Decl::ClassTemplateSpecialization: {
3400     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3401     if (DebugInfo &&
3402         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3403         Spec->hasDefinition())
3404       DebugInfo->completeTemplateDefinition(*Spec);
3405     break;
3406   }
3407 
3408   default:
3409     // Make sure we handled everything we should, every other kind is a
3410     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3411     // function. Need to recode Decl::Kind to do that easily.
3412     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3413     break;
3414   }
3415 }
3416 
3417 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3418   // Do we need to generate coverage mapping?
3419   if (!CodeGenOpts.CoverageMapping)
3420     return;
3421   switch (D->getKind()) {
3422   case Decl::CXXConversion:
3423   case Decl::CXXMethod:
3424   case Decl::Function:
3425   case Decl::ObjCMethod:
3426   case Decl::CXXConstructor:
3427   case Decl::CXXDestructor: {
3428     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3429       return;
3430     auto I = DeferredEmptyCoverageMappingDecls.find(D);
3431     if (I == DeferredEmptyCoverageMappingDecls.end())
3432       DeferredEmptyCoverageMappingDecls[D] = true;
3433     break;
3434   }
3435   default:
3436     break;
3437   };
3438 }
3439 
3440 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3441   // Do we need to generate coverage mapping?
3442   if (!CodeGenOpts.CoverageMapping)
3443     return;
3444   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3445     if (Fn->isTemplateInstantiation())
3446       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3447   }
3448   auto I = DeferredEmptyCoverageMappingDecls.find(D);
3449   if (I == DeferredEmptyCoverageMappingDecls.end())
3450     DeferredEmptyCoverageMappingDecls[D] = false;
3451   else
3452     I->second = false;
3453 }
3454 
3455 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3456   std::vector<const Decl *> DeferredDecls;
3457   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
3458     if (!I.second)
3459       continue;
3460     DeferredDecls.push_back(I.first);
3461   }
3462   // Sort the declarations by their location to make sure that the tests get a
3463   // predictable order for the coverage mapping for the unused declarations.
3464   if (CodeGenOpts.DumpCoverageMapping)
3465     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3466               [] (const Decl *LHS, const Decl *RHS) {
3467       return LHS->getLocStart() < RHS->getLocStart();
3468     });
3469   for (const auto *D : DeferredDecls) {
3470     switch (D->getKind()) {
3471     case Decl::CXXConversion:
3472     case Decl::CXXMethod:
3473     case Decl::Function:
3474     case Decl::ObjCMethod: {
3475       CodeGenPGO PGO(*this);
3476       GlobalDecl GD(cast<FunctionDecl>(D));
3477       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3478                                   getFunctionLinkage(GD));
3479       break;
3480     }
3481     case Decl::CXXConstructor: {
3482       CodeGenPGO PGO(*this);
3483       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3484       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3485                                   getFunctionLinkage(GD));
3486       break;
3487     }
3488     case Decl::CXXDestructor: {
3489       CodeGenPGO PGO(*this);
3490       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3491       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3492                                   getFunctionLinkage(GD));
3493       break;
3494     }
3495     default:
3496       break;
3497     };
3498   }
3499 }
3500 
3501 /// Turns the given pointer into a constant.
3502 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3503                                           const void *Ptr) {
3504   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3505   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3506   return llvm::ConstantInt::get(i64, PtrInt);
3507 }
3508 
3509 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3510                                    llvm::NamedMDNode *&GlobalMetadata,
3511                                    GlobalDecl D,
3512                                    llvm::GlobalValue *Addr) {
3513   if (!GlobalMetadata)
3514     GlobalMetadata =
3515       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3516 
3517   // TODO: should we report variant information for ctors/dtors?
3518   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3519                            llvm::ConstantAsMetadata::get(GetPointerConstant(
3520                                CGM.getLLVMContext(), D.getDecl()))};
3521   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3522 }
3523 
3524 /// For each function which is declared within an extern "C" region and marked
3525 /// as 'used', but has internal linkage, create an alias from the unmangled
3526 /// name to the mangled name if possible. People expect to be able to refer
3527 /// to such functions with an unmangled name from inline assembly within the
3528 /// same translation unit.
3529 void CodeGenModule::EmitStaticExternCAliases() {
3530   for (auto &I : StaticExternCValues) {
3531     IdentifierInfo *Name = I.first;
3532     llvm::GlobalValue *Val = I.second;
3533     if (Val && !getModule().getNamedValue(Name->getName()))
3534       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3535   }
3536 }
3537 
3538 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3539                                              GlobalDecl &Result) const {
3540   auto Res = Manglings.find(MangledName);
3541   if (Res == Manglings.end())
3542     return false;
3543   Result = Res->getValue();
3544   return true;
3545 }
3546 
3547 /// Emits metadata nodes associating all the global values in the
3548 /// current module with the Decls they came from.  This is useful for
3549 /// projects using IR gen as a subroutine.
3550 ///
3551 /// Since there's currently no way to associate an MDNode directly
3552 /// with an llvm::GlobalValue, we create a global named metadata
3553 /// with the name 'clang.global.decl.ptrs'.
3554 void CodeGenModule::EmitDeclMetadata() {
3555   llvm::NamedMDNode *GlobalMetadata = nullptr;
3556 
3557   // StaticLocalDeclMap
3558   for (auto &I : MangledDeclNames) {
3559     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3560     EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3561   }
3562 }
3563 
3564 /// Emits metadata nodes for all the local variables in the current
3565 /// function.
3566 void CodeGenFunction::EmitDeclMetadata() {
3567   if (LocalDeclMap.empty()) return;
3568 
3569   llvm::LLVMContext &Context = getLLVMContext();
3570 
3571   // Find the unique metadata ID for this name.
3572   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3573 
3574   llvm::NamedMDNode *GlobalMetadata = nullptr;
3575 
3576   for (auto &I : LocalDeclMap) {
3577     const Decl *D = I.first;
3578     llvm::Value *Addr = I.second;
3579     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3580       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3581       Alloca->setMetadata(
3582           DeclPtrKind, llvm::MDNode::get(
3583                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3584     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3585       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3586       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3587     }
3588   }
3589 }
3590 
3591 void CodeGenModule::EmitVersionIdentMetadata() {
3592   llvm::NamedMDNode *IdentMetadata =
3593     TheModule.getOrInsertNamedMetadata("llvm.ident");
3594   std::string Version = getClangFullVersion();
3595   llvm::LLVMContext &Ctx = TheModule.getContext();
3596 
3597   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3598   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3599 }
3600 
3601 void CodeGenModule::EmitTargetMetadata() {
3602   // Warning, new MangledDeclNames may be appended within this loop.
3603   // We rely on MapVector insertions adding new elements to the end
3604   // of the container.
3605   // FIXME: Move this loop into the one target that needs it, and only
3606   // loop over those declarations for which we couldn't emit the target
3607   // metadata when we emitted the declaration.
3608   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3609     auto Val = *(MangledDeclNames.begin() + I);
3610     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3611     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3612     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3613   }
3614 }
3615 
3616 void CodeGenModule::EmitCoverageFile() {
3617   if (!getCodeGenOpts().CoverageFile.empty()) {
3618     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3619       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3620       llvm::LLVMContext &Ctx = TheModule.getContext();
3621       llvm::MDString *CoverageFile =
3622           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3623       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3624         llvm::MDNode *CU = CUNode->getOperand(i);
3625         llvm::Metadata *Elts[] = {CoverageFile, CU};
3626         GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3627       }
3628     }
3629   }
3630 }
3631 
3632 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3633   // Sema has checked that all uuid strings are of the form
3634   // "12345678-1234-1234-1234-1234567890ab".
3635   assert(Uuid.size() == 36);
3636   for (unsigned i = 0; i < 36; ++i) {
3637     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3638     else                                         assert(isHexDigit(Uuid[i]));
3639   }
3640 
3641   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3642   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3643 
3644   llvm::Constant *Field3[8];
3645   for (unsigned Idx = 0; Idx < 8; ++Idx)
3646     Field3[Idx] = llvm::ConstantInt::get(
3647         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3648 
3649   llvm::Constant *Fields[4] = {
3650     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3651     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3652     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3653     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3654   };
3655 
3656   return llvm::ConstantStruct::getAnon(Fields);
3657 }
3658 
3659 llvm::Constant *
3660 CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
3661                                             QualType CatchHandlerType) {
3662   return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
3663 }
3664 
3665 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3666                                                        bool ForEH) {
3667   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3668   // FIXME: should we even be calling this method if RTTI is disabled
3669   // and it's not for EH?
3670   if (!ForEH && !getLangOpts().RTTI)
3671     return llvm::Constant::getNullValue(Int8PtrTy);
3672 
3673   if (ForEH && Ty->isObjCObjectPointerType() &&
3674       LangOpts.ObjCRuntime.isGNUFamily())
3675     return ObjCRuntime->GetEHType(Ty);
3676 
3677   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3678 }
3679 
3680 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3681   for (auto RefExpr : D->varlists()) {
3682     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3683     bool PerformInit =
3684         VD->getAnyInitializer() &&
3685         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3686                                                         /*ForRef=*/false);
3687     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
3688             VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
3689       CXXGlobalInits.push_back(InitFunction);
3690   }
3691 }
3692 
3693 llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry(
3694     llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) {
3695   std::string OutName;
3696   llvm::raw_string_ostream Out(OutName);
3697   getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
3698 
3699   llvm::Metadata *BitsetOps[] = {
3700       llvm::MDString::get(getLLVMContext(), Out.str()),
3701       llvm::ConstantAsMetadata::get(VTable),
3702       llvm::ConstantAsMetadata::get(
3703           llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
3704   return llvm::MDTuple::get(getLLVMContext(), BitsetOps);
3705 }
3706