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