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