clang  3.7.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 #include "llvm/Support/CrashRecoveryContext.h"
44 using namespace clang;
45 using namespace sema;
46 
48  return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
49 }
50 
51 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
52 
54  const Preprocessor &PP) {
55  PrintingPolicy Policy = Context.getPrintingPolicy();
56  Policy.Bool = Context.getLangOpts().Bool;
57  if (!Policy.Bool) {
58  if (const MacroInfo *
59  BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
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  PackContext(nullptr), MSStructPragmaOn(false),
84  MSPointerToMemberRepresentationMethod(
85  LangOpts.getMSPointerToMemberRepresentationMethod()),
86  VtorDispModeStack(1, MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
87  DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
88  CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
89  IsBuildingRecoveryCallExpr(false),
90  ExprNeedsCleanups(false), LateTemplateParser(nullptr),
91  LateTemplateParserCleanup(nullptr),
92  OpaqueParser(nullptr), IdResolver(pp), StdInitializerList(nullptr),
93  CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr),
94  NSNumberDecl(nullptr), NSValueDecl(nullptr),
95  NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
96  ValueWithBytesObjCTypeMethod(nullptr),
97  NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr),
98  NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr),
99  MSAsmLabelNameCounter(0),
100  GlobalNewDeleteDeclared(false),
101  TUKind(TUKind),
102  NumSFINAEErrors(0),
103  CachedFakeTopLevelModule(nullptr),
104  AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
105  NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
106  CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
107  TyposCorrected(0), AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
108  VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
109  Ident_super(nullptr), Ident___float128(nullptr)
110 {
111  TUScope = nullptr;
112 
113  LoadedExternalKnownNamespaces = false;
114  for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
115  NSNumberLiteralMethods[I] = nullptr;
116 
117  if (getLangOpts().ObjC1)
118  NSAPIObj.reset(new NSAPI(Context));
119 
120  if (getLangOpts().CPlusPlus)
121  FieldCollector.reset(new CXXFieldCollector());
122 
123  // Tell diagnostics how to render things from the AST library.
125  &Context);
126 
127  ExprEvalContexts.emplace_back(PotentiallyEvaluated, 0, false, nullptr, false);
128 
129  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
130 
131  // Initilization of data sharing attributes stack for OpenMP
132  InitDataSharingAttributesStack();
133 }
134 
135 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
136  DeclarationName DN = &Context.Idents.get(Name);
137  if (IdResolver.begin(DN) == IdResolver.end())
139 }
140 
142  // Tell the AST consumer about this Sema object.
144 
145  // FIXME: Isn't this redundant with the initialization above?
146  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
147  SC->InitializeSema(*this);
148 
149  // Tell the external Sema source about this Sema object.
150  if (ExternalSemaSource *ExternalSema
151  = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
152  ExternalSema->InitializeSema(*this);
153 
154  // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
155  // will not be able to merge any duplicate __va_list_tag decls correctly.
156  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
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 (PP.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  // Initialize Microsoft "predefined C++ types".
198  if (PP.getLangOpts().MSVCCompat) {
199  if (PP.getLangOpts().CPlusPlus &&
200  IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
202  TUScope);
203 
205  }
206 
207  // Initialize predefined OpenCL types.
208  if (PP.getLangOpts().OpenCL) {
210  addImplicitTypedef("image1d_array_t", Context.OCLImage1dArrayTy);
211  addImplicitTypedef("image1d_buffer_t", Context.OCLImage1dBufferTy);
213  addImplicitTypedef("image2d_array_t", Context.OCLImage2dArrayTy);
217  if (getLangOpts().OpenCLVersion >= 200) {
219  addImplicitTypedef("atomic_uint",
222  addImplicitTypedef("atomic_ulong",
224  addImplicitTypedef("atomic_float",
226  addImplicitTypedef("atomic_double",
228  // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
229  // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
231  addImplicitTypedef("atomic_intptr_t",
233  addImplicitTypedef("atomic_uintptr_t",
235  addImplicitTypedef("atomic_size_t",
237  addImplicitTypedef("atomic_ptrdiff_t",
239  }
240  }
241 
242  DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
243  if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
245 }
246 
248  llvm::DeleteContainerSeconds(LateParsedTemplateMap);
250  if (VisContext) FreeVisContext();
251  // Kill all the active scopes.
252  for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
253  delete FunctionScopes[I];
254  if (FunctionScopes.size() == 1)
255  delete FunctionScopes[0];
256 
257  // Tell the SemaConsumer to forget about us; we're going out of scope.
258  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
259  SC->ForgetSema();
260 
261  // Detach from the external Sema source.
262  if (ExternalSemaSource *ExternalSema
263  = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
264  ExternalSema->ForgetSema();
265 
266  // If Sema's ExternalSource is the multiplexer - we own it.
267  if (isMultiplexExternalSource)
268  delete ExternalSource;
269 
271 
272  // Destroys data sharing attributes stack for OpenMP
273  DestroyDataSharingAttributesStack();
274 
275  assert(DelayedTypos.empty() && "Uncorrected typos!");
276 }
277 
278 /// makeUnavailableInSystemHeader - There is an error in the current
279 /// context. If we're still in a system header, and we can plausibly
280 /// make the relevant declaration unavailable instead of erroring, do
281 /// so and return true.
283  StringRef msg) {
284  // If we're not in a function, it's an error.
285  FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
286  if (!fn) return false;
287 
288  // If we're in template instantiation, it's an error.
289  if (!ActiveTemplateInstantiations.empty())
290  return false;
291 
292  // If that function's not in a system header, it's an error.
294  return false;
295 
296  // If the function is already unavailable, it's not an error.
297  if (fn->hasAttr<UnavailableAttr>()) return true;
298 
299  fn->addAttr(UnavailableAttr::CreateImplicit(Context, msg, loc));
300  return true;
301 }
302 
305 }
306 
307 ///\brief Registers an external source. If an external source already exists,
308 /// creates a multiplex external source and appends to it.
309 ///
310 ///\param[in] E - A non-null external sema source.
311 ///
313  assert(E && "Cannot use with NULL ptr");
314 
315  if (!ExternalSource) {
316  ExternalSource = E;
317  return;
318  }
319 
320  if (isMultiplexExternalSource)
321  static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
322  else {
323  ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
324  isMultiplexExternalSource = true;
325  }
326 }
327 
328 /// \brief Print out statistics about the semantic analysis.
329 void Sema::PrintStats() const {
330  llvm::errs() << "\n*** Semantic Analysis Stats:\n";
331  llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
332 
333  BumpAlloc.PrintStats();
335 }
336 
337 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
338 /// If there is already an implicit cast, merge into the existing one.
339 /// The result is of the given category.
342  const CXXCastPath *BasePath,
343  CheckedConversionKind CCK) {
344 #ifndef NDEBUG
345  if (VK == VK_RValue && !E->isRValue()) {
346  switch (Kind) {
347  default:
348  llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
349  "kind");
350  case CK_LValueToRValue:
353  case CK_ToVoid:
354  break;
355  }
356  }
357  assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
358 #endif
359 
360  // Check whether we're implicitly casting from a nullable type to a nonnull
361  // type.
362  if (auto exprNullability = E->getType()->getNullability(Context)) {
363  if (*exprNullability == NullabilityKind::Nullable) {
364  if (auto typeNullability = Ty->getNullability(Context)) {
365  if (*typeNullability == NullabilityKind::NonNull) {
366  Diag(E->getLocStart(), diag::warn_nullability_lost)
367  << E->getType() << Ty;
368  }
369  }
370  }
371  }
372 
373  QualType ExprTy = Context.getCanonicalType(E->getType());
375 
376  if (ExprTy == TypeTy)
377  return E;
378 
379  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
380  if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
381  ImpCast->setType(Ty);
382  ImpCast->setValueKind(VK);
383  return E;
384  }
385  }
386 
387  return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
388 }
389 
390 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
391 /// to the conversion from scalar type ScalarTy to the Boolean type.
393  switch (ScalarTy->getScalarTypeKind()) {
394  case Type::STK_Bool: return CK_NoOp;
403  }
404  return CK_Invalid;
405 }
406 
407 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
408 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
409  if (D->getMostRecentDecl()->isUsed())
410  return true;
411 
412  if (D->isExternallyVisible())
413  return true;
414 
415  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
416  // UnusedFileScopedDecls stores the first declaration.
417  // The declaration may have become definition so check again.
418  const FunctionDecl *DeclToCheck;
419  if (FD->hasBody(DeclToCheck))
420  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
421 
422  // Later redecls may add new information resulting in not having to warn,
423  // so check again.
424  DeclToCheck = FD->getMostRecentDecl();
425  if (DeclToCheck != FD)
426  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
427  }
428 
429  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
430  // If a variable usable in constant expressions is referenced,
431  // don't warn if it isn't used: if the value of a variable is required
432  // for the computation of a constant expression, it doesn't make sense to
433  // warn even if the variable isn't odr-used. (isReferenced doesn't
434  // precisely reflect that, but it's a decent approximation.)
435  if (VD->isReferenced() &&
436  VD->isUsableInConstantExpressions(SemaRef->Context))
437  return true;
438 
439  // UnusedFileScopedDecls stores the first declaration.
440  // The declaration may have become definition so check again.
441  const VarDecl *DeclToCheck = VD->getDefinition();
442  if (DeclToCheck)
443  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
444 
445  // Later redecls may add new information resulting in not having to warn,
446  // so check again.
447  DeclToCheck = VD->getMostRecentDecl();
448  if (DeclToCheck != VD)
449  return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
450  }
451 
452  return false;
453 }
454 
455 /// Obtains a sorted list of functions that are undefined but ODR-used.
457  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
458  for (llvm::DenseMap<NamedDecl *, SourceLocation>::iterator
459  I = UndefinedButUsed.begin(), E = UndefinedButUsed.end();
460  I != E; ++I) {
461  NamedDecl *ND = I->first;
462 
463  // Ignore attributes that have become invalid.
464  if (ND->isInvalidDecl()) continue;
465 
466  // __attribute__((weakref)) is basically a definition.
467  if (ND->hasAttr<WeakRefAttr>()) continue;
468 
469  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
470  if (FD->isDefined())
471  continue;
472  if (FD->isExternallyVisible() &&
473  !FD->getMostRecentDecl()->isInlined())
474  continue;
475  } else {
476  if (cast<VarDecl>(ND)->hasDefinition() != VarDecl::DeclarationOnly)
477  continue;
478  if (ND->isExternallyVisible())
479  continue;
480  }
481 
482  Undefined.push_back(std::make_pair(ND, I->second));
483  }
484 
485  // Sort (in order of use site) so that we're not dependent on the iteration
486  // order through an llvm::DenseMap.
488  std::sort(Undefined.begin(), Undefined.end(),
489  [&SM](const std::pair<NamedDecl *, SourceLocation> &l,
490  const std::pair<NamedDecl *, SourceLocation> &r) {
491  if (l.second.isValid() && !r.second.isValid())
492  return true;
493  if (!l.second.isValid() && r.second.isValid())
494  return false;
495  if (l.second != r.second)
496  return SM.isBeforeInTranslationUnit(l.second, r.second);
497  return SM.isBeforeInTranslationUnit(l.first->getLocation(),
498  r.first->getLocation());
499  });
500 }
501 
502 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
503 /// or that are inline.
504 static void checkUndefinedButUsed(Sema &S) {
505  if (S.UndefinedButUsed.empty()) return;
506 
507  // Collect all the still-undefined entities with internal linkage.
509  S.getUndefinedButUsed(Undefined);
510  if (Undefined.empty()) return;
511 
512  for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
513  I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
514  NamedDecl *ND = I->first;
515 
516  if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
517  // An exported function will always be emitted when defined, so even if
518  // the function is inline, it doesn't have to be emitted in this TU. An
519  // imported function implies that it has been exported somewhere else.
520  continue;
521  }
522 
523  if (!ND->isExternallyVisible()) {
524  S.Diag(ND->getLocation(), diag::warn_undefined_internal)
525  << isa<VarDecl>(ND) << ND;
526  } else {
527  assert(cast<FunctionDecl>(ND)->getMostRecentDecl()->isInlined() &&
528  "used object requires definition but isn't inline or internal?");
529  S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
530  }
531  if (I->second.isValid())
532  S.Diag(I->second, diag::note_used_here);
533  }
534 }
535 
537  if (!ExternalSource)
538  return;
539 
541  ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
542  for (auto &WeakID : WeakIDs)
543  WeakUndeclaredIdentifiers.insert(WeakID);
544 }
545 
546 
547 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
548 
549 /// \brief Returns true, if all methods and nested classes of the given
550 /// CXXRecordDecl are defined in this translation unit.
551 ///
552 /// Should only be called from ActOnEndOfTranslationUnit so that all
553 /// definitions are actually read.
555  RecordCompleteMap &MNCComplete) {
556  RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
557  if (Cache != MNCComplete.end())
558  return Cache->second;
559  if (!RD->isCompleteDefinition())
560  return false;
561  bool Complete = true;
563  E = RD->decls_end();
564  I != E && Complete; ++I) {
565  if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
566  Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
567  else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
568  // If the template function is marked as late template parsed at this
569  // point, it has not been instantiated and therefore we have not
570  // performed semantic analysis on it yet, so we cannot know if the type
571  // can be considered complete.
572  Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
573  F->getTemplatedDecl()->isDefined();
574  else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
575  if (R->isInjectedClassName())
576  continue;
577  if (R->hasDefinition())
578  Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
579  MNCComplete);
580  else
581  Complete = false;
582  }
583  }
584  MNCComplete[RD] = Complete;
585  return Complete;
586 }
587 
588 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
589 /// translation unit, i.e. all methods are defined or pure virtual and all
590 /// friends, friend functions and nested classes are fully defined in this
591 /// translation unit.
592 ///
593 /// Should only be called from ActOnEndOfTranslationUnit so that all
594 /// definitions are actually read.
595 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
596  RecordCompleteMap &RecordsComplete,
597  RecordCompleteMap &MNCComplete) {
598  RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
599  if (Cache != RecordsComplete.end())
600  return Cache->second;
601  bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
603  E = RD->friend_end();
604  I != E && Complete; ++I) {
605  // Check if friend classes and methods are complete.
606  if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
607  // Friend classes are available as the TypeSourceInfo of the FriendDecl.
608  if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
609  Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
610  else
611  Complete = false;
612  } else {
613  // Friend functions are available through the NamedDecl of FriendDecl.
614  if (const FunctionDecl *FD =
615  dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
616  Complete = FD->isDefined();
617  else
618  // This is a template friend, give up.
619  Complete = false;
620  }
621  }
622  RecordsComplete[RD] = Complete;
623  return Complete;
624 }
625 
627  if (ExternalSource)
628  ExternalSource->ReadUnusedLocalTypedefNameCandidates(
631  if (TD->isReferenced())
632  continue;
633  Diag(TD->getLocation(), diag::warn_unused_local_typedef)
634  << isa<TypeAliasDecl>(TD) << TD->getDeclName();
635  }
636  UnusedLocalTypedefNameCandidates.clear();
637 }
638 
639 /// ActOnEndOfTranslationUnit - This is called at the very end of the
640 /// translation unit when EOF is reached and all but the top-level scope is
641 /// popped.
643  assert(DelayedDiagnostics.getCurrentPool() == nullptr
644  && "reached end of translation unit with a pool attached?");
645 
646  // If code completion is enabled, don't perform any end-of-translation-unit
647  // work.
649  return;
650 
651  // Complete translation units and modules define vtables and perform implicit
652  // instantiations. PCH files do not.
653  if (TUKind != TU_Prefix) {
655 
656  // If DefinedUsedVTables ends up marking any virtual member functions it
657  // might lead to more pending template instantiations, which we then need
658  // to instantiate.
660 
661  // C++: Perform implicit template instantiations.
662  //
663  // FIXME: When we perform these implicit instantiations, we do not
664  // carefully keep track of the point of instantiation (C++ [temp.point]).
665  // This means that name lookup that occurs within the template
666  // instantiation will always happen at the end of the translation unit,
667  // so it will find some names that are not required to be found. This is
668  // valid, but we could do better by diagnosing if an instantiation uses a
669  // name that was not visible at its first point of instantiation.
670  if (ExternalSource) {
671  // Load pending instantiations from the external source.
673  ExternalSource->ReadPendingInstantiations(Pending);
675  Pending.begin(), Pending.end());
676  }
678 
681 
683  }
684 
685  // All delayed member exception specs should be checked or we end up accepting
686  // incompatible declarations.
687  // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
688  // write out the lists to the AST file (if any).
689  assert(DelayedDefaultedMemberExceptionSpecs.empty());
690  assert(DelayedExceptionSpecChecks.empty());
691 
692  // Remove file scoped decls that turned out to be used.
694  std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
696  std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
698 
699  if (TUKind == TU_Prefix) {
700  // Translation unit prefixes don't need any of the checking below.
701  TUScope = nullptr;
702  return;
703  }
704 
705  // Check for #pragma weak identifiers that were never declared
707  for (auto WeakID : WeakUndeclaredIdentifiers) {
708  if (WeakID.second.getUsed())
709  continue;
710 
711  Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
712  << WeakID.first;
713  }
714 
715  if (LangOpts.CPlusPlus11 &&
716  !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
718 
719  if (TUKind == TU_Module) {
720  // If we are building a module, resolve all of the exported declarations
721  // now.
722  if (Module *CurrentModule = PP.getCurrentModule()) {
724 
726  Stack.push_back(CurrentModule);
727  while (!Stack.empty()) {
728  Module *Mod = Stack.pop_back_val();
729 
730  // Resolve the exported declarations and conflicts.
731  // FIXME: Actually complain, once we figure out how to teach the
732  // diagnostic client to deal with complaints in the module map at this
733  // point.
734  ModMap.resolveExports(Mod, /*Complain=*/false);
735  ModMap.resolveUses(Mod, /*Complain=*/false);
736  ModMap.resolveConflicts(Mod, /*Complain=*/false);
737 
738  // Queue the submodules, so their exports will also be resolved.
739  Stack.append(Mod->submodule_begin(), Mod->submodule_end());
740  }
741  }
742 
743  // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
744  // modules when they are built, not every time they are used.
746 
747  // Modules don't need any of the checking below.
748  TUScope = nullptr;
749  return;
750  }
751 
752  // C99 6.9.2p2:
753  // A declaration of an identifier for an object that has file
754  // scope without an initializer, and without a storage-class
755  // specifier or with the storage-class specifier static,
756  // constitutes a tentative definition. If a translation unit
757  // contains one or more tentative definitions for an identifier,
758  // and the translation unit contains no external definition for
759  // that identifier, then the behavior is exactly as if the
760  // translation unit contains a file scope declaration of that
761  // identifier, with the composite type as of the end of the
762  // translation unit, with an initializer equal to 0.
763  llvm::SmallSet<VarDecl *, 32> Seen;
764  for (TentativeDefinitionsType::iterator
765  T = TentativeDefinitions.begin(ExternalSource),
766  TEnd = TentativeDefinitions.end();
767  T != TEnd; ++T)
768  {
769  VarDecl *VD = (*T)->getActingDefinition();
770 
771  // If the tentative definition was completed, getActingDefinition() returns
772  // null. If we've already seen this variable before, insert()'s second
773  // return value is false.
774  if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
775  continue;
776 
777  if (const IncompleteArrayType *ArrayT
779  // Set the length of the array to 1 (C99 6.9.2p5).
780  Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
781  llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
782  QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
783  One, ArrayType::Normal, 0);
784  VD->setType(T);
785  } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
786  diag::err_tentative_def_incomplete_type))
787  VD->setInvalidDecl();
788 
790 
791  // Notify the consumer that we've completed a tentative definition.
792  if (!VD->isInvalidDecl())
794 
795  }
796 
797  // If there were errors, disable 'unused' warnings since they will mostly be
798  // noise.
799  if (!Diags.hasErrorOccurred()) {
800  // Output warning for unused file scoped decls.
801  for (UnusedFileScopedDeclsType::iterator
802  I = UnusedFileScopedDecls.begin(ExternalSource),
803  E = UnusedFileScopedDecls.end(); I != E; ++I) {
804  if (ShouldRemoveFromUnused(this, *I))
805  continue;
806 
807  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
808  const FunctionDecl *DiagD;
809  if (!FD->hasBody(DiagD))
810  DiagD = FD;
811  if (DiagD->isDeleted())
812  continue; // Deleted functions are supposed to be unused.
813  if (DiagD->isReferenced()) {
814  if (isa<CXXMethodDecl>(DiagD))
815  Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
816  << DiagD->getDeclName();
817  else {
818  if (FD->getStorageClass() == SC_Static &&
819  !FD->isInlineSpecified() &&
821  SourceMgr.getExpansionLoc(FD->getLocation())))
822  Diag(DiagD->getLocation(),
823  diag::warn_unneeded_static_internal_decl)
824  << DiagD->getDeclName();
825  else
826  Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
827  << /*function*/0 << DiagD->getDeclName();
828  }
829  } else {
830  Diag(DiagD->getLocation(),
831  isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
832  : diag::warn_unused_function)
833  << DiagD->getDeclName();
834  }
835  } else {
836  const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
837  if (!DiagD)
838  DiagD = cast<VarDecl>(*I);
839  if (DiagD->isReferenced()) {
840  Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
841  << /*variable*/1 << DiagD->getDeclName();
842  } else if (DiagD->getType().isConstQualified()) {
843  Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
844  << DiagD->getDeclName();
845  } else {
846  Diag(DiagD->getLocation(), diag::warn_unused_variable)
847  << DiagD->getDeclName();
848  }
849  }
850  }
851 
852  if (ExternalSource)
853  ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
854  checkUndefinedButUsed(*this);
855 
857  }
858 
859  if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
860  RecordCompleteMap RecordsComplete;
861  RecordCompleteMap MNCComplete;
862  for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
863  E = UnusedPrivateFields.end(); I != E; ++I) {
864  const NamedDecl *D = *I;
865  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
866  if (RD && !RD->isUnion() &&
867  IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
868  Diag(D->getLocation(), diag::warn_unused_private_field)
869  << D->getDeclName();
870  }
871  }
872  }
873 
874  if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
875  if (ExternalSource)
877  for (const auto &DeletedFieldInfo : DeleteExprs) {
878  for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
879  AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
880  DeleteExprLoc.second);
881  }
882  }
883  }
884 
885  // Check we've noticed that we're no longer parsing the initializer for every
886  // variable. If we miss cases, then at best we have a performance issue and
887  // at worst a rejects-valid bug.
888  assert(ParsingInitForAutoVars.empty() &&
889  "Didn't unmark var as having its initializer parsed");
890 
891  TUScope = nullptr;
892 }
893 
894 
895 //===----------------------------------------------------------------------===//
896 // Helper functions.
897 //===----------------------------------------------------------------------===//
898 
900  DeclContext *DC = CurContext;
901 
902  while (true) {
903  if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
904  DC = DC->getParent();
905  } else if (isa<CXXMethodDecl>(DC) &&
906  cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
907  cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
908  DC = DC->getParent()->getParent();
909  }
910  else break;
911  }
912 
913  return DC;
914 }
915 
916 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
917 /// to the function decl for the function being parsed. If we're currently
918 /// in a 'block', this returns the containing context.
921  return dyn_cast<FunctionDecl>(DC);
922 }
923 
926  while (isa<RecordDecl>(DC))
927  DC = DC->getParent();
928  return dyn_cast<ObjCMethodDecl>(DC);
929 }
930 
933  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
934  return cast<NamedDecl>(DC);
935  return nullptr;
936 }
937 
938 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
939  // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
940  // and yet we also use the current diag ID on the DiagnosticsEngine. This has
941  // been made more painfully obvious by the refactor that introduced this
942  // function, but it is possible that the incoming argument can be
943  // eliminnated. If it truly cannot be (for example, there is some reentrancy
944  // issue I am not seeing yet), then there should at least be a clarifying
945  // comment somewhere.
948  Diags.getCurrentDiagID())) {
950  // We'll report the diagnostic below.
951  break;
952 
954  // Count this failure so that we know that template argument deduction
955  // has failed.
956  ++NumSFINAEErrors;
957 
958  // Make a copy of this suppressed diagnostic and store it with the
959  // template-deduction information.
960  if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
961  Diagnostic DiagInfo(&Diags);
962  (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
964  }
965 
967  Diags.Clear();
968  return;
969 
971  // Per C++ Core Issue 1170, access control is part of SFINAE.
972  // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
973  // make access control a part of SFINAE for the purposes of checking
974  // type traits.
976  break;
977 
979 
980  // Suppress this diagnostic.
981  ++NumSFINAEErrors;
982 
983  // Make a copy of this suppressed diagnostic and store it with the
984  // template-deduction information.
985  if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
986  Diagnostic DiagInfo(&Diags);
987  (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
989  }
990 
992  Diags.Clear();
993 
994  // Now the diagnostic state is clear, produce a C++98 compatibility
995  // warning.
996  Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
997 
998  // The last diagnostic which Sema produced was ignored. Suppress any
999  // notes attached to it.
1001  return;
1002  }
1003 
1005  // Make a copy of this suppressed diagnostic and store it with the
1006  // template-deduction information;
1007  if (*Info) {
1008  Diagnostic DiagInfo(&Diags);
1009  (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1011  }
1012 
1013  // Suppress this diagnostic.
1015  Diags.Clear();
1016  return;
1017  }
1018  }
1019 
1020  // Set up the context's printing policy based on our current state.
1022 
1023  // Emit the diagnostic.
1025  return;
1026 
1027  // If this is not a note, and we're in a template instantiation
1028  // that is different from the last template instantiation where
1029  // we emitted an error, print a template instantiation
1030  // backtrace.
1031  if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
1032  !ActiveTemplateInstantiations.empty() &&
1037  }
1038 }
1039 
1043  PD.Emit(Builder);
1044 
1045  return Builder;
1046 }
1047 
1048 /// \brief Looks through the macro-expansion chain for the given
1049 /// location, looking for a macro expansion with the given name.
1050 /// If one is found, returns true and sets the location to that
1051 /// expansion loc.
1052 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1053  SourceLocation loc = locref;
1054  if (!loc.isMacroID()) return false;
1055 
1056  // There's no good way right now to look at the intermediate
1057  // expansions, so just jump to the expansion location.
1058  loc = getSourceManager().getExpansionLoc(loc);
1059 
1060  // If that's written with the name, stop here.
1061  SmallVector<char, 16> buffer;
1062  if (getPreprocessor().getSpelling(loc, buffer) == name) {
1063  locref = loc;
1064  return true;
1065  }
1066  return false;
1067 }
1068 
1069 /// \brief Determines the active Scope associated with the given declaration
1070 /// context.
1071 ///
1072 /// This routine maps a declaration context to the active Scope object that
1073 /// represents that declaration context in the parser. It is typically used
1074 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1075 /// declarations) that injects a name for name-lookup purposes and, therefore,
1076 /// must update the Scope.
1077 ///
1078 /// \returns The scope corresponding to the given declaraion context, or NULL
1079 /// if no such scope is open.
1081 
1082  if (!Ctx)
1083  return nullptr;
1084 
1085  Ctx = Ctx->getPrimaryContext();
1086  for (Scope *S = getCurScope(); S; S = S->getParent()) {
1087  // Ignore scopes that cannot have declarations. This is important for
1088  // out-of-line definitions of static class members.
1089  if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1090  if (DeclContext *Entity = S->getEntity())
1091  if (Ctx == Entity->getPrimaryContext())
1092  return S;
1093  }
1094 
1095  return nullptr;
1096 }
1097 
1098 /// \brief Enter a new function scope
1100  if (FunctionScopes.size() == 1) {
1101  // Use the "top" function scope rather than having to allocate
1102  // memory for a new scope.
1103  FunctionScopes.back()->Clear();
1104  FunctionScopes.push_back(FunctionScopes.back());
1105  return;
1106  }
1107 
1109 }
1110 
1111 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1113  BlockScope, Block));
1114 }
1115 
1117  LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1118  FunctionScopes.push_back(LSI);
1119  return LSI;
1120 }
1121 
1123  if (LambdaScopeInfo *const LSI = getCurLambda()) {
1124  LSI->AutoTemplateParameterDepth = Depth;
1125  return;
1126  }
1127  llvm_unreachable(
1128  "Remove assertion if intentionally called in a non-lambda context.");
1129 }
1130 
1132  const Decl *D, const BlockExpr *blkExpr) {
1133  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1134  assert(!FunctionScopes.empty() && "mismatched push/pop!");
1135 
1136  // Issue any analysis-based warnings.
1137  if (WP && D)
1138  AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1139  else
1140  for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1141  Diag(PUD.Loc, PUD.PD);
1142 
1143  if (FunctionScopes.back() != Scope)
1144  delete Scope;
1145 }
1146 
1149 }
1150 
1152  FunctionScopeInfo *CurFunction = getCurFunction();
1153  assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1154 
1155  CurFunction->CompoundScopes.pop_back();
1156 }
1157 
1158 /// \brief Determine whether any errors occurred within this function/method/
1159 /// block.
1162 }
1163 
1165  if (FunctionScopes.empty())
1166  return nullptr;
1167 
1168  auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1169  if (CurBSI && CurBSI->TheDecl &&
1170  !CurBSI->TheDecl->Encloses(CurContext)) {
1171  // We have switched contexts due to template instantiation.
1172  assert(!ActiveTemplateInstantiations.empty());
1173  return nullptr;
1174  }
1175 
1176  return CurBSI;
1177 }
1178 
1180  if (FunctionScopes.empty())
1181  return nullptr;
1182 
1183  auto CurLSI = dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
1184  if (CurLSI && CurLSI->Lambda &&
1185  !CurLSI->Lambda->Encloses(CurContext)) {
1186  // We have switched contexts due to template instantiation.
1187  assert(!ActiveTemplateInstantiations.empty());
1188  return nullptr;
1189  }
1190 
1191  return CurLSI;
1192 }
1193 // We have a generic lambda if we parsed auto parameters, or we have
1194 // an associated template parameter list.
1196  if (LambdaScopeInfo *LSI = getCurLambda()) {
1197  return (LSI->AutoTemplateParams.size() ||
1198  LSI->GLTemplateParameterList) ? LSI : nullptr;
1199  }
1200  return nullptr;
1201 }
1202 
1203 
1205  if (!LangOpts.RetainCommentsFromSystemHeaders &&
1206  SourceMgr.isInSystemHeader(Comment.getBegin()))
1207  return;
1208  RawComment RC(SourceMgr, Comment, false,
1210  if (RC.isAlmostTrailingComment()) {
1211  SourceRange MagicMarkerRange(Comment.getBegin(),
1212  Comment.getBegin().getLocWithOffset(3));
1213  StringRef MagicMarkerText;
1214  switch (RC.getKind()) {
1216  MagicMarkerText = "///<";
1217  break;
1219  MagicMarkerText = "/**<";
1220  break;
1221  default:
1222  llvm_unreachable("if this is an almost Doxygen comment, "
1223  "it should be ordinary");
1224  }
1225  Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1226  FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1227  }
1228  Context.addComment(RC);
1229 }
1230 
1231 // Pin this vtable to this file.
1233 
1235 
1237  SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1238 }
1239 
1241  llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) {
1242 }
1243 
1245  FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1246 
1247 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1248  SourceLocation Loc = this->Loc;
1249  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1250  if (Loc.isValid()) {
1251  Loc.print(OS, S.getSourceManager());
1252  OS << ": ";
1253  }
1254  OS << Message;
1255 
1256  if (TheDecl && isa<NamedDecl>(TheDecl)) {
1257  std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
1258  if (!Name.empty())
1259  OS << " '" << Name << '\'';
1260  }
1261 
1262  OS << '\n';
1263 }
1264 
1265 /// \brief Figure out if an expression could be turned into a call.
1266 ///
1267 /// Use this when trying to recover from an error where the programmer may have
1268 /// written just the name of a function instead of actually calling it.
1269 ///
1270 /// \param E - The expression to examine.
1271 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1272 /// with no arguments, this parameter is set to the type returned by such a
1273 /// call; otherwise, it is set to an empty QualType.
1274 /// \param OverloadSet - If the expression is an overloaded function
1275 /// name, this parameter is populated with the decls of the various overloads.
1276 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1277  UnresolvedSetImpl &OverloadSet) {
1278  ZeroArgCallReturnTy = QualType();
1279  OverloadSet.clear();
1280 
1281  const OverloadExpr *Overloads = nullptr;
1282  bool IsMemExpr = false;
1283  if (E.getType() == Context.OverloadTy) {
1284  OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1285 
1286  // Ignore overloads that are pointer-to-member constants.
1287  if (FR.HasFormOfMemberPointer)
1288  return false;
1289 
1290  Overloads = FR.Expression;
1291  } else if (E.getType() == Context.BoundMemberTy) {
1292  Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1293  IsMemExpr = true;
1294  }
1295 
1296  bool Ambiguous = false;
1297 
1298  if (Overloads) {
1299  for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1300  DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1301  OverloadSet.addDecl(*it);
1302 
1303  // Check whether the function is a non-template, non-member which takes no
1304  // arguments.
1305  if (IsMemExpr)
1306  continue;
1307  if (const FunctionDecl *OverloadDecl
1308  = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1309  if (OverloadDecl->getMinRequiredArguments() == 0) {
1310  if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1311  ZeroArgCallReturnTy = QualType();
1312  Ambiguous = true;
1313  } else
1314  ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1315  }
1316  }
1317  }
1318 
1319  // If it's not a member, use better machinery to try to resolve the call
1320  if (!IsMemExpr)
1321  return !ZeroArgCallReturnTy.isNull();
1322  }
1323 
1324  // Attempt to call the member with no arguments - this will correctly handle
1325  // member templates with defaults/deduction of template arguments, overloads
1326  // with default arguments, etc.
1327  if (IsMemExpr && !E.isTypeDependent()) {
1328  bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1331  None, SourceLocation());
1333  if (R.isUsable()) {
1334  ZeroArgCallReturnTy = R.get()->getType();
1335  return true;
1336  }
1337  return false;
1338  }
1339 
1340  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1341  if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1342  if (Fun->getMinRequiredArguments() == 0)
1343  ZeroArgCallReturnTy = Fun->getReturnType();
1344  return true;
1345  }
1346  }
1347 
1348  // We don't have an expression that's convenient to get a FunctionDecl from,
1349  // but we can at least check if the type is "function of 0 arguments".
1350  QualType ExprTy = E.getType();
1351  const FunctionType *FunTy = nullptr;
1352  QualType PointeeTy = ExprTy->getPointeeType();
1353  if (!PointeeTy.isNull())
1354  FunTy = PointeeTy->getAs<FunctionType>();
1355  if (!FunTy)
1356  FunTy = ExprTy->getAs<FunctionType>();
1357 
1358  if (const FunctionProtoType *FPT =
1359  dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1360  if (FPT->getNumParams() == 0)
1361  ZeroArgCallReturnTy = FunTy->getReturnType();
1362  return true;
1363  }
1364  return false;
1365 }
1366 
1367 /// \brief Give notes for a set of overloads.
1368 ///
1369 /// A companion to tryExprAsCall. In cases when the name that the programmer
1370 /// wrote was an overloaded function, we may be able to make some guesses about
1371 /// plausible overloads based on their return types; such guesses can be handed
1372 /// off to this method to be emitted as notes.
1373 ///
1374 /// \param Overloads - The overloads to note.
1375 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1376 /// -fshow-overloads=best, this is the location to attach to the note about too
1377 /// many candidates. Typically this will be the location of the original
1378 /// ill-formed expression.
1379 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1380  const SourceLocation FinalNoteLoc) {
1381  int ShownOverloads = 0;
1382  int SuppressedOverloads = 0;
1383  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1384  DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1385  // FIXME: Magic number for max shown overloads stolen from
1386  // OverloadCandidateSet::NoteCandidates.
1387  if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1388  ++SuppressedOverloads;
1389  continue;
1390  }
1391 
1392  NamedDecl *Fn = (*It)->getUnderlyingDecl();
1393  S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1394  ++ShownOverloads;
1395  }
1396 
1397  if (SuppressedOverloads)
1398  S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1399  << SuppressedOverloads;
1400 }
1401 
1403  const UnresolvedSetImpl &Overloads,
1404  bool (*IsPlausibleResult)(QualType)) {
1405  if (!IsPlausibleResult)
1406  return noteOverloads(S, Overloads, Loc);
1407 
1408  UnresolvedSet<2> PlausibleOverloads;
1409  for (OverloadExpr::decls_iterator It = Overloads.begin(),
1410  DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1411  const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1412  QualType OverloadResultTy = OverloadDecl->getReturnType();
1413  if (IsPlausibleResult(OverloadResultTy))
1414  PlausibleOverloads.addDecl(It.getDecl());
1415  }
1416  noteOverloads(S, PlausibleOverloads, Loc);
1417 }
1418 
1419 /// Determine whether the given expression can be called by just
1420 /// putting parentheses after it. Notably, expressions with unary
1421 /// operators can't be because the unary operator will start parsing
1422 /// outside the call.
1423 static bool IsCallableWithAppend(Expr *E) {
1424  E = E->IgnoreImplicit();
1425  return (!isa<CStyleCastExpr>(E) &&
1426  !isa<UnaryOperator>(E) &&
1427  !isa<BinaryOperator>(E) &&
1428  !isa<CXXOperatorCallExpr>(E));
1429 }
1430 
1432  bool ForceComplain,
1433  bool (*IsPlausibleResult)(QualType)) {
1434  SourceLocation Loc = E.get()->getExprLoc();
1435  SourceRange Range = E.get()->getSourceRange();
1436 
1437  QualType ZeroArgCallTy;
1438  UnresolvedSet<4> Overloads;
1439  if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1440  !ZeroArgCallTy.isNull() &&
1441  (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1442  // At this point, we know E is potentially callable with 0
1443  // arguments and that it returns something of a reasonable type,
1444  // so we can emit a fixit and carry on pretending that E was
1445  // actually a CallExpr.
1446  SourceLocation ParenInsertionLoc = PP.getLocForEndOfToken(Range.getEnd());
1447  Diag(Loc, PD)
1448  << /*zero-arg*/ 1 << Range
1449  << (IsCallableWithAppend(E.get())
1450  ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1451  : FixItHint());
1452  notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1453 
1454  // FIXME: Try this before emitting the fixit, and suppress diagnostics
1455  // while doing so.
1456  E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1457  Range.getEnd().getLocWithOffset(1));
1458  return true;
1459  }
1460 
1461  if (!ForceComplain) return false;
1462 
1463  Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1464  notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1465  E = ExprError();
1466  return true;
1467 }
1468 
1470  if (!Ident_super)
1471  Ident_super = &Context.Idents.get("super");
1472  return Ident_super;
1473 }
1474 
1476  if (!Ident___float128)
1477  Ident___float128 = &Context.Idents.get("__float128");
1478  return Ident___float128;
1479 }
1480 
1482  CapturedRegionKind K) {
1484  getDiagnostics(), S, CD, RD, CD->getContextParam(), K);
1485  CSI->ReturnType = Context.VoidTy;
1486  FunctionScopes.push_back(CSI);
1487 }
1488 
1490  if (FunctionScopes.empty())
1491  return nullptr;
1492 
1493  return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1494 }
1495 
1496 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
1498  return DeleteExprs;
1499 }
void FreePackedContext()
FreePackedContext - Deallocate and null out PackContext.
Definition: SemaAttr.cpp:110
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:493
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:455
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:8979
IdentifierInfo * getSuperIdentifier() const
Definition: Sema.cpp:1469
Smart pointer class that efficiently represents Objective-C method names.
ASTConsumer & Consumer
Definition: Sema.h:296
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1377
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
Definition: ASTContext.cpp:933
bool isMacroID() const
CanQualType OCLImage1dBufferTy
Definition: ASTContext.h:837
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:141
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:521
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:899
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:901
const LangOptions & getLangOpts() const
Definition: Sema.h:1019
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition: Sema.cpp:456
submodule_iterator submodule_begin()
Definition: Basic/Module.h:467
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Definition: Preprocessor.h:922
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition: Sema.h:781
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
Definition: Sema.cpp:1402
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1088
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:1987
void setType(QualType t)
Definition: Expr.h:126
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:6826
Scope * TUScope
Definition: Sema.h:680
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:168
bool hasErrorOccurred() const
Definition: Diagnostic.h:573
PtrTy get() const
Definition: Ownership.h:163
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
Definition: Sema.cpp:1234
CanQualType LongTy
Definition: ASTContext.h:825
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2009
Any normal BCPL comments.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:47
A container of type source information.
Definition: Decl.h:60
IdentifierInfo * getFloat128Identifier() const
Definition: Sema.cpp:1475
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:536
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:866
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:80
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition: Sema.cpp:51
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type...
DiagnosticsEngine & Diags
Definition: Sema.h:297
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:1701
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:318
Expr * IgnoreImplicit() LLVM_READONLY
Definition: Expr.h:694
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:585
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:35
decl_iterator decls_end() const
Definition: DeclBase.h:1415
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)
Definition: SemaExpr.cpp:4730
void threadSafetyCleanup(BeforeSet *Cache)
CanQualType OCLSamplerTy
Definition: ASTContext.h:840
void CheckDelayedMemberExceptionSpecs()
ActiveTemplateInstantiation LastTemplateInstantiationErrorContext
The last template from which a template instantiation error or warning was produced.
Definition: Sema.h:6553
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
Definition: SemaAttr.cpp:536
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:177
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:700
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:1160
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition: Sema.h:564
bool hasAttr() const
Definition: DeclBase.h:487
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:879
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:1195
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
CanQualType OCLImage2dArrayTy
Definition: ASTContext.h:838
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:1164
QualType getReturnType() const
Definition: Decl.h:1997
void erase(iterator From, iterator To)
bool isCompleteDefinition() const
Definition: Decl.h:2838
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition: Sema.h:6812
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:326
void ActOnEndOfTranslationUnit()
Definition: Sema.cpp:642
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
Definition: Preprocessor.h:846
CanQualType OCLEventTy
Definition: ASTContext.h:840
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:679
Represents a C++ member access expression for which lookup produced a set of overloaded functions...
Definition: ExprCXX.h:3209
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
Definition: ASTContext.h:490
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
Describes a module or submodule.
Definition: Basic/Module.h:49
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:915
IdentifierTable & Idents
Definition: ASTContext.h:439
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
Definition: Sema.cpp:1379
bool AccessCheckingSFINAE
When true, access checking violations are treated as SFINAE failures rather than hard errors...
Definition: Sema.h:5414
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:95
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:134
An abstract interface that should be implemented by clients that read ASTs and then require further s...
Definition: SemaConsumer.h:26
Converts a floating point complex to bool by comparing against 0+0i.
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU. Returns null if there is a pro...
Definition: Decl.cpp:1970
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:554
friend_iterator friend_end() const
Definition: DeclFriend.h:231
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created...
Definition: Diagnostic.h:839
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:1052
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:518
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
CanQualType OCLImage2dTy
Definition: ASTContext.h:838
const LangOptions & getLangOpts() const
Definition: ASTContext.h:533
ObjCMethodDecl * getCurMethodDecl()
Definition: Sema.cpp:924
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1148
unsigned getDiagID() const
uint32_t Offset
Definition: CacheTokens.cpp:43
QualType getReturnType() const
Definition: Type.h:2952
std::pair< SourceLocation, bool > DeleteExprLoc
Delete-expressions to be analyzed at the end of translation unit.
Definition: Sema.h:462
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:683
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:8022
~ExternalSemaSource() override
Definition: Sema.cpp:1232
Values of this type can never be null.
void addExternalSource(ExternalSemaSource *E)
Registers an external source. If an external source already exists, creates a multiplex external sour...
Definition: Sema.cpp:312
static const unsigned NumNSNumberLiteralMethods
Definition: NSAPI.h:187
submodule_iterator submodule_end()
Definition: Basic/Module.h:469
void emitAndClearUnusedLocalTypedefWarnings()
Definition: Sema.cpp:626
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:137
void CheckCompleteVariableDeclaration(VarDecl *var)
Definition: SemaDecl.cpp:9665
Preprocessor & PP
Definition: Sema.h:294
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:6811
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3616
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1141
void PushCompoundScope()
Definition: Sema.cpp:1147
CanQualType OCLImage3dTy
Definition: ASTContext.h:839
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type...
QualType getType() const
Definition: Decl.h:538
const LangOptions & LangOpts
Definition: Sema.h:293
Contains information about the compound statement currently being parsed.
Definition: ScopeInfo.h:53
bool EmitCurrentDiagnostic(bool Force=false)
Emit the current diagnostic and clear the diagnostic state.
Definition: Diagnostic.cpp:362
void Emit(const DiagnosticBuilder &DB) const
static bool IsCallableWithAppend(Expr *E)
Definition: Sema.cpp:1423
bool isUnion() const
Definition: Decl.h:2906
void setLastDiagnosticIgnored()
Pretend that the last diagnostic issued was ignored, so any subsequent notes will be suppressed...
Definition: Diagnostic.h:498
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:258
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:485
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Definition: Sema.cpp:1497
Retains information about a captured region.
Definition: ScopeInfo.h:579
unsigned getCurrentDiagID() const
Definition: Diagnostic.h:809
Represents a ValueDecl that came out of a declarator. Contains type source information through TypeSo...
Definition: Decl.h:586
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:1737
void PopCompoundScope()
Definition: Sema.cpp:1151
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 >> &)
Definition: Sema.cpp:1244
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
Definition: Type.cpp:414
SourceManager & SM
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:1236
int * Depth
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:110
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:552
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:1861
Any normal C comment.
An abstract interface that should be implemented by external AST sources that also provide informatio...
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Definition: Sema.cpp:408
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:759
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:92
bool isAlmostTrailingComment() const LLVM_READONLY
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
Definition: Sema.h:475
CanQualType OCLImage1dTy
Definition: ASTContext.h:837
decls_iterator decls_end() const
Definition: ExprCXX.h:2390
friend_iterator friend_begin() const
Definition: DeclFriend.h:227
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2362
void addImplicitTypedef(StringRef Name, QualType T)
Definition: Sema.cpp:135
SourceManager & SourceMgr
Definition: Format.cpp:1205
void setInvalidDecl(bool Invalid=true)
Definition: DeclBase.cpp:96
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:812
Defines the clang::Preprocessor interface.
llvm::MapVector< IdentifierInfo *, WeakInfo > WeakUndeclaredIdentifiers
Definition: Sema.h:656
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
DeclContext * getDeclContext()
Definition: DeclBase.h:381
void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, const BlockExpr *blkExpr=nullptr)
Definition: Sema.cpp:1131
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
Definition: ModuleMap.cpp:853
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:6354
llvm::DenseMap< NamedDecl *, SourceLocation > UndefinedButUsed
Definition: Sema.h:938
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:303
void Clear()
Clear out the current diagnostic.
Definition: Diagnostic.h:705
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:434
PartialDiagnostic::StorageAllocator & getDiagAllocator()
Definition: ASTContext.h:514
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1174
bool isExternallyVisible() const
Definition: Decl.h:279
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Definition: Sema.h:6518
DeclarationName getDeclName() const
Definition: Decl.h:189
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1023
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1202
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:1116
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:918
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:486
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
Definition: Sema.cpp:547
An abstract interface that should be implemented by external AST sources that also provide informatio...
void * PackContext
Definition: Sema.h:319
decls_iterator decls_begin() const
Definition: ExprCXX.h:2389
void addAttr(Attr *A)
Definition: DeclBase.h:437
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' (bec...
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:1111
CanQualType OverloadTy
Definition: ASTContext.h:832
#define false
Definition: stdbool.h:33
Kind
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2305
void print(raw_ostream &OS, const SourceManager &SM) const
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
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:864
bool isValid() const
Return true if this is a valid SourceLocation object.
bool getSuppressAllDiagnostics() const
Definition: Diagnostic.h:468
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1717
void DiagnoseUseOfUnimplementedSelectors()
CanQualType FloatTy
Definition: ASTContext.h:828
ASTConsumer & getASTConsumer() const
Definition: Sema.h:1027
CanQualType VoidTy
Definition: ASTContext.h:817
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:77
void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie)
Definition: Diagnostic.h:618
void EmitCurrentDiagnostic(unsigned DiagID)
Cause the active diagnostic on the DiagosticsEngine to be emitted. This is closely coupled to the Sem...
Definition: Sema.cpp:938
This declaration is only a declaration.
Definition: Decl.h:993
bool isRValue() const
Definition: Expr.h:251
The diagnostic should be suppressed entirely.
SourceLocation getBegin() const
bool isTypeDependent() const
Definition: Expr.h:166
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. all methods are defined or pure virtual and all friends, friend functions and nested classes are fully defined in this translation unit.
Definition: Sema.cpp:595
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:446
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
Definition: ASTContext.cpp:927
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1137
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition: Sema.cpp:1489
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:645
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:676
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.cpp:193
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2576
Abstract interface for a consumer of code-completion information.
QualType getType() const
Definition: Expr.h:125
sema::LambdaScopeInfo * getCurLambda()
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1179
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
Definition: ASTContext.cpp:917
LateTemplateParserCleanupCB * LateTemplateParserCleanup
Definition: Sema.h:527
ObjCMethodDecl * NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]
The Objective-C NSNumber methods used to create NSNumber literals.
Definition: Sema.h:715
Converts an integral complex to bool by comparing against 0+0i.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
Definition: Sema.cpp:340
bool isInvalidDecl() const
Definition: DeclBase.h:498
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing. Currently it is used to pass on the depth when parsing generic lambda 'auto' parameters.
Definition: Sema.cpp:1122
This is a scope that corresponds to the template parameters of a C++ template. Template parameter sco...
Definition: Scope.h:75
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. Returns true if recovery was attempted or...
Definition: Sema.cpp:1431
bool isUsed(bool CheckUsedAttr=true) const
Whether this declaration was used, meaning that a definition is required.
Definition: DeclBase.cpp:305
A set of unresolved declarations.
IdentifierResolver IdResolver
Definition: Sema.h:675
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:1855
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
Definition: Sema.cpp:392
Abstract interface for a module loader.
Definition: ModuleLoader.h:56
NamedDecl * getCurFunctionOrMethodDecl()
Definition: Sema.cpp:931
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Definition: Sema.h:464
Encapsulates the data about a macro definition (e.g. its tokens).
Definition: MacroInfo.h:34
DeclarationName VAListTagName
Definition: Sema.h:315
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>. Pointer - pointer requires t...
SourceManager & getSourceManager() const
Definition: Sema.h:1024
const T * getAs() const
Definition: Type.h:5555
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy.
Definition: Sema.h:1807
CanQualType UnsignedLongTy
Definition: ASTContext.h:826
FunctionDecl * getCurFunctionDecl()
Definition: Sema.cpp:919
void * OpaqueParser
Definition: Sema.h:528
void print(raw_ostream &OS) const override
Definition: Sema.cpp:1247
CanQualType BoundMemberTy
Definition: ASTContext.h:832
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:860
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
void addComment(const RawComment &RC)
Definition: ASTContext.h:625
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition: Decl.h:3658
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:4136
bool isUsable() const
Definition: Ownership.h:160
This is a scope that can contain a declaration. Some scopes just contain loop constructs but don't co...
Definition: Scope.h:57
SourceManager & getSourceManager()
Definition: ASTContext.h:494
void ActOnTranslationUnitScope(Scope *S)
Definition: Sema.cpp:69
virtual void Initialize(ASTContext &Context)
Definition: ASTConsumer.h:50
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1080
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:465
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition: Sema.h:398
virtual void ReadUndefinedButUsed(llvm::DenseMap< 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:1240
SmallVector< PossiblyUnreachableDiag, 4 > PossiblyUnreachableDiags
A list of PartialDiagnostics created but delayed within the current function scope. These diagnostics are vetted for reachability prior to being emitted.
Definition: ScopeInfo.h:152
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:285
BoundNodesTreeBuilder *const Builder
CommentKind getKind() const LLVM_READONLY
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:492
CanQualType OCLImage1dArrayTy
Definition: ASTContext.h:837
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:307
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:163
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
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:1276
TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:913
Defines the clang::TargetInfo interface.
ExprResult ExprError()
Definition: Ownership.h:267
The diagnostic should be reported.
CanQualType IntTy
Definition: ASTContext.h:825
bool makeUnavailableInSystemHeader(SourceLocation loc, StringRef message)
Definition: Sema.cpp:282
void PrintStats() const
Print out statistics about the semantic analysis.
Definition: Sema.cpp:329
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:1204
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:158
The diagnostic is an access-control diagnostic, which will be substitution failures in some contexts ...
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
Definition: Expr.h:899
NamedDecl * getMostRecentDecl()
Definition: Decl.h:330
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()
Definition: DeclBase.cpp:920
SourceManager & SourceMgr
Definition: Sema.h:298
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:811
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound stamement scopes in the function.
Definition: ScopeInfo.h:147
virtual void CompleteTentativeDefinition(VarDecl *D)
Definition: ASTConsumer.h:121
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:372
ASTContext & Context
Definition: Sema.h:295
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K)
Definition: Sema.cpp:1481
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:5075
CanQualType DoubleTy
Definition: ASTContext.h:828
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:507
bool isNull() const
isNull - Return true if this QualType doesn't point to a type yet.
Definition: Type.h:633
void setType(QualType newType)
Definition: Decl.h:539
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Definition: Type.cpp:3326
static void checkUndefinedButUsed(Sema &S)
Definition: Sema.cpp:504
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:517
This class handles loading and caching of source files into memory.
Preprocessor & getPreprocessor() const
Definition: Sema.h:1025
Declaration of a template function.
Definition: DeclTemplate.h:821
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:1099
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:451
ScalarTypeKind getScalarTypeKind() const
getScalarTypeKind - Given that this is a scalar type, classify it.
Definition: Type.cpp:1806
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1049
Expr * IgnoreParens() LLVM_READONLY
Definition: Expr.cpp:2408
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:96
CanQualType UnsignedIntTy
Definition: ASTContext.h:826
bool ParseAllComments
Treat ordinary comments as documentation comments.
The translation unit is a module.
Definition: LangOptions.h:170