clang  3.9.0
Sema.cpp
Go to the documentation of this file.
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
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 file implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/HeaderSearch.h"
29 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
40 #include "llvm/ADT/APFloat.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/SmallSet.h"
43 using namespace clang;
44 using namespace sema;
45 
47  return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
48 }
49 
50 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
51 
53  const Preprocessor &PP) {
54  PrintingPolicy Policy = Context.getPrintingPolicy();
55  // Our printing policy is copied over the ASTContext printing policy whenever
56  // a diagnostic is emitted, so recompute it.
57  Policy.Bool = Context.getLangOpts().Bool;
58  if (!Policy.Bool) {
59  if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
60  Policy.Bool = BoolMacro->isObjectLike() &&
61  BoolMacro->getNumTokens() == 1 &&
62  BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
63  }
64  }
65 
66  return Policy;
67 }
68 
70  TUScope = S;
71  PushDeclContext(S, Context.getTranslationUnitDecl());
72 }
73 
74 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
75  TranslationUnitKind TUKind,
76  CodeCompleteConsumer *CodeCompleter)
77  : ExternalSource(nullptr),
78  isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()),
79  LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
80  Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
81  CollectStats(false), CodeCompleter(CodeCompleter),
82  CurContext(nullptr), OriginalLexicalContext(nullptr),
83  MSStructPragmaOn(false),
84  MSPointerToMemberRepresentationMethod(
85  LangOpts.getMSPointerToMemberRepresentationMethod()),
86  VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
87  PackStack(0), DataSegStack(nullptr), BSSSegStack(nullptr),
88  ConstSegStack(nullptr), CodeSegStack(nullptr), CurInitSeg(nullptr),
89  VisContext(nullptr),
90  IsBuildingRecoveryCallExpr(false),
91  Cleanup{}, LateTemplateParser(nullptr),
92  LateTemplateParserCleanup(nullptr),
93  OpaqueParser(nullptr), IdResolver(pp), StdInitializerList(nullptr),
94  CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr),
95  NSNumberDecl(nullptr), NSValueDecl(nullptr),
96  NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
97  ValueWithBytesObjCTypeMethod(nullptr),
98  NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr),
99  NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr),
100  MSAsmLabelNameCounter(0),
101  GlobalNewDeleteDeclared(false),
102  TUKind(TUKind),
103  NumSFINAEErrors(0),
104  CachedFakeTopLevelModule(nullptr),
105  AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
106  NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
107  CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
108  TyposCorrected(0), AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
109  VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
110  Ident_super(nullptr), Ident___float128(nullptr)
111 {
112  TUScope = nullptr;
113 
114  LoadedExternalKnownNamespaces = false;
115  for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
116  NSNumberLiteralMethods[I] = nullptr;
117 
118  if (getLangOpts().ObjC1)
119  NSAPIObj.reset(new NSAPI(Context));
120 
121  if (getLangOpts().CPlusPlus)
122  FieldCollector.reset(new CXXFieldCollector());
123 
124  // Tell diagnostics how to render things from the AST library.
125  Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
126 
127  ExprEvalContexts.emplace_back(PotentiallyEvaluated, 0, CleanupInfo{}, nullptr,
128  false);
129 
130  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
131 
132  // Initilization of data sharing attributes stack for OpenMP
133  InitDataSharingAttributesStack();
134 }
135 
137  DeclarationName DN = &Context.Idents.get(Name);
138  if (IdResolver.begin(DN) == IdResolver.end())
140 }
141 
143  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
144  SC->InitializeSema(*this);
145 
146  // Tell the external Sema source about this Sema object.
147  if (ExternalSemaSource *ExternalSema
148  = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
149  ExternalSema->InitializeSema(*this);
150 
151  // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
152  // will not be able to merge any duplicate __va_list_tag decls correctly.
153  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
154 
155  if (!TUScope)
156  return;
157 
158  // Initialize predefined 128-bit integer types, if needed.
160  // If either of the 128-bit integer types are unavailable to name lookup,
161  // define them now.
162  DeclarationName Int128 = &Context.Idents.get("__int128_t");
163  if (IdResolver.begin(Int128) == IdResolver.end())
165 
166  DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
167  if (IdResolver.begin(UInt128) == IdResolver.end())
169  }
170 
171 
172  // Initialize predefined Objective-C types:
173  if (getLangOpts().ObjC1) {
174  // If 'SEL' does not yet refer to any declarations, make it refer to the
175  // predefined 'SEL'.
176  DeclarationName SEL = &Context.Idents.get("SEL");
177  if (IdResolver.begin(SEL) == IdResolver.end())
179 
180  // If 'id' does not yet refer to any declarations, make it refer to the
181  // predefined 'id'.
182  DeclarationName Id = &Context.Idents.get("id");
183  if (IdResolver.begin(Id) == IdResolver.end())
185 
186  // Create the built-in typedef for 'Class'.
187  DeclarationName Class = &Context.Idents.get("Class");
188  if (IdResolver.begin(Class) == IdResolver.end())
190 
191  // Create the built-in forward declaratino for 'Protocol'.
192  DeclarationName Protocol = &Context.Idents.get("Protocol");
193  if (IdResolver.begin(Protocol) == IdResolver.end())
195  }
196 
197  // Create the internal type for the *StringMakeConstantString builtins.
198  DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
199  if (IdResolver.begin(ConstantString) == IdResolver.end())
201 
202  // Initialize Microsoft "predefined C++ types".
203  if (getLangOpts().MSVCCompat) {
204  if (getLangOpts().CPlusPlus &&
205  IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
207  TUScope);
208 
210  }
211 
212  // Initialize predefined OpenCL types and supported optional core features.
213  if (getLangOpts().OpenCL) {
214 #define OPENCLEXT(Ext) \
215  if (Context.getTargetInfo().getSupportedOpenCLOpts().is_##Ext##_supported_core( \
216  getLangOpts().OpenCLVersion)) \
217  getOpenCLOptions().Ext = 1;
218 #include "clang/Basic/OpenCLExtensions.def"
219 
222  if (getLangOpts().OpenCLVersion >= 200) {
223  addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
226  addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
228  addImplicitTypedef("atomic_uint",
231  addImplicitTypedef("atomic_ulong",
233  addImplicitTypedef("atomic_float",
235  addImplicitTypedef("atomic_double",
237  // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
238  // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
240  addImplicitTypedef("atomic_intptr_t",
242  addImplicitTypedef("atomic_uintptr_t",
244  addImplicitTypedef("atomic_size_t",
246  addImplicitTypedef("atomic_ptrdiff_t",
248  }
249  }
250 
252  DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
253  if (IdResolver.begin(MSVaList) == IdResolver.end())
255  }
256 
257  DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
258  if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
260 }
261 
263  llvm::DeleteContainerSeconds(LateParsedTemplateMap);
264  if (VisContext) FreeVisContext();
265  // Kill all the active scopes.
266  for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
267  delete FunctionScopes[I];
268  if (FunctionScopes.size() == 1)
269  delete FunctionScopes[0];
270 
271  // Tell the SemaConsumer to forget about us; we're going out of scope.
272  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
273  SC->ForgetSema();
274 
275  // Detach from the external Sema source.
276  if (ExternalSemaSource *ExternalSema
277  = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
278  ExternalSema->ForgetSema();
279 
280  // If Sema's ExternalSource is the multiplexer - we own it.
281  if (isMultiplexExternalSource)
282  delete ExternalSource;
283 
285 
286  // Destroys data sharing attributes stack for OpenMP
287  DestroyDataSharingAttributesStack();
288 
289  assert(DelayedTypos.empty() && "Uncorrected typos!");
290 }
291 
292 /// makeUnavailableInSystemHeader - There is an error in the current
293 /// context. If we're still in a system header, and we can plausibly
294 /// make the relevant declaration unavailable instead of erroring, do
295 /// so and return true.
297  UnavailableAttr::ImplicitReason reason) {
298  // If we're not in a function, it's an error.
299  FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
300  if (!fn) return false;
301 
302  // If we're in template instantiation, it's an error.
303  if (!ActiveTemplateInstantiations.empty())
304  return false;
305 
306  // If that function's not in a system header, it's an error.
308  return false;
309 
310  // If the function is already unavailable, it's not an error.
311  if (fn->hasAttr<UnavailableAttr>()) return true;
312 
313  fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
314  return true;
315 }
316 
319 }
320 
321 ///\brief Registers an external source. If an external source already exists,
322 /// creates a multiplex external source and appends to it.
323 ///
324 ///\param[in] E - A non-null external sema source.
325 ///
327  assert(E && "Cannot use with NULL ptr");
328 
329  if (!ExternalSource) {
330  ExternalSource = E;
331  return;
332  }
333 
334  if (isMultiplexExternalSource)
335  static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
336  else {
337  ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
338  isMultiplexExternalSource = true;
339  }
340 }
341 
342 /// \brief Print out statistics about the semantic analysis.
343 void Sema::PrintStats() const {
344  llvm::errs() << "\n*** Semantic Analysis Stats:\n";
345  llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
346 
347  BumpAlloc.PrintStats();
349 }
350 
352  QualType SrcType,
353  SourceLocation Loc) {
354  Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
355  if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
356  return;
357 
358  Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
359  if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
360  return;
361 
362  Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
363 }
364 
365 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
366 /// If there is already an implicit cast, merge into the existing one.
367 /// The result is of the given category.
370  const CXXCastPath *BasePath,
371  CheckedConversionKind CCK) {
372 #ifndef NDEBUG
373  if (VK == VK_RValue && !E->isRValue()) {
374  switch (Kind) {
375  default:
376  llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
377  "kind");
378  case CK_LValueToRValue:
379  case CK_ArrayToPointerDecay:
380  case CK_FunctionToPointerDecay:
381  case CK_ToVoid:
382  break;
383  }
384  }
385  assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
386 #endif
387 
388  diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart());
389 
390  QualType ExprTy = Context.getCanonicalType(E->getType());
392 
393  if (ExprTy == TypeTy)
394  return E;
395 
396  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
397  if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
398  ImpCast->setType(Ty);
399  ImpCast->setValueKind(VK);
400  return E;
401  }
402  }
403 
404  return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
405 }
406 
407 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
408 /// to the conversion from scalar type ScalarTy to the Boolean type.
410  switch (ScalarTy->getScalarTypeKind()) {
411  case Type::STK_Bool: return CK_NoOp;
412  case Type::STK_CPointer: return CK_PointerToBoolean;
413  case Type::STK_BlockPointer: return CK_PointerToBoolean;
414  case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
415  case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
416  case Type::STK_Integral: return CK_IntegralToBoolean;
417  case Type::STK_Floating: return CK_FloatingToBoolean;
418  case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
419  case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
420  }
421  return CK_Invalid;
422 }
423 
424 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
425 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
426  if (D->getMostRecentDecl()->isUsed())
427  return true;
428 
429  if (D->isExternallyVisible())
430  return true;
431 
432  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
433  // UnusedFileScopedDecls stores the first declaration.
434  // The declaration may have become definition so check again.
435  const FunctionDecl *DeclToCheck;
436  if (FD->hasBody(DeclToCheck))
437  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
438 
439  // Later redecls may add new information resulting in not having to warn,
440  // so check again.
441  DeclToCheck = FD->getMostRecentDecl();
442  if (DeclToCheck != FD)
443  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
444  }
445 
446  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
447  // If a variable usable in constant expressions is referenced,
448  // don't warn if it isn't used: if the value of a variable is required
449  // for the computation of a constant expression, it doesn't make sense to
450  // warn even if the variable isn't odr-used. (isReferenced doesn't
451  // precisely reflect that, but it's a decent approximation.)
452  if (VD->isReferenced() &&
453  VD->isUsableInConstantExpressions(SemaRef->Context))
454  return true;
455 
456  // UnusedFileScopedDecls stores the first declaration.
457  // The declaration may have become definition so check again.
458  const VarDecl *DeclToCheck = VD->getDefinition();
459  if (DeclToCheck)
460  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
461 
462  // Later redecls may add new information resulting in not having to warn,
463  // so check again.
464  DeclToCheck = VD->getMostRecentDecl();
465  if (DeclToCheck != VD)
466  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
467  }
468 
469  return false;
470 }
471 
472 /// Obtains a sorted list of functions and variables that are undefined but
473 /// ODR-used.
475  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
476  for (const auto &UndefinedUse : UndefinedButUsed) {
477  NamedDecl *ND = UndefinedUse.first;
478 
479  // Ignore attributes that have become invalid.
480  if (ND->isInvalidDecl()) continue;
481 
482  // __attribute__((weakref)) is basically a definition.
483  if (ND->hasAttr<WeakRefAttr>()) continue;
484 
485  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
486  if (FD->isDefined())
487  continue;
488  if (FD->isExternallyVisible() &&
489  !FD->getMostRecentDecl()->isInlined())
490  continue;
491  } else {
492  auto *VD = cast<VarDecl>(ND);
493  if (VD->hasDefinition() != VarDecl::DeclarationOnly)
494  continue;
495  if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline())
496  continue;
497  }
498 
499  Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
500  }
501 }
502 
503 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
504 /// or that are inline.
505 static void checkUndefinedButUsed(Sema &S) {
506  if (S.UndefinedButUsed.empty()) return;
507 
508  // Collect all the still-undefined entities with internal linkage.
510  S.getUndefinedButUsed(Undefined);
511  if (Undefined.empty()) return;
512 
513  for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
514  I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
515  NamedDecl *ND = I->first;
516 
517  if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
518  // An exported function will always be emitted when defined, so even if
519  // the function is inline, it doesn't have to be emitted in this TU. An
520  // imported function implies that it has been exported somewhere else.
521  continue;
522  }
523 
524  if (!ND->isExternallyVisible()) {
525  S.Diag(ND->getLocation(), diag::warn_undefined_internal)
526  << isa<VarDecl>(ND) << ND;
527  } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
528  (void)FD;
529  assert(FD->getMostRecentDecl()->isInlined() &&
530  "used object requires definition but isn't inline or internal?");
531  // FIXME: This is ill-formed; we should reject.
532  S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
533  } else {
534  assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() &&
535  "used var requires definition but isn't inline or internal?");
536  S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND;
537  }
538  if (I->second.isValid())
539  S.Diag(I->second, diag::note_used_here);
540  }
541 
542  S.UndefinedButUsed.clear();
543 }
544 
546  if (!ExternalSource)
547  return;
548 
550  ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
551  for (auto &WeakID : WeakIDs)
552  WeakUndeclaredIdentifiers.insert(WeakID);
553 }
554 
555 
556 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
557 
558 /// \brief Returns true, if all methods and nested classes of the given
559 /// CXXRecordDecl are defined in this translation unit.
560 ///
561 /// Should only be called from ActOnEndOfTranslationUnit so that all
562 /// definitions are actually read.
564  RecordCompleteMap &MNCComplete) {
565  RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
566  if (Cache != MNCComplete.end())
567  return Cache->second;
568  if (!RD->isCompleteDefinition())
569  return false;
570  bool Complete = true;
572  E = RD->decls_end();
573  I != E && Complete; ++I) {
574  if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
575  Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
576  else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
577  // If the template function is marked as late template parsed at this
578  // point, it has not been instantiated and therefore we have not
579  // performed semantic analysis on it yet, so we cannot know if the type
580  // can be considered complete.
581  Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
582  F->getTemplatedDecl()->isDefined();
583  else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
584  if (R->isInjectedClassName())
585  continue;
586  if (R->hasDefinition())
587  Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
588  MNCComplete);
589  else
590  Complete = false;
591  }
592  }
593  MNCComplete[RD] = Complete;
594  return Complete;
595 }
596 
597 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
598 /// translation unit, i.e. all methods are defined or pure virtual and all
599 /// friends, friend functions and nested classes are fully defined in this
600 /// translation unit.
601 ///
602 /// Should only be called from ActOnEndOfTranslationUnit so that all
603 /// definitions are actually read.
604 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
605  RecordCompleteMap &RecordsComplete,
606  RecordCompleteMap &MNCComplete) {
607  RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
608  if (Cache != RecordsComplete.end())
609  return Cache->second;
610  bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
612  E = RD->friend_end();
613  I != E && Complete; ++I) {
614  // Check if friend classes and methods are complete.
615  if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
616  // Friend classes are available as the TypeSourceInfo of the FriendDecl.
617  if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
618  Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
619  else
620  Complete = false;
621  } else {
622  // Friend functions are available through the NamedDecl of FriendDecl.
623  if (const FunctionDecl *FD =
624  dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
625  Complete = FD->isDefined();
626  else
627  // This is a template friend, give up.
628  Complete = false;
629  }
630  }
631  RecordsComplete[RD] = Complete;
632  return Complete;
633 }
634 
636  if (ExternalSource)
637  ExternalSource->ReadUnusedLocalTypedefNameCandidates(
640  if (TD->isReferenced())
641  continue;
642  Diag(TD->getLocation(), diag::warn_unused_local_typedef)
643  << isa<TypeAliasDecl>(TD) << TD->getDeclName();
644  }
645  UnusedLocalTypedefNameCandidates.clear();
646 }
647 
648 /// ActOnEndOfTranslationUnit - This is called at the very end of the
649 /// translation unit when EOF is reached and all but the top-level scope is
650 /// popped.
652  assert(DelayedDiagnostics.getCurrentPool() == nullptr
653  && "reached end of translation unit with a pool attached?");
654 
655  // If code completion is enabled, don't perform any end-of-translation-unit
656  // work.
658  return;
659 
660  // Complete translation units and modules define vtables and perform implicit
661  // instantiations. PCH files do not.
662  if (TUKind != TU_Prefix) {
664 
665  // If DefinedUsedVTables ends up marking any virtual member functions it
666  // might lead to more pending template instantiations, which we then need
667  // to instantiate.
669 
670  // C++: Perform implicit template instantiations.
671  //
672  // FIXME: When we perform these implicit instantiations, we do not
673  // carefully keep track of the point of instantiation (C++ [temp.point]).
674  // This means that name lookup that occurs within the template
675  // instantiation will always happen at the end of the translation unit,
676  // so it will find some names that are not required to be found. This is
677  // valid, but we could do better by diagnosing if an instantiation uses a
678  // name that was not visible at its first point of instantiation.
679  if (ExternalSource) {
680  // Load pending instantiations from the external source.
682  ExternalSource->ReadPendingInstantiations(Pending);
684  Pending.begin(), Pending.end());
685  }
687 
690 
692  }
693 
694  // All delayed member exception specs should be checked or we end up accepting
695  // incompatible declarations.
696  // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
697  // write out the lists to the AST file (if any).
698  assert(DelayedDefaultedMemberExceptionSpecs.empty());
699  assert(DelayedExceptionSpecChecks.empty());
700 
701  // All dllexport classes should have been processed already.
702  assert(DelayedDllExportClasses.empty());
703 
704  // Remove file scoped decls that turned out to be used.
706  std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
708  std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
710 
711  if (TUKind == TU_Prefix) {
712  // Translation unit prefixes don't need any of the checking below.
713  TUScope = nullptr;
714  return;
715  }
716 
717  // Check for #pragma weak identifiers that were never declared
719  for (auto WeakID : WeakUndeclaredIdentifiers) {
720  if (WeakID.second.getUsed())
721  continue;
722 
723  Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
725  if (PrevDecl != nullptr &&
726  !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
727  Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
728  << "'weak'" << ExpectedVariableOrFunction;
729  else
730  Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
731  << WeakID.first;
732  }
733 
734  if (LangOpts.CPlusPlus11 &&
735  !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
737 
738  if (!Diags.hasErrorOccurred()) {
739  if (ExternalSource)
740  ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
741  checkUndefinedButUsed(*this);
742  }
743 
744  if (TUKind == TU_Module) {
745  // If we are building a module, resolve all of the exported declarations
746  // now.
747  if (Module *CurrentModule = PP.getCurrentModule()) {
749 
751  Stack.push_back(CurrentModule);
752  while (!Stack.empty()) {
753  Module *Mod = Stack.pop_back_val();
754 
755  // Resolve the exported declarations and conflicts.
756  // FIXME: Actually complain, once we figure out how to teach the
757  // diagnostic client to deal with complaints in the module map at this
758  // point.
759  ModMap.resolveExports(Mod, /*Complain=*/false);
760  ModMap.resolveUses(Mod, /*Complain=*/false);
761  ModMap.resolveConflicts(Mod, /*Complain=*/false);
762 
763  // Queue the submodules, so their exports will also be resolved.
764  Stack.append(Mod->submodule_begin(), Mod->submodule_end());
765  }
766  }
767 
768  // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
769  // modules when they are built, not every time they are used.
771 
772  // Modules don't need any of the checking below.
773  TUScope = nullptr;
774  return;
775  }
776 
777  // C99 6.9.2p2:
778  // A declaration of an identifier for an object that has file
779  // scope without an initializer, and without a storage-class
780  // specifier or with the storage-class specifier static,
781  // constitutes a tentative definition. If a translation unit
782  // contains one or more tentative definitions for an identifier,
783  // and the translation unit contains no external definition for
784  // that identifier, then the behavior is exactly as if the
785  // translation unit contains a file scope declaration of that
786  // identifier, with the composite type as of the end of the
787  // translation unit, with an initializer equal to 0.
788  llvm::SmallSet<VarDecl *, 32> Seen;
790  T = TentativeDefinitions.begin(ExternalSource),
791  TEnd = TentativeDefinitions.end();
792  T != TEnd; ++T)
793  {
794  VarDecl *VD = (*T)->getActingDefinition();
795 
796  // If the tentative definition was completed, getActingDefinition() returns
797  // null. If we've already seen this variable before, insert()'s second
798  // return value is false.
799  if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
800  continue;
801 
802  if (const IncompleteArrayType *ArrayT
804  // Set the length of the array to 1 (C99 6.9.2p5).
805  Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
806  llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
807  QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
808  One, ArrayType::Normal, 0);
809  VD->setType(T);
810  } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
811  diag::err_tentative_def_incomplete_type))
812  VD->setInvalidDecl();
813 
815 
816  // Notify the consumer that we've completed a tentative definition.
817  if (!VD->isInvalidDecl())
819 
820  }
821 
822  // If there were errors, disable 'unused' warnings since they will mostly be
823  // noise.
824  if (!Diags.hasErrorOccurred()) {
825  // Output warning for unused file scoped decls.
827  I = UnusedFileScopedDecls.begin(ExternalSource),
828  E = UnusedFileScopedDecls.end(); I != E; ++I) {
829  if (ShouldRemoveFromUnused(this, *I))
830  continue;
831 
832  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
833  const FunctionDecl *DiagD;
834  if (!FD->hasBody(DiagD))
835  DiagD = FD;
836  if (DiagD->isDeleted())
837  continue; // Deleted functions are supposed to be unused.
838  if (DiagD->isReferenced()) {
839  if (isa<CXXMethodDecl>(DiagD))
840  Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
841  << DiagD->getDeclName();
842  else {
843  if (FD->getStorageClass() == SC_Static &&
844  !FD->isInlineSpecified() &&
846  SourceMgr.getExpansionLoc(FD->getLocation())))
847  Diag(DiagD->getLocation(),
848  diag::warn_unneeded_static_internal_decl)
849  << DiagD->getDeclName();
850  else
851  Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
852  << /*function*/0 << DiagD->getDeclName();
853  }
854  } else {
855  Diag(DiagD->getLocation(),
856  isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
857  : diag::warn_unused_function)
858  << DiagD->getDeclName();
859  }
860  } else {
861  const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
862  if (!DiagD)
863  DiagD = cast<VarDecl>(*I);
864  if (DiagD->isReferenced()) {
865  Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
866  << /*variable*/1 << DiagD->getDeclName();
867  } else if (DiagD->getType().isConstQualified()) {
868  Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
869  << DiagD->getDeclName();
870  } else {
871  Diag(DiagD->getLocation(), diag::warn_unused_variable)
872  << DiagD->getDeclName();
873  }
874  }
875  }
876 
878  }
879 
880  if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
881  RecordCompleteMap RecordsComplete;
882  RecordCompleteMap MNCComplete;
884  E = UnusedPrivateFields.end(); I != E; ++I) {
885  const NamedDecl *D = *I;
886  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
887  if (RD && !RD->isUnion() &&
888  IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
889  Diag(D->getLocation(), diag::warn_unused_private_field)
890  << D->getDeclName();
891  }
892  }
893  }
894 
895  if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
896  if (ExternalSource)
898  for (const auto &DeletedFieldInfo : DeleteExprs) {
899  for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
900  AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
901  DeleteExprLoc.second);
902  }
903  }
904  }
905 
906  // Check we've noticed that we're no longer parsing the initializer for every
907  // variable. If we miss cases, then at best we have a performance issue and
908  // at worst a rejects-valid bug.
909  assert(ParsingInitForAutoVars.empty() &&
910  "Didn't unmark var as having its initializer parsed");
911 
912  TUScope = nullptr;
913 }
914 
915 
916 //===----------------------------------------------------------------------===//
917 // Helper functions.
918 //===----------------------------------------------------------------------===//
919 
921  DeclContext *DC = CurContext;
922 
923  while (true) {
924  if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
925  DC = DC->getParent();
926  } else if (isa<CXXMethodDecl>(DC) &&
927  cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
928  cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
929  DC = DC->getParent()->getParent();
930  }
931  else break;
932  }
933 
934  return DC;
935 }
936 
937 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
938 /// to the function decl for the function being parsed. If we're currently
939 /// in a 'block', this returns the containing context.
942  return dyn_cast<FunctionDecl>(DC);
943 }
944 
947  while (isa<RecordDecl>(DC))
948  DC = DC->getParent();
949  return dyn_cast<ObjCMethodDecl>(DC);
950 }
951 
954  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
955  return cast<NamedDecl>(DC);
956  return nullptr;
957 }
958 
959 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
960  // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
961  // and yet we also use the current diag ID on the DiagnosticsEngine. This has
962  // been made more painfully obvious by the refactor that introduced this
963  // function, but it is possible that the incoming argument can be
964  // eliminnated. If it truly cannot be (for example, there is some reentrancy
965  // issue I am not seeing yet), then there should at least be a clarifying
966  // comment somewhere.
969  Diags.getCurrentDiagID())) {
971  // We'll report the diagnostic below.
972  break;
973 
975  // Count this failure so that we know that template argument deduction
976  // has failed.
977  ++NumSFINAEErrors;
978 
979  // Make a copy of this suppressed diagnostic and store it with the
980  // template-deduction information.
981  if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
982  Diagnostic DiagInfo(&Diags);
983  (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
985  }
986 
988  Diags.Clear();
989  return;
990 
992  // Per C++ Core Issue 1170, access control is part of SFINAE.
993  // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
994  // make access control a part of SFINAE for the purposes of checking
995  // type traits.
997  break;
998 
1000 
1001  // Suppress this diagnostic.
1002  ++NumSFINAEErrors;
1003 
1004  // Make a copy of this suppressed diagnostic and store it with the
1005  // template-deduction information.
1006  if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1007  Diagnostic DiagInfo(&Diags);
1008  (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1010  }
1011 
1013  Diags.Clear();
1014 
1015  // Now the diagnostic state is clear, produce a C++98 compatibility
1016  // warning.
1017  Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1018 
1019  // The last diagnostic which Sema produced was ignored. Suppress any
1020  // notes attached to it.
1022  return;
1023  }
1024 
1026  // Make a copy of this suppressed diagnostic and store it with the
1027  // template-deduction information;
1028  if (*Info) {
1029  Diagnostic DiagInfo(&Diags);
1030  (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1032  }
1033 
1034  // Suppress this diagnostic.
1036  Diags.Clear();
1037  return;
1038  }
1039  }
1040 
1041  // Set up the context's printing policy based on our current state.
1043 
1044  // Emit the diagnostic.
1046  return;
1047 
1048  // If this is not a note, and we're in a template instantiation
1049  // that is different from the last template instantiation where
1050  // we emitted an error, print a template instantiation
1051  // backtrace.
1052  if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
1053  !ActiveTemplateInstantiations.empty() &&
1058  }
1059 }
1060 
1064  PD.Emit(Builder);
1065 
1066  return Builder;
1067 }
1068 
1069 /// \brief Looks through the macro-expansion chain for the given
1070 /// location, looking for a macro expansion with the given name.
1071 /// If one is found, returns true and sets the location to that
1072 /// expansion loc.
1073 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1074  SourceLocation loc = locref;
1075  if (!loc.isMacroID()) return false;
1076 
1077  // There's no good way right now to look at the intermediate
1078  // expansions, so just jump to the expansion location.
1079  loc = getSourceManager().getExpansionLoc(loc);
1080 
1081  // If that's written with the name, stop here.
1082  SmallVector<char, 16> buffer;
1083  if (getPreprocessor().getSpelling(loc, buffer) == name) {
1084  locref = loc;
1085  return true;
1086  }
1087  return false;
1088 }
1089 
1090 /// \brief Determines the active Scope associated with the given declaration
1091 /// context.
1092 ///
1093 /// This routine maps a declaration context to the active Scope object that
1094 /// represents that declaration context in the parser. It is typically used
1095 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1096 /// declarations) that injects a name for name-lookup purposes and, therefore,
1097 /// must update the Scope.
1098 ///
1099 /// \returns The scope corresponding to the given declaraion context, or NULL
1100 /// if no such scope is open.
1102 
1103  if (!Ctx)
1104  return nullptr;
1105 
1106  Ctx = Ctx->getPrimaryContext();
1107  for (Scope *S = getCurScope(); S; S = S->getParent()) {
1108  // Ignore scopes that cannot have declarations. This is important for
1109  // out-of-line definitions of static class members.
1110  if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1111  if (DeclContext *Entity = S->getEntity())
1112  if (Ctx == Entity->getPrimaryContext())
1113  return S;
1114  }
1115 
1116  return nullptr;
1117 }
1118 
1119 /// \brief Enter a new function scope
1121  if (FunctionScopes.size() == 1) {
1122  // Use the "top" function scope rather than having to allocate
1123  // memory for a new scope.
1124  FunctionScopes.back()->Clear();
1125  FunctionScopes.push_back(FunctionScopes.back());
1126  return;
1127  }
1128 
1130 }
1131 
1132 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1134  BlockScope, Block));
1135 }
1136 
1138  LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1139  FunctionScopes.push_back(LSI);
1140  return LSI;
1141 }
1142 
1144  if (LambdaScopeInfo *const LSI = getCurLambda()) {
1145  LSI->AutoTemplateParameterDepth = Depth;
1146  return;
1147  }
1148  llvm_unreachable(
1149  "Remove assertion if intentionally called in a non-lambda context.");
1150 }
1151 
1153  const Decl *D, const BlockExpr *blkExpr) {
1154  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1155  assert(!FunctionScopes.empty() && "mismatched push/pop!");
1156 
1157  // Issue any analysis-based warnings.
1158  if (WP && D)
1159  AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1160  else
1161  for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1162  Diag(PUD.Loc, PUD.PD);
1163 
1164  if (FunctionScopes.back() != Scope)
1165  delete Scope;
1166 }
1167 
1170 }
1171 
1173  FunctionScopeInfo *CurFunction = getCurFunction();
1174  assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1175 
1176  CurFunction->CompoundScopes.pop_back();
1177 }
1178 
1179 /// \brief Determine whether any errors occurred within this function/method/
1180 /// block.
1183 }
1184 
1186  if (FunctionScopes.empty())
1187  return nullptr;
1188 
1189  auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1190  if (CurBSI && CurBSI->TheDecl &&
1191  !CurBSI->TheDecl->Encloses(CurContext)) {
1192  // We have switched contexts due to template instantiation.
1193  assert(!ActiveTemplateInstantiations.empty());
1194  return nullptr;
1195  }
1196 
1197  return CurBSI;
1198 }
1199 
1201  if (FunctionScopes.empty())
1202  return nullptr;
1203 
1204  auto CurLSI = dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
1205  if (CurLSI && CurLSI->Lambda &&
1206  !CurLSI->Lambda->Encloses(CurContext)) {
1207  // We have switched contexts due to template instantiation.
1208  assert(!ActiveTemplateInstantiations.empty());
1209  return nullptr;
1210  }
1211 
1212  return CurLSI;
1213 }
1214 // We have a generic lambda if we parsed auto parameters, or we have
1215 // an associated template parameter list.
1217  if (LambdaScopeInfo *LSI = getCurLambda()) {
1218  return (LSI->AutoTemplateParams.size() ||
1219  LSI->GLTemplateParameterList) ? LSI : nullptr;
1220  }
1221  return nullptr;
1222 }
1223 
1224 
1226  if (!LangOpts.RetainCommentsFromSystemHeaders &&
1227  SourceMgr.isInSystemHeader(Comment.getBegin()))
1228  return;
1229  RawComment RC(SourceMgr, Comment, false,
1231  if (RC.isAlmostTrailingComment()) {
1232  SourceRange MagicMarkerRange(Comment.getBegin(),
1233  Comment.getBegin().getLocWithOffset(3));
1234  StringRef MagicMarkerText;
1235  switch (RC.getKind()) {
1237  MagicMarkerText = "///<";
1238  break;
1240  MagicMarkerText = "/**<";
1241  break;
1242  default:
1243  llvm_unreachable("if this is an almost Doxygen comment, "
1244  "it should be ordinary");
1245  }
1246  Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1247  FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1248  }
1249  Context.addComment(RC);
1250 }
1251 
1252 // Pin this vtable to this file.
1254 
1257 
1259  SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1260 }
1261 
1263  llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
1264 
1266  FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1267 
1268 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1269  SourceLocation Loc = this->Loc;
1270  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1271  if (Loc.isValid()) {
1272  Loc.print(OS, S.getSourceManager());
1273  OS << ": ";
1274  }
1275  OS << Message;
1276 
1277  if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
1278  OS << " '";
1279  ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
1280  OS << "'";
1281  }
1282 
1283  OS << '\n';
1284 }
1285 
1286 /// \brief Figure out if an expression could be turned into a call.
1287 ///
1288 /// Use this when trying to recover from an error where the programmer may have
1289 /// written just the name of a function instead of actually calling it.
1290 ///
1291 /// \param E - The expression to examine.
1292 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1293 /// with no arguments, this parameter is set to the type returned by such a
1294 /// call; otherwise, it is set to an empty QualType.
1295 /// \param OverloadSet - If the expression is an overloaded function
1296 /// name, this parameter is populated with the decls of the various overloads.
1297 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1298  UnresolvedSetImpl &OverloadSet) {
1299  ZeroArgCallReturnTy = QualType();
1300  OverloadSet.clear();
1301 
1302  const OverloadExpr *Overloads = nullptr;
1303  bool IsMemExpr = false;
1304  if (E.getType() == Context.OverloadTy) {
1305  OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1306 
1307  // Ignore overloads that are pointer-to-member constants.
1308  if (FR.HasFormOfMemberPointer)
1309  return false;
1310 
1311  Overloads = FR.Expression;
1312  } else if (E.getType() == Context.BoundMemberTy) {
1313  Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1314  IsMemExpr = true;
1315  }
1316 
1317  bool Ambiguous = false;
1318 
1319  if (Overloads) {
1320  for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1321  DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1322  OverloadSet.addDecl(*it);
1323 
1324  // Check whether the function is a non-template, non-member which takes no
1325  // arguments.
1326  if (IsMemExpr)
1327  continue;
1328  if (const FunctionDecl *OverloadDecl
1329  = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1330  if (OverloadDecl->getMinRequiredArguments() == 0) {
1331  if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1332  ZeroArgCallReturnTy = QualType();
1333  Ambiguous = true;
1334  } else
1335  ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1336  }
1337  }
1338  }
1339 
1340  // If it's not a member, use better machinery to try to resolve the call
1341  if (!IsMemExpr)
1342  return !ZeroArgCallReturnTy.isNull();
1343  }
1344 
1345  // Attempt to call the member with no arguments - this will correctly handle
1346  // member templates with defaults/deduction of template arguments, overloads
1347  // with default arguments, etc.
1348  if (IsMemExpr && !E.isTypeDependent()) {
1349  bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1352  None, SourceLocation());
1354  if (R.isUsable()) {
1355  ZeroArgCallReturnTy = R.get()->getType();
1356  return true;
1357  }
1358  return false;
1359  }
1360 
1361  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1362  if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1363  if (Fun->getMinRequiredArguments() == 0)
1364  ZeroArgCallReturnTy = Fun->getReturnType();
1365  return true;
1366  }
1367  }
1368 
1369  // We don't have an expression that's convenient to get a FunctionDecl from,
1370  // but we can at least check if the type is "function of 0 arguments".
1371  QualType ExprTy = E.getType();
1372  const FunctionType *FunTy = nullptr;
1373  QualType PointeeTy = ExprTy->getPointeeType();
1374  if (!PointeeTy.isNull())
1375  FunTy = PointeeTy->getAs<FunctionType>();
1376  if (!FunTy)
1377  FunTy = ExprTy->getAs<FunctionType>();
1378 
1379  if (const FunctionProtoType *FPT =
1380  dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1381  if (FPT->getNumParams() == 0)
1382  ZeroArgCallReturnTy = FunTy->getReturnType();
1383  return true;
1384  }
1385  return false;
1386 }
1387 
1388 /// \brief Give notes for a set of overloads.
1389 ///
1390 /// A companion to tryExprAsCall. In cases when the name that the programmer
1391 /// wrote was an overloaded function, we may be able to make some guesses about
1392 /// plausible overloads based on their return types; such guesses can be handed
1393 /// off to this method to be emitted as notes.
1394 ///
1395 /// \param Overloads - The overloads to note.
1396 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1397 /// -fshow-overloads=best, this is the location to attach to the note about too
1398 /// many candidates. Typically this will be the location of the original
1399 /// ill-formed expression.
1400 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1401  const SourceLocation FinalNoteLoc) {
1402  int ShownOverloads = 0;
1403  int SuppressedOverloads = 0;
1404  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1405  DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1406  // FIXME: Magic number for max shown overloads stolen from
1407  // OverloadCandidateSet::NoteCandidates.
1408  if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1409  ++SuppressedOverloads;
1410  continue;
1411  }
1412 
1413  NamedDecl *Fn = (*It)->getUnderlyingDecl();
1414  S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1415  ++ShownOverloads;
1416  }
1417 
1418  if (SuppressedOverloads)
1419  S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1420  << SuppressedOverloads;
1421 }
1422 
1424  const UnresolvedSetImpl &Overloads,
1425  bool (*IsPlausibleResult)(QualType)) {
1426  if (!IsPlausibleResult)
1427  return noteOverloads(S, Overloads, Loc);
1428 
1429  UnresolvedSet<2> PlausibleOverloads;
1430  for (OverloadExpr::decls_iterator It = Overloads.begin(),
1431  DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1432  const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1433  QualType OverloadResultTy = OverloadDecl->getReturnType();
1434  if (IsPlausibleResult(OverloadResultTy))
1435  PlausibleOverloads.addDecl(It.getDecl());
1436  }
1437  noteOverloads(S, PlausibleOverloads, Loc);
1438 }
1439 
1440 /// Determine whether the given expression can be called by just
1441 /// putting parentheses after it. Notably, expressions with unary
1442 /// operators can't be because the unary operator will start parsing
1443 /// outside the call.
1444 static bool IsCallableWithAppend(Expr *E) {
1445  E = E->IgnoreImplicit();
1446  return (!isa<CStyleCastExpr>(E) &&
1447  !isa<UnaryOperator>(E) &&
1448  !isa<BinaryOperator>(E) &&
1449  !isa<CXXOperatorCallExpr>(E));
1450 }
1451 
1453  bool ForceComplain,
1454  bool (*IsPlausibleResult)(QualType)) {
1455  SourceLocation Loc = E.get()->getExprLoc();
1456  SourceRange Range = E.get()->getSourceRange();
1457 
1458  QualType ZeroArgCallTy;
1459  UnresolvedSet<4> Overloads;
1460  if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1461  !ZeroArgCallTy.isNull() &&
1462  (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1463  // At this point, we know E is potentially callable with 0
1464  // arguments and that it returns something of a reasonable type,
1465  // so we can emit a fixit and carry on pretending that E was
1466  // actually a CallExpr.
1467  SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
1468  Diag(Loc, PD)
1469  << /*zero-arg*/ 1 << Range
1470  << (IsCallableWithAppend(E.get())
1471  ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1472  : FixItHint());
1473  notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1474 
1475  // FIXME: Try this before emitting the fixit, and suppress diagnostics
1476  // while doing so.
1477  E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1478  Range.getEnd().getLocWithOffset(1));
1479  return true;
1480  }
1481 
1482  if (!ForceComplain) return false;
1483 
1484  Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1485  notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1486  E = ExprError();
1487  return true;
1488 }
1489 
1491  if (!Ident_super)
1492  Ident_super = &Context.Idents.get("super");
1493  return Ident_super;
1494 }
1495 
1497  if (!Ident___float128)
1498  Ident___float128 = &Context.Idents.get("__float128");
1499  return Ident___float128;
1500 }
1501 
1503  CapturedRegionKind K) {
1505  getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
1506  (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
1507  CSI->ReturnType = Context.VoidTy;
1508  FunctionScopes.push_back(CSI);
1509 }
1510 
1512  if (FunctionScopes.empty())
1513  return nullptr;
1514 
1515  return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1516 }
1517 
1518 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
1520  return DeleteExprs;
1521 }
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used...
Definition: Sema.h:526
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1561
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:488
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:9565
IdentifierInfo * getSuperIdentifier() const
Definition: Sema.cpp:1490
CanQualType OCLQueueTy
Definition: ASTContext.h:918
Smart pointer class that efficiently represents Objective-C method names.
A (possibly-)qualified type.
Definition: Type.h:598
ASTConsumer & Consumer
Definition: Sema.h:300
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1419
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
Definition: ASTContext.cpp:970
bool isMacroID() const
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:142
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
Definition: ASTConsumer.h:36
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:554
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:920
static const CastKind CK_Invalid
Defines the clang::FileManager interface and associated types.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=TTK_Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
Definition: ASTContext.cpp:938
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2705
A class which encapsulates the logic for delaying diagnostics during parsing and other processing...
Definition: Sema.h:582
const LangOptions & getLangOpts() const
Definition: Sema.h:1062
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition: Sema.cpp:474
submodule_iterator submodule_begin()
Definition: Basic/Module.h:474
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2879
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:536
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:934
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
Definition: Sema.cpp:1423
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1139
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToMemberFunction - Build a call to a member function.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2008
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:7041
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:713
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:177
bool hasErrorOccurred() const
Definition: Diagnostic.h:580
PtrTy get() const
Definition: Ownership.h:164
virtual void updateOutOfDateSelector(Selector Sel)
Load the contents of the global method pool for a given selector if necessary.
Definition: Sema.cpp:1256
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
Definition: Sema.cpp:1255
CanQualType LongTy
Definition: ASTContext.h:901
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2120
Any normal BCPL comments.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
A container of type source information.
Definition: Decl.h:62
IdentifierInfo * getFloat128Identifier() const
Definition: Sema.cpp:1496
The diagnostic should not be reported, but it should cause template argument deduction to fail...
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition: Sema.cpp:545
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:888
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:81
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition: Sema.cpp:50
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:768
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type...
DiagnosticsEngine & Diags
Definition: Sema.h:301
virtual void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WI)
Read the set of weak, undeclared identifiers known to the external Sema source.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1813
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:387
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:9602
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:980
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:724
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:590
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
decl_iterator decls_end() const
Definition: DeclBase.h:1455
Defines the clang::Expr interface and subclasses for C++ expressions.
iterator begin(Source *source, bool LocalOnly=false)
iterator begin(DeclarationName Name)
begin - Returns an iterator for decls with the name 'Name'.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5115
void threadSafetyCleanup(BeforeSet *Cache)
CanQualType OCLSamplerTy
Definition: ASTContext.h:917
void CheckDelayedMemberExceptionSpecs()
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3253
ActiveTemplateInstantiation LastTemplateInstantiationErrorContext
The last template from which a template instantiation error or warning was produced.
Definition: Sema.h:6771
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
Definition: SemaAttr.cpp:421
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class...
An iterator over the friend declarations of a class.
Definition: DeclFriend.h:173
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
One of these records is kept for each identifier that is lexed.
virtual void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls)
Read the set of potentially unused typedefs known to the source.
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:1181
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition: Sema.h:597
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4549
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:901
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:1216
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:92
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:1185
QualType getReturnType() const
Definition: Decl.h:2034
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2293
void erase(iterator From, iterator To)
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2871
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition: Sema.h:7027
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition: Sema.cpp:651
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
Definition: Preprocessor.h:858
CanQualType OCLEventTy
Definition: ASTContext.h:917
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:28
Represents a C++ member access expression for which lookup produced a set of overloaded functions...
Definition: ExprCXX.h:3366
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
Definition: ASTContext.h:557
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CanQualType OCLReserveIDTy
Definition: ASTContext.h:918
Describes a module or submodule.
Definition: Basic/Module.h:47
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:957
IdentifierTable & Idents
Definition: ASTContext.h:459
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
Definition: Sema.cpp:1400
bool AccessCheckingSFINAE
When true, access checking violations are treated as SFINAE failures rather than hard errors...
Definition: Sema.h:5621
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:105
Values of this type can be null.
iterator end()
end - Returns an iterator that has 'finished'.
DiagnosticErrorTrap ErrorTrap
Used to determine if errors occurred in this function or block.
Definition: ScopeInfo.h:144
An abstract interface that should be implemented by clients that read ASTs and then require further s...
Definition: SemaConsumer.h:26
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:1991
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, RecordCompleteMap &MNCComplete)
Returns true, if all methods and nested classes of the given CXXRecordDecl are defined in this transl...
Definition: Sema.cpp:563
friend_iterator friend_end() const
Definition: DeclFriend.h:227
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created...
Definition: Diagnostic.h:846
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:1073
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:588
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:604
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:945
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1154
unsigned getDiagID() const
uint32_t Offset
Definition: CacheTokens.cpp:44
QualType getReturnType() const
Definition: Type.h:3009
std::pair< SourceLocation, bool > DeleteExprLoc
Delete-expressions to be analyzed at the end of translation unit.
Definition: Sema.h:495
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:695
void PerformPendingInstantiations(bool LocalOnly=false)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
A set of unresolved declarations.
Definition: UnresolvedSet.h:55
void IssueWarnings(Policy P, FunctionScopeInfo *fscope, const Decl *D, const BlockExpr *blkExpr)
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void CheckDelegatingCtorCycles()
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:8499
~ExternalSemaSource() override
Definition: Sema.cpp:1253
Values of this type can never be null.
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:326
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
static const unsigned NumNSNumberLiteralMethods
Definition: NSAPI.h:187
submodule_iterator submodule_end()
Definition: Basic/Module.h:476
void emitAndClearUnusedLocalTypedefWarnings()
Definition: Sema.cpp:635
virtual ASTMutationListener * GetASTMutationListener()
If the consumer is interested in entities getting modified after their initial creation, it should return a pointer to an ASTMutationListener here.
Definition: ASTConsumer.h:126
void CheckCompleteVariableDeclaration(VarDecl *var)
Definition: SemaDecl.cpp:10295
Preprocessor & PP
Definition: Sema.h:298
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:7026
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3625
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1206
detail::InMemoryDirectory::const_iterator I
void PushCompoundScope()
Definition: Sema.cpp:1168
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type...
QualType getType() const
Definition: Decl.h:599
const LangOptions & LangOpts
Definition: Sema.h:297
Contains information about the compound statement currently being parsed.
Definition: ScopeInfo.h:54
bool EmitCurrentDiagnostic(bool Force=false)
Emit the current diagnostic and clear the diagnostic state.
Definition: Diagnostic.cpp:363
void Emit(const DiagnosticBuilder &DB) const
static bool IsCallableWithAppend(Expr *E)
Determine whether the given expression can be called by just putting parentheses after it...
Definition: Sema.cpp:1444
bool isUnion() const
Definition: Decl.h:2939
void setLastDiagnosticIgnored()
Pretend that the last diagnostic issued was ignored, so any subsequent notes will be suppressed...
Definition: Diagnostic.h:505
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:263
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3073
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:518
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit...
Definition: Sema.cpp:1519
Retains information about a captured region.
Definition: ScopeInfo.h:624
unsigned getCurrentDiagID() const
Definition: Diagnostic.h:816
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:646
CastKind
CastKind - The kind of operation required for a conversion.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1652
void PopCompoundScope()
Definition: Sema.cpp:1172
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 >> &)
Definition: Sema.cpp:1265
ASTContext * Context
std::vector< bool > & Stack
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:415
CanQualType OCLNDRangeTy
Definition: ASTContext.h:918
virtual void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces)
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition: Sema.cpp:1258
int * Depth
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:116
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:597
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:1909
Any normal C comment.
An abstract interface that should be implemented by external AST sources that also provide informatio...
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3456
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Definition: Sema.cpp:425
Expr - This represents one expression.
Definition: Expr.h:105
Show just the "best" overload candidates.
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:761
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:102
bool isAlmostTrailingComment() const LLVM_READONLY
Returns true if it is a probable typo:
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:508
decls_iterator decls_end() const
Definition: ExprCXX.h:2573
friend_iterator friend_begin() const
Definition: DeclFriend.h:223
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2545
void addImplicitTypedef(StringRef Name, QualType T)
Definition: Sema.cpp:136
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:4567
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:886
Defines the clang::Preprocessor interface.
llvm::MapVector< IdentifierInfo *, WeakInfo > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition: Sema.h:689
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, const BlockExpr *blkExpr=nullptr)
Definition: Sema.cpp:1152
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
Definition: ModuleMap.cpp:875
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:6826
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:317
void Clear()
Clear out the current diagnostic.
Definition: Diagnostic.h:712
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:467
PartialDiagnostic::StorageAllocator & getDiagAllocator()
Definition: ASTContext.h:584
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1214
bool isExternallyVisible() const
Definition: Decl.h:348
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Definition: Sema.h:6732
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1066
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1244
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:1137
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:960
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:553
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
Definition: Sema.cpp:556
An abstract interface that should be implemented by external AST sources that also provide informatio...
decls_iterator decls_begin() const
Definition: ExprCXX.h:2572
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
unsigned Bool
Whether we can use 'bool' rather than '_Bool' (even if the language doesn't actually have 'bool'...
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:1132
CanQualType OverloadTy
Definition: ASTContext.h:909
#define false
Definition: stdbool.h:33
Kind
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2483
void print(raw_ostream &OS, const SourceManager &SM) const
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:943
const TemplateArgument * iterator
Definition: Type.h:4233
bool isValid() const
Return true if this is a valid SourceLocation object.
bool getSuppressAllDiagnostics() const
Definition: Diagnostic.h:475
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition: Sema.cpp:296
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1736
void DiagnoseUseOfUnimplementedSelectors()
CanQualType FloatTy
Definition: ASTContext.h:904
ASTConsumer & getASTConsumer() const
Definition: Sema.h:1070
CanQualType VoidTy
Definition: ASTContext.h:893
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:82
virtual void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined)
Load the set of used but not defined functions or variables with internal linkage, or used but not defined internal functions.
Definition: Sema.cpp:1262
void EmitCurrentDiagnostic(unsigned DiagID)
Cause the active diagnostic on the DiagosticsEngine to be emitted.
Definition: Sema.cpp:959
This declaration is only a declaration.
Definition: Decl.h:1069
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2734
bool isRValue() const
Definition: Expr.h:248
The diagnostic should be suppressed entirely.
SourceLocation getBegin() const
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:165
static bool IsRecordFullyDefined(const CXXRecordDecl *RD, RecordCompleteMap &RecordsComplete, RecordCompleteMap &MNCComplete)
Returns true, if the given CXXRecordDecl is fully defined in this translation unit, i.e.
Definition: Sema.cpp:604
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
Definition: ASTContext.cpp:964
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1188
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition: Sema.cpp:1511
static bool isBuiltinNote(unsigned DiagID)
Determine whether the given built-in diagnostic ID is a Note.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:652
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:193
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1412
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2609
Abstract interface for a consumer of code-completion information.
QualType getType() const
Definition: Expr.h:126
sema::LambdaScopeInfo * getCurLambda()
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1200
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
Represents a template argument.
Definition: TemplateBase.h:40
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
Definition: ASTContext.cpp:954
LateTemplateParserCleanupCB * LateTemplateParserCleanup
Definition: Sema.h:560
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1135
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:368
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition: Sema.cpp:1143
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:76
DeclarationName - The name of a declaration.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition: Sema.cpp:1452
A set of unresolved declarations.
detail::InMemoryDirectory::const_iterator E
IdentifierResolver IdResolver
Definition: Sema.h:708
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1966
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:409
Abstract interface for a module loader.
Definition: ModuleLoader.h:56
NamedDecl * getCurFunctionOrMethodDecl()
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in...
Definition: Sema.cpp:952
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Definition: Sema.h:497
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:34
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition: Sema.h:319
void FormatASTNodeDiagnosticArgument(DiagnosticsEngine::ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< DiagnosticsEngine::ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, void *Cookie, ArrayRef< intptr_t > QualTypeVals)
DiagnosticsEngine argument formatting function for diagnostics that involve AST nodes.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
SourceManager & getSourceManager() const
Definition: Sema.h:1067
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5818
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy.
Definition: Sema.h:1912
CanQualType UnsignedLongTy
Definition: ASTContext.h:902
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
Definition: Sema.cpp:940
void * OpaqueParser
Definition: Sema.h:561
void print(raw_ostream &OS) const override
Definition: Sema.cpp:1268
CanQualType BoundMemberTy
Definition: ASTContext.h:909
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
void addComment(const RawComment &RC)
Definition: ASTContext.h:696
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition: Decl.h:3684
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:78
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
The "class" keyword.
Definition: Type.h:4350
bool isUsable() const
Definition: Ownership.h:161
This is a scope that can contain a declaration.
Definition: Scope.h:58
SourceManager & getSourceManager()
Definition: ASTContext.h:561
The type-property cache.
Definition: Type.cpp:3242
void ActOnTranslationUnitScope(Scope *S)
Definition: Sema.cpp:69
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1101
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
void setSuppressAllDiagnostics(bool Val=true)
Suppress all diagnostics, to silence the front end when we know that we don't want any more diagnosti...
Definition: Diagnostic.h:472
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition: Sema.h:432
SmallVector< PossiblyUnreachableDiag, 4 > PossiblyUnreachableDiags
A list of PartialDiagnostics created but delayed within the current function scope.
Definition: ScopeInfo.h:170
static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID)
Determines whether the given built-in diagnostic ID is for an error that is suppressed if it occurs d...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:263
BoundNodesTreeBuilder *const Builder
CommentKind getKind() const LLVM_READONLY
Represents a C array with an unspecified size.
Definition: Type.h:2562
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:499
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:311
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:172
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:115
TypedefDecl * getCFConstantStringDecl() const
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:1297
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1144
TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:955
Defines the clang::TargetInfo interface.
ExprResult ExprError()
Definition: Ownership.h:268
The diagnostic should be reported.
CanQualType IntTy
Definition: ASTContext.h:901
void PrintStats() const
Print out statistics about the semantic analysis.
Definition: Sema.cpp:343
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:1225
virtual void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending)
Read the set of pending instantiations known to the external Sema source.
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:166
The diagnostic is an access-control diagnostic, which will be substitution failures in some contexts ...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:932
NamedDecl * getMostRecentDecl()
Definition: Decl.h:401
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
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...
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:991
SourceManager & SourceMgr
Definition: Sema.h:302
CapturedRegionKind
The different kinds of captured statement.
Definition: CapturedStmt.h:17
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:52
SourceLocation getCurrentDiagLoc() const
Definition: Diagnostic.h:818
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type...
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound stamement scopes in the function.
Definition: ScopeInfo.h:165
virtual void CompleteTentativeDefinition(VarDecl *D)
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
Definition: ASTConsumer.h:106
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:299
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one. ...
Definition: Sema.cpp:351
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K)
Definition: Sema.cpp:1502
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5318
CanQualType DoubleTy
Definition: ASTContext.h:904
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition: Sema.h:540
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:665
void setType(QualType newType)
Definition: Decl.h:600
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3480
static void checkUndefinedButUsed(Sema &S)
checkUndefinedButUsed - Check for undefined objects with internal linkage or that are inline...
Definition: Sema.cpp:505
SmallVector< std::pair< CXXMethodDecl *, const FunctionProtoType * >, 2 > DelayedDefaultedMemberExceptionSpecs
All the members seen during a class definition which were both explicitly defaulted and had explicitl...
Definition: Sema.h:550
Preprocessor & getPreprocessor() const
Definition: Sema.h:1068
Declaration of a template function.
Definition: DeclTemplate.h:838
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:1120
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:484
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:1829
CanQualType OCLClkEventTy
Definition: ASTContext.h:917
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1092
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2295
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:97
CanQualType UnsignedIntTy
Definition: ASTContext.h:902
bool ParseAllComments
Treat ordinary comments as documentation comments.
IdentifierInfo * getBoolName() const
Retrieve the identifier 'bool'.
Definition: ASTContext.h:1469
The translation unit is a module.
Definition: LangOptions.h:179