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