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