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