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