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