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