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