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