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