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