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