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