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