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