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