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