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