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