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