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