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