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