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