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