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