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