xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 7f416cc426384ad1f891addb61d93e7ca1ffa0f2)
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 
946 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
947   assert(!GV->isDeclaration() &&
948          "Only globals with definition can force usage.");
949   LLVMUsed.emplace_back(GV);
950 }
951 
952 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
953   assert(!GV->isDeclaration() &&
954          "Only globals with definition can force usage.");
955   LLVMCompilerUsed.emplace_back(GV);
956 }
957 
958 static void emitUsed(CodeGenModule &CGM, StringRef Name,
959                      std::vector<llvm::WeakVH> &List) {
960   // Don't create llvm.used if there is no need.
961   if (List.empty())
962     return;
963 
964   // Convert List to what ConstantArray needs.
965   SmallVector<llvm::Constant*, 8> UsedArray;
966   UsedArray.resize(List.size());
967   for (unsigned i = 0, e = List.size(); i != e; ++i) {
968     UsedArray[i] =
969         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
970             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
971   }
972 
973   if (UsedArray.empty())
974     return;
975   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
976 
977   auto *GV = new llvm::GlobalVariable(
978       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
979       llvm::ConstantArray::get(ATy, UsedArray), Name);
980 
981   GV->setSection("llvm.metadata");
982 }
983 
984 void CodeGenModule::emitLLVMUsed() {
985   emitUsed(*this, "llvm.used", LLVMUsed);
986   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
987 }
988 
989 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
990   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
991   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
992 }
993 
994 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
995   llvm::SmallString<32> Opt;
996   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
997   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
998   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
999 }
1000 
1001 void CodeGenModule::AddDependentLib(StringRef Lib) {
1002   llvm::SmallString<24> Opt;
1003   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1004   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1005   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1006 }
1007 
1008 /// \brief Add link options implied by the given module, including modules
1009 /// it depends on, using a postorder walk.
1010 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1011                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1012                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1013   // Import this module's parent.
1014   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1015     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1016   }
1017 
1018   // Import this module's dependencies.
1019   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1020     if (Visited.insert(Mod->Imports[I - 1]).second)
1021       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1022   }
1023 
1024   // Add linker options to link against the libraries/frameworks
1025   // described by this module.
1026   llvm::LLVMContext &Context = CGM.getLLVMContext();
1027   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1028     // Link against a framework.  Frameworks are currently Darwin only, so we
1029     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1030     if (Mod->LinkLibraries[I-1].IsFramework) {
1031       llvm::Metadata *Args[2] = {
1032           llvm::MDString::get(Context, "-framework"),
1033           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1034 
1035       Metadata.push_back(llvm::MDNode::get(Context, Args));
1036       continue;
1037     }
1038 
1039     // Link against a library.
1040     llvm::SmallString<24> Opt;
1041     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1042       Mod->LinkLibraries[I-1].Library, Opt);
1043     auto *OptString = llvm::MDString::get(Context, Opt);
1044     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1045   }
1046 }
1047 
1048 void CodeGenModule::EmitModuleLinkOptions() {
1049   // Collect the set of all of the modules we want to visit to emit link
1050   // options, which is essentially the imported modules and all of their
1051   // non-explicit child modules.
1052   llvm::SetVector<clang::Module *> LinkModules;
1053   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1054   SmallVector<clang::Module *, 16> Stack;
1055 
1056   // Seed the stack with imported modules.
1057   for (Module *M : ImportedModules)
1058     if (Visited.insert(M).second)
1059       Stack.push_back(M);
1060 
1061   // Find all of the modules to import, making a little effort to prune
1062   // non-leaf modules.
1063   while (!Stack.empty()) {
1064     clang::Module *Mod = Stack.pop_back_val();
1065 
1066     bool AnyChildren = false;
1067 
1068     // Visit the submodules of this module.
1069     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1070                                         SubEnd = Mod->submodule_end();
1071          Sub != SubEnd; ++Sub) {
1072       // Skip explicit children; they need to be explicitly imported to be
1073       // linked against.
1074       if ((*Sub)->IsExplicit)
1075         continue;
1076 
1077       if (Visited.insert(*Sub).second) {
1078         Stack.push_back(*Sub);
1079         AnyChildren = true;
1080       }
1081     }
1082 
1083     // We didn't find any children, so add this module to the list of
1084     // modules to link against.
1085     if (!AnyChildren) {
1086       LinkModules.insert(Mod);
1087     }
1088   }
1089 
1090   // Add link options for all of the imported modules in reverse topological
1091   // order.  We don't do anything to try to order import link flags with respect
1092   // to linker options inserted by things like #pragma comment().
1093   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1094   Visited.clear();
1095   for (Module *M : LinkModules)
1096     if (Visited.insert(M).second)
1097       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1098   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1099   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1100 
1101   // Add the linker options metadata flag.
1102   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1103                             llvm::MDNode::get(getLLVMContext(),
1104                                               LinkerOptionsMetadata));
1105 }
1106 
1107 void CodeGenModule::EmitDeferred() {
1108   // Emit code for any potentially referenced deferred decls.  Since a
1109   // previously unused static decl may become used during the generation of code
1110   // for a static function, iterate until no changes are made.
1111 
1112   if (!DeferredVTables.empty()) {
1113     EmitDeferredVTables();
1114 
1115     // Emitting a v-table doesn't directly cause more v-tables to
1116     // become deferred, although it can cause functions to be
1117     // emitted that then need those v-tables.
1118     assert(DeferredVTables.empty());
1119   }
1120 
1121   // Stop if we're out of both deferred v-tables and deferred declarations.
1122   if (DeferredDeclsToEmit.empty())
1123     return;
1124 
1125   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1126   // work, it will not interfere with this.
1127   std::vector<DeferredGlobal> CurDeclsToEmit;
1128   CurDeclsToEmit.swap(DeferredDeclsToEmit);
1129 
1130   for (DeferredGlobal &G : CurDeclsToEmit) {
1131     GlobalDecl D = G.GD;
1132     llvm::GlobalValue *GV = G.GV;
1133     G.GV = nullptr;
1134 
1135     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1136     // to get GlobalValue with exactly the type we need, not something that
1137     // might had been created for another decl with the same mangled name but
1138     // different type.
1139     // FIXME: Support for variables is not implemented yet.
1140     if (isa<FunctionDecl>(D.getDecl()))
1141       GV = cast<llvm::GlobalValue>(GetAddrOfGlobal(D, /*IsForDefinition=*/true));
1142     else
1143       if (!GV)
1144         GV = GetGlobalValue(getMangledName(D));
1145 
1146     // Check to see if we've already emitted this.  This is necessary
1147     // for a couple of reasons: first, decls can end up in the
1148     // deferred-decls queue multiple times, and second, decls can end
1149     // up with definitions in unusual ways (e.g. by an extern inline
1150     // function acquiring a strong function redefinition).  Just
1151     // ignore these cases.
1152     if (GV && !GV->isDeclaration())
1153       continue;
1154 
1155     // Otherwise, emit the definition and move on to the next one.
1156     EmitGlobalDefinition(D, GV);
1157 
1158     // If we found out that we need to emit more decls, do that recursively.
1159     // This has the advantage that the decls are emitted in a DFS and related
1160     // ones are close together, which is convenient for testing.
1161     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1162       EmitDeferred();
1163       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1164     }
1165   }
1166 }
1167 
1168 void CodeGenModule::EmitGlobalAnnotations() {
1169   if (Annotations.empty())
1170     return;
1171 
1172   // Create a new global variable for the ConstantStruct in the Module.
1173   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1174     Annotations[0]->getType(), Annotations.size()), Annotations);
1175   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1176                                       llvm::GlobalValue::AppendingLinkage,
1177                                       Array, "llvm.global.annotations");
1178   gv->setSection(AnnotationSection);
1179 }
1180 
1181 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1182   llvm::Constant *&AStr = AnnotationStrings[Str];
1183   if (AStr)
1184     return AStr;
1185 
1186   // Not found yet, create a new global.
1187   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1188   auto *gv =
1189       new llvm::GlobalVariable(getModule(), s->getType(), true,
1190                                llvm::GlobalValue::PrivateLinkage, s, ".str");
1191   gv->setSection(AnnotationSection);
1192   gv->setUnnamedAddr(true);
1193   AStr = gv;
1194   return gv;
1195 }
1196 
1197 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1198   SourceManager &SM = getContext().getSourceManager();
1199   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1200   if (PLoc.isValid())
1201     return EmitAnnotationString(PLoc.getFilename());
1202   return EmitAnnotationString(SM.getBufferName(Loc));
1203 }
1204 
1205 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1206   SourceManager &SM = getContext().getSourceManager();
1207   PresumedLoc PLoc = SM.getPresumedLoc(L);
1208   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1209     SM.getExpansionLineNumber(L);
1210   return llvm::ConstantInt::get(Int32Ty, LineNo);
1211 }
1212 
1213 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1214                                                 const AnnotateAttr *AA,
1215                                                 SourceLocation L) {
1216   // Get the globals for file name, annotation, and the line number.
1217   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1218                  *UnitGV = EmitAnnotationUnit(L),
1219                  *LineNoCst = EmitAnnotationLineNo(L);
1220 
1221   // Create the ConstantStruct for the global annotation.
1222   llvm::Constant *Fields[4] = {
1223     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1224     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1225     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1226     LineNoCst
1227   };
1228   return llvm::ConstantStruct::getAnon(Fields);
1229 }
1230 
1231 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1232                                          llvm::GlobalValue *GV) {
1233   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1234   // Get the struct elements for these annotations.
1235   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1236     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1237 }
1238 
1239 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1240                                            SourceLocation Loc) const {
1241   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1242   // Blacklist by function name.
1243   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1244     return true;
1245   // Blacklist by location.
1246   if (!Loc.isInvalid())
1247     return SanitizerBL.isBlacklistedLocation(Loc);
1248   // If location is unknown, this may be a compiler-generated function. Assume
1249   // it's located in the main file.
1250   auto &SM = Context.getSourceManager();
1251   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1252     return SanitizerBL.isBlacklistedFile(MainFile->getName());
1253   }
1254   return false;
1255 }
1256 
1257 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1258                                            SourceLocation Loc, QualType Ty,
1259                                            StringRef Category) const {
1260   // For now globals can be blacklisted only in ASan and KASan.
1261   if (!LangOpts.Sanitize.hasOneOf(
1262           SanitizerKind::Address | SanitizerKind::KernelAddress))
1263     return false;
1264   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1265   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1266     return true;
1267   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1268     return true;
1269   // Check global type.
1270   if (!Ty.isNull()) {
1271     // Drill down the array types: if global variable of a fixed type is
1272     // blacklisted, we also don't instrument arrays of them.
1273     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1274       Ty = AT->getElementType();
1275     Ty = Ty.getCanonicalType().getUnqualifiedType();
1276     // We allow to blacklist only record types (classes, structs etc.)
1277     if (Ty->isRecordType()) {
1278       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1279       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1280         return true;
1281     }
1282   }
1283   return false;
1284 }
1285 
1286 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1287   // Never defer when EmitAllDecls is specified.
1288   if (LangOpts.EmitAllDecls)
1289     return true;
1290 
1291   return getContext().DeclMustBeEmitted(Global);
1292 }
1293 
1294 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1295   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1296     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1297       // Implicit template instantiations may change linkage if they are later
1298       // explicitly instantiated, so they should not be emitted eagerly.
1299       return false;
1300   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1301   // codegen for global variables, because they may be marked as threadprivate.
1302   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1303       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1304     return false;
1305 
1306   return true;
1307 }
1308 
1309 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1310     const CXXUuidofExpr* E) {
1311   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1312   // well-formed.
1313   StringRef Uuid = E->getUuidAsStringRef(Context);
1314   std::string Name = "_GUID_" + Uuid.lower();
1315   std::replace(Name.begin(), Name.end(), '-', '_');
1316 
1317   // Contains a 32-bit field.
1318   CharUnits Alignment = CharUnits::fromQuantity(4);
1319 
1320   // Look for an existing global.
1321   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1322     return ConstantAddress(GV, Alignment);
1323 
1324   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1325   assert(Init && "failed to initialize as constant");
1326 
1327   auto *GV = new llvm::GlobalVariable(
1328       getModule(), Init->getType(),
1329       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1330   if (supportsCOMDAT())
1331     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1332   return ConstantAddress(GV, Alignment);
1333 }
1334 
1335 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1336   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1337   assert(AA && "No alias?");
1338 
1339   CharUnits Alignment = getContext().getDeclAlign(VD);
1340   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1341 
1342   // See if there is already something with the target's name in the module.
1343   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1344   if (Entry) {
1345     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1346     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1347     return ConstantAddress(Ptr, Alignment);
1348   }
1349 
1350   llvm::Constant *Aliasee;
1351   if (isa<llvm::FunctionType>(DeclTy))
1352     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1353                                       GlobalDecl(cast<FunctionDecl>(VD)),
1354                                       /*ForVTable=*/false);
1355   else
1356     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1357                                     llvm::PointerType::getUnqual(DeclTy),
1358                                     nullptr);
1359 
1360   auto *F = cast<llvm::GlobalValue>(Aliasee);
1361   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1362   WeakRefReferences.insert(F);
1363 
1364   return ConstantAddress(Aliasee, Alignment);
1365 }
1366 
1367 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1368   const auto *Global = cast<ValueDecl>(GD.getDecl());
1369 
1370   // Weak references don't produce any output by themselves.
1371   if (Global->hasAttr<WeakRefAttr>())
1372     return;
1373 
1374   // If this is an alias definition (which otherwise looks like a declaration)
1375   // emit it now.
1376   if (Global->hasAttr<AliasAttr>())
1377     return EmitAliasDefinition(GD);
1378 
1379   // If this is CUDA, be selective about which declarations we emit.
1380   if (LangOpts.CUDA) {
1381     if (LangOpts.CUDAIsDevice) {
1382       if (!Global->hasAttr<CUDADeviceAttr>() &&
1383           !Global->hasAttr<CUDAGlobalAttr>() &&
1384           !Global->hasAttr<CUDAConstantAttr>() &&
1385           !Global->hasAttr<CUDASharedAttr>())
1386         return;
1387     } else {
1388       if (!Global->hasAttr<CUDAHostAttr>() && (
1389             Global->hasAttr<CUDADeviceAttr>() ||
1390             Global->hasAttr<CUDAConstantAttr>() ||
1391             Global->hasAttr<CUDASharedAttr>()))
1392         return;
1393     }
1394   }
1395 
1396   // Ignore declarations, they will be emitted on their first use.
1397   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1398     // Forward declarations are emitted lazily on first use.
1399     if (!FD->doesThisDeclarationHaveABody()) {
1400       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1401         return;
1402 
1403       StringRef MangledName = getMangledName(GD);
1404 
1405       // Compute the function info and LLVM type.
1406       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1407       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1408 
1409       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1410                               /*DontDefer=*/false);
1411       return;
1412     }
1413   } else {
1414     const auto *VD = cast<VarDecl>(Global);
1415     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1416 
1417     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1418         !Context.isMSStaticDataMemberInlineDefinition(VD))
1419       return;
1420   }
1421 
1422   // Defer code generation to first use when possible, e.g. if this is an inline
1423   // function. If the global must always be emitted, do it eagerly if possible
1424   // to benefit from cache locality.
1425   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1426     // Emit the definition if it can't be deferred.
1427     EmitGlobalDefinition(GD);
1428     return;
1429   }
1430 
1431   // If we're deferring emission of a C++ variable with an
1432   // initializer, remember the order in which it appeared in the file.
1433   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1434       cast<VarDecl>(Global)->hasInit()) {
1435     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1436     CXXGlobalInits.push_back(nullptr);
1437   }
1438 
1439   StringRef MangledName = getMangledName(GD);
1440   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1441     // The value has already been used and should therefore be emitted.
1442     addDeferredDeclToEmit(GV, GD);
1443   } else if (MustBeEmitted(Global)) {
1444     // The value must be emitted, but cannot be emitted eagerly.
1445     assert(!MayBeEmittedEagerly(Global));
1446     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1447   } else {
1448     // Otherwise, remember that we saw a deferred decl with this name.  The
1449     // first use of the mangled name will cause it to move into
1450     // DeferredDeclsToEmit.
1451     DeferredDecls[MangledName] = GD;
1452   }
1453 }
1454 
1455 namespace {
1456   struct FunctionIsDirectlyRecursive :
1457     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1458     const StringRef Name;
1459     const Builtin::Context &BI;
1460     bool Result;
1461     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1462       Name(N), BI(C), Result(false) {
1463     }
1464     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1465 
1466     bool TraverseCallExpr(CallExpr *E) {
1467       const FunctionDecl *FD = E->getDirectCallee();
1468       if (!FD)
1469         return true;
1470       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1471       if (Attr && Name == Attr->getLabel()) {
1472         Result = true;
1473         return false;
1474       }
1475       unsigned BuiltinID = FD->getBuiltinID();
1476       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1477         return true;
1478       StringRef BuiltinName = BI.getName(BuiltinID);
1479       if (BuiltinName.startswith("__builtin_") &&
1480           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1481         Result = true;
1482         return false;
1483       }
1484       return true;
1485     }
1486   };
1487 
1488   struct DLLImportFunctionVisitor
1489       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1490     bool SafeToInline = true;
1491 
1492     bool VisitVarDecl(VarDecl *VD) {
1493       // A thread-local variable cannot be imported.
1494       SafeToInline = !VD->getTLSKind();
1495       return SafeToInline;
1496     }
1497 
1498     // Make sure we're not referencing non-imported vars or functions.
1499     bool VisitDeclRefExpr(DeclRefExpr *E) {
1500       ValueDecl *VD = E->getDecl();
1501       if (isa<FunctionDecl>(VD))
1502         SafeToInline = VD->hasAttr<DLLImportAttr>();
1503       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1504         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1505       return SafeToInline;
1506     }
1507     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1508       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1509       return SafeToInline;
1510     }
1511     bool VisitCXXNewExpr(CXXNewExpr *E) {
1512       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1513       return SafeToInline;
1514     }
1515   };
1516 }
1517 
1518 // isTriviallyRecursive - Check if this function calls another
1519 // decl that, because of the asm attribute or the other decl being a builtin,
1520 // ends up pointing to itself.
1521 bool
1522 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1523   StringRef Name;
1524   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1525     // asm labels are a special kind of mangling we have to support.
1526     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1527     if (!Attr)
1528       return false;
1529     Name = Attr->getLabel();
1530   } else {
1531     Name = FD->getName();
1532   }
1533 
1534   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1535   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1536   return Walker.Result;
1537 }
1538 
1539 bool
1540 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1541   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1542     return true;
1543   const auto *F = cast<FunctionDecl>(GD.getDecl());
1544   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1545     return false;
1546 
1547   if (F->hasAttr<DLLImportAttr>()) {
1548     // Check whether it would be safe to inline this dllimport function.
1549     DLLImportFunctionVisitor Visitor;
1550     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1551     if (!Visitor.SafeToInline)
1552       return false;
1553   }
1554 
1555   // PR9614. Avoid cases where the source code is lying to us. An available
1556   // externally function should have an equivalent function somewhere else,
1557   // but a function that calls itself is clearly not equivalent to the real
1558   // implementation.
1559   // This happens in glibc's btowc and in some configure checks.
1560   return !isTriviallyRecursive(F);
1561 }
1562 
1563 /// If the type for the method's class was generated by
1564 /// CGDebugInfo::createContextChain(), the cache contains only a
1565 /// limited DIType without any declarations. Since EmitFunctionStart()
1566 /// needs to find the canonical declaration for each method, we need
1567 /// to construct the complete type prior to emitting the method.
1568 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1569   if (!D->isInstance())
1570     return;
1571 
1572   if (CGDebugInfo *DI = getModuleDebugInfo())
1573     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1574       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1575       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1576     }
1577 }
1578 
1579 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1580   const auto *D = cast<ValueDecl>(GD.getDecl());
1581 
1582   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1583                                  Context.getSourceManager(),
1584                                  "Generating code for declaration");
1585 
1586   if (isa<FunctionDecl>(D)) {
1587     // At -O0, don't generate IR for functions with available_externally
1588     // linkage.
1589     if (!shouldEmitFunction(GD))
1590       return;
1591 
1592     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1593       CompleteDIClassType(Method);
1594       // Make sure to emit the definition(s) before we emit the thunks.
1595       // This is necessary for the generation of certain thunks.
1596       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1597         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1598       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1599         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1600       else
1601         EmitGlobalFunctionDefinition(GD, GV);
1602 
1603       if (Method->isVirtual())
1604         getVTables().EmitThunks(GD);
1605 
1606       return;
1607     }
1608 
1609     return EmitGlobalFunctionDefinition(GD, GV);
1610   }
1611 
1612   if (const auto *VD = dyn_cast<VarDecl>(D))
1613     return EmitGlobalVarDefinition(VD);
1614 
1615   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1616 }
1617 
1618 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1619                                                       llvm::Function *NewFn);
1620 
1621 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1622 /// module, create and return an llvm Function with the specified type. If there
1623 /// is something in the module with the specified name, return it potentially
1624 /// bitcasted to the right type.
1625 ///
1626 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1627 /// to set the attributes on the function when it is first created.
1628 llvm::Constant *
1629 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1630                                        llvm::Type *Ty,
1631                                        GlobalDecl GD, bool ForVTable,
1632                                        bool DontDefer, bool IsThunk,
1633                                        llvm::AttributeSet ExtraAttrs,
1634                                        bool IsForDefinition) {
1635   const Decl *D = GD.getDecl();
1636 
1637   // Lookup the entry, lazily creating it if necessary.
1638   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1639   if (Entry) {
1640     if (WeakRefReferences.erase(Entry)) {
1641       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1642       if (FD && !FD->hasAttr<WeakAttr>())
1643         Entry->setLinkage(llvm::Function::ExternalLinkage);
1644     }
1645 
1646     // Handle dropped DLL attributes.
1647     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1648       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1649 
1650     // If there are two attempts to define the same mangled name, issue an
1651     // error.
1652     if (IsForDefinition && !Entry->isDeclaration()) {
1653       GlobalDecl OtherGD;
1654       // Check that GD is not yet in ExplicitDefinitions is required to make
1655       // sure that we issue an error only once.
1656       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1657           (GD.getCanonicalDecl().getDecl() !=
1658            OtherGD.getCanonicalDecl().getDecl()) &&
1659           DiagnosedConflictingDefinitions.insert(GD).second) {
1660         getDiags().Report(D->getLocation(),
1661                           diag::err_duplicate_mangled_name);
1662         getDiags().Report(OtherGD.getDecl()->getLocation(),
1663                           diag::note_previous_definition);
1664       }
1665     }
1666 
1667     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1668         (Entry->getType()->getElementType() == Ty)) {
1669       return Entry;
1670     }
1671 
1672     // Make sure the result is of the correct type.
1673     // (If function is requested for a definition, we always need to create a new
1674     // function, not just return a bitcast.)
1675     if (!IsForDefinition)
1676       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1677   }
1678 
1679   // This function doesn't have a complete type (for example, the return
1680   // type is an incomplete struct). Use a fake type instead, and make
1681   // sure not to try to set attributes.
1682   bool IsIncompleteFunction = false;
1683 
1684   llvm::FunctionType *FTy;
1685   if (isa<llvm::FunctionType>(Ty)) {
1686     FTy = cast<llvm::FunctionType>(Ty);
1687   } else {
1688     FTy = llvm::FunctionType::get(VoidTy, false);
1689     IsIncompleteFunction = true;
1690   }
1691 
1692   llvm::Function *F =
1693       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1694                              Entry ? StringRef() : MangledName, &getModule());
1695 
1696   // If we already created a function with the same mangled name (but different
1697   // type) before, take its name and add it to the list of functions to be
1698   // replaced with F at the end of CodeGen.
1699   //
1700   // This happens if there is a prototype for a function (e.g. "int f()") and
1701   // then a definition of a different type (e.g. "int f(int x)").
1702   if (Entry) {
1703     F->takeName(Entry);
1704 
1705     // This might be an implementation of a function without a prototype, in
1706     // which case, try to do special replacement of calls which match the new
1707     // prototype.  The really key thing here is that we also potentially drop
1708     // arguments from the call site so as to make a direct call, which makes the
1709     // inliner happier and suppresses a number of optimizer warnings (!) about
1710     // dropping arguments.
1711     if (!Entry->use_empty()) {
1712       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
1713       Entry->removeDeadConstantUsers();
1714     }
1715 
1716     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1717         F, Entry->getType()->getElementType()->getPointerTo());
1718     addGlobalValReplacement(Entry, BC);
1719   }
1720 
1721   assert(F->getName() == MangledName && "name was uniqued!");
1722   if (D)
1723     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1724   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1725     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1726     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1727                      llvm::AttributeSet::get(VMContext,
1728                                              llvm::AttributeSet::FunctionIndex,
1729                                              B));
1730   }
1731 
1732   if (!DontDefer) {
1733     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1734     // each other bottoming out with the base dtor.  Therefore we emit non-base
1735     // dtors on usage, even if there is no dtor definition in the TU.
1736     if (D && isa<CXXDestructorDecl>(D) &&
1737         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1738                                            GD.getDtorType()))
1739       addDeferredDeclToEmit(F, GD);
1740 
1741     // This is the first use or definition of a mangled name.  If there is a
1742     // deferred decl with this name, remember that we need to emit it at the end
1743     // of the file.
1744     auto DDI = DeferredDecls.find(MangledName);
1745     if (DDI != DeferredDecls.end()) {
1746       // Move the potentially referenced deferred decl to the
1747       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1748       // don't need it anymore).
1749       addDeferredDeclToEmit(F, DDI->second);
1750       DeferredDecls.erase(DDI);
1751 
1752       // Otherwise, there are cases we have to worry about where we're
1753       // using a declaration for which we must emit a definition but where
1754       // we might not find a top-level definition:
1755       //   - member functions defined inline in their classes
1756       //   - friend functions defined inline in some class
1757       //   - special member functions with implicit definitions
1758       // If we ever change our AST traversal to walk into class methods,
1759       // this will be unnecessary.
1760       //
1761       // We also don't emit a definition for a function if it's going to be an
1762       // entry in a vtable, unless it's already marked as used.
1763     } else if (getLangOpts().CPlusPlus && D) {
1764       // Look for a declaration that's lexically in a record.
1765       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1766            FD = FD->getPreviousDecl()) {
1767         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1768           if (FD->doesThisDeclarationHaveABody()) {
1769             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1770             break;
1771           }
1772         }
1773       }
1774     }
1775   }
1776 
1777   // Make sure the result is of the requested type.
1778   if (!IsIncompleteFunction) {
1779     assert(F->getType()->getElementType() == Ty);
1780     return F;
1781   }
1782 
1783   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1784   return llvm::ConstantExpr::getBitCast(F, PTy);
1785 }
1786 
1787 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1788 /// non-null, then this function will use the specified type if it has to
1789 /// create it (this occurs when we see a definition of the function).
1790 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1791                                                  llvm::Type *Ty,
1792                                                  bool ForVTable,
1793                                                  bool DontDefer,
1794                                                  bool IsForDefinition) {
1795   // If there was no specific requested type, just convert it now.
1796   if (!Ty)
1797     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1798 
1799   StringRef MangledName = getMangledName(GD);
1800   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
1801                                  /*IsThunk=*/false, llvm::AttributeSet(),
1802                                  IsForDefinition);
1803 }
1804 
1805 /// CreateRuntimeFunction - Create a new runtime function with the specified
1806 /// type and name.
1807 llvm::Constant *
1808 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1809                                      StringRef Name,
1810                                      llvm::AttributeSet ExtraAttrs) {
1811   llvm::Constant *C =
1812       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1813                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1814   if (auto *F = dyn_cast<llvm::Function>(C))
1815     if (F->empty())
1816       F->setCallingConv(getRuntimeCC());
1817   return C;
1818 }
1819 
1820 /// CreateBuiltinFunction - Create a new builtin function with the specified
1821 /// type and name.
1822 llvm::Constant *
1823 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1824                                      StringRef Name,
1825                                      llvm::AttributeSet ExtraAttrs) {
1826   llvm::Constant *C =
1827       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1828                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1829   if (auto *F = dyn_cast<llvm::Function>(C))
1830     if (F->empty())
1831       F->setCallingConv(getBuiltinCC());
1832   return C;
1833 }
1834 
1835 /// isTypeConstant - Determine whether an object of this type can be emitted
1836 /// as a constant.
1837 ///
1838 /// If ExcludeCtor is true, the duration when the object's constructor runs
1839 /// will not be considered. The caller will need to verify that the object is
1840 /// not written to during its construction.
1841 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1842   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1843     return false;
1844 
1845   if (Context.getLangOpts().CPlusPlus) {
1846     if (const CXXRecordDecl *Record
1847           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1848       return ExcludeCtor && !Record->hasMutableFields() &&
1849              Record->hasTrivialDestructor();
1850   }
1851 
1852   return true;
1853 }
1854 
1855 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1856 /// create and return an llvm GlobalVariable with the specified type.  If there
1857 /// is something in the module with the specified name, return it potentially
1858 /// bitcasted to the right type.
1859 ///
1860 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1861 /// to set the attributes on the global when it is first created.
1862 llvm::Constant *
1863 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1864                                      llvm::PointerType *Ty,
1865                                      const VarDecl *D) {
1866   // Lookup the entry, lazily creating it if necessary.
1867   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1868   if (Entry) {
1869     if (WeakRefReferences.erase(Entry)) {
1870       if (D && !D->hasAttr<WeakAttr>())
1871         Entry->setLinkage(llvm::Function::ExternalLinkage);
1872     }
1873 
1874     // Handle dropped DLL attributes.
1875     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1876       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1877 
1878     if (Entry->getType() == Ty)
1879       return Entry;
1880 
1881     // Make sure the result is of the correct type.
1882     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1883       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1884 
1885     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1886   }
1887 
1888   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1889   auto *GV = new llvm::GlobalVariable(
1890       getModule(), Ty->getElementType(), false,
1891       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
1892       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1893 
1894   // This is the first use or definition of a mangled name.  If there is a
1895   // deferred decl with this name, remember that we need to emit it at the end
1896   // of the file.
1897   auto DDI = DeferredDecls.find(MangledName);
1898   if (DDI != DeferredDecls.end()) {
1899     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1900     // list, and remove it from DeferredDecls (since we don't need it anymore).
1901     addDeferredDeclToEmit(GV, DDI->second);
1902     DeferredDecls.erase(DDI);
1903   }
1904 
1905   // Handle things which are present even on external declarations.
1906   if (D) {
1907     // FIXME: This code is overly simple and should be merged with other global
1908     // handling.
1909     GV->setConstant(isTypeConstant(D->getType(), false));
1910 
1911     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1912 
1913     setLinkageAndVisibilityForGV(GV, D);
1914 
1915     if (D->getTLSKind()) {
1916       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1917         CXXThreadLocals.push_back(std::make_pair(D, GV));
1918       setTLSMode(GV, *D);
1919     }
1920 
1921     // If required by the ABI, treat declarations of static data members with
1922     // inline initializers as definitions.
1923     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
1924       EmitGlobalVarDefinition(D);
1925     }
1926 
1927     // Handle XCore specific ABI requirements.
1928     if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1929         D->getLanguageLinkage() == CLanguageLinkage &&
1930         D->getType().isConstant(Context) &&
1931         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1932       GV->setSection(".cp.rodata");
1933   }
1934 
1935   if (AddrSpace != Ty->getAddressSpace())
1936     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1937 
1938   return GV;
1939 }
1940 
1941 llvm::Constant *
1942 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
1943                                bool IsForDefinition) {
1944   if (isa<CXXConstructorDecl>(GD.getDecl()))
1945     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
1946                                 getFromCtorType(GD.getCtorType()),
1947                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
1948                                 /*DontDefer=*/false, IsForDefinition);
1949   else if (isa<CXXDestructorDecl>(GD.getDecl()))
1950     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
1951                                 getFromDtorType(GD.getDtorType()),
1952                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
1953                                 /*DontDefer=*/false, IsForDefinition);
1954   else if (isa<CXXMethodDecl>(GD.getDecl())) {
1955     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
1956         cast<CXXMethodDecl>(GD.getDecl()));
1957     auto Ty = getTypes().GetFunctionType(*FInfo);
1958     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
1959                              IsForDefinition);
1960   } else if (isa<FunctionDecl>(GD.getDecl())) {
1961     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1962     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
1963     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
1964                              IsForDefinition);
1965   } else
1966     return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
1967 }
1968 
1969 llvm::GlobalVariable *
1970 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1971                                       llvm::Type *Ty,
1972                                       llvm::GlobalValue::LinkageTypes Linkage) {
1973   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1974   llvm::GlobalVariable *OldGV = nullptr;
1975 
1976   if (GV) {
1977     // Check if the variable has the right type.
1978     if (GV->getType()->getElementType() == Ty)
1979       return GV;
1980 
1981     // Because C++ name mangling, the only way we can end up with an already
1982     // existing global with the same name is if it has been declared extern "C".
1983     assert(GV->isDeclaration() && "Declaration has wrong type!");
1984     OldGV = GV;
1985   }
1986 
1987   // Create a new variable.
1988   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1989                                 Linkage, nullptr, Name);
1990 
1991   if (OldGV) {
1992     // Replace occurrences of the old variable if needed.
1993     GV->takeName(OldGV);
1994 
1995     if (!OldGV->use_empty()) {
1996       llvm::Constant *NewPtrForOldDecl =
1997       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1998       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1999     }
2000 
2001     OldGV->eraseFromParent();
2002   }
2003 
2004   if (supportsCOMDAT() && GV->isWeakForLinker() &&
2005       !GV->hasAvailableExternallyLinkage())
2006     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2007 
2008   return GV;
2009 }
2010 
2011 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2012 /// given global variable.  If Ty is non-null and if the global doesn't exist,
2013 /// then it will be created with the specified type instead of whatever the
2014 /// normal requested type would be.
2015 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2016                                                   llvm::Type *Ty) {
2017   assert(D->hasGlobalStorage() && "Not a global variable");
2018   QualType ASTTy = D->getType();
2019   if (!Ty)
2020     Ty = getTypes().ConvertTypeForMem(ASTTy);
2021 
2022   llvm::PointerType *PTy =
2023     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2024 
2025   StringRef MangledName = getMangledName(D);
2026   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
2027 }
2028 
2029 /// CreateRuntimeVariable - Create a new runtime global variable with the
2030 /// specified type and name.
2031 llvm::Constant *
2032 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2033                                      StringRef Name) {
2034   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2035 }
2036 
2037 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2038   assert(!D->getInit() && "Cannot emit definite definitions here!");
2039 
2040   if (!MustBeEmitted(D)) {
2041     // If we have not seen a reference to this variable yet, place it
2042     // into the deferred declarations table to be emitted if needed
2043     // later.
2044     StringRef MangledName = getMangledName(D);
2045     if (!GetGlobalValue(MangledName)) {
2046       DeferredDecls[MangledName] = D;
2047       return;
2048     }
2049   }
2050 
2051   // The tentative definition is the only definition.
2052   EmitGlobalVarDefinition(D);
2053 }
2054 
2055 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2056   return Context.toCharUnitsFromBits(
2057       getDataLayout().getTypeStoreSizeInBits(Ty));
2058 }
2059 
2060 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2061                                                  unsigned AddrSpace) {
2062   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2063     if (D->hasAttr<CUDAConstantAttr>())
2064       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2065     else if (D->hasAttr<CUDASharedAttr>())
2066       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2067     else
2068       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2069   }
2070 
2071   return AddrSpace;
2072 }
2073 
2074 template<typename SomeDecl>
2075 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2076                                                llvm::GlobalValue *GV) {
2077   if (!getLangOpts().CPlusPlus)
2078     return;
2079 
2080   // Must have 'used' attribute, or else inline assembly can't rely on
2081   // the name existing.
2082   if (!D->template hasAttr<UsedAttr>())
2083     return;
2084 
2085   // Must have internal linkage and an ordinary name.
2086   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2087     return;
2088 
2089   // Must be in an extern "C" context. Entities declared directly within
2090   // a record are not extern "C" even if the record is in such a context.
2091   const SomeDecl *First = D->getFirstDecl();
2092   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2093     return;
2094 
2095   // OK, this is an internal linkage entity inside an extern "C" linkage
2096   // specification. Make a note of that so we can give it the "expected"
2097   // mangled name if nothing else is using that name.
2098   std::pair<StaticExternCMap::iterator, bool> R =
2099       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2100 
2101   // If we have multiple internal linkage entities with the same name
2102   // in extern "C" regions, none of them gets that name.
2103   if (!R.second)
2104     R.first->second = nullptr;
2105 }
2106 
2107 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2108   if (!CGM.supportsCOMDAT())
2109     return false;
2110 
2111   if (D.hasAttr<SelectAnyAttr>())
2112     return true;
2113 
2114   GVALinkage Linkage;
2115   if (auto *VD = dyn_cast<VarDecl>(&D))
2116     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2117   else
2118     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2119 
2120   switch (Linkage) {
2121   case GVA_Internal:
2122   case GVA_AvailableExternally:
2123   case GVA_StrongExternal:
2124     return false;
2125   case GVA_DiscardableODR:
2126   case GVA_StrongODR:
2127     return true;
2128   }
2129   llvm_unreachable("No such linkage");
2130 }
2131 
2132 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2133                                           llvm::GlobalObject &GO) {
2134   if (!shouldBeInCOMDAT(*this, D))
2135     return;
2136   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2137 }
2138 
2139 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
2140   llvm::Constant *Init = nullptr;
2141   QualType ASTTy = D->getType();
2142   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2143   bool NeedsGlobalCtor = false;
2144   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2145 
2146   const VarDecl *InitDecl;
2147   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2148 
2149   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization as part
2150   // of their declaration."
2151   if (getLangOpts().CPlusPlus && getLangOpts().CUDAIsDevice
2152       && D->hasAttr<CUDASharedAttr>()) {
2153     if (InitExpr) {
2154       Error(D->getLocation(),
2155             "__shared__ variable cannot have an initialization.");
2156     }
2157     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2158   } else if (!InitExpr) {
2159     // This is a tentative definition; tentative definitions are
2160     // implicitly initialized with { 0 }.
2161     //
2162     // Note that tentative definitions are only emitted at the end of
2163     // a translation unit, so they should never have incomplete
2164     // type. In addition, EmitTentativeDefinition makes sure that we
2165     // never attempt to emit a tentative definition if a real one
2166     // exists. A use may still exists, however, so we still may need
2167     // to do a RAUW.
2168     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2169     Init = EmitNullConstant(D->getType());
2170   } else {
2171     initializedGlobalDecl = GlobalDecl(D);
2172     Init = EmitConstantInit(*InitDecl);
2173 
2174     if (!Init) {
2175       QualType T = InitExpr->getType();
2176       if (D->getType()->isReferenceType())
2177         T = D->getType();
2178 
2179       if (getLangOpts().CPlusPlus) {
2180         Init = EmitNullConstant(T);
2181         NeedsGlobalCtor = true;
2182       } else {
2183         ErrorUnsupported(D, "static initializer");
2184         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2185       }
2186     } else {
2187       // We don't need an initializer, so remove the entry for the delayed
2188       // initializer position (just in case this entry was delayed) if we
2189       // also don't need to register a destructor.
2190       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2191         DelayedCXXInitPosition.erase(D);
2192     }
2193   }
2194 
2195   llvm::Type* InitType = Init->getType();
2196   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
2197 
2198   // Strip off a bitcast if we got one back.
2199   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2200     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2201            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2202            // All zero index gep.
2203            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2204     Entry = CE->getOperand(0);
2205   }
2206 
2207   // Entry is now either a Function or GlobalVariable.
2208   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2209 
2210   // We have a definition after a declaration with the wrong type.
2211   // We must make a new GlobalVariable* and update everything that used OldGV
2212   // (a declaration or tentative definition) with the new GlobalVariable*
2213   // (which will be a definition).
2214   //
2215   // This happens if there is a prototype for a global (e.g.
2216   // "extern int x[];") and then a definition of a different type (e.g.
2217   // "int x[10];"). This also happens when an initializer has a different type
2218   // from the type of the global (this happens with unions).
2219   if (!GV ||
2220       GV->getType()->getElementType() != InitType ||
2221       GV->getType()->getAddressSpace() !=
2222        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2223 
2224     // Move the old entry aside so that we'll create a new one.
2225     Entry->setName(StringRef());
2226 
2227     // Make a new global with the correct type, this is now guaranteed to work.
2228     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
2229 
2230     // Replace all uses of the old global with the new global
2231     llvm::Constant *NewPtrForOldDecl =
2232         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2233     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2234 
2235     // Erase the old global, since it is no longer used.
2236     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2237   }
2238 
2239   MaybeHandleStaticInExternC(D, GV);
2240 
2241   if (D->hasAttr<AnnotateAttr>())
2242     AddGlobalAnnotations(D, GV);
2243 
2244   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2245   // the device. [...]"
2246   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2247   // __device__, declares a variable that: [...]
2248   // Is accessible from all the threads within the grid and from the host
2249   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2250   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2251   if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice &&
2252       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) {
2253     GV->setExternallyInitialized(true);
2254   }
2255   GV->setInitializer(Init);
2256 
2257   // If it is safe to mark the global 'constant', do so now.
2258   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2259                   isTypeConstant(D->getType(), true));
2260 
2261   // If it is in a read-only section, mark it 'constant'.
2262   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2263     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2264     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2265       GV->setConstant(true);
2266   }
2267 
2268   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2269 
2270   // Set the llvm linkage type as appropriate.
2271   llvm::GlobalValue::LinkageTypes Linkage =
2272       getLLVMLinkageVarDefinition(D, GV->isConstant());
2273 
2274   // On Darwin, the backing variable for a C++11 thread_local variable always
2275   // has internal linkage; all accesses should just be calls to the
2276   // Itanium-specified entry point, which has the normal linkage of the
2277   // variable.
2278   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2279       Context.getTargetInfo().getTriple().isMacOSX())
2280     Linkage = llvm::GlobalValue::InternalLinkage;
2281 
2282   GV->setLinkage(Linkage);
2283   if (D->hasAttr<DLLImportAttr>())
2284     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2285   else if (D->hasAttr<DLLExportAttr>())
2286     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2287   else
2288     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2289 
2290   if (Linkage == llvm::GlobalVariable::CommonLinkage)
2291     // common vars aren't constant even if declared const.
2292     GV->setConstant(false);
2293 
2294   setNonAliasAttributes(D, GV);
2295 
2296   if (D->getTLSKind() && !GV->isThreadLocal()) {
2297     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2298       CXXThreadLocals.push_back(std::make_pair(D, GV));
2299     setTLSMode(GV, *D);
2300   }
2301 
2302   maybeSetTrivialComdat(*D, *GV);
2303 
2304   // Emit the initializer function if necessary.
2305   if (NeedsGlobalCtor || NeedsGlobalDtor)
2306     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2307 
2308   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2309 
2310   // Emit global variable debug information.
2311   if (CGDebugInfo *DI = getModuleDebugInfo())
2312     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2313       DI->EmitGlobalVariable(GV, D);
2314 }
2315 
2316 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2317                                       CodeGenModule &CGM, const VarDecl *D,
2318                                       bool NoCommon) {
2319   // Don't give variables common linkage if -fno-common was specified unless it
2320   // was overridden by a NoCommon attribute.
2321   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2322     return true;
2323 
2324   // C11 6.9.2/2:
2325   //   A declaration of an identifier for an object that has file scope without
2326   //   an initializer, and without a storage-class specifier or with the
2327   //   storage-class specifier static, constitutes a tentative definition.
2328   if (D->getInit() || D->hasExternalStorage())
2329     return true;
2330 
2331   // A variable cannot be both common and exist in a section.
2332   if (D->hasAttr<SectionAttr>())
2333     return true;
2334 
2335   // Thread local vars aren't considered common linkage.
2336   if (D->getTLSKind())
2337     return true;
2338 
2339   // Tentative definitions marked with WeakImportAttr are true definitions.
2340   if (D->hasAttr<WeakImportAttr>())
2341     return true;
2342 
2343   // A variable cannot be both common and exist in a comdat.
2344   if (shouldBeInCOMDAT(CGM, *D))
2345     return true;
2346 
2347   // Declarations with a required alignment do not have common linakge in MSVC
2348   // mode.
2349   if (Context.getLangOpts().MSVCCompat) {
2350     if (D->hasAttr<AlignedAttr>())
2351       return true;
2352     QualType VarType = D->getType();
2353     if (Context.isAlignmentRequired(VarType))
2354       return true;
2355 
2356     if (const auto *RT = VarType->getAs<RecordType>()) {
2357       const RecordDecl *RD = RT->getDecl();
2358       for (const FieldDecl *FD : RD->fields()) {
2359         if (FD->isBitField())
2360           continue;
2361         if (FD->hasAttr<AlignedAttr>())
2362           return true;
2363         if (Context.isAlignmentRequired(FD->getType()))
2364           return true;
2365       }
2366     }
2367   }
2368 
2369   return false;
2370 }
2371 
2372 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2373     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2374   if (Linkage == GVA_Internal)
2375     return llvm::Function::InternalLinkage;
2376 
2377   if (D->hasAttr<WeakAttr>()) {
2378     if (IsConstantVariable)
2379       return llvm::GlobalVariable::WeakODRLinkage;
2380     else
2381       return llvm::GlobalVariable::WeakAnyLinkage;
2382   }
2383 
2384   // We are guaranteed to have a strong definition somewhere else,
2385   // so we can use available_externally linkage.
2386   if (Linkage == GVA_AvailableExternally)
2387     return llvm::Function::AvailableExternallyLinkage;
2388 
2389   // Note that Apple's kernel linker doesn't support symbol
2390   // coalescing, so we need to avoid linkonce and weak linkages there.
2391   // Normally, this means we just map to internal, but for explicit
2392   // instantiations we'll map to external.
2393 
2394   // In C++, the compiler has to emit a definition in every translation unit
2395   // that references the function.  We should use linkonce_odr because
2396   // a) if all references in this translation unit are optimized away, we
2397   // don't need to codegen it.  b) if the function persists, it needs to be
2398   // merged with other definitions. c) C++ has the ODR, so we know the
2399   // definition is dependable.
2400   if (Linkage == GVA_DiscardableODR)
2401     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2402                                             : llvm::Function::InternalLinkage;
2403 
2404   // An explicit instantiation of a template has weak linkage, since
2405   // explicit instantiations can occur in multiple translation units
2406   // and must all be equivalent. However, we are not allowed to
2407   // throw away these explicit instantiations.
2408   if (Linkage == GVA_StrongODR)
2409     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2410                                             : llvm::Function::ExternalLinkage;
2411 
2412   // C++ doesn't have tentative definitions and thus cannot have common
2413   // linkage.
2414   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2415       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2416                                  CodeGenOpts.NoCommon))
2417     return llvm::GlobalVariable::CommonLinkage;
2418 
2419   // selectany symbols are externally visible, so use weak instead of
2420   // linkonce.  MSVC optimizes away references to const selectany globals, so
2421   // all definitions should be the same and ODR linkage should be used.
2422   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2423   if (D->hasAttr<SelectAnyAttr>())
2424     return llvm::GlobalVariable::WeakODRLinkage;
2425 
2426   // Otherwise, we have strong external linkage.
2427   assert(Linkage == GVA_StrongExternal);
2428   return llvm::GlobalVariable::ExternalLinkage;
2429 }
2430 
2431 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2432     const VarDecl *VD, bool IsConstant) {
2433   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2434   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2435 }
2436 
2437 /// Replace the uses of a function that was declared with a non-proto type.
2438 /// We want to silently drop extra arguments from call sites
2439 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2440                                           llvm::Function *newFn) {
2441   // Fast path.
2442   if (old->use_empty()) return;
2443 
2444   llvm::Type *newRetTy = newFn->getReturnType();
2445   SmallVector<llvm::Value*, 4> newArgs;
2446 
2447   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2448          ui != ue; ) {
2449     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2450     llvm::User *user = use->getUser();
2451 
2452     // Recognize and replace uses of bitcasts.  Most calls to
2453     // unprototyped functions will use bitcasts.
2454     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2455       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2456         replaceUsesOfNonProtoConstant(bitcast, newFn);
2457       continue;
2458     }
2459 
2460     // Recognize calls to the function.
2461     llvm::CallSite callSite(user);
2462     if (!callSite) continue;
2463     if (!callSite.isCallee(&*use)) continue;
2464 
2465     // If the return types don't match exactly, then we can't
2466     // transform this call unless it's dead.
2467     if (callSite->getType() != newRetTy && !callSite->use_empty())
2468       continue;
2469 
2470     // Get the call site's attribute list.
2471     SmallVector<llvm::AttributeSet, 8> newAttrs;
2472     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2473 
2474     // Collect any return attributes from the call.
2475     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2476       newAttrs.push_back(
2477         llvm::AttributeSet::get(newFn->getContext(),
2478                                 oldAttrs.getRetAttributes()));
2479 
2480     // If the function was passed too few arguments, don't transform.
2481     unsigned newNumArgs = newFn->arg_size();
2482     if (callSite.arg_size() < newNumArgs) continue;
2483 
2484     // If extra arguments were passed, we silently drop them.
2485     // If any of the types mismatch, we don't transform.
2486     unsigned argNo = 0;
2487     bool dontTransform = false;
2488     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2489            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2490       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2491         dontTransform = true;
2492         break;
2493       }
2494 
2495       // Add any parameter attributes.
2496       if (oldAttrs.hasAttributes(argNo + 1))
2497         newAttrs.
2498           push_back(llvm::
2499                     AttributeSet::get(newFn->getContext(),
2500                                       oldAttrs.getParamAttributes(argNo + 1)));
2501     }
2502     if (dontTransform)
2503       continue;
2504 
2505     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2506       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2507                                                  oldAttrs.getFnAttributes()));
2508 
2509     // Okay, we can transform this.  Create the new call instruction and copy
2510     // over the required information.
2511     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2512 
2513     llvm::CallSite newCall;
2514     if (callSite.isCall()) {
2515       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2516                                        callSite.getInstruction());
2517     } else {
2518       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2519       newCall = llvm::InvokeInst::Create(newFn,
2520                                          oldInvoke->getNormalDest(),
2521                                          oldInvoke->getUnwindDest(),
2522                                          newArgs, "",
2523                                          callSite.getInstruction());
2524     }
2525     newArgs.clear(); // for the next iteration
2526 
2527     if (!newCall->getType()->isVoidTy())
2528       newCall->takeName(callSite.getInstruction());
2529     newCall.setAttributes(
2530                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2531     newCall.setCallingConv(callSite.getCallingConv());
2532 
2533     // Finally, remove the old call, replacing any uses with the new one.
2534     if (!callSite->use_empty())
2535       callSite->replaceAllUsesWith(newCall.getInstruction());
2536 
2537     // Copy debug location attached to CI.
2538     if (callSite->getDebugLoc())
2539       newCall->setDebugLoc(callSite->getDebugLoc());
2540     callSite->eraseFromParent();
2541   }
2542 }
2543 
2544 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2545 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2546 /// existing call uses of the old function in the module, this adjusts them to
2547 /// call the new function directly.
2548 ///
2549 /// This is not just a cleanup: the always_inline pass requires direct calls to
2550 /// functions to be able to inline them.  If there is a bitcast in the way, it
2551 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2552 /// run at -O0.
2553 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2554                                                       llvm::Function *NewFn) {
2555   // If we're redefining a global as a function, don't transform it.
2556   if (!isa<llvm::Function>(Old)) return;
2557 
2558   replaceUsesOfNonProtoConstant(Old, NewFn);
2559 }
2560 
2561 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2562   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2563   // If we have a definition, this might be a deferred decl. If the
2564   // instantiation is explicit, make sure we emit it at the end.
2565   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2566     GetAddrOfGlobalVar(VD);
2567 
2568   EmitTopLevelDecl(VD);
2569 }
2570 
2571 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2572                                                  llvm::GlobalValue *GV) {
2573   const auto *D = cast<FunctionDecl>(GD.getDecl());
2574 
2575   // Compute the function info and LLVM type.
2576   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2577   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2578 
2579   // Get or create the prototype for the function.
2580   if (!GV || (GV->getType()->getElementType() != Ty))
2581     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
2582                                                    /*DontDefer=*/true,
2583                                                    /*IsForDefinition=*/true));
2584 
2585   // Already emitted.
2586   if (!GV->isDeclaration())
2587     return;
2588 
2589   // We need to set linkage and visibility on the function before
2590   // generating code for it because various parts of IR generation
2591   // want to propagate this information down (e.g. to local static
2592   // declarations).
2593   auto *Fn = cast<llvm::Function>(GV);
2594   setFunctionLinkage(GD, Fn);
2595   setFunctionDLLStorageClass(GD, Fn);
2596 
2597   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2598   setGlobalVisibility(Fn, D);
2599 
2600   MaybeHandleStaticInExternC(D, Fn);
2601 
2602   maybeSetTrivialComdat(*D, *Fn);
2603 
2604   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2605 
2606   setFunctionDefinitionAttributes(D, Fn);
2607   SetLLVMFunctionAttributesForDefinition(D, Fn);
2608 
2609   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2610     AddGlobalCtor(Fn, CA->getPriority());
2611   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2612     AddGlobalDtor(Fn, DA->getPriority());
2613   if (D->hasAttr<AnnotateAttr>())
2614     AddGlobalAnnotations(D, Fn);
2615 }
2616 
2617 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2618   const auto *D = cast<ValueDecl>(GD.getDecl());
2619   const AliasAttr *AA = D->getAttr<AliasAttr>();
2620   assert(AA && "Not an alias?");
2621 
2622   StringRef MangledName = getMangledName(GD);
2623 
2624   if (AA->getAliasee() == MangledName) {
2625     Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2626     return;
2627   }
2628 
2629   // If there is a definition in the module, then it wins over the alias.
2630   // This is dubious, but allow it to be safe.  Just ignore the alias.
2631   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2632   if (Entry && !Entry->isDeclaration())
2633     return;
2634 
2635   Aliases.push_back(GD);
2636 
2637   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2638 
2639   // Create a reference to the named value.  This ensures that it is emitted
2640   // if a deferred decl.
2641   llvm::Constant *Aliasee;
2642   if (isa<llvm::FunctionType>(DeclTy))
2643     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2644                                       /*ForVTable=*/false);
2645   else
2646     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2647                                     llvm::PointerType::getUnqual(DeclTy),
2648                                     /*D=*/nullptr);
2649 
2650   // Create the new alias itself, but don't set a name yet.
2651   auto *GA = llvm::GlobalAlias::create(
2652       cast<llvm::PointerType>(Aliasee->getType()),
2653       llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2654 
2655   if (Entry) {
2656     if (GA->getAliasee() == Entry) {
2657       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2658       return;
2659     }
2660 
2661     assert(Entry->isDeclaration());
2662 
2663     // If there is a declaration in the module, then we had an extern followed
2664     // by the alias, as in:
2665     //   extern int test6();
2666     //   ...
2667     //   int test6() __attribute__((alias("test7")));
2668     //
2669     // Remove it and replace uses of it with the alias.
2670     GA->takeName(Entry);
2671 
2672     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2673                                                           Entry->getType()));
2674     Entry->eraseFromParent();
2675   } else {
2676     GA->setName(MangledName);
2677   }
2678 
2679   // Set attributes which are particular to an alias; this is a
2680   // specialization of the attributes which may be set on a global
2681   // variable/function.
2682   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2683       D->isWeakImported()) {
2684     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2685   }
2686 
2687   if (const auto *VD = dyn_cast<VarDecl>(D))
2688     if (VD->getTLSKind())
2689       setTLSMode(GA, *VD);
2690 
2691   setAliasAttributes(D, GA);
2692 }
2693 
2694 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2695                                             ArrayRef<llvm::Type*> Tys) {
2696   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2697                                          Tys);
2698 }
2699 
2700 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2701 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2702                          const StringLiteral *Literal, bool TargetIsLSB,
2703                          bool &IsUTF16, unsigned &StringLength) {
2704   StringRef String = Literal->getString();
2705   unsigned NumBytes = String.size();
2706 
2707   // Check for simple case.
2708   if (!Literal->containsNonAsciiOrNull()) {
2709     StringLength = NumBytes;
2710     return *Map.insert(std::make_pair(String, nullptr)).first;
2711   }
2712 
2713   // Otherwise, convert the UTF8 literals into a string of shorts.
2714   IsUTF16 = true;
2715 
2716   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2717   const UTF8 *FromPtr = (const UTF8 *)String.data();
2718   UTF16 *ToPtr = &ToBuf[0];
2719 
2720   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2721                            &ToPtr, ToPtr + NumBytes,
2722                            strictConversion);
2723 
2724   // ConvertUTF8toUTF16 returns the length in ToPtr.
2725   StringLength = ToPtr - &ToBuf[0];
2726 
2727   // Add an explicit null.
2728   *ToPtr = 0;
2729   return *Map.insert(std::make_pair(
2730                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2731                                    (StringLength + 1) * 2),
2732                          nullptr)).first;
2733 }
2734 
2735 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2736 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2737                        const StringLiteral *Literal, unsigned &StringLength) {
2738   StringRef String = Literal->getString();
2739   StringLength = String.size();
2740   return *Map.insert(std::make_pair(String, nullptr)).first;
2741 }
2742 
2743 ConstantAddress
2744 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2745   unsigned StringLength = 0;
2746   bool isUTF16 = false;
2747   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2748       GetConstantCFStringEntry(CFConstantStringMap, Literal,
2749                                getDataLayout().isLittleEndian(), isUTF16,
2750                                StringLength);
2751 
2752   if (auto *C = Entry.second)
2753     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2754 
2755   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2756   llvm::Constant *Zeros[] = { Zero, Zero };
2757   llvm::Value *V;
2758 
2759   // If we don't already have it, get __CFConstantStringClassReference.
2760   if (!CFConstantStringClassRef) {
2761     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2762     Ty = llvm::ArrayType::get(Ty, 0);
2763     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2764                                            "__CFConstantStringClassReference");
2765     // Decay array -> ptr
2766     V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2767     CFConstantStringClassRef = V;
2768   }
2769   else
2770     V = CFConstantStringClassRef;
2771 
2772   QualType CFTy = getContext().getCFConstantStringType();
2773 
2774   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2775 
2776   llvm::Constant *Fields[4];
2777 
2778   // Class pointer.
2779   Fields[0] = cast<llvm::ConstantExpr>(V);
2780 
2781   // Flags.
2782   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2783   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2784     llvm::ConstantInt::get(Ty, 0x07C8);
2785 
2786   // String pointer.
2787   llvm::Constant *C = nullptr;
2788   if (isUTF16) {
2789     ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2790         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2791         Entry.first().size() / 2);
2792     C = llvm::ConstantDataArray::get(VMContext, Arr);
2793   } else {
2794     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2795   }
2796 
2797   // Note: -fwritable-strings doesn't make the backing store strings of
2798   // CFStrings writable. (See <rdar://problem/10657500>)
2799   auto *GV =
2800       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2801                                llvm::GlobalValue::PrivateLinkage, C, ".str");
2802   GV->setUnnamedAddr(true);
2803   // Don't enforce the target's minimum global alignment, since the only use
2804   // of the string is via this class initializer.
2805   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2806   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2807   // that changes the section it ends in, which surprises ld64.
2808   if (isUTF16) {
2809     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2810     GV->setAlignment(Align.getQuantity());
2811     GV->setSection("__TEXT,__ustring");
2812   } else {
2813     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2814     GV->setAlignment(Align.getQuantity());
2815     GV->setSection("__TEXT,__cstring,cstring_literals");
2816   }
2817 
2818   // String.
2819   Fields[2] =
2820       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2821 
2822   if (isUTF16)
2823     // Cast the UTF16 string to the correct type.
2824     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2825 
2826   // String length.
2827   Ty = getTypes().ConvertType(getContext().LongTy);
2828   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2829 
2830   CharUnits Alignment = getPointerAlign();
2831 
2832   // The struct.
2833   C = llvm::ConstantStruct::get(STy, Fields);
2834   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2835                                 llvm::GlobalVariable::PrivateLinkage, C,
2836                                 "_unnamed_cfstring_");
2837   GV->setSection("__DATA,__cfstring");
2838   GV->setAlignment(Alignment.getQuantity());
2839   Entry.second = GV;
2840 
2841   return ConstantAddress(GV, Alignment);
2842 }
2843 
2844 ConstantAddress
2845 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2846   unsigned StringLength = 0;
2847   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2848       GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2849 
2850   if (auto *C = Entry.second)
2851     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2852 
2853   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2854   llvm::Constant *Zeros[] = { Zero, Zero };
2855   llvm::Value *V;
2856   // If we don't already have it, get _NSConstantStringClassReference.
2857   if (!ConstantStringClassRef) {
2858     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2859     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2860     llvm::Constant *GV;
2861     if (LangOpts.ObjCRuntime.isNonFragile()) {
2862       std::string str =
2863         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2864                             : "OBJC_CLASS_$_" + StringClass;
2865       GV = getObjCRuntime().GetClassGlobal(str);
2866       // Make sure the result is of the correct type.
2867       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2868       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2869       ConstantStringClassRef = V;
2870     } else {
2871       std::string str =
2872         StringClass.empty() ? "_NSConstantStringClassReference"
2873                             : "_" + StringClass + "ClassReference";
2874       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2875       GV = CreateRuntimeVariable(PTy, str);
2876       // Decay array -> ptr
2877       V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
2878       ConstantStringClassRef = V;
2879     }
2880   } else
2881     V = ConstantStringClassRef;
2882 
2883   if (!NSConstantStringType) {
2884     // Construct the type for a constant NSString.
2885     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2886     D->startDefinition();
2887 
2888     QualType FieldTypes[3];
2889 
2890     // const int *isa;
2891     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2892     // const char *str;
2893     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2894     // unsigned int length;
2895     FieldTypes[2] = Context.UnsignedIntTy;
2896 
2897     // Create fields
2898     for (unsigned i = 0; i < 3; ++i) {
2899       FieldDecl *Field = FieldDecl::Create(Context, D,
2900                                            SourceLocation(),
2901                                            SourceLocation(), nullptr,
2902                                            FieldTypes[i], /*TInfo=*/nullptr,
2903                                            /*BitWidth=*/nullptr,
2904                                            /*Mutable=*/false,
2905                                            ICIS_NoInit);
2906       Field->setAccess(AS_public);
2907       D->addDecl(Field);
2908     }
2909 
2910     D->completeDefinition();
2911     QualType NSTy = Context.getTagDeclType(D);
2912     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2913   }
2914 
2915   llvm::Constant *Fields[3];
2916 
2917   // Class pointer.
2918   Fields[0] = cast<llvm::ConstantExpr>(V);
2919 
2920   // String pointer.
2921   llvm::Constant *C =
2922       llvm::ConstantDataArray::getString(VMContext, Entry.first());
2923 
2924   llvm::GlobalValue::LinkageTypes Linkage;
2925   bool isConstant;
2926   Linkage = llvm::GlobalValue::PrivateLinkage;
2927   isConstant = !LangOpts.WritableStrings;
2928 
2929   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2930                                       Linkage, C, ".str");
2931   GV->setUnnamedAddr(true);
2932   // Don't enforce the target's minimum global alignment, since the only use
2933   // of the string is via this class initializer.
2934   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2935   GV->setAlignment(Align.getQuantity());
2936   Fields[1] =
2937       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2938 
2939   // String length.
2940   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2941   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2942 
2943   // The struct.
2944   CharUnits Alignment = getPointerAlign();
2945   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2946   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2947                                 llvm::GlobalVariable::PrivateLinkage, C,
2948                                 "_unnamed_nsstring_");
2949   GV->setAlignment(Alignment.getQuantity());
2950   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2951   const char *NSStringNonFragileABISection =
2952       "__DATA,__objc_stringobj,regular,no_dead_strip";
2953   // FIXME. Fix section.
2954   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2955                      ? NSStringNonFragileABISection
2956                      : NSStringSection);
2957   Entry.second = GV;
2958 
2959   return ConstantAddress(GV, Alignment);
2960 }
2961 
2962 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2963   if (ObjCFastEnumerationStateType.isNull()) {
2964     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2965     D->startDefinition();
2966 
2967     QualType FieldTypes[] = {
2968       Context.UnsignedLongTy,
2969       Context.getPointerType(Context.getObjCIdType()),
2970       Context.getPointerType(Context.UnsignedLongTy),
2971       Context.getConstantArrayType(Context.UnsignedLongTy,
2972                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2973     };
2974 
2975     for (size_t i = 0; i < 4; ++i) {
2976       FieldDecl *Field = FieldDecl::Create(Context,
2977                                            D,
2978                                            SourceLocation(),
2979                                            SourceLocation(), nullptr,
2980                                            FieldTypes[i], /*TInfo=*/nullptr,
2981                                            /*BitWidth=*/nullptr,
2982                                            /*Mutable=*/false,
2983                                            ICIS_NoInit);
2984       Field->setAccess(AS_public);
2985       D->addDecl(Field);
2986     }
2987 
2988     D->completeDefinition();
2989     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2990   }
2991 
2992   return ObjCFastEnumerationStateType;
2993 }
2994 
2995 llvm::Constant *
2996 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2997   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2998 
2999   // Don't emit it as the address of the string, emit the string data itself
3000   // as an inline array.
3001   if (E->getCharByteWidth() == 1) {
3002     SmallString<64> Str(E->getString());
3003 
3004     // Resize the string to the right size, which is indicated by its type.
3005     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3006     Str.resize(CAT->getSize().getZExtValue());
3007     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3008   }
3009 
3010   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3011   llvm::Type *ElemTy = AType->getElementType();
3012   unsigned NumElements = AType->getNumElements();
3013 
3014   // Wide strings have either 2-byte or 4-byte elements.
3015   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3016     SmallVector<uint16_t, 32> Elements;
3017     Elements.reserve(NumElements);
3018 
3019     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3020       Elements.push_back(E->getCodeUnit(i));
3021     Elements.resize(NumElements);
3022     return llvm::ConstantDataArray::get(VMContext, Elements);
3023   }
3024 
3025   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3026   SmallVector<uint32_t, 32> Elements;
3027   Elements.reserve(NumElements);
3028 
3029   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3030     Elements.push_back(E->getCodeUnit(i));
3031   Elements.resize(NumElements);
3032   return llvm::ConstantDataArray::get(VMContext, Elements);
3033 }
3034 
3035 static llvm::GlobalVariable *
3036 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3037                       CodeGenModule &CGM, StringRef GlobalName,
3038                       CharUnits Alignment) {
3039   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3040   unsigned AddrSpace = 0;
3041   if (CGM.getLangOpts().OpenCL)
3042     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3043 
3044   llvm::Module &M = CGM.getModule();
3045   // Create a global variable for this string
3046   auto *GV = new llvm::GlobalVariable(
3047       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3048       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3049   GV->setAlignment(Alignment.getQuantity());
3050   GV->setUnnamedAddr(true);
3051   if (GV->isWeakForLinker()) {
3052     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3053     GV->setComdat(M.getOrInsertComdat(GV->getName()));
3054   }
3055 
3056   return GV;
3057 }
3058 
3059 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3060 /// constant array for the given string literal.
3061 ConstantAddress
3062 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3063                                                   StringRef Name) {
3064   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3065 
3066   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3067   llvm::GlobalVariable **Entry = nullptr;
3068   if (!LangOpts.WritableStrings) {
3069     Entry = &ConstantStringMap[C];
3070     if (auto GV = *Entry) {
3071       if (Alignment.getQuantity() > GV->getAlignment())
3072         GV->setAlignment(Alignment.getQuantity());
3073       return ConstantAddress(GV, Alignment);
3074     }
3075   }
3076 
3077   SmallString<256> MangledNameBuffer;
3078   StringRef GlobalVariableName;
3079   llvm::GlobalValue::LinkageTypes LT;
3080 
3081   // Mangle the string literal if the ABI allows for it.  However, we cannot
3082   // do this if  we are compiling with ASan or -fwritable-strings because they
3083   // rely on strings having normal linkage.
3084   if (!LangOpts.WritableStrings &&
3085       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3086       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3087     llvm::raw_svector_ostream Out(MangledNameBuffer);
3088     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3089 
3090     LT = llvm::GlobalValue::LinkOnceODRLinkage;
3091     GlobalVariableName = MangledNameBuffer;
3092   } else {
3093     LT = llvm::GlobalValue::PrivateLinkage;
3094     GlobalVariableName = Name;
3095   }
3096 
3097   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3098   if (Entry)
3099     *Entry = GV;
3100 
3101   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3102                                   QualType());
3103   return ConstantAddress(GV, Alignment);
3104 }
3105 
3106 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3107 /// array for the given ObjCEncodeExpr node.
3108 ConstantAddress
3109 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3110   std::string Str;
3111   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3112 
3113   return GetAddrOfConstantCString(Str);
3114 }
3115 
3116 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3117 /// the literal and a terminating '\0' character.
3118 /// The result has pointer to array type.
3119 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3120     const std::string &Str, const char *GlobalName) {
3121   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3122   CharUnits Alignment =
3123     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3124 
3125   llvm::Constant *C =
3126       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3127 
3128   // Don't share any string literals if strings aren't constant.
3129   llvm::GlobalVariable **Entry = nullptr;
3130   if (!LangOpts.WritableStrings) {
3131     Entry = &ConstantStringMap[C];
3132     if (auto GV = *Entry) {
3133       if (Alignment.getQuantity() > GV->getAlignment())
3134         GV->setAlignment(Alignment.getQuantity());
3135       return ConstantAddress(GV, Alignment);
3136     }
3137   }
3138 
3139   // Get the default prefix if a name wasn't specified.
3140   if (!GlobalName)
3141     GlobalName = ".str";
3142   // Create a global variable for this.
3143   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3144                                   GlobalName, Alignment);
3145   if (Entry)
3146     *Entry = GV;
3147   return ConstantAddress(GV, Alignment);
3148 }
3149 
3150 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3151     const MaterializeTemporaryExpr *E, const Expr *Init) {
3152   assert((E->getStorageDuration() == SD_Static ||
3153           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3154   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3155 
3156   // If we're not materializing a subobject of the temporary, keep the
3157   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3158   QualType MaterializedType = Init->getType();
3159   if (Init == E->GetTemporaryExpr())
3160     MaterializedType = E->getType();
3161 
3162   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3163 
3164   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3165     return ConstantAddress(Slot, Align);
3166 
3167   // FIXME: If an externally-visible declaration extends multiple temporaries,
3168   // we need to give each temporary the same name in every translation unit (and
3169   // we also need to make the temporaries externally-visible).
3170   SmallString<256> Name;
3171   llvm::raw_svector_ostream Out(Name);
3172   getCXXABI().getMangleContext().mangleReferenceTemporary(
3173       VD, E->getManglingNumber(), Out);
3174 
3175   APValue *Value = nullptr;
3176   if (E->getStorageDuration() == SD_Static) {
3177     // We might have a cached constant initializer for this temporary. Note
3178     // that this might have a different value from the value computed by
3179     // evaluating the initializer if the surrounding constant expression
3180     // modifies the temporary.
3181     Value = getContext().getMaterializedTemporaryValue(E, false);
3182     if (Value && Value->isUninit())
3183       Value = nullptr;
3184   }
3185 
3186   // Try evaluating it now, it might have a constant initializer.
3187   Expr::EvalResult EvalResult;
3188   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3189       !EvalResult.hasSideEffects())
3190     Value = &EvalResult.Val;
3191 
3192   llvm::Constant *InitialValue = nullptr;
3193   bool Constant = false;
3194   llvm::Type *Type;
3195   if (Value) {
3196     // The temporary has a constant initializer, use it.
3197     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3198     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3199     Type = InitialValue->getType();
3200   } else {
3201     // No initializer, the initialization will be provided when we
3202     // initialize the declaration which performed lifetime extension.
3203     Type = getTypes().ConvertTypeForMem(MaterializedType);
3204   }
3205 
3206   // Create a global variable for this lifetime-extended temporary.
3207   llvm::GlobalValue::LinkageTypes Linkage =
3208       getLLVMLinkageVarDefinition(VD, Constant);
3209   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3210     const VarDecl *InitVD;
3211     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3212         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3213       // Temporaries defined inside a class get linkonce_odr linkage because the
3214       // class can be defined in multipe translation units.
3215       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3216     } else {
3217       // There is no need for this temporary to have external linkage if the
3218       // VarDecl has external linkage.
3219       Linkage = llvm::GlobalVariable::InternalLinkage;
3220     }
3221   }
3222   unsigned AddrSpace = GetGlobalVarAddressSpace(
3223       VD, getContext().getTargetAddressSpace(MaterializedType));
3224   auto *GV = new llvm::GlobalVariable(
3225       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3226       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3227       AddrSpace);
3228   setGlobalVisibility(GV, VD);
3229   GV->setAlignment(Align.getQuantity());
3230   if (supportsCOMDAT() && GV->isWeakForLinker())
3231     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3232   if (VD->getTLSKind())
3233     setTLSMode(GV, *VD);
3234   MaterializedGlobalTemporaryMap[E] = GV;
3235   return ConstantAddress(GV, Align);
3236 }
3237 
3238 /// EmitObjCPropertyImplementations - Emit information for synthesized
3239 /// properties for an implementation.
3240 void CodeGenModule::EmitObjCPropertyImplementations(const
3241                                                     ObjCImplementationDecl *D) {
3242   for (const auto *PID : D->property_impls()) {
3243     // Dynamic is just for type-checking.
3244     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3245       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3246 
3247       // Determine which methods need to be implemented, some may have
3248       // been overridden. Note that ::isPropertyAccessor is not the method
3249       // we want, that just indicates if the decl came from a
3250       // property. What we want to know is if the method is defined in
3251       // this implementation.
3252       if (!D->getInstanceMethod(PD->getGetterName()))
3253         CodeGenFunction(*this).GenerateObjCGetter(
3254                                  const_cast<ObjCImplementationDecl *>(D), PID);
3255       if (!PD->isReadOnly() &&
3256           !D->getInstanceMethod(PD->getSetterName()))
3257         CodeGenFunction(*this).GenerateObjCSetter(
3258                                  const_cast<ObjCImplementationDecl *>(D), PID);
3259     }
3260   }
3261 }
3262 
3263 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3264   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3265   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3266        ivar; ivar = ivar->getNextIvar())
3267     if (ivar->getType().isDestructedType())
3268       return true;
3269 
3270   return false;
3271 }
3272 
3273 static bool AllTrivialInitializers(CodeGenModule &CGM,
3274                                    ObjCImplementationDecl *D) {
3275   CodeGenFunction CGF(CGM);
3276   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3277        E = D->init_end(); B != E; ++B) {
3278     CXXCtorInitializer *CtorInitExp = *B;
3279     Expr *Init = CtorInitExp->getInit();
3280     if (!CGF.isTrivialInitializer(Init))
3281       return false;
3282   }
3283   return true;
3284 }
3285 
3286 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3287 /// for an implementation.
3288 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3289   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3290   if (needsDestructMethod(D)) {
3291     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3292     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3293     ObjCMethodDecl *DTORMethod =
3294       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3295                              cxxSelector, getContext().VoidTy, nullptr, D,
3296                              /*isInstance=*/true, /*isVariadic=*/false,
3297                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3298                              /*isDefined=*/false, ObjCMethodDecl::Required);
3299     D->addInstanceMethod(DTORMethod);
3300     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3301     D->setHasDestructors(true);
3302   }
3303 
3304   // If the implementation doesn't have any ivar initializers, we don't need
3305   // a .cxx_construct.
3306   if (D->getNumIvarInitializers() == 0 ||
3307       AllTrivialInitializers(*this, D))
3308     return;
3309 
3310   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3311   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3312   // The constructor returns 'self'.
3313   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3314                                                 D->getLocation(),
3315                                                 D->getLocation(),
3316                                                 cxxSelector,
3317                                                 getContext().getObjCIdType(),
3318                                                 nullptr, D, /*isInstance=*/true,
3319                                                 /*isVariadic=*/false,
3320                                                 /*isPropertyAccessor=*/true,
3321                                                 /*isImplicitlyDeclared=*/true,
3322                                                 /*isDefined=*/false,
3323                                                 ObjCMethodDecl::Required);
3324   D->addInstanceMethod(CTORMethod);
3325   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3326   D->setHasNonZeroConstructors(true);
3327 }
3328 
3329 /// EmitNamespace - Emit all declarations in a namespace.
3330 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3331   for (auto *I : ND->decls()) {
3332     if (const auto *VD = dyn_cast<VarDecl>(I))
3333       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3334           VD->getTemplateSpecializationKind() != TSK_Undeclared)
3335         continue;
3336     EmitTopLevelDecl(I);
3337   }
3338 }
3339 
3340 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3341 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3342   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3343       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3344     ErrorUnsupported(LSD, "linkage spec");
3345     return;
3346   }
3347 
3348   for (auto *I : LSD->decls()) {
3349     // Meta-data for ObjC class includes references to implemented methods.
3350     // Generate class's method definitions first.
3351     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3352       for (auto *M : OID->methods())
3353         EmitTopLevelDecl(M);
3354     }
3355     EmitTopLevelDecl(I);
3356   }
3357 }
3358 
3359 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3360 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3361   // Ignore dependent declarations.
3362   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3363     return;
3364 
3365   switch (D->getKind()) {
3366   case Decl::CXXConversion:
3367   case Decl::CXXMethod:
3368   case Decl::Function:
3369     // Skip function templates
3370     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3371         cast<FunctionDecl>(D)->isLateTemplateParsed())
3372       return;
3373 
3374     EmitGlobal(cast<FunctionDecl>(D));
3375     // Always provide some coverage mapping
3376     // even for the functions that aren't emitted.
3377     AddDeferredUnusedCoverageMapping(D);
3378     break;
3379 
3380   case Decl::Var:
3381     // Skip variable templates
3382     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3383       return;
3384   case Decl::VarTemplateSpecialization:
3385     EmitGlobal(cast<VarDecl>(D));
3386     break;
3387 
3388   // Indirect fields from global anonymous structs and unions can be
3389   // ignored; only the actual variable requires IR gen support.
3390   case Decl::IndirectField:
3391     break;
3392 
3393   // C++ Decls
3394   case Decl::Namespace:
3395     EmitNamespace(cast<NamespaceDecl>(D));
3396     break;
3397     // No code generation needed.
3398   case Decl::UsingShadow:
3399   case Decl::ClassTemplate:
3400   case Decl::VarTemplate:
3401   case Decl::VarTemplatePartialSpecialization:
3402   case Decl::FunctionTemplate:
3403   case Decl::TypeAliasTemplate:
3404   case Decl::Block:
3405   case Decl::Empty:
3406     break;
3407   case Decl::Using:          // using X; [C++]
3408     if (CGDebugInfo *DI = getModuleDebugInfo())
3409         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3410     return;
3411   case Decl::NamespaceAlias:
3412     if (CGDebugInfo *DI = getModuleDebugInfo())
3413         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3414     return;
3415   case Decl::UsingDirective: // using namespace X; [C++]
3416     if (CGDebugInfo *DI = getModuleDebugInfo())
3417       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3418     return;
3419   case Decl::CXXConstructor:
3420     // Skip function templates
3421     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3422         cast<FunctionDecl>(D)->isLateTemplateParsed())
3423       return;
3424 
3425     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3426     break;
3427   case Decl::CXXDestructor:
3428     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3429       return;
3430     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3431     break;
3432 
3433   case Decl::StaticAssert:
3434     // Nothing to do.
3435     break;
3436 
3437   // Objective-C Decls
3438 
3439   // Forward declarations, no (immediate) code generation.
3440   case Decl::ObjCInterface:
3441   case Decl::ObjCCategory:
3442     break;
3443 
3444   case Decl::ObjCProtocol: {
3445     auto *Proto = cast<ObjCProtocolDecl>(D);
3446     if (Proto->isThisDeclarationADefinition())
3447       ObjCRuntime->GenerateProtocol(Proto);
3448     break;
3449   }
3450 
3451   case Decl::ObjCCategoryImpl:
3452     // Categories have properties but don't support synthesize so we
3453     // can ignore them here.
3454     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3455     break;
3456 
3457   case Decl::ObjCImplementation: {
3458     auto *OMD = cast<ObjCImplementationDecl>(D);
3459     EmitObjCPropertyImplementations(OMD);
3460     EmitObjCIvarInitializations(OMD);
3461     ObjCRuntime->GenerateClass(OMD);
3462     // Emit global variable debug information.
3463     if (CGDebugInfo *DI = getModuleDebugInfo())
3464       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3465         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3466             OMD->getClassInterface()), OMD->getLocation());
3467     break;
3468   }
3469   case Decl::ObjCMethod: {
3470     auto *OMD = cast<ObjCMethodDecl>(D);
3471     // If this is not a prototype, emit the body.
3472     if (OMD->getBody())
3473       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3474     break;
3475   }
3476   case Decl::ObjCCompatibleAlias:
3477     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3478     break;
3479 
3480   case Decl::LinkageSpec:
3481     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3482     break;
3483 
3484   case Decl::FileScopeAsm: {
3485     // File-scope asm is ignored during device-side CUDA compilation.
3486     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3487       break;
3488     auto *AD = cast<FileScopeAsmDecl>(D);
3489     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3490     break;
3491   }
3492 
3493   case Decl::Import: {
3494     auto *Import = cast<ImportDecl>(D);
3495 
3496     // Ignore import declarations that come from imported modules.
3497     if (Import->getImportedOwningModule())
3498       break;
3499     if (CGDebugInfo *DI = getModuleDebugInfo())
3500       DI->EmitImportDecl(*Import);
3501 
3502     ImportedModules.insert(Import->getImportedModule());
3503     break;
3504   }
3505 
3506   case Decl::OMPThreadPrivate:
3507     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3508     break;
3509 
3510   case Decl::ClassTemplateSpecialization: {
3511     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3512     if (DebugInfo &&
3513         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3514         Spec->hasDefinition())
3515       DebugInfo->completeTemplateDefinition(*Spec);
3516     break;
3517   }
3518 
3519   default:
3520     // Make sure we handled everything we should, every other kind is a
3521     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3522     // function. Need to recode Decl::Kind to do that easily.
3523     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3524     break;
3525   }
3526 }
3527 
3528 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3529   // Do we need to generate coverage mapping?
3530   if (!CodeGenOpts.CoverageMapping)
3531     return;
3532   switch (D->getKind()) {
3533   case Decl::CXXConversion:
3534   case Decl::CXXMethod:
3535   case Decl::Function:
3536   case Decl::ObjCMethod:
3537   case Decl::CXXConstructor:
3538   case Decl::CXXDestructor: {
3539     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3540       return;
3541     auto I = DeferredEmptyCoverageMappingDecls.find(D);
3542     if (I == DeferredEmptyCoverageMappingDecls.end())
3543       DeferredEmptyCoverageMappingDecls[D] = true;
3544     break;
3545   }
3546   default:
3547     break;
3548   };
3549 }
3550 
3551 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3552   // Do we need to generate coverage mapping?
3553   if (!CodeGenOpts.CoverageMapping)
3554     return;
3555   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3556     if (Fn->isTemplateInstantiation())
3557       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3558   }
3559   auto I = DeferredEmptyCoverageMappingDecls.find(D);
3560   if (I == DeferredEmptyCoverageMappingDecls.end())
3561     DeferredEmptyCoverageMappingDecls[D] = false;
3562   else
3563     I->second = false;
3564 }
3565 
3566 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3567   std::vector<const Decl *> DeferredDecls;
3568   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
3569     if (!I.second)
3570       continue;
3571     DeferredDecls.push_back(I.first);
3572   }
3573   // Sort the declarations by their location to make sure that the tests get a
3574   // predictable order for the coverage mapping for the unused declarations.
3575   if (CodeGenOpts.DumpCoverageMapping)
3576     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3577               [] (const Decl *LHS, const Decl *RHS) {
3578       return LHS->getLocStart() < RHS->getLocStart();
3579     });
3580   for (const auto *D : DeferredDecls) {
3581     switch (D->getKind()) {
3582     case Decl::CXXConversion:
3583     case Decl::CXXMethod:
3584     case Decl::Function:
3585     case Decl::ObjCMethod: {
3586       CodeGenPGO PGO(*this);
3587       GlobalDecl GD(cast<FunctionDecl>(D));
3588       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3589                                   getFunctionLinkage(GD));
3590       break;
3591     }
3592     case Decl::CXXConstructor: {
3593       CodeGenPGO PGO(*this);
3594       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3595       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3596                                   getFunctionLinkage(GD));
3597       break;
3598     }
3599     case Decl::CXXDestructor: {
3600       CodeGenPGO PGO(*this);
3601       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3602       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3603                                   getFunctionLinkage(GD));
3604       break;
3605     }
3606     default:
3607       break;
3608     };
3609   }
3610 }
3611 
3612 /// Turns the given pointer into a constant.
3613 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3614                                           const void *Ptr) {
3615   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3616   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3617   return llvm::ConstantInt::get(i64, PtrInt);
3618 }
3619 
3620 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3621                                    llvm::NamedMDNode *&GlobalMetadata,
3622                                    GlobalDecl D,
3623                                    llvm::GlobalValue *Addr) {
3624   if (!GlobalMetadata)
3625     GlobalMetadata =
3626       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3627 
3628   // TODO: should we report variant information for ctors/dtors?
3629   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3630                            llvm::ConstantAsMetadata::get(GetPointerConstant(
3631                                CGM.getLLVMContext(), D.getDecl()))};
3632   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3633 }
3634 
3635 /// For each function which is declared within an extern "C" region and marked
3636 /// as 'used', but has internal linkage, create an alias from the unmangled
3637 /// name to the mangled name if possible. People expect to be able to refer
3638 /// to such functions with an unmangled name from inline assembly within the
3639 /// same translation unit.
3640 void CodeGenModule::EmitStaticExternCAliases() {
3641   for (auto &I : StaticExternCValues) {
3642     IdentifierInfo *Name = I.first;
3643     llvm::GlobalValue *Val = I.second;
3644     if (Val && !getModule().getNamedValue(Name->getName()))
3645       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3646   }
3647 }
3648 
3649 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3650                                              GlobalDecl &Result) const {
3651   auto Res = Manglings.find(MangledName);
3652   if (Res == Manglings.end())
3653     return false;
3654   Result = Res->getValue();
3655   return true;
3656 }
3657 
3658 /// Emits metadata nodes associating all the global values in the
3659 /// current module with the Decls they came from.  This is useful for
3660 /// projects using IR gen as a subroutine.
3661 ///
3662 /// Since there's currently no way to associate an MDNode directly
3663 /// with an llvm::GlobalValue, we create a global named metadata
3664 /// with the name 'clang.global.decl.ptrs'.
3665 void CodeGenModule::EmitDeclMetadata() {
3666   llvm::NamedMDNode *GlobalMetadata = nullptr;
3667 
3668   // StaticLocalDeclMap
3669   for (auto &I : MangledDeclNames) {
3670     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3671     EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3672   }
3673 }
3674 
3675 /// Emits metadata nodes for all the local variables in the current
3676 /// function.
3677 void CodeGenFunction::EmitDeclMetadata() {
3678   if (LocalDeclMap.empty()) return;
3679 
3680   llvm::LLVMContext &Context = getLLVMContext();
3681 
3682   // Find the unique metadata ID for this name.
3683   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3684 
3685   llvm::NamedMDNode *GlobalMetadata = nullptr;
3686 
3687   for (auto &I : LocalDeclMap) {
3688     const Decl *D = I.first;
3689     llvm::Value *Addr = I.second.getPointer();
3690     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3691       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3692       Alloca->setMetadata(
3693           DeclPtrKind, llvm::MDNode::get(
3694                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3695     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3696       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3697       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3698     }
3699   }
3700 }
3701 
3702 void CodeGenModule::EmitVersionIdentMetadata() {
3703   llvm::NamedMDNode *IdentMetadata =
3704     TheModule.getOrInsertNamedMetadata("llvm.ident");
3705   std::string Version = getClangFullVersion();
3706   llvm::LLVMContext &Ctx = TheModule.getContext();
3707 
3708   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3709   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3710 }
3711 
3712 void CodeGenModule::EmitTargetMetadata() {
3713   // Warning, new MangledDeclNames may be appended within this loop.
3714   // We rely on MapVector insertions adding new elements to the end
3715   // of the container.
3716   // FIXME: Move this loop into the one target that needs it, and only
3717   // loop over those declarations for which we couldn't emit the target
3718   // metadata when we emitted the declaration.
3719   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3720     auto Val = *(MangledDeclNames.begin() + I);
3721     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3722     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3723     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3724   }
3725 }
3726 
3727 void CodeGenModule::EmitCoverageFile() {
3728   if (!getCodeGenOpts().CoverageFile.empty()) {
3729     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3730       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3731       llvm::LLVMContext &Ctx = TheModule.getContext();
3732       llvm::MDString *CoverageFile =
3733           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3734       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3735         llvm::MDNode *CU = CUNode->getOperand(i);
3736         llvm::Metadata *Elts[] = {CoverageFile, CU};
3737         GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3738       }
3739     }
3740   }
3741 }
3742 
3743 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3744   // Sema has checked that all uuid strings are of the form
3745   // "12345678-1234-1234-1234-1234567890ab".
3746   assert(Uuid.size() == 36);
3747   for (unsigned i = 0; i < 36; ++i) {
3748     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3749     else                                         assert(isHexDigit(Uuid[i]));
3750   }
3751 
3752   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3753   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3754 
3755   llvm::Constant *Field3[8];
3756   for (unsigned Idx = 0; Idx < 8; ++Idx)
3757     Field3[Idx] = llvm::ConstantInt::get(
3758         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3759 
3760   llvm::Constant *Fields[4] = {
3761     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3762     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3763     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3764     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3765   };
3766 
3767   return llvm::ConstantStruct::getAnon(Fields);
3768 }
3769 
3770 llvm::Constant *
3771 CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
3772                                             QualType CatchHandlerType) {
3773   return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
3774 }
3775 
3776 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3777                                                        bool ForEH) {
3778   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3779   // FIXME: should we even be calling this method if RTTI is disabled
3780   // and it's not for EH?
3781   if (!ForEH && !getLangOpts().RTTI)
3782     return llvm::Constant::getNullValue(Int8PtrTy);
3783 
3784   if (ForEH && Ty->isObjCObjectPointerType() &&
3785       LangOpts.ObjCRuntime.isGNUFamily())
3786     return ObjCRuntime->GetEHType(Ty);
3787 
3788   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3789 }
3790 
3791 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3792   for (auto RefExpr : D->varlists()) {
3793     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3794     bool PerformInit =
3795         VD->getAnyInitializer() &&
3796         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3797                                                         /*ForRef=*/false);
3798 
3799     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
3800     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
3801             VD, Addr, RefExpr->getLocStart(), PerformInit))
3802       CXXGlobalInits.push_back(InitFunction);
3803   }
3804 }
3805 
3806 llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry(
3807     llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) {
3808   std::string OutName;
3809   llvm::raw_string_ostream Out(OutName);
3810   getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
3811 
3812   llvm::Metadata *BitsetOps[] = {
3813       llvm::MDString::get(getLLVMContext(), Out.str()),
3814       llvm::ConstantAsMetadata::get(VTable),
3815       llvm::ConstantAsMetadata::get(
3816           llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
3817   return llvm::MDTuple::get(getLLVMContext(), BitsetOps);
3818 }
3819