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