xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 0ed613612c5daa047e639877b1c24b36f6069384)
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   std::vector<GlobalDecl> MVFuncsToEmit;
3193   MultiVersionFuncs.swap(MVFuncsToEmit);
3194   for (GlobalDecl GD : MVFuncsToEmit) {
3195     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3196     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3197     getContext().forEachMultiversionedFunctionVersion(
3198         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3199           GlobalDecl CurGD{
3200               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3201           StringRef MangledName = getMangledName(CurGD);
3202           llvm::Constant *Func = GetGlobalValue(MangledName);
3203           if (!Func) {
3204             if (CurFD->isDefined()) {
3205               EmitGlobalFunctionDefinition(CurGD, nullptr);
3206               Func = GetGlobalValue(MangledName);
3207             } else {
3208               const CGFunctionInfo &FI =
3209                   getTypes().arrangeGlobalDeclaration(GD);
3210               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3211               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3212                                        /*DontDefer=*/false, ForDefinition);
3213             }
3214             assert(Func && "This should have just been created");
3215           }
3216 
3217           const auto *TA = CurFD->getAttr<TargetAttr>();
3218           llvm::SmallVector<StringRef, 8> Feats;
3219           TA->getAddedFeatures(Feats);
3220 
3221           Options.emplace_back(cast<llvm::Function>(Func),
3222                                TA->getArchitecture(), Feats);
3223         });
3224 
3225     llvm::Function *ResolverFunc;
3226     const TargetInfo &TI = getTarget();
3227 
3228     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
3229       ResolverFunc = cast<llvm::Function>(
3230           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3231       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3232     } else {
3233       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3234     }
3235 
3236     if (supportsCOMDAT())
3237       ResolverFunc->setComdat(
3238           getModule().getOrInsertComdat(ResolverFunc->getName()));
3239 
3240     llvm::stable_sort(
3241         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3242                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
3243           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3244         });
3245     CodeGenFunction CGF(*this);
3246     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3247   }
3248 
3249   // Ensure that any additions to the deferred decls list caused by emitting a
3250   // variant are emitted.  This can happen when the variant itself is inline and
3251   // calls a function without linkage.
3252   if (!MVFuncsToEmit.empty())
3253     EmitDeferred();
3254 
3255   // Ensure that any additions to the multiversion funcs list from either the
3256   // deferred decls or the multiversion functions themselves are emitted.
3257   if (!MultiVersionFuncs.empty())
3258     emitMultiVersionFunctions();
3259 }
3260 
3261 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3262   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3263   assert(FD && "Not a FunctionDecl?");
3264   const auto *DD = FD->getAttr<CPUDispatchAttr>();
3265   assert(DD && "Not a cpu_dispatch Function?");
3266   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
3267 
3268   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
3269     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
3270     DeclTy = getTypes().GetFunctionType(FInfo);
3271   }
3272 
3273   StringRef ResolverName = getMangledName(GD);
3274 
3275   llvm::Type *ResolverType;
3276   GlobalDecl ResolverGD;
3277   if (getTarget().supportsIFunc())
3278     ResolverType = llvm::FunctionType::get(
3279         llvm::PointerType::get(DeclTy,
3280                                Context.getTargetAddressSpace(FD->getType())),
3281         false);
3282   else {
3283     ResolverType = DeclTy;
3284     ResolverGD = GD;
3285   }
3286 
3287   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3288       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3289   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3290   if (supportsCOMDAT())
3291     ResolverFunc->setComdat(
3292         getModule().getOrInsertComdat(ResolverFunc->getName()));
3293 
3294   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3295   const TargetInfo &Target = getTarget();
3296   unsigned Index = 0;
3297   for (const IdentifierInfo *II : DD->cpus()) {
3298     // Get the name of the target function so we can look it up/create it.
3299     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3300                               getCPUSpecificMangling(*this, II->getName());
3301 
3302     llvm::Constant *Func = GetGlobalValue(MangledName);
3303 
3304     if (!Func) {
3305       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3306       if (ExistingDecl.getDecl() &&
3307           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3308         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3309         Func = GetGlobalValue(MangledName);
3310       } else {
3311         if (!ExistingDecl.getDecl())
3312           ExistingDecl = GD.getWithMultiVersionIndex(Index);
3313 
3314       Func = GetOrCreateLLVMFunction(
3315           MangledName, DeclTy, ExistingDecl,
3316           /*ForVTable=*/false, /*DontDefer=*/true,
3317           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3318       }
3319     }
3320 
3321     llvm::SmallVector<StringRef, 32> Features;
3322     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3323     llvm::transform(Features, Features.begin(),
3324                     [](StringRef Str) { return Str.substr(1); });
3325     Features.erase(std::remove_if(
3326         Features.begin(), Features.end(), [&Target](StringRef Feat) {
3327           return !Target.validateCpuSupports(Feat);
3328         }), Features.end());
3329     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3330     ++Index;
3331   }
3332 
3333   llvm::sort(
3334       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3335                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
3336         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3337                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3338       });
3339 
3340   // If the list contains multiple 'default' versions, such as when it contains
3341   // 'pentium' and 'generic', don't emit the call to the generic one (since we
3342   // always run on at least a 'pentium'). We do this by deleting the 'least
3343   // advanced' (read, lowest mangling letter).
3344   while (Options.size() > 1 &&
3345          CodeGenFunction::GetX86CpuSupportsMask(
3346              (Options.end() - 2)->Conditions.Features) == 0) {
3347     StringRef LHSName = (Options.end() - 2)->Function->getName();
3348     StringRef RHSName = (Options.end() - 1)->Function->getName();
3349     if (LHSName.compare(RHSName) < 0)
3350       Options.erase(Options.end() - 2);
3351     else
3352       Options.erase(Options.end() - 1);
3353   }
3354 
3355   CodeGenFunction CGF(*this);
3356   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3357 
3358   if (getTarget().supportsIFunc()) {
3359     std::string AliasName = getMangledNameImpl(
3360         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3361     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3362     if (!AliasFunc) {
3363       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3364           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3365           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3366       auto *GA = llvm::GlobalAlias::create(
3367          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3368       GA->setLinkage(llvm::Function::WeakODRLinkage);
3369       SetCommonAttributes(GD, GA);
3370     }
3371   }
3372 }
3373 
3374 /// If a dispatcher for the specified mangled name is not in the module, create
3375 /// and return an llvm Function with the specified type.
3376 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3377     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3378   std::string MangledName =
3379       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3380 
3381   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3382   // a separate resolver).
3383   std::string ResolverName = MangledName;
3384   if (getTarget().supportsIFunc())
3385     ResolverName += ".ifunc";
3386   else if (FD->isTargetMultiVersion())
3387     ResolverName += ".resolver";
3388 
3389   // If this already exists, just return that one.
3390   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3391     return ResolverGV;
3392 
3393   // Since this is the first time we've created this IFunc, make sure
3394   // that we put this multiversioned function into the list to be
3395   // replaced later if necessary (target multiversioning only).
3396   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3397     MultiVersionFuncs.push_back(GD);
3398 
3399   if (getTarget().supportsIFunc()) {
3400     llvm::Type *ResolverType = llvm::FunctionType::get(
3401         llvm::PointerType::get(
3402             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3403         false);
3404     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3405         MangledName + ".resolver", ResolverType, GlobalDecl{},
3406         /*ForVTable=*/false);
3407     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3408         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3409     GIF->setName(ResolverName);
3410     SetCommonAttributes(FD, GIF);
3411 
3412     return GIF;
3413   }
3414 
3415   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3416       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3417   assert(isa<llvm::GlobalValue>(Resolver) &&
3418          "Resolver should be created for the first time");
3419   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3420   return Resolver;
3421 }
3422 
3423 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3424 /// module, create and return an llvm Function with the specified type. If there
3425 /// is something in the module with the specified name, return it potentially
3426 /// bitcasted to the right type.
3427 ///
3428 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3429 /// to set the attributes on the function when it is first created.
3430 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3431     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3432     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3433     ForDefinition_t IsForDefinition) {
3434   const Decl *D = GD.getDecl();
3435 
3436   // Any attempts to use a MultiVersion function should result in retrieving
3437   // the iFunc instead. Name Mangling will handle the rest of the changes.
3438   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3439     // For the device mark the function as one that should be emitted.
3440     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3441         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3442         !DontDefer && !IsForDefinition) {
3443       if (const FunctionDecl *FDDef = FD->getDefinition()) {
3444         GlobalDecl GDDef;
3445         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3446           GDDef = GlobalDecl(CD, GD.getCtorType());
3447         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3448           GDDef = GlobalDecl(DD, GD.getDtorType());
3449         else
3450           GDDef = GlobalDecl(FDDef);
3451         EmitGlobal(GDDef);
3452       }
3453     }
3454 
3455     if (FD->isMultiVersion()) {
3456       if (FD->hasAttr<TargetAttr>())
3457         UpdateMultiVersionNames(GD, FD);
3458       if (!IsForDefinition)
3459         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3460     }
3461   }
3462 
3463   // Lookup the entry, lazily creating it if necessary.
3464   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3465   if (Entry) {
3466     if (WeakRefReferences.erase(Entry)) {
3467       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3468       if (FD && !FD->hasAttr<WeakAttr>())
3469         Entry->setLinkage(llvm::Function::ExternalLinkage);
3470     }
3471 
3472     // Handle dropped DLL attributes.
3473     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3474       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3475       setDSOLocal(Entry);
3476     }
3477 
3478     // If there are two attempts to define the same mangled name, issue an
3479     // error.
3480     if (IsForDefinition && !Entry->isDeclaration()) {
3481       GlobalDecl OtherGD;
3482       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3483       // to make sure that we issue an error only once.
3484       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3485           (GD.getCanonicalDecl().getDecl() !=
3486            OtherGD.getCanonicalDecl().getDecl()) &&
3487           DiagnosedConflictingDefinitions.insert(GD).second) {
3488         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3489             << MangledName;
3490         getDiags().Report(OtherGD.getDecl()->getLocation(),
3491                           diag::note_previous_definition);
3492       }
3493     }
3494 
3495     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3496         (Entry->getValueType() == Ty)) {
3497       return Entry;
3498     }
3499 
3500     // Make sure the result is of the correct type.
3501     // (If function is requested for a definition, we always need to create a new
3502     // function, not just return a bitcast.)
3503     if (!IsForDefinition)
3504       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3505   }
3506 
3507   // This function doesn't have a complete type (for example, the return
3508   // type is an incomplete struct). Use a fake type instead, and make
3509   // sure not to try to set attributes.
3510   bool IsIncompleteFunction = false;
3511 
3512   llvm::FunctionType *FTy;
3513   if (isa<llvm::FunctionType>(Ty)) {
3514     FTy = cast<llvm::FunctionType>(Ty);
3515   } else {
3516     FTy = llvm::FunctionType::get(VoidTy, false);
3517     IsIncompleteFunction = true;
3518   }
3519 
3520   llvm::Function *F =
3521       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3522                              Entry ? StringRef() : MangledName, &getModule());
3523 
3524   // If we already created a function with the same mangled name (but different
3525   // type) before, take its name and add it to the list of functions to be
3526   // replaced with F at the end of CodeGen.
3527   //
3528   // This happens if there is a prototype for a function (e.g. "int f()") and
3529   // then a definition of a different type (e.g. "int f(int x)").
3530   if (Entry) {
3531     F->takeName(Entry);
3532 
3533     // This might be an implementation of a function without a prototype, in
3534     // which case, try to do special replacement of calls which match the new
3535     // prototype.  The really key thing here is that we also potentially drop
3536     // arguments from the call site so as to make a direct call, which makes the
3537     // inliner happier and suppresses a number of optimizer warnings (!) about
3538     // dropping arguments.
3539     if (!Entry->use_empty()) {
3540       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3541       Entry->removeDeadConstantUsers();
3542     }
3543 
3544     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3545         F, Entry->getValueType()->getPointerTo());
3546     addGlobalValReplacement(Entry, BC);
3547   }
3548 
3549   assert(F->getName() == MangledName && "name was uniqued!");
3550   if (D)
3551     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3552   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3553     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3554     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3555   }
3556 
3557   if (!DontDefer) {
3558     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3559     // each other bottoming out with the base dtor.  Therefore we emit non-base
3560     // dtors on usage, even if there is no dtor definition in the TU.
3561     if (D && isa<CXXDestructorDecl>(D) &&
3562         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3563                                            GD.getDtorType()))
3564       addDeferredDeclToEmit(GD);
3565 
3566     // This is the first use or definition of a mangled name.  If there is a
3567     // deferred decl with this name, remember that we need to emit it at the end
3568     // of the file.
3569     auto DDI = DeferredDecls.find(MangledName);
3570     if (DDI != DeferredDecls.end()) {
3571       // Move the potentially referenced deferred decl to the
3572       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3573       // don't need it anymore).
3574       addDeferredDeclToEmit(DDI->second);
3575       DeferredDecls.erase(DDI);
3576 
3577       // Otherwise, there are cases we have to worry about where we're
3578       // using a declaration for which we must emit a definition but where
3579       // we might not find a top-level definition:
3580       //   - member functions defined inline in their classes
3581       //   - friend functions defined inline in some class
3582       //   - special member functions with implicit definitions
3583       // If we ever change our AST traversal to walk into class methods,
3584       // this will be unnecessary.
3585       //
3586       // We also don't emit a definition for a function if it's going to be an
3587       // entry in a vtable, unless it's already marked as used.
3588     } else if (getLangOpts().CPlusPlus && D) {
3589       // Look for a declaration that's lexically in a record.
3590       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3591            FD = FD->getPreviousDecl()) {
3592         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3593           if (FD->doesThisDeclarationHaveABody()) {
3594             addDeferredDeclToEmit(GD.getWithDecl(FD));
3595             break;
3596           }
3597         }
3598       }
3599     }
3600   }
3601 
3602   // Make sure the result is of the requested type.
3603   if (!IsIncompleteFunction) {
3604     assert(F->getFunctionType() == Ty);
3605     return F;
3606   }
3607 
3608   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3609   return llvm::ConstantExpr::getBitCast(F, PTy);
3610 }
3611 
3612 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
3613 /// non-null, then this function will use the specified type if it has to
3614 /// create it (this occurs when we see a definition of the function).
3615 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3616                                                  llvm::Type *Ty,
3617                                                  bool ForVTable,
3618                                                  bool DontDefer,
3619                                               ForDefinition_t IsForDefinition) {
3620   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
3621          "consteval function should never be emitted");
3622   // If there was no specific requested type, just convert it now.
3623   if (!Ty) {
3624     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3625     Ty = getTypes().ConvertType(FD->getType());
3626   }
3627 
3628   // Devirtualized destructor calls may come through here instead of via
3629   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3630   // of the complete destructor when necessary.
3631   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3632     if (getTarget().getCXXABI().isMicrosoft() &&
3633         GD.getDtorType() == Dtor_Complete &&
3634         DD->getParent()->getNumVBases() == 0)
3635       GD = GlobalDecl(DD, Dtor_Base);
3636   }
3637 
3638   StringRef MangledName = getMangledName(GD);
3639   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3640                                     /*IsThunk=*/false, llvm::AttributeList(),
3641                                     IsForDefinition);
3642   // Returns kernel handle for HIP kernel stub function.
3643   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
3644       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
3645     auto *Handle = getCUDARuntime().getKernelHandle(
3646         cast<llvm::Function>(F->stripPointerCasts()), GD);
3647     if (IsForDefinition)
3648       return F;
3649     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
3650   }
3651   return F;
3652 }
3653 
3654 static const FunctionDecl *
3655 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3656   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3657   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3658 
3659   IdentifierInfo &CII = C.Idents.get(Name);
3660   for (const auto *Result : DC->lookup(&CII))
3661     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3662       return FD;
3663 
3664   if (!C.getLangOpts().CPlusPlus)
3665     return nullptr;
3666 
3667   // Demangle the premangled name from getTerminateFn()
3668   IdentifierInfo &CXXII =
3669       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3670           ? C.Idents.get("terminate")
3671           : C.Idents.get(Name);
3672 
3673   for (const auto &N : {"__cxxabiv1", "std"}) {
3674     IdentifierInfo &NS = C.Idents.get(N);
3675     for (const auto *Result : DC->lookup(&NS)) {
3676       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3677       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
3678         for (const auto *Result : LSD->lookup(&NS))
3679           if ((ND = dyn_cast<NamespaceDecl>(Result)))
3680             break;
3681 
3682       if (ND)
3683         for (const auto *Result : ND->lookup(&CXXII))
3684           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3685             return FD;
3686     }
3687   }
3688 
3689   return nullptr;
3690 }
3691 
3692 /// CreateRuntimeFunction - Create a new runtime function with the specified
3693 /// type and name.
3694 llvm::FunctionCallee
3695 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3696                                      llvm::AttributeList ExtraAttrs, bool Local,
3697                                      bool AssumeConvergent) {
3698   if (AssumeConvergent) {
3699     ExtraAttrs =
3700         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3701                                 llvm::Attribute::Convergent);
3702   }
3703 
3704   llvm::Constant *C =
3705       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3706                               /*DontDefer=*/false, /*IsThunk=*/false,
3707                               ExtraAttrs);
3708 
3709   if (auto *F = dyn_cast<llvm::Function>(C)) {
3710     if (F->empty()) {
3711       F->setCallingConv(getRuntimeCC());
3712 
3713       // In Windows Itanium environments, try to mark runtime functions
3714       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3715       // will link their standard library statically or dynamically. Marking
3716       // functions imported when they are not imported can cause linker errors
3717       // and warnings.
3718       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3719           !getCodeGenOpts().LTOVisibilityPublicStd) {
3720         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3721         if (!FD || FD->hasAttr<DLLImportAttr>()) {
3722           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3723           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3724         }
3725       }
3726       setDSOLocal(F);
3727     }
3728   }
3729 
3730   return {FTy, C};
3731 }
3732 
3733 /// isTypeConstant - Determine whether an object of this type can be emitted
3734 /// as a constant.
3735 ///
3736 /// If ExcludeCtor is true, the duration when the object's constructor runs
3737 /// will not be considered. The caller will need to verify that the object is
3738 /// not written to during its construction.
3739 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3740   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3741     return false;
3742 
3743   if (Context.getLangOpts().CPlusPlus) {
3744     if (const CXXRecordDecl *Record
3745           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3746       return ExcludeCtor && !Record->hasMutableFields() &&
3747              Record->hasTrivialDestructor();
3748   }
3749 
3750   return true;
3751 }
3752 
3753 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3754 /// create and return an llvm GlobalVariable with the specified type.  If there
3755 /// is something in the module with the specified name, return it potentially
3756 /// bitcasted to the right type.
3757 ///
3758 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3759 /// to set the attributes on the global when it is first created.
3760 ///
3761 /// If IsForDefinition is true, it is guaranteed that an actual global with
3762 /// type Ty will be returned, not conversion of a variable with the same
3763 /// mangled name but some other type.
3764 llvm::Constant *
3765 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3766                                      llvm::PointerType *Ty,
3767                                      const VarDecl *D,
3768                                      ForDefinition_t IsForDefinition) {
3769   // Lookup the entry, lazily creating it if necessary.
3770   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3771   if (Entry) {
3772     if (WeakRefReferences.erase(Entry)) {
3773       if (D && !D->hasAttr<WeakAttr>())
3774         Entry->setLinkage(llvm::Function::ExternalLinkage);
3775     }
3776 
3777     // Handle dropped DLL attributes.
3778     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3779       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3780 
3781     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3782       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3783 
3784     if (Entry->getType() == Ty)
3785       return Entry;
3786 
3787     // If there are two attempts to define the same mangled name, issue an
3788     // error.
3789     if (IsForDefinition && !Entry->isDeclaration()) {
3790       GlobalDecl OtherGD;
3791       const VarDecl *OtherD;
3792 
3793       // Check that D is not yet in DiagnosedConflictingDefinitions is required
3794       // to make sure that we issue an error only once.
3795       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3796           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3797           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3798           OtherD->hasInit() &&
3799           DiagnosedConflictingDefinitions.insert(D).second) {
3800         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3801             << MangledName;
3802         getDiags().Report(OtherGD.getDecl()->getLocation(),
3803                           diag::note_previous_definition);
3804       }
3805     }
3806 
3807     // Make sure the result is of the correct type.
3808     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3809       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3810 
3811     // (If global is requested for a definition, we always need to create a new
3812     // global, not just return a bitcast.)
3813     if (!IsForDefinition)
3814       return llvm::ConstantExpr::getBitCast(Entry, Ty);
3815   }
3816 
3817   auto AddrSpace = GetGlobalVarAddressSpace(D);
3818   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3819 
3820   auto *GV = new llvm::GlobalVariable(
3821       getModule(), Ty->getElementType(), false,
3822       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3823       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3824 
3825   // If we already created a global with the same mangled name (but different
3826   // type) before, take its name and remove it from its parent.
3827   if (Entry) {
3828     GV->takeName(Entry);
3829 
3830     if (!Entry->use_empty()) {
3831       llvm::Constant *NewPtrForOldDecl =
3832           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3833       Entry->replaceAllUsesWith(NewPtrForOldDecl);
3834     }
3835 
3836     Entry->eraseFromParent();
3837   }
3838 
3839   // This is the first use or definition of a mangled name.  If there is a
3840   // deferred decl with this name, remember that we need to emit it at the end
3841   // of the file.
3842   auto DDI = DeferredDecls.find(MangledName);
3843   if (DDI != DeferredDecls.end()) {
3844     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3845     // list, and remove it from DeferredDecls (since we don't need it anymore).
3846     addDeferredDeclToEmit(DDI->second);
3847     DeferredDecls.erase(DDI);
3848   }
3849 
3850   // Handle things which are present even on external declarations.
3851   if (D) {
3852     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3853       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3854 
3855     // FIXME: This code is overly simple and should be merged with other global
3856     // handling.
3857     GV->setConstant(isTypeConstant(D->getType(), false));
3858 
3859     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3860 
3861     setLinkageForGV(GV, D);
3862 
3863     if (D->getTLSKind()) {
3864       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3865         CXXThreadLocals.push_back(D);
3866       setTLSMode(GV, *D);
3867     }
3868 
3869     setGVProperties(GV, D);
3870 
3871     // If required by the ABI, treat declarations of static data members with
3872     // inline initializers as definitions.
3873     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3874       EmitGlobalVarDefinition(D);
3875     }
3876 
3877     // Emit section information for extern variables.
3878     if (D->hasExternalStorage()) {
3879       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3880         GV->setSection(SA->getName());
3881     }
3882 
3883     // Handle XCore specific ABI requirements.
3884     if (getTriple().getArch() == llvm::Triple::xcore &&
3885         D->getLanguageLinkage() == CLanguageLinkage &&
3886         D->getType().isConstant(Context) &&
3887         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3888       GV->setSection(".cp.rodata");
3889 
3890     // Check if we a have a const declaration with an initializer, we may be
3891     // able to emit it as available_externally to expose it's value to the
3892     // optimizer.
3893     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3894         D->getType().isConstQualified() && !GV->hasInitializer() &&
3895         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3896       const auto *Record =
3897           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3898       bool HasMutableFields = Record && Record->hasMutableFields();
3899       if (!HasMutableFields) {
3900         const VarDecl *InitDecl;
3901         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3902         if (InitExpr) {
3903           ConstantEmitter emitter(*this);
3904           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3905           if (Init) {
3906             auto *InitType = Init->getType();
3907             if (GV->getValueType() != InitType) {
3908               // The type of the initializer does not match the definition.
3909               // This happens when an initializer has a different type from
3910               // the type of the global (because of padding at the end of a
3911               // structure for instance).
3912               GV->setName(StringRef());
3913               // Make a new global with the correct type, this is now guaranteed
3914               // to work.
3915               auto *NewGV = cast<llvm::GlobalVariable>(
3916                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3917                       ->stripPointerCasts());
3918 
3919               // Erase the old global, since it is no longer used.
3920               GV->eraseFromParent();
3921               GV = NewGV;
3922             } else {
3923               GV->setInitializer(Init);
3924               GV->setConstant(true);
3925               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3926             }
3927             emitter.finalize(GV);
3928           }
3929         }
3930       }
3931     }
3932   }
3933 
3934   if (GV->isDeclaration()) {
3935     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3936     // External HIP managed variables needed to be recorded for transformation
3937     // in both device and host compilations.
3938     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
3939         D->hasExternalStorage())
3940       getCUDARuntime().handleVarRegistration(D, *GV);
3941   }
3942 
3943   LangAS ExpectedAS =
3944       D ? D->getType().getAddressSpace()
3945         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3946   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3947          Ty->getPointerAddressSpace());
3948   if (AddrSpace != ExpectedAS)
3949     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3950                                                        ExpectedAS, Ty);
3951 
3952   return GV;
3953 }
3954 
3955 llvm::Constant *
3956 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
3957   const Decl *D = GD.getDecl();
3958 
3959   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3960     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3961                                 /*DontDefer=*/false, IsForDefinition);
3962 
3963   if (isa<CXXMethodDecl>(D)) {
3964     auto FInfo =
3965         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
3966     auto Ty = getTypes().GetFunctionType(*FInfo);
3967     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3968                              IsForDefinition);
3969   }
3970 
3971   if (isa<FunctionDecl>(D)) {
3972     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3973     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3974     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3975                              IsForDefinition);
3976   }
3977 
3978   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
3979 }
3980 
3981 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3982     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3983     unsigned Alignment) {
3984   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3985   llvm::GlobalVariable *OldGV = nullptr;
3986 
3987   if (GV) {
3988     // Check if the variable has the right type.
3989     if (GV->getValueType() == Ty)
3990       return GV;
3991 
3992     // Because C++ name mangling, the only way we can end up with an already
3993     // existing global with the same name is if it has been declared extern "C".
3994     assert(GV->isDeclaration() && "Declaration has wrong type!");
3995     OldGV = GV;
3996   }
3997 
3998   // Create a new variable.
3999   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4000                                 Linkage, nullptr, Name);
4001 
4002   if (OldGV) {
4003     // Replace occurrences of the old variable if needed.
4004     GV->takeName(OldGV);
4005 
4006     if (!OldGV->use_empty()) {
4007       llvm::Constant *NewPtrForOldDecl =
4008       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4009       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4010     }
4011 
4012     OldGV->eraseFromParent();
4013   }
4014 
4015   if (supportsCOMDAT() && GV->isWeakForLinker() &&
4016       !GV->hasAvailableExternallyLinkage())
4017     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4018 
4019   GV->setAlignment(llvm::MaybeAlign(Alignment));
4020 
4021   return GV;
4022 }
4023 
4024 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4025 /// given global variable.  If Ty is non-null and if the global doesn't exist,
4026 /// then it will be created with the specified type instead of whatever the
4027 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4028 /// that an actual global with type Ty will be returned, not conversion of a
4029 /// variable with the same mangled name but some other type.
4030 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4031                                                   llvm::Type *Ty,
4032                                            ForDefinition_t IsForDefinition) {
4033   assert(D->hasGlobalStorage() && "Not a global variable");
4034   QualType ASTTy = D->getType();
4035   if (!Ty)
4036     Ty = getTypes().ConvertTypeForMem(ASTTy);
4037 
4038   llvm::PointerType *PTy =
4039     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4040 
4041   StringRef MangledName = getMangledName(D);
4042   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
4043 }
4044 
4045 /// CreateRuntimeVariable - Create a new runtime global variable with the
4046 /// specified type and name.
4047 llvm::Constant *
4048 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4049                                      StringRef Name) {
4050   auto PtrTy =
4051       getContext().getLangOpts().OpenCL
4052           ? llvm::PointerType::get(
4053                 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
4054           : llvm::PointerType::getUnqual(Ty);
4055   auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
4056   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4057   return Ret;
4058 }
4059 
4060 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4061   assert(!D->getInit() && "Cannot emit definite definitions here!");
4062 
4063   StringRef MangledName = getMangledName(D);
4064   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4065 
4066   // We already have a definition, not declaration, with the same mangled name.
4067   // Emitting of declaration is not required (and actually overwrites emitted
4068   // definition).
4069   if (GV && !GV->isDeclaration())
4070     return;
4071 
4072   // If we have not seen a reference to this variable yet, place it into the
4073   // deferred declarations table to be emitted if needed later.
4074   if (!MustBeEmitted(D) && !GV) {
4075       DeferredDecls[MangledName] = D;
4076       return;
4077   }
4078 
4079   // The tentative definition is the only definition.
4080   EmitGlobalVarDefinition(D);
4081 }
4082 
4083 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4084   EmitExternalVarDeclaration(D);
4085 }
4086 
4087 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4088   return Context.toCharUnitsFromBits(
4089       getDataLayout().getTypeStoreSizeInBits(Ty));
4090 }
4091 
4092 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4093   LangAS AddrSpace = LangAS::Default;
4094   if (LangOpts.OpenCL) {
4095     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4096     assert(AddrSpace == LangAS::opencl_global ||
4097            AddrSpace == LangAS::opencl_global_device ||
4098            AddrSpace == LangAS::opencl_global_host ||
4099            AddrSpace == LangAS::opencl_constant ||
4100            AddrSpace == LangAS::opencl_local ||
4101            AddrSpace >= LangAS::FirstTargetAddressSpace);
4102     return AddrSpace;
4103   }
4104 
4105   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4106     if (D && D->hasAttr<CUDAConstantAttr>())
4107       return LangAS::cuda_constant;
4108     else if (D && D->hasAttr<CUDASharedAttr>())
4109       return LangAS::cuda_shared;
4110     else if (D && D->hasAttr<CUDADeviceAttr>())
4111       return LangAS::cuda_device;
4112     else if (D && D->getType().isConstQualified())
4113       return LangAS::cuda_constant;
4114     else
4115       return LangAS::cuda_device;
4116   }
4117 
4118   if (LangOpts.OpenMP) {
4119     LangAS AS;
4120     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4121       return AS;
4122   }
4123   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4124 }
4125 
4126 LangAS CodeGenModule::getStringLiteralAddressSpace() const {
4127   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4128   if (LangOpts.OpenCL)
4129     return LangAS::opencl_constant;
4130   if (auto AS = getTarget().getConstantAddressSpace())
4131     return AS.getValue();
4132   return LangAS::Default;
4133 }
4134 
4135 // In address space agnostic languages, string literals are in default address
4136 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4137 // emitted in constant address space in LLVM IR. To be consistent with other
4138 // parts of AST, string literal global variables in constant address space
4139 // need to be casted to default address space before being put into address
4140 // map and referenced by other part of CodeGen.
4141 // In OpenCL, string literals are in constant address space in AST, therefore
4142 // they should not be casted to default address space.
4143 static llvm::Constant *
4144 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4145                                        llvm::GlobalVariable *GV) {
4146   llvm::Constant *Cast = GV;
4147   if (!CGM.getLangOpts().OpenCL) {
4148     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
4149       if (AS != LangAS::Default)
4150         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4151             CGM, GV, AS.getValue(), LangAS::Default,
4152             GV->getValueType()->getPointerTo(
4153                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4154     }
4155   }
4156   return Cast;
4157 }
4158 
4159 template<typename SomeDecl>
4160 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4161                                                llvm::GlobalValue *GV) {
4162   if (!getLangOpts().CPlusPlus)
4163     return;
4164 
4165   // Must have 'used' attribute, or else inline assembly can't rely on
4166   // the name existing.
4167   if (!D->template hasAttr<UsedAttr>())
4168     return;
4169 
4170   // Must have internal linkage and an ordinary name.
4171   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4172     return;
4173 
4174   // Must be in an extern "C" context. Entities declared directly within
4175   // a record are not extern "C" even if the record is in such a context.
4176   const SomeDecl *First = D->getFirstDecl();
4177   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4178     return;
4179 
4180   // OK, this is an internal linkage entity inside an extern "C" linkage
4181   // specification. Make a note of that so we can give it the "expected"
4182   // mangled name if nothing else is using that name.
4183   std::pair<StaticExternCMap::iterator, bool> R =
4184       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4185 
4186   // If we have multiple internal linkage entities with the same name
4187   // in extern "C" regions, none of them gets that name.
4188   if (!R.second)
4189     R.first->second = nullptr;
4190 }
4191 
4192 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4193   if (!CGM.supportsCOMDAT())
4194     return false;
4195 
4196   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
4197   // them being "merged" by the COMDAT Folding linker optimization.
4198   if (D.hasAttr<CUDAGlobalAttr>())
4199     return false;
4200 
4201   if (D.hasAttr<SelectAnyAttr>())
4202     return true;
4203 
4204   GVALinkage Linkage;
4205   if (auto *VD = dyn_cast<VarDecl>(&D))
4206     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4207   else
4208     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4209 
4210   switch (Linkage) {
4211   case GVA_Internal:
4212   case GVA_AvailableExternally:
4213   case GVA_StrongExternal:
4214     return false;
4215   case GVA_DiscardableODR:
4216   case GVA_StrongODR:
4217     return true;
4218   }
4219   llvm_unreachable("No such linkage");
4220 }
4221 
4222 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4223                                           llvm::GlobalObject &GO) {
4224   if (!shouldBeInCOMDAT(*this, D))
4225     return;
4226   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4227 }
4228 
4229 /// Pass IsTentative as true if you want to create a tentative definition.
4230 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4231                                             bool IsTentative) {
4232   // OpenCL global variables of sampler type are translated to function calls,
4233   // therefore no need to be translated.
4234   QualType ASTTy = D->getType();
4235   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4236     return;
4237 
4238   // If this is OpenMP device, check if it is legal to emit this global
4239   // normally.
4240   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4241       OpenMPRuntime->emitTargetGlobalVariable(D))
4242     return;
4243 
4244   llvm::Constant *Init = nullptr;
4245   bool NeedsGlobalCtor = false;
4246   bool NeedsGlobalDtor =
4247       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4248 
4249   const VarDecl *InitDecl;
4250   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4251 
4252   Optional<ConstantEmitter> emitter;
4253 
4254   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4255   // as part of their declaration."  Sema has already checked for
4256   // error cases, so we just need to set Init to UndefValue.
4257   bool IsCUDASharedVar =
4258       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4259   // Shadows of initialized device-side global variables are also left
4260   // undefined.
4261   // Managed Variables should be initialized on both host side and device side.
4262   bool IsCUDAShadowVar =
4263       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4264       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4265        D->hasAttr<CUDASharedAttr>());
4266   bool IsCUDADeviceShadowVar =
4267       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4268       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4269        D->getType()->isCUDADeviceBuiltinTextureType());
4270   if (getLangOpts().CUDA &&
4271       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4272     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4273   else if (D->hasAttr<LoaderUninitializedAttr>())
4274     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4275   else if (!InitExpr) {
4276     // This is a tentative definition; tentative definitions are
4277     // implicitly initialized with { 0 }.
4278     //
4279     // Note that tentative definitions are only emitted at the end of
4280     // a translation unit, so they should never have incomplete
4281     // type. In addition, EmitTentativeDefinition makes sure that we
4282     // never attempt to emit a tentative definition if a real one
4283     // exists. A use may still exists, however, so we still may need
4284     // to do a RAUW.
4285     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4286     Init = EmitNullConstant(D->getType());
4287   } else {
4288     initializedGlobalDecl = GlobalDecl(D);
4289     emitter.emplace(*this);
4290     Init = emitter->tryEmitForInitializer(*InitDecl);
4291 
4292     if (!Init) {
4293       QualType T = InitExpr->getType();
4294       if (D->getType()->isReferenceType())
4295         T = D->getType();
4296 
4297       if (getLangOpts().CPlusPlus) {
4298         Init = EmitNullConstant(T);
4299         NeedsGlobalCtor = true;
4300       } else {
4301         ErrorUnsupported(D, "static initializer");
4302         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4303       }
4304     } else {
4305       // We don't need an initializer, so remove the entry for the delayed
4306       // initializer position (just in case this entry was delayed) if we
4307       // also don't need to register a destructor.
4308       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4309         DelayedCXXInitPosition.erase(D);
4310     }
4311   }
4312 
4313   llvm::Type* InitType = Init->getType();
4314   llvm::Constant *Entry =
4315       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4316 
4317   // Strip off pointer casts if we got them.
4318   Entry = Entry->stripPointerCasts();
4319 
4320   // Entry is now either a Function or GlobalVariable.
4321   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4322 
4323   // We have a definition after a declaration with the wrong type.
4324   // We must make a new GlobalVariable* and update everything that used OldGV
4325   // (a declaration or tentative definition) with the new GlobalVariable*
4326   // (which will be a definition).
4327   //
4328   // This happens if there is a prototype for a global (e.g.
4329   // "extern int x[];") and then a definition of a different type (e.g.
4330   // "int x[10];"). This also happens when an initializer has a different type
4331   // from the type of the global (this happens with unions).
4332   if (!GV || GV->getValueType() != InitType ||
4333       GV->getType()->getAddressSpace() !=
4334           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4335 
4336     // Move the old entry aside so that we'll create a new one.
4337     Entry->setName(StringRef());
4338 
4339     // Make a new global with the correct type, this is now guaranteed to work.
4340     GV = cast<llvm::GlobalVariable>(
4341         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4342             ->stripPointerCasts());
4343 
4344     // Replace all uses of the old global with the new global
4345     llvm::Constant *NewPtrForOldDecl =
4346         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4347     Entry->replaceAllUsesWith(NewPtrForOldDecl);
4348 
4349     // Erase the old global, since it is no longer used.
4350     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4351   }
4352 
4353   MaybeHandleStaticInExternC(D, GV);
4354 
4355   if (D->hasAttr<AnnotateAttr>())
4356     AddGlobalAnnotations(D, GV);
4357 
4358   // Set the llvm linkage type as appropriate.
4359   llvm::GlobalValue::LinkageTypes Linkage =
4360       getLLVMLinkageVarDefinition(D, GV->isConstant());
4361 
4362   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4363   // the device. [...]"
4364   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4365   // __device__, declares a variable that: [...]
4366   // Is accessible from all the threads within the grid and from the host
4367   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4368   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4369   if (GV && LangOpts.CUDA) {
4370     if (LangOpts.CUDAIsDevice) {
4371       if (Linkage != llvm::GlobalValue::InternalLinkage &&
4372           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
4373         GV->setExternallyInitialized(true);
4374     } else {
4375       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4376     }
4377     getCUDARuntime().handleVarRegistration(D, *GV);
4378   }
4379 
4380   GV->setInitializer(Init);
4381   if (emitter)
4382     emitter->finalize(GV);
4383 
4384   // If it is safe to mark the global 'constant', do so now.
4385   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4386                   isTypeConstant(D->getType(), true));
4387 
4388   // If it is in a read-only section, mark it 'constant'.
4389   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4390     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4391     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4392       GV->setConstant(true);
4393   }
4394 
4395   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4396 
4397   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4398   // function is only defined alongside the variable, not also alongside
4399   // callers. Normally, all accesses to a thread_local go through the
4400   // thread-wrapper in order to ensure initialization has occurred, underlying
4401   // variable will never be used other than the thread-wrapper, so it can be
4402   // converted to internal linkage.
4403   //
4404   // However, if the variable has the 'constinit' attribute, it _can_ be
4405   // referenced directly, without calling the thread-wrapper, so the linkage
4406   // must not be changed.
4407   //
4408   // Additionally, if the variable isn't plain external linkage, e.g. if it's
4409   // weak or linkonce, the de-duplication semantics are important to preserve,
4410   // so we don't change the linkage.
4411   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4412       Linkage == llvm::GlobalValue::ExternalLinkage &&
4413       Context.getTargetInfo().getTriple().isOSDarwin() &&
4414       !D->hasAttr<ConstInitAttr>())
4415     Linkage = llvm::GlobalValue::InternalLinkage;
4416 
4417   GV->setLinkage(Linkage);
4418   if (D->hasAttr<DLLImportAttr>())
4419     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4420   else if (D->hasAttr<DLLExportAttr>())
4421     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4422   else
4423     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4424 
4425   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4426     // common vars aren't constant even if declared const.
4427     GV->setConstant(false);
4428     // Tentative definition of global variables may be initialized with
4429     // non-zero null pointers. In this case they should have weak linkage
4430     // since common linkage must have zero initializer and must not have
4431     // explicit section therefore cannot have non-zero initial value.
4432     if (!GV->getInitializer()->isNullValue())
4433       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4434   }
4435 
4436   setNonAliasAttributes(D, GV);
4437 
4438   if (D->getTLSKind() && !GV->isThreadLocal()) {
4439     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4440       CXXThreadLocals.push_back(D);
4441     setTLSMode(GV, *D);
4442   }
4443 
4444   maybeSetTrivialComdat(*D, *GV);
4445 
4446   // Emit the initializer function if necessary.
4447   if (NeedsGlobalCtor || NeedsGlobalDtor)
4448     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4449 
4450   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4451 
4452   // Emit global variable debug information.
4453   if (CGDebugInfo *DI = getModuleDebugInfo())
4454     if (getCodeGenOpts().hasReducedDebugInfo())
4455       DI->EmitGlobalVariable(GV, D);
4456 }
4457 
4458 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4459   if (CGDebugInfo *DI = getModuleDebugInfo())
4460     if (getCodeGenOpts().hasReducedDebugInfo()) {
4461       QualType ASTTy = D->getType();
4462       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4463       llvm::PointerType *PTy =
4464           llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4465       llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4466       DI->EmitExternalVariable(
4467           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4468     }
4469 }
4470 
4471 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4472                                       CodeGenModule &CGM, const VarDecl *D,
4473                                       bool NoCommon) {
4474   // Don't give variables common linkage if -fno-common was specified unless it
4475   // was overridden by a NoCommon attribute.
4476   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4477     return true;
4478 
4479   // C11 6.9.2/2:
4480   //   A declaration of an identifier for an object that has file scope without
4481   //   an initializer, and without a storage-class specifier or with the
4482   //   storage-class specifier static, constitutes a tentative definition.
4483   if (D->getInit() || D->hasExternalStorage())
4484     return true;
4485 
4486   // A variable cannot be both common and exist in a section.
4487   if (D->hasAttr<SectionAttr>())
4488     return true;
4489 
4490   // A variable cannot be both common and exist in a section.
4491   // We don't try to determine which is the right section in the front-end.
4492   // If no specialized section name is applicable, it will resort to default.
4493   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4494       D->hasAttr<PragmaClangDataSectionAttr>() ||
4495       D->hasAttr<PragmaClangRelroSectionAttr>() ||
4496       D->hasAttr<PragmaClangRodataSectionAttr>())
4497     return true;
4498 
4499   // Thread local vars aren't considered common linkage.
4500   if (D->getTLSKind())
4501     return true;
4502 
4503   // Tentative definitions marked with WeakImportAttr are true definitions.
4504   if (D->hasAttr<WeakImportAttr>())
4505     return true;
4506 
4507   // A variable cannot be both common and exist in a comdat.
4508   if (shouldBeInCOMDAT(CGM, *D))
4509     return true;
4510 
4511   // Declarations with a required alignment do not have common linkage in MSVC
4512   // mode.
4513   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4514     if (D->hasAttr<AlignedAttr>())
4515       return true;
4516     QualType VarType = D->getType();
4517     if (Context.isAlignmentRequired(VarType))
4518       return true;
4519 
4520     if (const auto *RT = VarType->getAs<RecordType>()) {
4521       const RecordDecl *RD = RT->getDecl();
4522       for (const FieldDecl *FD : RD->fields()) {
4523         if (FD->isBitField())
4524           continue;
4525         if (FD->hasAttr<AlignedAttr>())
4526           return true;
4527         if (Context.isAlignmentRequired(FD->getType()))
4528           return true;
4529       }
4530     }
4531   }
4532 
4533   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4534   // common symbols, so symbols with greater alignment requirements cannot be
4535   // common.
4536   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4537   // alignments for common symbols via the aligncomm directive, so this
4538   // restriction only applies to MSVC environments.
4539   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4540       Context.getTypeAlignIfKnown(D->getType()) >
4541           Context.toBits(CharUnits::fromQuantity(32)))
4542     return true;
4543 
4544   return false;
4545 }
4546 
4547 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4548     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4549   if (Linkage == GVA_Internal)
4550     return llvm::Function::InternalLinkage;
4551 
4552   if (D->hasAttr<WeakAttr>()) {
4553     if (IsConstantVariable)
4554       return llvm::GlobalVariable::WeakODRLinkage;
4555     else
4556       return llvm::GlobalVariable::WeakAnyLinkage;
4557   }
4558 
4559   if (const auto *FD = D->getAsFunction())
4560     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4561       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4562 
4563   // We are guaranteed to have a strong definition somewhere else,
4564   // so we can use available_externally linkage.
4565   if (Linkage == GVA_AvailableExternally)
4566     return llvm::GlobalValue::AvailableExternallyLinkage;
4567 
4568   // Note that Apple's kernel linker doesn't support symbol
4569   // coalescing, so we need to avoid linkonce and weak linkages there.
4570   // Normally, this means we just map to internal, but for explicit
4571   // instantiations we'll map to external.
4572 
4573   // In C++, the compiler has to emit a definition in every translation unit
4574   // that references the function.  We should use linkonce_odr because
4575   // a) if all references in this translation unit are optimized away, we
4576   // don't need to codegen it.  b) if the function persists, it needs to be
4577   // merged with other definitions. c) C++ has the ODR, so we know the
4578   // definition is dependable.
4579   if (Linkage == GVA_DiscardableODR)
4580     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4581                                             : llvm::Function::InternalLinkage;
4582 
4583   // An explicit instantiation of a template has weak linkage, since
4584   // explicit instantiations can occur in multiple translation units
4585   // and must all be equivalent. However, we are not allowed to
4586   // throw away these explicit instantiations.
4587   //
4588   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
4589   // so say that CUDA templates are either external (for kernels) or internal.
4590   // This lets llvm perform aggressive inter-procedural optimizations. For
4591   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4592   // therefore we need to follow the normal linkage paradigm.
4593   if (Linkage == GVA_StrongODR) {
4594     if (getLangOpts().AppleKext)
4595       return llvm::Function::ExternalLinkage;
4596     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4597         !getLangOpts().GPURelocatableDeviceCode)
4598       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4599                                           : llvm::Function::InternalLinkage;
4600     return llvm::Function::WeakODRLinkage;
4601   }
4602 
4603   // C++ doesn't have tentative definitions and thus cannot have common
4604   // linkage.
4605   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4606       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4607                                  CodeGenOpts.NoCommon))
4608     return llvm::GlobalVariable::CommonLinkage;
4609 
4610   // selectany symbols are externally visible, so use weak instead of
4611   // linkonce.  MSVC optimizes away references to const selectany globals, so
4612   // all definitions should be the same and ODR linkage should be used.
4613   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4614   if (D->hasAttr<SelectAnyAttr>())
4615     return llvm::GlobalVariable::WeakODRLinkage;
4616 
4617   // Otherwise, we have strong external linkage.
4618   assert(Linkage == GVA_StrongExternal);
4619   return llvm::GlobalVariable::ExternalLinkage;
4620 }
4621 
4622 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4623     const VarDecl *VD, bool IsConstant) {
4624   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4625   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4626 }
4627 
4628 /// Replace the uses of a function that was declared with a non-proto type.
4629 /// We want to silently drop extra arguments from call sites
4630 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4631                                           llvm::Function *newFn) {
4632   // Fast path.
4633   if (old->use_empty()) return;
4634 
4635   llvm::Type *newRetTy = newFn->getReturnType();
4636   SmallVector<llvm::Value*, 4> newArgs;
4637 
4638   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4639          ui != ue; ) {
4640     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4641     llvm::User *user = use->getUser();
4642 
4643     // Recognize and replace uses of bitcasts.  Most calls to
4644     // unprototyped functions will use bitcasts.
4645     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4646       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4647         replaceUsesOfNonProtoConstant(bitcast, newFn);
4648       continue;
4649     }
4650 
4651     // Recognize calls to the function.
4652     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4653     if (!callSite) continue;
4654     if (!callSite->isCallee(&*use))
4655       continue;
4656 
4657     // If the return types don't match exactly, then we can't
4658     // transform this call unless it's dead.
4659     if (callSite->getType() != newRetTy && !callSite->use_empty())
4660       continue;
4661 
4662     // Get the call site's attribute list.
4663     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4664     llvm::AttributeList oldAttrs = callSite->getAttributes();
4665 
4666     // If the function was passed too few arguments, don't transform.
4667     unsigned newNumArgs = newFn->arg_size();
4668     if (callSite->arg_size() < newNumArgs)
4669       continue;
4670 
4671     // If extra arguments were passed, we silently drop them.
4672     // If any of the types mismatch, we don't transform.
4673     unsigned argNo = 0;
4674     bool dontTransform = false;
4675     for (llvm::Argument &A : newFn->args()) {
4676       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4677         dontTransform = true;
4678         break;
4679       }
4680 
4681       // Add any parameter attributes.
4682       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4683       argNo++;
4684     }
4685     if (dontTransform)
4686       continue;
4687 
4688     // Okay, we can transform this.  Create the new call instruction and copy
4689     // over the required information.
4690     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4691 
4692     // Copy over any operand bundles.
4693     SmallVector<llvm::OperandBundleDef, 1> newBundles;
4694     callSite->getOperandBundlesAsDefs(newBundles);
4695 
4696     llvm::CallBase *newCall;
4697     if (dyn_cast<llvm::CallInst>(callSite)) {
4698       newCall =
4699           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4700     } else {
4701       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4702       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4703                                          oldInvoke->getUnwindDest(), newArgs,
4704                                          newBundles, "", callSite);
4705     }
4706     newArgs.clear(); // for the next iteration
4707 
4708     if (!newCall->getType()->isVoidTy())
4709       newCall->takeName(callSite);
4710     newCall->setAttributes(llvm::AttributeList::get(
4711         newFn->getContext(), oldAttrs.getFnAttributes(),
4712         oldAttrs.getRetAttributes(), newArgAttrs));
4713     newCall->setCallingConv(callSite->getCallingConv());
4714 
4715     // Finally, remove the old call, replacing any uses with the new one.
4716     if (!callSite->use_empty())
4717       callSite->replaceAllUsesWith(newCall);
4718 
4719     // Copy debug location attached to CI.
4720     if (callSite->getDebugLoc())
4721       newCall->setDebugLoc(callSite->getDebugLoc());
4722 
4723     callSite->eraseFromParent();
4724   }
4725 }
4726 
4727 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4728 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
4729 /// existing call uses of the old function in the module, this adjusts them to
4730 /// call the new function directly.
4731 ///
4732 /// This is not just a cleanup: the always_inline pass requires direct calls to
4733 /// functions to be able to inline them.  If there is a bitcast in the way, it
4734 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
4735 /// run at -O0.
4736 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4737                                                       llvm::Function *NewFn) {
4738   // If we're redefining a global as a function, don't transform it.
4739   if (!isa<llvm::Function>(Old)) return;
4740 
4741   replaceUsesOfNonProtoConstant(Old, NewFn);
4742 }
4743 
4744 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4745   auto DK = VD->isThisDeclarationADefinition();
4746   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4747     return;
4748 
4749   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4750   // If we have a definition, this might be a deferred decl. If the
4751   // instantiation is explicit, make sure we emit it at the end.
4752   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4753     GetAddrOfGlobalVar(VD);
4754 
4755   EmitTopLevelDecl(VD);
4756 }
4757 
4758 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4759                                                  llvm::GlobalValue *GV) {
4760   const auto *D = cast<FunctionDecl>(GD.getDecl());
4761 
4762   // Compute the function info and LLVM type.
4763   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4764   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4765 
4766   // Get or create the prototype for the function.
4767   if (!GV || (GV->getValueType() != Ty))
4768     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4769                                                    /*DontDefer=*/true,
4770                                                    ForDefinition));
4771 
4772   // Already emitted.
4773   if (!GV->isDeclaration())
4774     return;
4775 
4776   // We need to set linkage and visibility on the function before
4777   // generating code for it because various parts of IR generation
4778   // want to propagate this information down (e.g. to local static
4779   // declarations).
4780   auto *Fn = cast<llvm::Function>(GV);
4781   setFunctionLinkage(GD, Fn);
4782 
4783   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4784   setGVProperties(Fn, GD);
4785 
4786   MaybeHandleStaticInExternC(D, Fn);
4787 
4788   maybeSetTrivialComdat(*D, *Fn);
4789 
4790   // Set CodeGen attributes that represent floating point environment.
4791   setLLVMFunctionFEnvAttributes(D, Fn);
4792 
4793   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4794 
4795   setNonAliasAttributes(GD, Fn);
4796   SetLLVMFunctionAttributesForDefinition(D, Fn);
4797 
4798   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4799     AddGlobalCtor(Fn, CA->getPriority());
4800   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4801     AddGlobalDtor(Fn, DA->getPriority(), true);
4802   if (D->hasAttr<AnnotateAttr>())
4803     AddGlobalAnnotations(D, Fn);
4804 }
4805 
4806 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4807   const auto *D = cast<ValueDecl>(GD.getDecl());
4808   const AliasAttr *AA = D->getAttr<AliasAttr>();
4809   assert(AA && "Not an alias?");
4810 
4811   StringRef MangledName = getMangledName(GD);
4812 
4813   if (AA->getAliasee() == MangledName) {
4814     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4815     return;
4816   }
4817 
4818   // If there is a definition in the module, then it wins over the alias.
4819   // This is dubious, but allow it to be safe.  Just ignore the alias.
4820   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4821   if (Entry && !Entry->isDeclaration())
4822     return;
4823 
4824   Aliases.push_back(GD);
4825 
4826   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4827 
4828   // Create a reference to the named value.  This ensures that it is emitted
4829   // if a deferred decl.
4830   llvm::Constant *Aliasee;
4831   llvm::GlobalValue::LinkageTypes LT;
4832   if (isa<llvm::FunctionType>(DeclTy)) {
4833     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4834                                       /*ForVTable=*/false);
4835     LT = getFunctionLinkage(GD);
4836   } else {
4837     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4838                                     llvm::PointerType::getUnqual(DeclTy),
4839                                     /*D=*/nullptr);
4840     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
4841       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
4842     else
4843       LT = getFunctionLinkage(GD);
4844   }
4845 
4846   // Create the new alias itself, but don't set a name yet.
4847   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4848   auto *GA =
4849       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4850 
4851   if (Entry) {
4852     if (GA->getAliasee() == Entry) {
4853       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4854       return;
4855     }
4856 
4857     assert(Entry->isDeclaration());
4858 
4859     // If there is a declaration in the module, then we had an extern followed
4860     // by the alias, as in:
4861     //   extern int test6();
4862     //   ...
4863     //   int test6() __attribute__((alias("test7")));
4864     //
4865     // Remove it and replace uses of it with the alias.
4866     GA->takeName(Entry);
4867 
4868     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4869                                                           Entry->getType()));
4870     Entry->eraseFromParent();
4871   } else {
4872     GA->setName(MangledName);
4873   }
4874 
4875   // Set attributes which are particular to an alias; this is a
4876   // specialization of the attributes which may be set on a global
4877   // variable/function.
4878   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4879       D->isWeakImported()) {
4880     GA->setLinkage(llvm::Function::WeakAnyLinkage);
4881   }
4882 
4883   if (const auto *VD = dyn_cast<VarDecl>(D))
4884     if (VD->getTLSKind())
4885       setTLSMode(GA, *VD);
4886 
4887   SetCommonAttributes(GD, GA);
4888 }
4889 
4890 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4891   const auto *D = cast<ValueDecl>(GD.getDecl());
4892   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4893   assert(IFA && "Not an ifunc?");
4894 
4895   StringRef MangledName = getMangledName(GD);
4896 
4897   if (IFA->getResolver() == MangledName) {
4898     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4899     return;
4900   }
4901 
4902   // Report an error if some definition overrides ifunc.
4903   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4904   if (Entry && !Entry->isDeclaration()) {
4905     GlobalDecl OtherGD;
4906     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4907         DiagnosedConflictingDefinitions.insert(GD).second) {
4908       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4909           << MangledName;
4910       Diags.Report(OtherGD.getDecl()->getLocation(),
4911                    diag::note_previous_definition);
4912     }
4913     return;
4914   }
4915 
4916   Aliases.push_back(GD);
4917 
4918   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4919   llvm::Constant *Resolver =
4920       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4921                               /*ForVTable=*/false);
4922   llvm::GlobalIFunc *GIF =
4923       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4924                                 "", Resolver, &getModule());
4925   if (Entry) {
4926     if (GIF->getResolver() == Entry) {
4927       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4928       return;
4929     }
4930     assert(Entry->isDeclaration());
4931 
4932     // If there is a declaration in the module, then we had an extern followed
4933     // by the ifunc, as in:
4934     //   extern int test();
4935     //   ...
4936     //   int test() __attribute__((ifunc("resolver")));
4937     //
4938     // Remove it and replace uses of it with the ifunc.
4939     GIF->takeName(Entry);
4940 
4941     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4942                                                           Entry->getType()));
4943     Entry->eraseFromParent();
4944   } else
4945     GIF->setName(MangledName);
4946 
4947   SetCommonAttributes(GD, GIF);
4948 }
4949 
4950 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4951                                             ArrayRef<llvm::Type*> Tys) {
4952   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4953                                          Tys);
4954 }
4955 
4956 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4957 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4958                          const StringLiteral *Literal, bool TargetIsLSB,
4959                          bool &IsUTF16, unsigned &StringLength) {
4960   StringRef String = Literal->getString();
4961   unsigned NumBytes = String.size();
4962 
4963   // Check for simple case.
4964   if (!Literal->containsNonAsciiOrNull()) {
4965     StringLength = NumBytes;
4966     return *Map.insert(std::make_pair(String, nullptr)).first;
4967   }
4968 
4969   // Otherwise, convert the UTF8 literals into a string of shorts.
4970   IsUTF16 = true;
4971 
4972   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4973   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4974   llvm::UTF16 *ToPtr = &ToBuf[0];
4975 
4976   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4977                                  ToPtr + NumBytes, llvm::strictConversion);
4978 
4979   // ConvertUTF8toUTF16 returns the length in ToPtr.
4980   StringLength = ToPtr - &ToBuf[0];
4981 
4982   // Add an explicit null.
4983   *ToPtr = 0;
4984   return *Map.insert(std::make_pair(
4985                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4986                                    (StringLength + 1) * 2),
4987                          nullptr)).first;
4988 }
4989 
4990 ConstantAddress
4991 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4992   unsigned StringLength = 0;
4993   bool isUTF16 = false;
4994   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4995       GetConstantCFStringEntry(CFConstantStringMap, Literal,
4996                                getDataLayout().isLittleEndian(), isUTF16,
4997                                StringLength);
4998 
4999   if (auto *C = Entry.second)
5000     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
5001 
5002   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5003   llvm::Constant *Zeros[] = { Zero, Zero };
5004 
5005   const ASTContext &Context = getContext();
5006   const llvm::Triple &Triple = getTriple();
5007 
5008   const auto CFRuntime = getLangOpts().CFRuntime;
5009   const bool IsSwiftABI =
5010       static_cast<unsigned>(CFRuntime) >=
5011       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5012   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5013 
5014   // If we don't already have it, get __CFConstantStringClassReference.
5015   if (!CFConstantStringClassRef) {
5016     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5017     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5018     Ty = llvm::ArrayType::get(Ty, 0);
5019 
5020     switch (CFRuntime) {
5021     default: break;
5022     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
5023     case LangOptions::CoreFoundationABI::Swift5_0:
5024       CFConstantStringClassName =
5025           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5026                               : "$s10Foundation19_NSCFConstantStringCN";
5027       Ty = IntPtrTy;
5028       break;
5029     case LangOptions::CoreFoundationABI::Swift4_2:
5030       CFConstantStringClassName =
5031           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5032                               : "$S10Foundation19_NSCFConstantStringCN";
5033       Ty = IntPtrTy;
5034       break;
5035     case LangOptions::CoreFoundationABI::Swift4_1:
5036       CFConstantStringClassName =
5037           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5038                               : "__T010Foundation19_NSCFConstantStringCN";
5039       Ty = IntPtrTy;
5040       break;
5041     }
5042 
5043     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5044 
5045     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5046       llvm::GlobalValue *GV = nullptr;
5047 
5048       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5049         IdentifierInfo &II = Context.Idents.get(GV->getName());
5050         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5051         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5052 
5053         const VarDecl *VD = nullptr;
5054         for (const auto *Result : DC->lookup(&II))
5055           if ((VD = dyn_cast<VarDecl>(Result)))
5056             break;
5057 
5058         if (Triple.isOSBinFormatELF()) {
5059           if (!VD)
5060             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5061         } else {
5062           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5063           if (!VD || !VD->hasAttr<DLLExportAttr>())
5064             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5065           else
5066             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5067         }
5068 
5069         setDSOLocal(GV);
5070       }
5071     }
5072 
5073     // Decay array -> ptr
5074     CFConstantStringClassRef =
5075         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5076                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5077   }
5078 
5079   QualType CFTy = Context.getCFConstantStringType();
5080 
5081   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5082 
5083   ConstantInitBuilder Builder(*this);
5084   auto Fields = Builder.beginStruct(STy);
5085 
5086   // Class pointer.
5087   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
5088 
5089   // Flags.
5090   if (IsSwiftABI) {
5091     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5092     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5093   } else {
5094     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5095   }
5096 
5097   // String pointer.
5098   llvm::Constant *C = nullptr;
5099   if (isUTF16) {
5100     auto Arr = llvm::makeArrayRef(
5101         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5102         Entry.first().size() / 2);
5103     C = llvm::ConstantDataArray::get(VMContext, Arr);
5104   } else {
5105     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5106   }
5107 
5108   // Note: -fwritable-strings doesn't make the backing store strings of
5109   // CFStrings writable. (See <rdar://problem/10657500>)
5110   auto *GV =
5111       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5112                                llvm::GlobalValue::PrivateLinkage, C, ".str");
5113   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5114   // Don't enforce the target's minimum global alignment, since the only use
5115   // of the string is via this class initializer.
5116   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5117                             : Context.getTypeAlignInChars(Context.CharTy);
5118   GV->setAlignment(Align.getAsAlign());
5119 
5120   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5121   // Without it LLVM can merge the string with a non unnamed_addr one during
5122   // LTO.  Doing that changes the section it ends in, which surprises ld64.
5123   if (Triple.isOSBinFormatMachO())
5124     GV->setSection(isUTF16 ? "__TEXT,__ustring"
5125                            : "__TEXT,__cstring,cstring_literals");
5126   // Make sure the literal ends up in .rodata to allow for safe ICF and for
5127   // the static linker to adjust permissions to read-only later on.
5128   else if (Triple.isOSBinFormatELF())
5129     GV->setSection(".rodata");
5130 
5131   // String.
5132   llvm::Constant *Str =
5133       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5134 
5135   if (isUTF16)
5136     // Cast the UTF16 string to the correct type.
5137     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5138   Fields.add(Str);
5139 
5140   // String length.
5141   llvm::IntegerType *LengthTy =
5142       llvm::IntegerType::get(getModule().getContext(),
5143                              Context.getTargetInfo().getLongWidth());
5144   if (IsSwiftABI) {
5145     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5146         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5147       LengthTy = Int32Ty;
5148     else
5149       LengthTy = IntPtrTy;
5150   }
5151   Fields.addInt(LengthTy, StringLength);
5152 
5153   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5154   // properly aligned on 32-bit platforms.
5155   CharUnits Alignment =
5156       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5157 
5158   // The struct.
5159   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5160                                     /*isConstant=*/false,
5161                                     llvm::GlobalVariable::PrivateLinkage);
5162   GV->addAttribute("objc_arc_inert");
5163   switch (Triple.getObjectFormat()) {
5164   case llvm::Triple::UnknownObjectFormat:
5165     llvm_unreachable("unknown file format");
5166   case llvm::Triple::GOFF:
5167     llvm_unreachable("GOFF is not yet implemented");
5168   case llvm::Triple::XCOFF:
5169     llvm_unreachable("XCOFF is not yet implemented");
5170   case llvm::Triple::COFF:
5171   case llvm::Triple::ELF:
5172   case llvm::Triple::Wasm:
5173     GV->setSection("cfstring");
5174     break;
5175   case llvm::Triple::MachO:
5176     GV->setSection("__DATA,__cfstring");
5177     break;
5178   }
5179   Entry.second = GV;
5180 
5181   return ConstantAddress(GV, Alignment);
5182 }
5183 
5184 bool CodeGenModule::getExpressionLocationsEnabled() const {
5185   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5186 }
5187 
5188 QualType CodeGenModule::getObjCFastEnumerationStateType() {
5189   if (ObjCFastEnumerationStateType.isNull()) {
5190     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5191     D->startDefinition();
5192 
5193     QualType FieldTypes[] = {
5194       Context.UnsignedLongTy,
5195       Context.getPointerType(Context.getObjCIdType()),
5196       Context.getPointerType(Context.UnsignedLongTy),
5197       Context.getConstantArrayType(Context.UnsignedLongTy,
5198                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5199     };
5200 
5201     for (size_t i = 0; i < 4; ++i) {
5202       FieldDecl *Field = FieldDecl::Create(Context,
5203                                            D,
5204                                            SourceLocation(),
5205                                            SourceLocation(), nullptr,
5206                                            FieldTypes[i], /*TInfo=*/nullptr,
5207                                            /*BitWidth=*/nullptr,
5208                                            /*Mutable=*/false,
5209                                            ICIS_NoInit);
5210       Field->setAccess(AS_public);
5211       D->addDecl(Field);
5212     }
5213 
5214     D->completeDefinition();
5215     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5216   }
5217 
5218   return ObjCFastEnumerationStateType;
5219 }
5220 
5221 llvm::Constant *
5222 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5223   assert(!E->getType()->isPointerType() && "Strings are always arrays");
5224 
5225   // Don't emit it as the address of the string, emit the string data itself
5226   // as an inline array.
5227   if (E->getCharByteWidth() == 1) {
5228     SmallString<64> Str(E->getString());
5229 
5230     // Resize the string to the right size, which is indicated by its type.
5231     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5232     Str.resize(CAT->getSize().getZExtValue());
5233     return llvm::ConstantDataArray::getString(VMContext, Str, false);
5234   }
5235 
5236   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5237   llvm::Type *ElemTy = AType->getElementType();
5238   unsigned NumElements = AType->getNumElements();
5239 
5240   // Wide strings have either 2-byte or 4-byte elements.
5241   if (ElemTy->getPrimitiveSizeInBits() == 16) {
5242     SmallVector<uint16_t, 32> Elements;
5243     Elements.reserve(NumElements);
5244 
5245     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5246       Elements.push_back(E->getCodeUnit(i));
5247     Elements.resize(NumElements);
5248     return llvm::ConstantDataArray::get(VMContext, Elements);
5249   }
5250 
5251   assert(ElemTy->getPrimitiveSizeInBits() == 32);
5252   SmallVector<uint32_t, 32> Elements;
5253   Elements.reserve(NumElements);
5254 
5255   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5256     Elements.push_back(E->getCodeUnit(i));
5257   Elements.resize(NumElements);
5258   return llvm::ConstantDataArray::get(VMContext, Elements);
5259 }
5260 
5261 static llvm::GlobalVariable *
5262 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5263                       CodeGenModule &CGM, StringRef GlobalName,
5264                       CharUnits Alignment) {
5265   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5266       CGM.getStringLiteralAddressSpace());
5267 
5268   llvm::Module &M = CGM.getModule();
5269   // Create a global variable for this string
5270   auto *GV = new llvm::GlobalVariable(
5271       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5272       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5273   GV->setAlignment(Alignment.getAsAlign());
5274   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5275   if (GV->isWeakForLinker()) {
5276     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5277     GV->setComdat(M.getOrInsertComdat(GV->getName()));
5278   }
5279   CGM.setDSOLocal(GV);
5280 
5281   return GV;
5282 }
5283 
5284 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5285 /// constant array for the given string literal.
5286 ConstantAddress
5287 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5288                                                   StringRef Name) {
5289   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5290 
5291   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5292   llvm::GlobalVariable **Entry = nullptr;
5293   if (!LangOpts.WritableStrings) {
5294     Entry = &ConstantStringMap[C];
5295     if (auto GV = *Entry) {
5296       if (Alignment.getQuantity() > GV->getAlignment())
5297         GV->setAlignment(Alignment.getAsAlign());
5298       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5299                              Alignment);
5300     }
5301   }
5302 
5303   SmallString<256> MangledNameBuffer;
5304   StringRef GlobalVariableName;
5305   llvm::GlobalValue::LinkageTypes LT;
5306 
5307   // Mangle the string literal if that's how the ABI merges duplicate strings.
5308   // Don't do it if they are writable, since we don't want writes in one TU to
5309   // affect strings in another.
5310   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5311       !LangOpts.WritableStrings) {
5312     llvm::raw_svector_ostream Out(MangledNameBuffer);
5313     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5314     LT = llvm::GlobalValue::LinkOnceODRLinkage;
5315     GlobalVariableName = MangledNameBuffer;
5316   } else {
5317     LT = llvm::GlobalValue::PrivateLinkage;
5318     GlobalVariableName = Name;
5319   }
5320 
5321   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5322   if (Entry)
5323     *Entry = GV;
5324 
5325   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5326                                   QualType());
5327 
5328   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5329                          Alignment);
5330 }
5331 
5332 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5333 /// array for the given ObjCEncodeExpr node.
5334 ConstantAddress
5335 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5336   std::string Str;
5337   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5338 
5339   return GetAddrOfConstantCString(Str);
5340 }
5341 
5342 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5343 /// the literal and a terminating '\0' character.
5344 /// The result has pointer to array type.
5345 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5346     const std::string &Str, const char *GlobalName) {
5347   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5348   CharUnits Alignment =
5349     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5350 
5351   llvm::Constant *C =
5352       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5353 
5354   // Don't share any string literals if strings aren't constant.
5355   llvm::GlobalVariable **Entry = nullptr;
5356   if (!LangOpts.WritableStrings) {
5357     Entry = &ConstantStringMap[C];
5358     if (auto GV = *Entry) {
5359       if (Alignment.getQuantity() > GV->getAlignment())
5360         GV->setAlignment(Alignment.getAsAlign());
5361       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5362                              Alignment);
5363     }
5364   }
5365 
5366   // Get the default prefix if a name wasn't specified.
5367   if (!GlobalName)
5368     GlobalName = ".str";
5369   // Create a global variable for this.
5370   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5371                                   GlobalName, Alignment);
5372   if (Entry)
5373     *Entry = GV;
5374 
5375   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5376                          Alignment);
5377 }
5378 
5379 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5380     const MaterializeTemporaryExpr *E, const Expr *Init) {
5381   assert((E->getStorageDuration() == SD_Static ||
5382           E->getStorageDuration() == SD_Thread) && "not a global temporary");
5383   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5384 
5385   // If we're not materializing a subobject of the temporary, keep the
5386   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5387   QualType MaterializedType = Init->getType();
5388   if (Init == E->getSubExpr())
5389     MaterializedType = E->getType();
5390 
5391   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5392 
5393   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
5394   if (!InsertResult.second) {
5395     // We've seen this before: either we already created it or we're in the
5396     // process of doing so.
5397     if (!InsertResult.first->second) {
5398       // We recursively re-entered this function, probably during emission of
5399       // the initializer. Create a placeholder. We'll clean this up in the
5400       // outer call, at the end of this function.
5401       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
5402       InsertResult.first->second = new llvm::GlobalVariable(
5403           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
5404           nullptr);
5405     }
5406     return ConstantAddress(InsertResult.first->second, Align);
5407   }
5408 
5409   // FIXME: If an externally-visible declaration extends multiple temporaries,
5410   // we need to give each temporary the same name in every translation unit (and
5411   // we also need to make the temporaries externally-visible).
5412   SmallString<256> Name;
5413   llvm::raw_svector_ostream Out(Name);
5414   getCXXABI().getMangleContext().mangleReferenceTemporary(
5415       VD, E->getManglingNumber(), Out);
5416 
5417   APValue *Value = nullptr;
5418   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5419     // If the initializer of the extending declaration is a constant
5420     // initializer, we should have a cached constant initializer for this
5421     // temporary. Note that this might have a different value from the value
5422     // computed by evaluating the initializer if the surrounding constant
5423     // expression modifies the temporary.
5424     Value = E->getOrCreateValue(false);
5425   }
5426 
5427   // Try evaluating it now, it might have a constant initializer.
5428   Expr::EvalResult EvalResult;
5429   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5430       !EvalResult.hasSideEffects())
5431     Value = &EvalResult.Val;
5432 
5433   LangAS AddrSpace =
5434       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5435 
5436   Optional<ConstantEmitter> emitter;
5437   llvm::Constant *InitialValue = nullptr;
5438   bool Constant = false;
5439   llvm::Type *Type;
5440   if (Value) {
5441     // The temporary has a constant initializer, use it.
5442     emitter.emplace(*this);
5443     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5444                                                MaterializedType);
5445     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5446     Type = InitialValue->getType();
5447   } else {
5448     // No initializer, the initialization will be provided when we
5449     // initialize the declaration which performed lifetime extension.
5450     Type = getTypes().ConvertTypeForMem(MaterializedType);
5451   }
5452 
5453   // Create a global variable for this lifetime-extended temporary.
5454   llvm::GlobalValue::LinkageTypes Linkage =
5455       getLLVMLinkageVarDefinition(VD, Constant);
5456   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5457     const VarDecl *InitVD;
5458     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5459         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5460       // Temporaries defined inside a class get linkonce_odr linkage because the
5461       // class can be defined in multiple translation units.
5462       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5463     } else {
5464       // There is no need for this temporary to have external linkage if the
5465       // VarDecl has external linkage.
5466       Linkage = llvm::GlobalVariable::InternalLinkage;
5467     }
5468   }
5469   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5470   auto *GV = new llvm::GlobalVariable(
5471       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5472       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5473   if (emitter) emitter->finalize(GV);
5474   setGVProperties(GV, VD);
5475   GV->setAlignment(Align.getAsAlign());
5476   if (supportsCOMDAT() && GV->isWeakForLinker())
5477     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5478   if (VD->getTLSKind())
5479     setTLSMode(GV, *VD);
5480   llvm::Constant *CV = GV;
5481   if (AddrSpace != LangAS::Default)
5482     CV = getTargetCodeGenInfo().performAddrSpaceCast(
5483         *this, GV, AddrSpace, LangAS::Default,
5484         Type->getPointerTo(
5485             getContext().getTargetAddressSpace(LangAS::Default)));
5486 
5487   // Update the map with the new temporary. If we created a placeholder above,
5488   // replace it with the new global now.
5489   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
5490   if (Entry) {
5491     Entry->replaceAllUsesWith(
5492         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
5493     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
5494   }
5495   Entry = CV;
5496 
5497   return ConstantAddress(CV, Align);
5498 }
5499 
5500 /// EmitObjCPropertyImplementations - Emit information for synthesized
5501 /// properties for an implementation.
5502 void CodeGenModule::EmitObjCPropertyImplementations(const
5503                                                     ObjCImplementationDecl *D) {
5504   for (const auto *PID : D->property_impls()) {
5505     // Dynamic is just for type-checking.
5506     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5507       ObjCPropertyDecl *PD = PID->getPropertyDecl();
5508 
5509       // Determine which methods need to be implemented, some may have
5510       // been overridden. Note that ::isPropertyAccessor is not the method
5511       // we want, that just indicates if the decl came from a
5512       // property. What we want to know is if the method is defined in
5513       // this implementation.
5514       auto *Getter = PID->getGetterMethodDecl();
5515       if (!Getter || Getter->isSynthesizedAccessorStub())
5516         CodeGenFunction(*this).GenerateObjCGetter(
5517             const_cast<ObjCImplementationDecl *>(D), PID);
5518       auto *Setter = PID->getSetterMethodDecl();
5519       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5520         CodeGenFunction(*this).GenerateObjCSetter(
5521                                  const_cast<ObjCImplementationDecl *>(D), PID);
5522     }
5523   }
5524 }
5525 
5526 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5527   const ObjCInterfaceDecl *iface = impl->getClassInterface();
5528   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5529        ivar; ivar = ivar->getNextIvar())
5530     if (ivar->getType().isDestructedType())
5531       return true;
5532 
5533   return false;
5534 }
5535 
5536 static bool AllTrivialInitializers(CodeGenModule &CGM,
5537                                    ObjCImplementationDecl *D) {
5538   CodeGenFunction CGF(CGM);
5539   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5540        E = D->init_end(); B != E; ++B) {
5541     CXXCtorInitializer *CtorInitExp = *B;
5542     Expr *Init = CtorInitExp->getInit();
5543     if (!CGF.isTrivialInitializer(Init))
5544       return false;
5545   }
5546   return true;
5547 }
5548 
5549 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5550 /// for an implementation.
5551 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5552   // We might need a .cxx_destruct even if we don't have any ivar initializers.
5553   if (needsDestructMethod(D)) {
5554     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5555     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5556     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5557         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5558         getContext().VoidTy, nullptr, D,
5559         /*isInstance=*/true, /*isVariadic=*/false,
5560         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5561         /*isImplicitlyDeclared=*/true,
5562         /*isDefined=*/false, ObjCMethodDecl::Required);
5563     D->addInstanceMethod(DTORMethod);
5564     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5565     D->setHasDestructors(true);
5566   }
5567 
5568   // If the implementation doesn't have any ivar initializers, we don't need
5569   // a .cxx_construct.
5570   if (D->getNumIvarInitializers() == 0 ||
5571       AllTrivialInitializers(*this, D))
5572     return;
5573 
5574   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5575   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5576   // The constructor returns 'self'.
5577   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5578       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5579       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5580       /*isVariadic=*/false,
5581       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5582       /*isImplicitlyDeclared=*/true,
5583       /*isDefined=*/false, ObjCMethodDecl::Required);
5584   D->addInstanceMethod(CTORMethod);
5585   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5586   D->setHasNonZeroConstructors(true);
5587 }
5588 
5589 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5590 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5591   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5592       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5593     ErrorUnsupported(LSD, "linkage spec");
5594     return;
5595   }
5596 
5597   EmitDeclContext(LSD);
5598 }
5599 
5600 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5601   for (auto *I : DC->decls()) {
5602     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5603     // are themselves considered "top-level", so EmitTopLevelDecl on an
5604     // ObjCImplDecl does not recursively visit them. We need to do that in
5605     // case they're nested inside another construct (LinkageSpecDecl /
5606     // ExportDecl) that does stop them from being considered "top-level".
5607     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5608       for (auto *M : OID->methods())
5609         EmitTopLevelDecl(M);
5610     }
5611 
5612     EmitTopLevelDecl(I);
5613   }
5614 }
5615 
5616 /// EmitTopLevelDecl - Emit code for a single top level declaration.
5617 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5618   // Ignore dependent declarations.
5619   if (D->isTemplated())
5620     return;
5621 
5622   // Consteval function shouldn't be emitted.
5623   if (auto *FD = dyn_cast<FunctionDecl>(D))
5624     if (FD->isConsteval())
5625       return;
5626 
5627   switch (D->getKind()) {
5628   case Decl::CXXConversion:
5629   case Decl::CXXMethod:
5630   case Decl::Function:
5631     EmitGlobal(cast<FunctionDecl>(D));
5632     // Always provide some coverage mapping
5633     // even for the functions that aren't emitted.
5634     AddDeferredUnusedCoverageMapping(D);
5635     break;
5636 
5637   case Decl::CXXDeductionGuide:
5638     // Function-like, but does not result in code emission.
5639     break;
5640 
5641   case Decl::Var:
5642   case Decl::Decomposition:
5643   case Decl::VarTemplateSpecialization:
5644     EmitGlobal(cast<VarDecl>(D));
5645     if (auto *DD = dyn_cast<DecompositionDecl>(D))
5646       for (auto *B : DD->bindings())
5647         if (auto *HD = B->getHoldingVar())
5648           EmitGlobal(HD);
5649     break;
5650 
5651   // Indirect fields from global anonymous structs and unions can be
5652   // ignored; only the actual variable requires IR gen support.
5653   case Decl::IndirectField:
5654     break;
5655 
5656   // C++ Decls
5657   case Decl::Namespace:
5658     EmitDeclContext(cast<NamespaceDecl>(D));
5659     break;
5660   case Decl::ClassTemplateSpecialization: {
5661     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5662     if (CGDebugInfo *DI = getModuleDebugInfo())
5663       if (Spec->getSpecializationKind() ==
5664               TSK_ExplicitInstantiationDefinition &&
5665           Spec->hasDefinition())
5666         DI->completeTemplateDefinition(*Spec);
5667   } LLVM_FALLTHROUGH;
5668   case Decl::CXXRecord: {
5669     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5670     if (CGDebugInfo *DI = getModuleDebugInfo()) {
5671       if (CRD->hasDefinition())
5672         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5673       if (auto *ES = D->getASTContext().getExternalSource())
5674         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5675           DI->completeUnusedClass(*CRD);
5676     }
5677     // Emit any static data members, they may be definitions.
5678     for (auto *I : CRD->decls())
5679       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5680         EmitTopLevelDecl(I);
5681     break;
5682   }
5683     // No code generation needed.
5684   case Decl::UsingShadow:
5685   case Decl::ClassTemplate:
5686   case Decl::VarTemplate:
5687   case Decl::Concept:
5688   case Decl::VarTemplatePartialSpecialization:
5689   case Decl::FunctionTemplate:
5690   case Decl::TypeAliasTemplate:
5691   case Decl::Block:
5692   case Decl::Empty:
5693   case Decl::Binding:
5694     break;
5695   case Decl::Using:          // using X; [C++]
5696     if (CGDebugInfo *DI = getModuleDebugInfo())
5697         DI->EmitUsingDecl(cast<UsingDecl>(*D));
5698     break;
5699   case Decl::NamespaceAlias:
5700     if (CGDebugInfo *DI = getModuleDebugInfo())
5701         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5702     break;
5703   case Decl::UsingDirective: // using namespace X; [C++]
5704     if (CGDebugInfo *DI = getModuleDebugInfo())
5705       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5706     break;
5707   case Decl::CXXConstructor:
5708     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5709     break;
5710   case Decl::CXXDestructor:
5711     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5712     break;
5713 
5714   case Decl::StaticAssert:
5715     // Nothing to do.
5716     break;
5717 
5718   // Objective-C Decls
5719 
5720   // Forward declarations, no (immediate) code generation.
5721   case Decl::ObjCInterface:
5722   case Decl::ObjCCategory:
5723     break;
5724 
5725   case Decl::ObjCProtocol: {
5726     auto *Proto = cast<ObjCProtocolDecl>(D);
5727     if (Proto->isThisDeclarationADefinition())
5728       ObjCRuntime->GenerateProtocol(Proto);
5729     break;
5730   }
5731 
5732   case Decl::ObjCCategoryImpl:
5733     // Categories have properties but don't support synthesize so we
5734     // can ignore them here.
5735     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5736     break;
5737 
5738   case Decl::ObjCImplementation: {
5739     auto *OMD = cast<ObjCImplementationDecl>(D);
5740     EmitObjCPropertyImplementations(OMD);
5741     EmitObjCIvarInitializations(OMD);
5742     ObjCRuntime->GenerateClass(OMD);
5743     // Emit global variable debug information.
5744     if (CGDebugInfo *DI = getModuleDebugInfo())
5745       if (getCodeGenOpts().hasReducedDebugInfo())
5746         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5747             OMD->getClassInterface()), OMD->getLocation());
5748     break;
5749   }
5750   case Decl::ObjCMethod: {
5751     auto *OMD = cast<ObjCMethodDecl>(D);
5752     // If this is not a prototype, emit the body.
5753     if (OMD->getBody())
5754       CodeGenFunction(*this).GenerateObjCMethod(OMD);
5755     break;
5756   }
5757   case Decl::ObjCCompatibleAlias:
5758     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5759     break;
5760 
5761   case Decl::PragmaComment: {
5762     const auto *PCD = cast<PragmaCommentDecl>(D);
5763     switch (PCD->getCommentKind()) {
5764     case PCK_Unknown:
5765       llvm_unreachable("unexpected pragma comment kind");
5766     case PCK_Linker:
5767       AppendLinkerOptions(PCD->getArg());
5768       break;
5769     case PCK_Lib:
5770         AddDependentLib(PCD->getArg());
5771       break;
5772     case PCK_Compiler:
5773     case PCK_ExeStr:
5774     case PCK_User:
5775       break; // We ignore all of these.
5776     }
5777     break;
5778   }
5779 
5780   case Decl::PragmaDetectMismatch: {
5781     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5782     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5783     break;
5784   }
5785 
5786   case Decl::LinkageSpec:
5787     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5788     break;
5789 
5790   case Decl::FileScopeAsm: {
5791     // File-scope asm is ignored during device-side CUDA compilation.
5792     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5793       break;
5794     // File-scope asm is ignored during device-side OpenMP compilation.
5795     if (LangOpts.OpenMPIsDevice)
5796       break;
5797     // File-scope asm is ignored during device-side SYCL compilation.
5798     if (LangOpts.SYCLIsDevice)
5799       break;
5800     auto *AD = cast<FileScopeAsmDecl>(D);
5801     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5802     break;
5803   }
5804 
5805   case Decl::Import: {
5806     auto *Import = cast<ImportDecl>(D);
5807 
5808     // If we've already imported this module, we're done.
5809     if (!ImportedModules.insert(Import->getImportedModule()))
5810       break;
5811 
5812     // Emit debug information for direct imports.
5813     if (!Import->getImportedOwningModule()) {
5814       if (CGDebugInfo *DI = getModuleDebugInfo())
5815         DI->EmitImportDecl(*Import);
5816     }
5817 
5818     // Find all of the submodules and emit the module initializers.
5819     llvm::SmallPtrSet<clang::Module *, 16> Visited;
5820     SmallVector<clang::Module *, 16> Stack;
5821     Visited.insert(Import->getImportedModule());
5822     Stack.push_back(Import->getImportedModule());
5823 
5824     while (!Stack.empty()) {
5825       clang::Module *Mod = Stack.pop_back_val();
5826       if (!EmittedModuleInitializers.insert(Mod).second)
5827         continue;
5828 
5829       for (auto *D : Context.getModuleInitializers(Mod))
5830         EmitTopLevelDecl(D);
5831 
5832       // Visit the submodules of this module.
5833       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5834                                              SubEnd = Mod->submodule_end();
5835            Sub != SubEnd; ++Sub) {
5836         // Skip explicit children; they need to be explicitly imported to emit
5837         // the initializers.
5838         if ((*Sub)->IsExplicit)
5839           continue;
5840 
5841         if (Visited.insert(*Sub).second)
5842           Stack.push_back(*Sub);
5843       }
5844     }
5845     break;
5846   }
5847 
5848   case Decl::Export:
5849     EmitDeclContext(cast<ExportDecl>(D));
5850     break;
5851 
5852   case Decl::OMPThreadPrivate:
5853     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5854     break;
5855 
5856   case Decl::OMPAllocate:
5857     break;
5858 
5859   case Decl::OMPDeclareReduction:
5860     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5861     break;
5862 
5863   case Decl::OMPDeclareMapper:
5864     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5865     break;
5866 
5867   case Decl::OMPRequires:
5868     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5869     break;
5870 
5871   case Decl::Typedef:
5872   case Decl::TypeAlias: // using foo = bar; [C++11]
5873     if (CGDebugInfo *DI = getModuleDebugInfo())
5874       DI->EmitAndRetainType(
5875           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
5876     break;
5877 
5878   case Decl::Record:
5879     if (CGDebugInfo *DI = getModuleDebugInfo())
5880       if (cast<RecordDecl>(D)->getDefinition())
5881         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5882     break;
5883 
5884   case Decl::Enum:
5885     if (CGDebugInfo *DI = getModuleDebugInfo())
5886       if (cast<EnumDecl>(D)->getDefinition())
5887         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
5888     break;
5889 
5890   default:
5891     // Make sure we handled everything we should, every other kind is a
5892     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
5893     // function. Need to recode Decl::Kind to do that easily.
5894     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5895     break;
5896   }
5897 }
5898 
5899 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5900   // Do we need to generate coverage mapping?
5901   if (!CodeGenOpts.CoverageMapping)
5902     return;
5903   switch (D->getKind()) {
5904   case Decl::CXXConversion:
5905   case Decl::CXXMethod:
5906   case Decl::Function:
5907   case Decl::ObjCMethod:
5908   case Decl::CXXConstructor:
5909   case Decl::CXXDestructor: {
5910     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5911       break;
5912     SourceManager &SM = getContext().getSourceManager();
5913     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5914       break;
5915     auto I = DeferredEmptyCoverageMappingDecls.find(D);
5916     if (I == DeferredEmptyCoverageMappingDecls.end())
5917       DeferredEmptyCoverageMappingDecls[D] = true;
5918     break;
5919   }
5920   default:
5921     break;
5922   };
5923 }
5924 
5925 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5926   // Do we need to generate coverage mapping?
5927   if (!CodeGenOpts.CoverageMapping)
5928     return;
5929   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5930     if (Fn->isTemplateInstantiation())
5931       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5932   }
5933   auto I = DeferredEmptyCoverageMappingDecls.find(D);
5934   if (I == DeferredEmptyCoverageMappingDecls.end())
5935     DeferredEmptyCoverageMappingDecls[D] = false;
5936   else
5937     I->second = false;
5938 }
5939 
5940 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5941   // We call takeVector() here to avoid use-after-free.
5942   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5943   // we deserialize function bodies to emit coverage info for them, and that
5944   // deserializes more declarations. How should we handle that case?
5945   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5946     if (!Entry.second)
5947       continue;
5948     const Decl *D = Entry.first;
5949     switch (D->getKind()) {
5950     case Decl::CXXConversion:
5951     case Decl::CXXMethod:
5952     case Decl::Function:
5953     case Decl::ObjCMethod: {
5954       CodeGenPGO PGO(*this);
5955       GlobalDecl GD(cast<FunctionDecl>(D));
5956       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5957                                   getFunctionLinkage(GD));
5958       break;
5959     }
5960     case Decl::CXXConstructor: {
5961       CodeGenPGO PGO(*this);
5962       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5963       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5964                                   getFunctionLinkage(GD));
5965       break;
5966     }
5967     case Decl::CXXDestructor: {
5968       CodeGenPGO PGO(*this);
5969       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5970       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5971                                   getFunctionLinkage(GD));
5972       break;
5973     }
5974     default:
5975       break;
5976     };
5977   }
5978 }
5979 
5980 void CodeGenModule::EmitMainVoidAlias() {
5981   // In order to transition away from "__original_main" gracefully, emit an
5982   // alias for "main" in the no-argument case so that libc can detect when
5983   // new-style no-argument main is in used.
5984   if (llvm::Function *F = getModule().getFunction("main")) {
5985     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
5986         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
5987       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
5988   }
5989 }
5990 
5991 /// Turns the given pointer into a constant.
5992 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5993                                           const void *Ptr) {
5994   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5995   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5996   return llvm::ConstantInt::get(i64, PtrInt);
5997 }
5998 
5999 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6000                                    llvm::NamedMDNode *&GlobalMetadata,
6001                                    GlobalDecl D,
6002                                    llvm::GlobalValue *Addr) {
6003   if (!GlobalMetadata)
6004     GlobalMetadata =
6005       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6006 
6007   // TODO: should we report variant information for ctors/dtors?
6008   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6009                            llvm::ConstantAsMetadata::get(GetPointerConstant(
6010                                CGM.getLLVMContext(), D.getDecl()))};
6011   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6012 }
6013 
6014 /// For each function which is declared within an extern "C" region and marked
6015 /// as 'used', but has internal linkage, create an alias from the unmangled
6016 /// name to the mangled name if possible. People expect to be able to refer
6017 /// to such functions with an unmangled name from inline assembly within the
6018 /// same translation unit.
6019 void CodeGenModule::EmitStaticExternCAliases() {
6020   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
6021     return;
6022   for (auto &I : StaticExternCValues) {
6023     IdentifierInfo *Name = I.first;
6024     llvm::GlobalValue *Val = I.second;
6025     if (Val && !getModule().getNamedValue(Name->getName()))
6026       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
6027   }
6028 }
6029 
6030 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
6031                                              GlobalDecl &Result) const {
6032   auto Res = Manglings.find(MangledName);
6033   if (Res == Manglings.end())
6034     return false;
6035   Result = Res->getValue();
6036   return true;
6037 }
6038 
6039 /// Emits metadata nodes associating all the global values in the
6040 /// current module with the Decls they came from.  This is useful for
6041 /// projects using IR gen as a subroutine.
6042 ///
6043 /// Since there's currently no way to associate an MDNode directly
6044 /// with an llvm::GlobalValue, we create a global named metadata
6045 /// with the name 'clang.global.decl.ptrs'.
6046 void CodeGenModule::EmitDeclMetadata() {
6047   llvm::NamedMDNode *GlobalMetadata = nullptr;
6048 
6049   for (auto &I : MangledDeclNames) {
6050     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
6051     // Some mangled names don't necessarily have an associated GlobalValue
6052     // in this module, e.g. if we mangled it for DebugInfo.
6053     if (Addr)
6054       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
6055   }
6056 }
6057 
6058 /// Emits metadata nodes for all the local variables in the current
6059 /// function.
6060 void CodeGenFunction::EmitDeclMetadata() {
6061   if (LocalDeclMap.empty()) return;
6062 
6063   llvm::LLVMContext &Context = getLLVMContext();
6064 
6065   // Find the unique metadata ID for this name.
6066   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
6067 
6068   llvm::NamedMDNode *GlobalMetadata = nullptr;
6069 
6070   for (auto &I : LocalDeclMap) {
6071     const Decl *D = I.first;
6072     llvm::Value *Addr = I.second.getPointer();
6073     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
6074       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
6075       Alloca->setMetadata(
6076           DeclPtrKind, llvm::MDNode::get(
6077                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
6078     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
6079       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
6080       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
6081     }
6082   }
6083 }
6084 
6085 void CodeGenModule::EmitVersionIdentMetadata() {
6086   llvm::NamedMDNode *IdentMetadata =
6087     TheModule.getOrInsertNamedMetadata("llvm.ident");
6088   std::string Version = getClangFullVersion();
6089   llvm::LLVMContext &Ctx = TheModule.getContext();
6090 
6091   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
6092   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
6093 }
6094 
6095 void CodeGenModule::EmitCommandLineMetadata() {
6096   llvm::NamedMDNode *CommandLineMetadata =
6097     TheModule.getOrInsertNamedMetadata("llvm.commandline");
6098   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
6099   llvm::LLVMContext &Ctx = TheModule.getContext();
6100 
6101   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
6102   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
6103 }
6104 
6105 void CodeGenModule::EmitCoverageFile() {
6106   if (getCodeGenOpts().CoverageDataFile.empty() &&
6107       getCodeGenOpts().CoverageNotesFile.empty())
6108     return;
6109 
6110   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
6111   if (!CUNode)
6112     return;
6113 
6114   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
6115   llvm::LLVMContext &Ctx = TheModule.getContext();
6116   auto *CoverageDataFile =
6117       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
6118   auto *CoverageNotesFile =
6119       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
6120   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
6121     llvm::MDNode *CU = CUNode->getOperand(i);
6122     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
6123     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
6124   }
6125 }
6126 
6127 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
6128                                                        bool ForEH) {
6129   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
6130   // FIXME: should we even be calling this method if RTTI is disabled
6131   // and it's not for EH?
6132   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6133       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6134        getTriple().isNVPTX()))
6135     return llvm::Constant::getNullValue(Int8PtrTy);
6136 
6137   if (ForEH && Ty->isObjCObjectPointerType() &&
6138       LangOpts.ObjCRuntime.isGNUFamily())
6139     return ObjCRuntime->GetEHType(Ty);
6140 
6141   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
6142 }
6143 
6144 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
6145   // Do not emit threadprivates in simd-only mode.
6146   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
6147     return;
6148   for (auto RefExpr : D->varlists()) {
6149     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
6150     bool PerformInit =
6151         VD->getAnyInitializer() &&
6152         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
6153                                                         /*ForRef=*/false);
6154 
6155     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
6156     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
6157             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
6158       CXXGlobalInits.push_back(InitFunction);
6159   }
6160 }
6161 
6162 llvm::Metadata *
6163 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
6164                                             StringRef Suffix) {
6165   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
6166   if (InternalId)
6167     return InternalId;
6168 
6169   if (isExternallyVisible(T->getLinkage())) {
6170     std::string OutName;
6171     llvm::raw_string_ostream Out(OutName);
6172     getCXXABI().getMangleContext().mangleTypeName(T, Out);
6173     Out << Suffix;
6174 
6175     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
6176   } else {
6177     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
6178                                            llvm::ArrayRef<llvm::Metadata *>());
6179   }
6180 
6181   return InternalId;
6182 }
6183 
6184 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
6185   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
6186 }
6187 
6188 llvm::Metadata *
6189 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6190   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6191 }
6192 
6193 // Generalize pointer types to a void pointer with the qualifiers of the
6194 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
6195 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
6196 // 'void *'.
6197 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6198   if (!Ty->isPointerType())
6199     return Ty;
6200 
6201   return Ctx.getPointerType(
6202       QualType(Ctx.VoidTy).withCVRQualifiers(
6203           Ty->getPointeeType().getCVRQualifiers()));
6204 }
6205 
6206 // Apply type generalization to a FunctionType's return and argument types
6207 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6208   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6209     SmallVector<QualType, 8> GeneralizedParams;
6210     for (auto &Param : FnType->param_types())
6211       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
6212 
6213     return Ctx.getFunctionType(
6214         GeneralizeType(Ctx, FnType->getReturnType()),
6215         GeneralizedParams, FnType->getExtProtoInfo());
6216   }
6217 
6218   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
6219     return Ctx.getFunctionNoProtoType(
6220         GeneralizeType(Ctx, FnType->getReturnType()));
6221 
6222   llvm_unreachable("Encountered unknown FunctionType");
6223 }
6224 
6225 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
6226   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
6227                                       GeneralizedMetadataIdMap, ".generalized");
6228 }
6229 
6230 /// Returns whether this module needs the "all-vtables" type identifier.
6231 bool CodeGenModule::NeedAllVtablesTypeId() const {
6232   // Returns true if at least one of vtable-based CFI checkers is enabled and
6233   // is not in the trapping mode.
6234   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
6235            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
6236           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
6237            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
6238           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
6239            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
6240           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
6241            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
6242 }
6243 
6244 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
6245                                           CharUnits Offset,
6246                                           const CXXRecordDecl *RD) {
6247   llvm::Metadata *MD =
6248       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
6249   VTable->addTypeMetadata(Offset.getQuantity(), MD);
6250 
6251   if (CodeGenOpts.SanitizeCfiCrossDso)
6252     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
6253       VTable->addTypeMetadata(Offset.getQuantity(),
6254                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
6255 
6256   if (NeedAllVtablesTypeId()) {
6257     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
6258     VTable->addTypeMetadata(Offset.getQuantity(), MD);
6259   }
6260 }
6261 
6262 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
6263   if (!SanStats)
6264     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
6265 
6266   return *SanStats;
6267 }
6268 
6269 llvm::Value *
6270 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
6271                                                   CodeGenFunction &CGF) {
6272   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6273   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6274   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6275   auto *Call = CGF.EmitRuntimeCall(
6276       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6277   return Call;
6278 }
6279 
6280 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6281     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6282   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6283                                  /* forPointeeType= */ true);
6284 }
6285 
6286 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6287                                                  LValueBaseInfo *BaseInfo,
6288                                                  TBAAAccessInfo *TBAAInfo,
6289                                                  bool forPointeeType) {
6290   if (TBAAInfo)
6291     *TBAAInfo = getTBAAAccessInfo(T);
6292 
6293   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6294   // that doesn't return the information we need to compute BaseInfo.
6295 
6296   // Honor alignment typedef attributes even on incomplete types.
6297   // We also honor them straight for C++ class types, even as pointees;
6298   // there's an expressivity gap here.
6299   if (auto TT = T->getAs<TypedefType>()) {
6300     if (auto Align = TT->getDecl()->getMaxAlignment()) {
6301       if (BaseInfo)
6302         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6303       return getContext().toCharUnitsFromBits(Align);
6304     }
6305   }
6306 
6307   bool AlignForArray = T->isArrayType();
6308 
6309   // Analyze the base element type, so we don't get confused by incomplete
6310   // array types.
6311   T = getContext().getBaseElementType(T);
6312 
6313   if (T->isIncompleteType()) {
6314     // We could try to replicate the logic from
6315     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6316     // type is incomplete, so it's impossible to test. We could try to reuse
6317     // getTypeAlignIfKnown, but that doesn't return the information we need
6318     // to set BaseInfo.  So just ignore the possibility that the alignment is
6319     // greater than one.
6320     if (BaseInfo)
6321       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6322     return CharUnits::One();
6323   }
6324 
6325   if (BaseInfo)
6326     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6327 
6328   CharUnits Alignment;
6329   const CXXRecordDecl *RD;
6330   if (T.getQualifiers().hasUnaligned()) {
6331     Alignment = CharUnits::One();
6332   } else if (forPointeeType && !AlignForArray &&
6333              (RD = T->getAsCXXRecordDecl())) {
6334     // For C++ class pointees, we don't know whether we're pointing at a
6335     // base or a complete object, so we generally need to use the
6336     // non-virtual alignment.
6337     Alignment = getClassPointerAlignment(RD);
6338   } else {
6339     Alignment = getContext().getTypeAlignInChars(T);
6340   }
6341 
6342   // Cap to the global maximum type alignment unless the alignment
6343   // was somehow explicit on the type.
6344   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6345     if (Alignment.getQuantity() > MaxAlign &&
6346         !getContext().isAlignmentRequired(T))
6347       Alignment = CharUnits::fromQuantity(MaxAlign);
6348   }
6349   return Alignment;
6350 }
6351 
6352 bool CodeGenModule::stopAutoInit() {
6353   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6354   if (StopAfter) {
6355     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6356     // used
6357     if (NumAutoVarInit >= StopAfter) {
6358       return true;
6359     }
6360     if (!NumAutoVarInit) {
6361       unsigned DiagID = getDiags().getCustomDiagID(
6362           DiagnosticsEngine::Warning,
6363           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6364           "number of times ftrivial-auto-var-init=%1 gets applied.");
6365       getDiags().Report(DiagID)
6366           << StopAfter
6367           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6368                       LangOptions::TrivialAutoVarInitKind::Zero
6369                   ? "zero"
6370                   : "pattern");
6371     }
6372     ++NumAutoVarInit;
6373   }
6374   return false;
6375 }
6376 
6377 void CodeGenModule::printPostfixForExternalizedStaticVar(
6378     llvm::raw_ostream &OS) const {
6379   OS << ".static." << getContext().getCUIDHash();
6380 }
6381