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