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