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