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