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