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