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