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