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