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