1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Sema class, which performs semantic analysis and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SEMA_H
16 #define LLVM_CLANG_SEMA_SEMA_H
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/LambdaMangleContext.h"
24 #include "clang/AST/NSAPI.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/ExpressionTraits.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TemplateKinds.h"
31 #include "clang/Basic/TypeTraits.h"
32 #include "clang/Lex/ModuleLoader.h"
33 #include "clang/Sema/AnalysisBasedWarnings.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/ExternalSemaSource.h"
36 #include "clang/Sema/IdentifierResolver.h"
37 #include "clang/Sema/LocInfoType.h"
38 #include "clang/Sema/ObjCMethodList.h"
39 #include "clang/Sema/Ownership.h"
40 #include "clang/Sema/ScopeInfo.h"
41 #include "clang/Sema/TypoCorrection.h"
42 #include "clang/Sema/Weak.h"
43 #include "llvm/ADT/ArrayRef.h"
44 #include "llvm/ADT/Optional.h"
45 #include "llvm/ADT/OwningPtr.h"
46 #include "llvm/ADT/SetVector.h"
47 #include "llvm/ADT/SmallPtrSet.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/MC/MCParser/MCAsmParser.h"
55 template <typename ValueT> struct DenseMapInfo;
56 template <typename ValueT, typename ValueInfoT> class DenseSet;
64 class ASTMutationListener;
73 class CXXBindTemporaryExpr;
74 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
75 class CXXConstructorDecl;
76 class CXXConversionDecl;
77 class CXXDestructorDecl;
78 class CXXFieldCollector;
79 class CXXMemberCallExpr;
85 class ClassTemplateDecl;
86 class ClassTemplatePartialSpecializationDecl;
87 class ClassTemplateSpecializationDecl;
88 class CodeCompleteConsumer;
89 class CodeCompletionAllocator;
90 class CodeCompletionTUInfo;
91 class CodeCompletionResult;
97 class DeducedTemplateArgument;
98 class DependentDiagnostic;
99 class DesignatedInitExpr;
101 class EnumConstantDecl;
104 class ExternalSemaSource;
108 class FunctionProtoType;
109 class FunctionTemplateDecl;
110 class ImplicitConversionSequence;
112 class InitializationKind;
113 class InitializationSequence;
114 class InitializedEntity;
115 class IntegerLiteral;
119 class LocalInstantiationScope;
122 class MultiLevelTemplateArgumentList;
125 class ObjCCategoryDecl;
126 class ObjCCategoryImplDecl;
127 class ObjCCompatibleAliasDecl;
128 class ObjCContainerDecl;
130 class ObjCImplementationDecl;
131 class ObjCInterfaceDecl;
133 template <class T> class ObjCList;
134 class ObjCMessageExpr;
135 class ObjCMethodDecl;
136 class ObjCPropertyDecl;
137 class ObjCProtocolDecl;
138 class OMPThreadPrivateDecl;
139 class OverloadCandidateSet;
144 class PseudoDestructorTypeStorage;
145 class PseudoObjectExpr;
147 class StandardConversionSequence;
151 class TargetAttributesSema;
152 class TemplateArgument;
153 class TemplateArgumentList;
154 class TemplateArgumentLoc;
156 class TemplateParameterList;
157 class TemplatePartialOrderingContext;
158 class TemplateTemplateParmDecl;
162 class TypedefNameDecl;
165 class UnresolvedLookupExpr;
166 class UnresolvedMemberExpr;
167 class UnresolvedSetImpl;
168 class UnresolvedSetIterator;
170 class UsingShadowDecl;
173 class VisibilityAttr;
174 class VisibleDeclConsumer;
175 class IndirectFieldDecl;
178 class AccessedEntity;
179 class BlockScopeInfo;
180 class CapturedRegionScopeInfo;
181 class CapturingScopeInfo;
182 class CompoundScopeInfo;
183 class DelayedDiagnostic;
184 class DelayedDiagnosticPool;
185 class FunctionScopeInfo;
186 class LambdaScopeInfo;
187 class PossiblyUnreachableDiag;
188 class TemplateDeductionInfo;
191 // FIXME: No way to easily map from TemplateTypeParmTypes to
192 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
193 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
194 SourceLocation> UnexpandedParameterPack;
196 /// Sema - This implements semantic analysis and AST building for C.
198 Sema(const Sema &) LLVM_DELETED_FUNCTION;
199 void operator=(const Sema &) LLVM_DELETED_FUNCTION;
200 mutable const TargetAttributesSema* TheTargetAttributesSema;
202 ///\brief Source of additional semantic information.
203 ExternalSemaSource *ExternalSource;
205 ///\brief Whether Sema has generated a multiplexer and has to delete it.
206 bool isMultiplexExternalSource;
208 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
211 shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) {
212 // We are about to link these. It is now safe to compute the linkage of
213 // the new decl. If the new decl has external linkage, we will
214 // link it with the hidden decl (which also has external linkage) and
215 // it will keep having external linkage. If it has internal linkage, we
216 // will not link it. Since it has no previous decls, it will remain
217 // with internal linkage.
218 return !Old->isHidden() || New->hasExternalLinkage();
222 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
223 typedef OpaquePtr<TemplateName> TemplateTy;
224 typedef OpaquePtr<QualType> TypeTy;
226 OpenCLOptions OpenCLFeatures;
227 FPOptions FPFeatures;
229 const LangOptions &LangOpts;
232 ASTConsumer &Consumer;
233 DiagnosticsEngine &Diags;
234 SourceManager &SourceMgr;
236 /// \brief Flag indicating whether or not to collect detailed statistics.
239 /// \brief Code-completion consumer.
240 CodeCompleteConsumer *CodeCompleter;
242 /// CurContext - This is the current declaration context of parsing.
243 DeclContext *CurContext;
245 /// \brief Generally null except when we temporarily switch decl contexts,
246 /// like in \see ActOnObjCTemporaryExitContainerContext.
247 DeclContext *OriginalLexicalContext;
249 /// VAListTagName - The declaration name corresponding to __va_list_tag.
250 /// This is used as part of a hack to omit that class from ADL results.
251 DeclarationName VAListTagName;
253 /// PackContext - Manages the stack for \#pragma pack. An alignment
254 /// of 0 indicates default alignment.
255 void *PackContext; // Really a "PragmaPackStack*"
257 bool MSStructPragmaOn; // True when \#pragma ms_struct on
259 /// VisContext - Manages the stack for \#pragma GCC visibility.
260 void *VisContext; // Really a "PragmaVisStack*"
262 /// \brief Flag indicating if Sema is building a recovery call expression.
264 /// This flag is used to avoid building recovery call expressions
265 /// if Sema is already doing so, which would cause infinite recursions.
266 bool IsBuildingRecoveryCallExpr;
268 /// ExprNeedsCleanups - True if the current evaluation context
269 /// requires cleanups to be run at its conclusion.
270 bool ExprNeedsCleanups;
272 /// ExprCleanupObjects - This is the stack of objects requiring
273 /// cleanup that are created by the current full expression. The
274 /// element type here is ExprWithCleanups::Object.
275 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
277 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
279 /// \brief Stack containing information about each of the nested
280 /// function, block, and method scopes that are currently active.
282 /// This array is never empty. Clients should ignore the first
283 /// element, which is used to cache a single FunctionScopeInfo
284 /// that's used to parse every top-level function.
285 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
287 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
288 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
291 /// ExtVectorDecls - This is a list all the extended vector types. This allows
292 /// us to associate a raw vector type with one of the ext_vector type names.
293 /// This is only necessary for issuing pretty diagnostics.
294 ExtVectorDeclsType ExtVectorDecls;
296 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
297 OwningPtr<CXXFieldCollector> FieldCollector;
299 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
301 /// \brief Set containing all declared private fields that are not used.
302 NamedDeclSetType UnusedPrivateFields;
304 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
306 /// PureVirtualClassDiagSet - a set of class declarations which we have
307 /// emitted a list of pure virtual functions. Used to prevent emitting the
308 /// same list more than once.
309 OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
311 /// ParsingInitForAutoVars - a set of declarations with auto types for which
312 /// we are currently parsing the initializer.
313 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
315 /// \brief A mapping from external names to the most recent
316 /// locally-scoped extern "C" declaration with that name.
318 /// This map contains external declarations introduced in local
322 /// extern "C" void f() {
323 /// void foo(int, int);
327 /// Here, the name "foo" will be associated with the declaration of
328 /// "foo" within f. This name is not visible outside of
329 /// "f". However, we still find it in two cases:
331 /// - If we are declaring another global or extern "C" entity with
332 /// the name "foo", we can find "foo" as a previous declaration,
333 /// so that the types of this external declaration can be checked
334 /// for compatibility.
336 /// - If we would implicitly declare "foo" (e.g., due to a call to
337 /// "foo" in C when no prototype or definition is visible), then
338 /// we find this declaration of "foo" and complain that it is
340 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls;
342 /// \brief Look for a locally scoped extern "C" declaration by the given name.
343 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
344 findLocallyScopedExternCDecl(DeclarationName Name);
346 typedef LazyVector<VarDecl *, ExternalSemaSource,
347 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
348 TentativeDefinitionsType;
350 /// \brief All the tentative definitions encountered in the TU.
351 TentativeDefinitionsType TentativeDefinitions;
353 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
354 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
355 UnusedFileScopedDeclsType;
357 /// \brief The set of file scoped decls seen so far that have not been used
358 /// and must warn if not used. Only contains the first declaration.
359 UnusedFileScopedDeclsType UnusedFileScopedDecls;
361 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
362 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
363 DelegatingCtorDeclsType;
365 /// \brief All the delegating constructors seen so far in the file, used for
366 /// cycle detection at the end of the TU.
367 DelegatingCtorDeclsType DelegatingCtorDecls;
369 /// \brief All the destructors seen during a class definition that had their
370 /// exception spec computation delayed because it depended on an unparsed
372 SmallVector<CXXDestructorDecl*, 2> DelayedDestructorExceptionSpecs;
374 /// \brief All the overriding destructors seen during a class definition
375 /// (there could be multiple due to nested classes) that had their exception
376 /// spec checks delayed, plus the overridden destructor.
377 SmallVector<std::pair<const CXXDestructorDecl*,
378 const CXXDestructorDecl*>, 2>
379 DelayedDestructorExceptionSpecChecks;
381 /// \brief All the members seen during a class definition which were both
382 /// explicitly defaulted and had explicitly-specified exception
383 /// specifications, along with the function type containing their
384 /// user-specified exception specification. Those exception specifications
385 /// were overridden with the default specifications, but we still need to
386 /// check whether they are compatible with the default specification, and
387 /// we can't do that until the nesting set of class definitions is complete.
388 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
389 DelayedDefaultedMemberExceptionSpecs;
391 /// \brief Callback to the parser to parse templated functions when needed.
392 typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD);
393 LateTemplateParserCB *LateTemplateParser;
396 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
397 LateTemplateParser = LTP;
401 class DelayedDiagnostics;
403 class DelayedDiagnosticsState {
404 sema::DelayedDiagnosticPool *SavedPool;
405 friend class Sema::DelayedDiagnostics;
407 typedef DelayedDiagnosticsState ParsingDeclState;
408 typedef DelayedDiagnosticsState ProcessingContextState;
410 /// A class which encapsulates the logic for delaying diagnostics
411 /// during parsing and other processing.
412 class DelayedDiagnostics {
413 /// \brief The current pool of diagnostics into which delayed
414 /// diagnostics should go.
415 sema::DelayedDiagnosticPool *CurPool;
418 DelayedDiagnostics() : CurPool(0) {}
420 /// Adds a delayed diagnostic.
421 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
423 /// Determines whether diagnostics should be delayed.
424 bool shouldDelayDiagnostics() { return CurPool != 0; }
426 /// Returns the current delayed-diagnostics pool.
427 sema::DelayedDiagnosticPool *getCurrentPool() const {
431 /// Enter a new scope. Access and deprecation diagnostics will be
432 /// collected in this pool.
433 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
434 DelayedDiagnosticsState state;
435 state.SavedPool = CurPool;
440 /// Leave a delayed-diagnostic state that was previously pushed.
441 /// Do not emit any of the diagnostics. This is performed as part
442 /// of the bookkeeping of popping a pool "properly".
443 void popWithoutEmitting(DelayedDiagnosticsState state) {
444 CurPool = state.SavedPool;
447 /// Enter a new scope where access and deprecation diagnostics are
449 DelayedDiagnosticsState pushUndelayed() {
450 DelayedDiagnosticsState state;
451 state.SavedPool = CurPool;
456 /// Undo a previous pushUndelayed().
457 void popUndelayed(DelayedDiagnosticsState state) {
458 assert(CurPool == NULL);
459 CurPool = state.SavedPool;
461 } DelayedDiagnostics;
463 /// A RAII object to temporarily push a declaration context.
467 DeclContext *SavedContext;
468 ProcessingContextState SavedContextState;
469 QualType SavedCXXThisTypeOverride;
472 ContextRAII(Sema &S, DeclContext *ContextToPush)
473 : S(S), SavedContext(S.CurContext),
474 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
475 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
477 assert(ContextToPush && "pushing null context");
478 S.CurContext = ContextToPush;
482 if (!SavedContext) return;
483 S.CurContext = SavedContext;
484 S.DelayedDiagnostics.popUndelayed(SavedContextState);
485 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
494 /// \brief RAII object to handle the state changes required to synthesize
496 class SynthesizedFunctionScope {
498 Sema::ContextRAII SavedContext;
501 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
502 : S(S), SavedContext(S, DC)
504 S.PushFunctionScope();
505 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
508 ~SynthesizedFunctionScope() {
509 S.PopExpressionEvaluationContext();
510 S.PopFunctionScopeInfo();
514 /// WeakUndeclaredIdentifiers - Identifiers contained in
515 /// \#pragma weak before declared. rare. may alias another
516 /// identifier, declared or undeclared
517 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
519 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
520 /// \#pragma redefine_extname before declared. Used in Solaris system headers
521 /// to define functions that occur in multiple standards to call the version
522 /// in the currently selected standard.
523 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
526 /// \brief Load weak undeclared identifiers from the external source.
527 void LoadExternalWeakUndeclaredIdentifiers();
529 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
530 /// \#pragma weak during processing of other Decls.
531 /// I couldn't figure out a clean way to generate these in-line, so
532 /// we store them here and handle separately -- which is a hack.
533 /// It would be best to refactor this.
534 SmallVector<Decl*,2> WeakTopLevelDecl;
536 IdentifierResolver IdResolver;
538 /// Translation Unit Scope - useful to Objective-C actions that need
539 /// to lookup file scope declarations in the "ordinary" C decl namespace.
540 /// For example, user-defined classes, built-in "id" type, etc.
543 /// \brief The C++ "std" namespace, where the standard library resides.
544 LazyDeclPtr StdNamespace;
546 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
547 /// standard library.
548 LazyDeclPtr StdBadAlloc;
550 /// \brief The C++ "std::initializer_list" template, which is defined in
551 /// \<initializer_list>.
552 ClassTemplateDecl *StdInitializerList;
554 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
555 RecordDecl *CXXTypeInfoDecl;
557 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
558 RecordDecl *MSVCGuidDecl;
560 /// \brief Caches identifiers/selectors for NSFoundation APIs.
561 OwningPtr<NSAPI> NSAPIObj;
563 /// \brief The declaration of the Objective-C NSNumber class.
564 ObjCInterfaceDecl *NSNumberDecl;
566 /// \brief Pointer to NSNumber type (NSNumber *).
567 QualType NSNumberPointer;
569 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
570 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
572 /// \brief The declaration of the Objective-C NSString class.
573 ObjCInterfaceDecl *NSStringDecl;
575 /// \brief Pointer to NSString type (NSString *).
576 QualType NSStringPointer;
578 /// \brief The declaration of the stringWithUTF8String: method.
579 ObjCMethodDecl *StringWithUTF8StringMethod;
581 /// \brief The declaration of the Objective-C NSArray class.
582 ObjCInterfaceDecl *NSArrayDecl;
584 /// \brief The declaration of the arrayWithObjects:count: method.
585 ObjCMethodDecl *ArrayWithObjectsMethod;
587 /// \brief The declaration of the Objective-C NSDictionary class.
588 ObjCInterfaceDecl *NSDictionaryDecl;
590 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
591 ObjCMethodDecl *DictionaryWithObjectsMethod;
593 /// \brief id<NSCopying> type.
594 QualType QIDNSCopying;
596 /// \brief will hold 'respondsToSelector:'
597 Selector RespondsToSelectorSel;
599 /// A flag to remember whether the implicit forms of operator new and delete
600 /// have been declared.
601 bool GlobalNewDeleteDeclared;
603 /// A flag to indicate that we're in a context that permits abstract
604 /// references to fields. This is really a
605 bool AllowAbstractFieldReference;
607 /// \brief Describes how the expressions currently being parsed are
608 /// evaluated at run-time, if at all.
609 enum ExpressionEvaluationContext {
610 /// \brief The current expression and its subexpressions occur within an
611 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
612 /// \c sizeof, where the type of the expression may be significant but
613 /// no code will be generated to evaluate the value of the expression at
617 /// \brief The current expression occurs within an unevaluated
618 /// operand that unconditionally permits abstract references to
619 /// fields, such as a SIZE operator in MS-style inline assembly.
622 /// \brief The current context is "potentially evaluated" in C++11 terms,
623 /// but the expression is evaluated at compile-time (like the values of
624 /// cases in a switch statment).
627 /// \brief The current expression is potentially evaluated at run time,
628 /// which means that code may be generated to evaluate the value of the
629 /// expression at run time.
630 PotentiallyEvaluated,
632 /// \brief The current expression is potentially evaluated, but any
633 /// declarations referenced inside that expression are only used if
634 /// in fact the current expression is used.
636 /// This value is used when parsing default function arguments, for which
637 /// we would like to provide diagnostics (e.g., passing non-POD arguments
638 /// through varargs) but do not want to mark declarations as "referenced"
639 /// until the default argument is used.
640 PotentiallyEvaluatedIfUsed
643 /// \brief Data structure used to record current or nested
644 /// expression evaluation contexts.
645 struct ExpressionEvaluationContextRecord {
646 /// \brief The expression evaluation context.
647 ExpressionEvaluationContext Context;
649 /// \brief Whether the enclosing context needed a cleanup.
650 bool ParentNeedsCleanups;
652 /// \brief Whether we are in a decltype expression.
655 /// \brief The number of active cleanup objects when we entered
656 /// this expression evaluation context.
657 unsigned NumCleanupObjects;
659 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
661 /// \brief The lambdas that are present within this context, if it
662 /// is indeed an unevaluated context.
663 SmallVector<LambdaExpr *, 2> Lambdas;
665 /// \brief The declaration that provides context for the lambda expression
666 /// if the normal declaration context does not suffice, e.g., in a
667 /// default function argument.
668 Decl *LambdaContextDecl;
670 /// \brief The context information used to mangle lambda expressions
671 /// within this context.
673 /// This mangling information is allocated lazily, since most contexts
674 /// do not have lambda expressions.
675 IntrusiveRefCntPtr<LambdaMangleContext> LambdaMangle;
677 /// \brief If we are processing a decltype type, a set of call expressions
678 /// for which we have deferred checking the completeness of the return type.
679 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
681 /// \brief If we are processing a decltype type, a set of temporary binding
682 /// expressions for which we have deferred checking the destructor.
683 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
685 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
686 unsigned NumCleanupObjects,
687 bool ParentNeedsCleanups,
688 Decl *LambdaContextDecl,
690 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
691 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
692 LambdaContextDecl(LambdaContextDecl), LambdaMangle() { }
694 /// \brief Retrieve the mangling context for lambdas.
695 LambdaMangleContext &getLambdaMangleContext() {
696 assert(LambdaContextDecl && "Need to have a lambda context declaration");
698 LambdaMangle = new LambdaMangleContext;
699 return *LambdaMangle;
702 bool isUnevaluated() const {
703 return Context == Unevaluated || Context == UnevaluatedAbstract;
707 /// A stack of expression evaluation contexts.
708 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
710 /// SpecialMemberOverloadResult - The overloading result for a special member
713 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
714 /// integer are used to determine whether overload resolution succeeded.
715 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
724 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
727 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
728 : FastFoldingSetNode(ID)
731 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
732 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
734 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
735 void setKind(Kind K) { Pair.setInt(K); }
738 /// \brief A cache of special member function overload resolution results
740 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
742 /// \brief The kind of translation unit we are processing.
744 /// When we're processing a complete translation unit, Sema will perform
745 /// end-of-translation-unit semantic tasks (such as creating
746 /// initializers for tentative definitions in C) once parsing has
747 /// completed. Modules and precompiled headers perform different kinds of
749 TranslationUnitKind TUKind;
751 llvm::BumpPtrAllocator BumpAlloc;
753 /// \brief The number of SFINAE diagnostics that have been trapped.
754 unsigned NumSFINAEErrors;
756 typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> >
757 UnparsedDefaultArgInstantiationsMap;
759 /// \brief A mapping from parameters with unparsed default arguments to the
760 /// set of instantiations of each parameter.
762 /// This mapping is a temporary data structure used when parsing
763 /// nested class templates or nested classes of class templates,
764 /// where we might end up instantiating an inner class before the
765 /// default arguments of its methods have been parsed.
766 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
768 // Contains the locations of the beginning of unparsed default
769 // argument locations.
770 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
772 /// UndefinedInternals - all the used, undefined objects which require a
773 /// definition in this translation unit.
774 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
776 /// Obtain a sorted list of functions that are undefined but ODR-used.
777 void getUndefinedButUsed(
778 llvm::SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
780 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
781 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
783 /// Method Pool - allows efficient lookup when typechecking messages to "id".
784 /// We need to maintain a list, since selectors can have differing signatures
785 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
786 /// of selectors are "overloaded").
787 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
788 /// methods inside categories with a particular selector.
789 GlobalMethodPool MethodPool;
791 /// Method selectors used in a \@selector expression. Used for implementation
793 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
795 /// Kinds of C++ special members.
796 enum CXXSpecialMember {
797 CXXDefaultConstructor,
806 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
808 /// The C++ special members which we are currently in the process of
809 /// declaring. If this process recursively triggers the declaration of the
810 /// same special member, we should act as if it is not yet declared.
811 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
813 void ReadMethodPool(Selector Sel);
815 /// Private Helper predicate to check for 'self'.
816 bool isSelfExpr(Expr *RExpr);
818 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
819 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
820 /// should not be used elsewhere.
821 void EmitCurrentDiagnostic(unsigned DiagID);
823 /// Records and restores the FP_CONTRACT state on entry/exit of compound
825 class FPContractStateRAII {
827 FPContractStateRAII(Sema& S)
828 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
829 ~FPContractStateRAII() {
830 S.FPFeatures.fp_contract = OldFPContractState;
834 bool OldFPContractState : 1;
837 typedef llvm::MCAsmParserSemaCallback::InlineAsmIdentifierInfo
838 InlineAsmIdentifierInfo;
841 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
842 TranslationUnitKind TUKind = TU_Complete,
843 CodeCompleteConsumer *CompletionConsumer = 0);
846 /// \brief Perform initialization that occurs after the parser has been
847 /// initialized but before it parses anything.
850 const LangOptions &getLangOpts() const { return LangOpts; }
851 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
852 FPOptions &getFPOptions() { return FPFeatures; }
854 DiagnosticsEngine &getDiagnostics() const { return Diags; }
855 SourceManager &getSourceManager() const { return SourceMgr; }
856 const TargetAttributesSema &getTargetAttributesSema() const;
857 Preprocessor &getPreprocessor() const { return PP; }
858 ASTContext &getASTContext() const { return Context; }
859 ASTConsumer &getASTConsumer() const { return Consumer; }
860 ASTMutationListener *getASTMutationListener() const;
861 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
863 ///\brief Registers an external source. If an external source already exists,
864 /// creates a multiplex external source and appends to it.
866 ///\param[in] E - A non-null external sema source.
868 void addExternalSource(ExternalSemaSource *E);
870 void PrintStats() const;
872 /// \brief Helper class that creates diagnostics with optional
873 /// template instantiation stacks.
875 /// This class provides a wrapper around the basic DiagnosticBuilder
876 /// class that emits diagnostics. SemaDiagnosticBuilder is
877 /// responsible for emitting the diagnostic (as DiagnosticBuilder
878 /// does) and, if the diagnostic comes from inside a template
879 /// instantiation, printing the template instantiation stack as
881 class SemaDiagnosticBuilder : public DiagnosticBuilder {
886 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
887 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
889 ~SemaDiagnosticBuilder() {
890 // If we aren't active, there is nothing to do.
891 if (!isActive()) return;
893 // Otherwise, we need to emit the diagnostic. First flush the underlying
894 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
895 // won't emit the diagnostic in its own destructor.
897 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
898 // do its own needless checks to see if the diagnostic needs to be
899 // emitted. However, because we take care to ensure that the builder
900 // objects never escape, a sufficiently smart compiler will be able to
901 // eliminate that code.
905 // Dispatch to Sema to emit the diagnostic.
906 SemaRef.EmitCurrentDiagnostic(DiagID);
910 /// \brief Emit a diagnostic.
911 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
912 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
913 return SemaDiagnosticBuilder(DB, *this, DiagID);
916 /// \brief Emit a partial diagnostic.
917 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
919 /// \brief Build a partial diagnostic.
920 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
922 bool findMacroSpelling(SourceLocation &loc, StringRef name);
924 /// \brief Get a string to suggest for zero-initialization of a type.
925 std::string getFixItZeroInitializerForType(QualType T) const;
926 std::string getFixItZeroLiteralForType(QualType T) const;
928 ExprResult Owned(Expr* E) { return E; }
929 ExprResult Owned(ExprResult R) { return R; }
930 StmtResult Owned(Stmt* S) { return S; }
932 void ActOnEndOfTranslationUnit();
934 void CheckDelegatingCtorCycles();
936 Scope *getScopeForContext(DeclContext *Ctx);
938 void PushFunctionScope();
939 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
940 void PushLambdaScope(CXXRecordDecl *Lambda, CXXMethodDecl *CallOperator);
941 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
943 CapturedRegionKind K);
944 void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP =0,
945 const Decl *D = 0, const BlockExpr *blkExpr = 0);
947 sema::FunctionScopeInfo *getCurFunction() const {
948 return FunctionScopes.back();
951 void PushCompoundScope();
952 void PopCompoundScope();
954 sema::CompoundScopeInfo &getCurCompoundScope() const;
956 bool hasAnyUnrecoverableErrorsInThisFunction() const;
958 /// \brief Retrieve the current block, if any.
959 sema::BlockScopeInfo *getCurBlock();
961 /// \brief Retrieve the current lambda expression, if any.
962 sema::LambdaScopeInfo *getCurLambda();
964 /// \brief Retrieve the current captured region, if any.
965 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
967 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
968 SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
970 void ActOnComment(SourceRange Comment);
972 //===--------------------------------------------------------------------===//
973 // Type Analysis / Processing: SemaType.cpp.
976 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
977 const DeclSpec *DS = 0);
978 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
979 const DeclSpec *DS = 0);
980 QualType BuildPointerType(QualType T,
981 SourceLocation Loc, DeclarationName Entity);
982 QualType BuildReferenceType(QualType T, bool LValueRef,
983 SourceLocation Loc, DeclarationName Entity);
984 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
985 Expr *ArraySize, unsigned Quals,
986 SourceRange Brackets, DeclarationName Entity);
987 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
988 SourceLocation AttrLoc);
990 /// \brief Build a function type.
992 /// This routine checks the function type according to C++ rules and
993 /// under the assumption that the result type and parameter types have
994 /// just been instantiated from a template. It therefore duplicates
995 /// some of the behavior of GetTypeForDeclarator, but in a much
996 /// simpler form that is only suitable for this narrow use case.
998 /// \param T The return type of the function.
1000 /// \param ParamTypes The parameter types of the function. This array
1001 /// will be modified to account for adjustments to the types of the
1002 /// function parameters.
1004 /// \param Loc The location of the entity whose type involves this
1005 /// function type or, if there is no such entity, the location of the
1006 /// type that will have function type.
1008 /// \param Entity The name of the entity that involves the function
1011 /// \param EPI Extra information about the function type. Usually this will
1012 /// be taken from an existing function with the same prototype.
1014 /// \returns A suitable function type, if there are no errors. The
1015 /// unqualified type will always be a FunctionProtoType.
1016 /// Otherwise, returns a NULL type.
1017 QualType BuildFunctionType(QualType T,
1018 llvm::MutableArrayRef<QualType> ParamTypes,
1019 SourceLocation Loc, DeclarationName Entity,
1020 const FunctionProtoType::ExtProtoInfo &EPI);
1022 QualType BuildMemberPointerType(QualType T, QualType Class,
1024 DeclarationName Entity);
1025 QualType BuildBlockPointerType(QualType T,
1026 SourceLocation Loc, DeclarationName Entity);
1027 QualType BuildParenType(QualType T);
1028 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1030 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1031 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1032 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1033 TypeSourceInfo *ReturnTypeInfo);
1035 /// \brief Package the given type and TSI into a ParsedType.
1036 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1037 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1038 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1039 static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
1040 CanThrowResult canThrow(const Expr *E);
1041 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1042 const FunctionProtoType *FPT);
1043 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1044 bool CheckDistantExceptionSpec(QualType T);
1045 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1046 bool CheckEquivalentExceptionSpec(
1047 const FunctionProtoType *Old, SourceLocation OldLoc,
1048 const FunctionProtoType *New, SourceLocation NewLoc);
1049 bool CheckEquivalentExceptionSpec(
1050 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1051 const FunctionProtoType *Old, SourceLocation OldLoc,
1052 const FunctionProtoType *New, SourceLocation NewLoc,
1053 bool *MissingExceptionSpecification = 0,
1054 bool *MissingEmptyExceptionSpecification = 0,
1055 bool AllowNoexceptAllMatchWithNoSpec = false,
1056 bool IsOperatorNew = false);
1057 bool CheckExceptionSpecSubset(
1058 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1059 const FunctionProtoType *Superset, SourceLocation SuperLoc,
1060 const FunctionProtoType *Subset, SourceLocation SubLoc);
1061 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1062 const FunctionProtoType *Target, SourceLocation TargetLoc,
1063 const FunctionProtoType *Source, SourceLocation SourceLoc);
1065 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1067 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1068 /// in an Objective-C message declaration. Return the appropriate type.
1069 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1071 /// \brief Abstract class used to diagnose incomplete types.
1072 struct TypeDiagnoser {
1075 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1077 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1078 virtual ~TypeDiagnoser() {}
1081 static int getPrintable(int I) { return I; }
1082 static unsigned getPrintable(unsigned I) { return I; }
1083 static bool getPrintable(bool B) { return B; }
1084 static const char * getPrintable(const char *S) { return S; }
1085 static StringRef getPrintable(StringRef S) { return S; }
1086 static const std::string &getPrintable(const std::string &S) { return S; }
1087 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1090 static DeclarationName getPrintable(DeclarationName N) { return N; }
1091 static QualType getPrintable(QualType T) { return T; }
1092 static SourceRange getPrintable(SourceRange R) { return R; }
1093 static SourceRange getPrintable(SourceLocation L) { return L; }
1094 static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); }
1095 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1097 template<typename T1>
1098 class BoundTypeDiagnoser1 : public TypeDiagnoser {
1103 BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1)
1104 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { }
1105 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1106 if (Suppressed) return;
1107 S.Diag(Loc, DiagID) << getPrintable(Arg1) << T;
1110 virtual ~BoundTypeDiagnoser1() { }
1113 template<typename T1, typename T2>
1114 class BoundTypeDiagnoser2 : public TypeDiagnoser {
1120 BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1,
1122 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1125 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1126 if (Suppressed) return;
1127 S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T;
1130 virtual ~BoundTypeDiagnoser2() { }
1133 template<typename T1, typename T2, typename T3>
1134 class BoundTypeDiagnoser3 : public TypeDiagnoser {
1141 BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1,
1142 const T2 &Arg2, const T3 &Arg3)
1143 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1144 Arg2(Arg2), Arg3(Arg3) { }
1146 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1147 if (Suppressed) return;
1149 << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T;
1152 virtual ~BoundTypeDiagnoser3() { }
1155 bool RequireCompleteType(SourceLocation Loc, QualType T,
1156 TypeDiagnoser &Diagnoser);
1157 bool RequireCompleteType(SourceLocation Loc, QualType T,
1160 template<typename T1>
1161 bool RequireCompleteType(SourceLocation Loc, QualType T,
1162 unsigned DiagID, const T1 &Arg1) {
1163 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1164 return RequireCompleteType(Loc, T, Diagnoser);
1167 template<typename T1, typename T2>
1168 bool RequireCompleteType(SourceLocation Loc, QualType T,
1169 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1170 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1171 return RequireCompleteType(Loc, T, Diagnoser);
1174 template<typename T1, typename T2, typename T3>
1175 bool RequireCompleteType(SourceLocation Loc, QualType T,
1176 unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1178 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1180 return RequireCompleteType(Loc, T, Diagnoser);
1183 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1184 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1186 template<typename T1>
1187 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) {
1188 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1189 return RequireCompleteExprType(E, Diagnoser);
1192 template<typename T1, typename T2>
1193 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1195 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1196 return RequireCompleteExprType(E, Diagnoser);
1199 template<typename T1, typename T2, typename T3>
1200 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1201 const T2 &Arg2, const T3 &Arg3) {
1202 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1204 return RequireCompleteExprType(E, Diagnoser);
1207 bool RequireLiteralType(SourceLocation Loc, QualType T,
1208 TypeDiagnoser &Diagnoser);
1209 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1211 template<typename T1>
1212 bool RequireLiteralType(SourceLocation Loc, QualType T,
1213 unsigned DiagID, const T1 &Arg1) {
1214 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1215 return RequireLiteralType(Loc, T, Diagnoser);
1218 template<typename T1, typename T2>
1219 bool RequireLiteralType(SourceLocation Loc, QualType T,
1220 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1221 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1222 return RequireLiteralType(Loc, T, Diagnoser);
1225 template<typename T1, typename T2, typename T3>
1226 bool RequireLiteralType(SourceLocation Loc, QualType T,
1227 unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1229 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1231 return RequireLiteralType(Loc, T, Diagnoser);
1234 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1235 const CXXScopeSpec &SS, QualType T);
1237 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1238 QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
1239 QualType BuildUnaryTransformType(QualType BaseType,
1240 UnaryTransformType::UTTKind UKind,
1241 SourceLocation Loc);
1243 //===--------------------------------------------------------------------===//
1244 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1247 /// List of decls defined in a function prototype. This contains EnumConstants
1248 /// that incorrectly end up in translation unit scope because there is no
1249 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1250 /// them into the FunctionDecl.
1251 std::vector<NamedDecl*> DeclsInPrototypeScope;
1252 /// Nonzero if we are currently parsing a function declarator. This is a counter
1253 /// as opposed to a boolean so we can deal with nested function declarators
1255 /// void f(void (*g)(), ...)
1256 unsigned InFunctionDeclarator;
1258 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0);
1260 void DiagnoseUseOfUnimplementedSelectors();
1262 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1264 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1265 Scope *S, CXXScopeSpec *SS = 0,
1266 bool isClassName = false,
1267 bool HasTrailingDot = false,
1268 ParsedType ObjectType = ParsedType(),
1269 bool IsCtorOrDtorName = false,
1270 bool WantNontrivialTypeSourceInfo = false,
1271 IdentifierInfo **CorrectedII = 0);
1272 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1273 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1274 bool DiagnoseUnknownTypeName(IdentifierInfo *&II,
1275 SourceLocation IILoc,
1278 ParsedType &SuggestedType);
1280 /// \brief Describes the result of the name lookup and resolution performed
1281 /// by \c ClassifyName().
1282 enum NameClassificationKind {
1288 NC_NestedNameSpecifier,
1293 class NameClassification {
1294 NameClassificationKind Kind;
1296 TemplateName Template;
1298 const IdentifierInfo *Keyword;
1300 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1303 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1305 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1307 NameClassification(const IdentifierInfo *Keyword)
1308 : Kind(NC_Keyword), Keyword(Keyword) { }
1310 static NameClassification Error() {
1311 return NameClassification(NC_Error);
1314 static NameClassification Unknown() {
1315 return NameClassification(NC_Unknown);
1318 static NameClassification NestedNameSpecifier() {
1319 return NameClassification(NC_NestedNameSpecifier);
1322 static NameClassification TypeTemplate(TemplateName Name) {
1323 NameClassification Result(NC_TypeTemplate);
1324 Result.Template = Name;
1328 static NameClassification FunctionTemplate(TemplateName Name) {
1329 NameClassification Result(NC_FunctionTemplate);
1330 Result.Template = Name;
1334 NameClassificationKind getKind() const { return Kind; }
1336 ParsedType getType() const {
1337 assert(Kind == NC_Type);
1341 ExprResult getExpression() const {
1342 assert(Kind == NC_Expression);
1346 TemplateName getTemplateName() const {
1347 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
1351 TemplateNameKind getTemplateNameKind() const {
1352 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
1353 return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template;
1357 /// \brief Perform name lookup on the given name, classifying it based on
1358 /// the results of name lookup and the following token.
1360 /// This routine is used by the parser to resolve identifiers and help direct
1361 /// parsing. When the identifier cannot be found, this routine will attempt
1362 /// to correct the typo and classify based on the resulting name.
1364 /// \param S The scope in which we're performing name lookup.
1366 /// \param SS The nested-name-specifier that precedes the name.
1368 /// \param Name The identifier. If typo correction finds an alternative name,
1369 /// this pointer parameter will be updated accordingly.
1371 /// \param NameLoc The location of the identifier.
1373 /// \param NextToken The token following the identifier. Used to help
1374 /// disambiguate the name.
1376 /// \param IsAddressOfOperand True if this name is the operand of a unary
1377 /// address of ('&') expression, assuming it is classified as an
1380 /// \param CCC The correction callback, if typo correction is desired.
1381 NameClassification ClassifyName(Scope *S,
1383 IdentifierInfo *&Name,
1384 SourceLocation NameLoc,
1385 const Token &NextToken,
1386 bool IsAddressOfOperand,
1387 CorrectionCandidateCallback *CCC = 0);
1389 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1391 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1392 MultiTemplateParamsArg TemplateParameterLists);
1393 void RegisterLocallyScopedExternCDecl(NamedDecl *ND,
1394 const LookupResult &Previous,
1396 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1397 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1398 DeclarationName Name,
1399 SourceLocation Loc);
1400 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1401 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1402 void CheckShadow(Scope *S, VarDecl *D);
1403 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1404 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1405 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1406 TypeSourceInfo *TInfo,
1407 LookupResult &Previous);
1408 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1409 LookupResult &Previous, bool &Redeclaration);
1410 NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1411 TypeSourceInfo *TInfo,
1412 LookupResult &Previous,
1413 MultiTemplateParamsArg TemplateParamLists);
1414 // Returns true if the variable declaration is a redeclaration
1415 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1416 void CheckVariableDeclarationType(VarDecl *NewVD);
1417 void CheckCompleteVariableDeclaration(VarDecl *var);
1418 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1419 void ActOnStartFunctionDeclarator();
1420 void ActOnEndFunctionDeclarator();
1421 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1422 TypeSourceInfo *TInfo,
1423 LookupResult &Previous,
1424 MultiTemplateParamsArg TemplateParamLists,
1426 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1427 void checkVoidParamDecl(ParmVarDecl *Param);
1429 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1430 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1432 void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1433 // Returns true if the function declaration is a redeclaration
1434 bool CheckFunctionDeclaration(Scope *S,
1435 FunctionDecl *NewFD, LookupResult &Previous,
1436 bool IsExplicitSpecialization);
1437 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1438 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1439 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1442 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1443 SourceLocation NameLoc, IdentifierInfo *Name,
1444 QualType T, TypeSourceInfo *TSInfo,
1446 void ActOnParamDefaultArgument(Decl *param,
1447 SourceLocation EqualLoc,
1449 void ActOnParamUnparsedDefaultArgument(Decl *param,
1450 SourceLocation EqualLoc,
1451 SourceLocation ArgLoc);
1452 void ActOnParamDefaultArgumentError(Decl *param);
1453 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1454 SourceLocation EqualLoc);
1456 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1457 bool TypeMayContainAuto);
1458 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1459 void ActOnInitializerError(Decl *Dcl);
1460 void ActOnCXXForRangeDecl(Decl *D);
1461 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1462 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1463 void FinalizeDeclaration(Decl *D);
1464 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1467 DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
1468 bool TypeMayContainAuto = true);
1470 /// Should be called on all declarations that might have attached
1471 /// documentation comments.
1472 void ActOnDocumentableDecl(Decl *D);
1473 void ActOnDocumentableDecls(Decl **Group, unsigned NumDecls);
1475 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1476 SourceLocation LocAfterDecls);
1477 void CheckForFunctionRedefinition(FunctionDecl *FD);
1478 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1479 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1480 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1481 bool isObjCMethodDecl(Decl *D) {
1482 return D && isa<ObjCMethodDecl>(D);
1485 /// \brief Determine whether we can skip parsing the body of a function
1486 /// definition, assuming we don't care about analyzing its body or emitting
1487 /// code for that function.
1489 /// This will be \c false only if we may need the body of the function in
1490 /// order to parse the rest of the program (for instance, if it is
1491 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1492 bool canSkipFunctionBody(Decl *D);
1494 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1495 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1496 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1497 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1499 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1500 /// attribute for which parsing is delayed.
1501 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1503 /// \brief Diagnose any unused parameters in the given sequence of
1504 /// ParmVarDecl pointers.
1505 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1506 ParmVarDecl * const *End);
1508 /// \brief Diagnose whether the size of parameters or return value of a
1509 /// function or obj-c method definition is pass-by-value and larger than a
1510 /// specified threshold.
1511 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1512 ParmVarDecl * const *End,
1516 void DiagnoseInvalidJumps(Stmt *Body);
1517 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1518 SourceLocation AsmLoc,
1519 SourceLocation RParenLoc);
1521 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1522 Decl *ActOnEmptyDeclaration(Scope *S,
1523 AttributeList *AttrList,
1524 SourceLocation SemiLoc);
1526 /// \brief The parser has processed a module import declaration.
1528 /// \param AtLoc The location of the '@' symbol, if any.
1530 /// \param ImportLoc The location of the 'import' keyword.
1532 /// \param Path The module access path.
1533 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1536 /// \brief Create an implicit import of the given module at the given
1537 /// source location.
1539 /// This routine is typically used for error recovery, when the entity found
1540 /// by name lookup is actually hidden within a module that we know about but
1541 /// the user has forgotten to import.
1542 void createImplicitModuleImport(SourceLocation Loc, Module *Mod);
1544 /// \brief Retrieve a suitable printing policy.
1545 PrintingPolicy getPrintingPolicy() const {
1546 return getPrintingPolicy(Context, PP);
1549 /// \brief Retrieve a suitable printing policy.
1550 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1551 const Preprocessor &PP);
1554 void ActOnPopScope(SourceLocation Loc, Scope *S);
1555 void ActOnTranslationUnitScope(Scope *S);
1557 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1559 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1561 MultiTemplateParamsArg TemplateParams,
1562 bool IsExplicitInstantiation = false);
1564 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1566 RecordDecl *Record);
1568 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1569 RecordDecl *Record);
1571 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1572 TagTypeKind NewTag, bool isDefinition,
1573 SourceLocation NewTagLoc,
1574 const IdentifierInfo &Name);
1577 TUK_Reference, // Reference to a tag: 'struct foo *X;'
1578 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
1579 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
1580 TUK_Friend // Friend declaration: 'friend struct foo;'
1583 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1584 SourceLocation KWLoc, CXXScopeSpec &SS,
1585 IdentifierInfo *Name, SourceLocation NameLoc,
1586 AttributeList *Attr, AccessSpecifier AS,
1587 SourceLocation ModulePrivateLoc,
1588 MultiTemplateParamsArg TemplateParameterLists,
1589 bool &OwnedDecl, bool &IsDependent,
1590 SourceLocation ScopedEnumKWLoc,
1591 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
1593 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1594 unsigned TagSpec, SourceLocation TagLoc,
1596 IdentifierInfo *Name, SourceLocation NameLoc,
1597 AttributeList *Attr,
1598 MultiTemplateParamsArg TempParamLists);
1600 TypeResult ActOnDependentTag(Scope *S,
1603 const CXXScopeSpec &SS,
1604 IdentifierInfo *Name,
1605 SourceLocation TagLoc,
1606 SourceLocation NameLoc);
1608 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1609 IdentifierInfo *ClassName,
1610 SmallVectorImpl<Decl *> &Decls);
1611 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1612 Declarator &D, Expr *BitfieldWidth);
1614 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1615 Declarator &D, Expr *BitfieldWidth,
1616 InClassInitStyle InitStyle,
1617 AccessSpecifier AS);
1618 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1619 SourceLocation DeclStart,
1620 Declarator &D, Expr *BitfieldWidth,
1621 InClassInitStyle InitStyle,
1623 AttributeList *MSPropertyAttr);
1625 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1626 TypeSourceInfo *TInfo,
1627 RecordDecl *Record, SourceLocation Loc,
1628 bool Mutable, Expr *BitfieldWidth,
1629 InClassInitStyle InitStyle,
1630 SourceLocation TSSL,
1631 AccessSpecifier AS, NamedDecl *PrevDecl,
1634 bool CheckNontrivialField(FieldDecl *FD);
1635 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1636 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1637 bool Diagnose = false);
1638 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1639 void ActOnLastBitfield(SourceLocation DeclStart,
1640 SmallVectorImpl<Decl *> &AllIvarDecls);
1641 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1642 Declarator &D, Expr *BitfieldWidth,
1643 tok::ObjCKeywordKind visibility);
1645 // This is used for both record definitions and ObjC interface declarations.
1646 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1647 ArrayRef<Decl *> Fields,
1648 SourceLocation LBrac, SourceLocation RBrac,
1649 AttributeList *AttrList);
1651 /// ActOnTagStartDefinition - Invoked when we have entered the
1652 /// scope of a tag's definition (e.g., for an enumeration, class,
1653 /// struct, or union).
1654 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1656 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1658 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1659 /// C++ record definition's base-specifiers clause and are starting its
1660 /// member declarations.
1661 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1662 SourceLocation FinalLoc,
1663 SourceLocation LBraceLoc);
1665 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1666 /// the definition of a tag (enumeration, class, struct, or union).
1667 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1668 SourceLocation RBraceLoc);
1670 void ActOnObjCContainerFinishDefinition();
1672 /// \brief Invoked when we must temporarily exit the objective-c container
1673 /// scope for parsing/looking-up C constructs.
1675 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1676 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1677 void ActOnObjCReenterContainerContext(DeclContext *DC);
1679 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1680 /// error parsing the definition of a tag.
1681 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1683 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1684 EnumConstantDecl *LastEnumConst,
1685 SourceLocation IdLoc,
1688 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1689 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1690 QualType EnumUnderlyingTy, const EnumDecl *Prev);
1692 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1693 SourceLocation IdLoc, IdentifierInfo *Id,
1694 AttributeList *Attrs,
1695 SourceLocation EqualLoc, Expr *Val);
1696 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1697 SourceLocation RBraceLoc, Decl *EnumDecl,
1698 ArrayRef<Decl *> Elements,
1699 Scope *S, AttributeList *Attr);
1701 DeclContext *getContainingDC(DeclContext *DC);
1703 /// Set the current declaration context until it gets popped.
1704 void PushDeclContext(Scope *S, DeclContext *DC);
1705 void PopDeclContext();
1707 /// EnterDeclaratorContext - Used when we must lookup names in the context
1708 /// of a declarator's nested name specifier.
1709 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1710 void ExitDeclaratorContext(Scope *S);
1712 /// Push the parameters of D, which must be a function, into scope.
1713 void ActOnReenterFunctionContext(Scope* S, Decl* D);
1714 void ActOnExitFunctionContext();
1716 DeclContext *getFunctionLevelDeclContext();
1718 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1719 /// to the function decl for the function being parsed. If we're currently
1720 /// in a 'block', this returns the containing context.
1721 FunctionDecl *getCurFunctionDecl();
1723 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1724 /// the method decl for the method being parsed. If we're currently
1725 /// in a 'block', this returns the containing context.
1726 ObjCMethodDecl *getCurMethodDecl();
1728 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1729 /// or C function we're in, otherwise return null. If we're currently
1730 /// in a 'block', this returns the containing context.
1731 NamedDecl *getCurFunctionOrMethodDecl();
1733 /// Add this decl to the scope shadowed decl chains.
1734 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1736 /// \brief Make the given externally-produced declaration visible at the
1737 /// top level scope.
1739 /// \param D The externally-produced declaration to push.
1741 /// \param Name The name of the externally-produced declaration.
1742 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1744 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1745 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1746 /// true if 'D' belongs to the given declaration context.
1748 /// \param ExplicitInstantiationOrSpecialization When true, we are checking
1749 /// whether the declaration is in scope for the purposes of explicit template
1750 /// instantiation or specialization. The default is false.
1751 bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0,
1752 bool ExplicitInstantiationOrSpecialization = false);
1754 /// Finds the scope corresponding to the given decl context, if it
1755 /// happens to be an enclosing scope. Otherwise return NULL.
1756 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1758 /// Subroutines of ActOnDeclarator().
1759 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1760 TypeSourceInfo *TInfo);
1761 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
1763 /// Attribute merging methods. Return true if a new attribute was added.
1764 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1765 IdentifierInfo *Platform,
1766 VersionTuple Introduced,
1767 VersionTuple Deprecated,
1768 VersionTuple Obsoleted,
1772 unsigned AttrSpellingListIndex);
1773 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1774 TypeVisibilityAttr::VisibilityType Vis,
1775 unsigned AttrSpellingListIndex);
1776 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
1777 VisibilityAttr::VisibilityType Vis,
1778 unsigned AttrSpellingListIndex);
1779 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
1780 unsigned AttrSpellingListIndex);
1781 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
1782 unsigned AttrSpellingListIndex);
1783 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, StringRef Format,
1784 int FormatIdx, int FirstArg,
1785 unsigned AttrSpellingListIndex);
1786 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
1787 unsigned AttrSpellingListIndex);
1789 /// \brief Describes the kind of merge to perform for availability
1790 /// attributes (including "deprecated", "unavailable", and "availability").
1791 enum AvailabilityMergeKind {
1792 /// \brief Don't merge availability attributes at all.
1794 /// \brief Merge availability attributes for a redeclaration, which requires
1797 /// \brief Merge availability attributes for an override, which requires
1798 /// an exact match or a weakening of constraints.
1802 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
1803 AvailabilityMergeKind AMK = AMK_Redeclaration);
1804 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
1805 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S);
1806 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
1808 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
1809 void MergeVarDecl(VarDecl *New, LookupResult &OldDecls,
1810 bool OldDeclsWereHidden);
1811 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool OldIsHidden);
1812 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
1813 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
1815 // AssignmentAction - This is used by all the assignment diagnostic functions
1816 // to represent what is actually causing the operation
1817 enum AssignmentAction {
1827 /// C++ Overloading.
1829 /// This is a legitimate overload: the existing declarations are
1830 /// functions or function templates with different signatures.
1833 /// This is not an overload because the signature exactly matches
1834 /// an existing declaration.
1837 /// This is not an overload because the lookup results contain a
1841 OverloadKind CheckOverload(Scope *S,
1843 const LookupResult &OldDecls,
1844 NamedDecl *&OldDecl,
1845 bool IsForUsingDecl);
1846 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
1848 /// \brief Checks availability of the function depending on the current
1849 /// function context.Inside an unavailable function,unavailability is ignored.
1851 /// \returns true if \p FD is unavailable and current context is inside
1852 /// an available function, false otherwise.
1853 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
1855 ImplicitConversionSequence
1856 TryImplicitConversion(Expr *From, QualType ToType,
1857 bool SuppressUserConversions,
1859 bool InOverloadResolution,
1861 bool AllowObjCWritebackConversion);
1863 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
1864 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
1865 bool IsComplexPromotion(QualType FromType, QualType ToType);
1866 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1867 bool InOverloadResolution,
1868 QualType& ConvertedType, bool &IncompatibleObjC);
1869 bool isObjCPointerConversion(QualType FromType, QualType ToType,
1870 QualType& ConvertedType, bool &IncompatibleObjC);
1871 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
1872 QualType &ConvertedType);
1873 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
1874 QualType& ConvertedType);
1875 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1876 const FunctionProtoType *NewType,
1877 unsigned *ArgPos = 0);
1878 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
1879 QualType FromType, QualType ToType);
1881 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
1882 bool CheckPointerConversion(Expr *From, QualType ToType,
1884 CXXCastPath& BasePath,
1885 bool IgnoreBaseAccess);
1886 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
1887 bool InOverloadResolution,
1888 QualType &ConvertedType);
1889 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
1891 CXXCastPath &BasePath,
1892 bool IgnoreBaseAccess);
1893 bool IsQualificationConversion(QualType FromType, QualType ToType,
1894 bool CStyle, bool &ObjCLifetimeConversion);
1895 bool IsNoReturnConversion(QualType FromType, QualType ToType,
1896 QualType &ResultTy);
1897 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
1898 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
1900 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1901 const VarDecl *NRVOCandidate,
1902 QualType ResultType,
1904 bool AllowNRVO = true);
1906 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
1908 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
1909 SourceLocation EqualLoc,
1911 bool TopLevelOfInitList = false,
1912 bool AllowExplicit = false);
1913 ExprResult PerformObjectArgumentInitialization(Expr *From,
1914 NestedNameSpecifier *Qualifier,
1915 NamedDecl *FoundDecl,
1916 CXXMethodDecl *Method);
1918 ExprResult PerformContextuallyConvertToBool(Expr *From);
1919 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
1921 /// Contexts in which a converted constant expression is required.
1923 CCEK_CaseValue, ///< Expression in a case label.
1924 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
1925 CCEK_TemplateArg ///< Value of a non-type template parameter.
1927 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
1928 llvm::APSInt &Value, CCEKind CCE);
1930 /// \brief Abstract base class used to diagnose problems that occur while
1931 /// trying to convert an expression to integral or enumeration type.
1932 class ICEConvertDiagnoser {
1935 bool SuppressConversion;
1937 ICEConvertDiagnoser(bool Suppress = false,
1938 bool SuppressConversion = false)
1939 : Suppress(Suppress), SuppressConversion(SuppressConversion) { }
1941 /// \brief Emits a diagnostic complaining that the expression does not have
1942 /// integral or enumeration type.
1943 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1946 /// \brief Emits a diagnostic when the expression has incomplete class type.
1947 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
1950 /// \brief Emits a diagnostic when the only matching conversion function
1952 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
1954 QualType ConvTy) = 0;
1956 /// \brief Emits a note for the explicit conversion function.
1957 virtual DiagnosticBuilder
1958 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
1960 /// \brief Emits a diagnostic when there are multiple possible conversion
1962 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1965 /// \brief Emits a note for one of the candidate conversions.
1966 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
1967 QualType ConvTy) = 0;
1969 /// \brief Emits a diagnostic when we picked a conversion function
1970 /// (for cases when we are not allowed to pick a conversion function).
1971 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1973 QualType ConvTy) = 0;
1975 virtual ~ICEConvertDiagnoser() {}
1979 ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE,
1980 ICEConvertDiagnoser &Diagnoser,
1981 bool AllowScopedEnumerations);
1983 enum ObjCSubscriptKind {
1988 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
1990 // Note that LK_String is intentionally after the other literals, as
1991 // this is used for diagnostics logic.
1992 enum ObjCLiteralKind {
2001 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2003 ExprResult PerformObjectMemberConversion(Expr *From,
2004 NestedNameSpecifier *Qualifier,
2005 NamedDecl *FoundDecl,
2008 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2009 // TODO: make this is a typesafe union.
2010 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
2011 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2013 void AddOverloadCandidate(FunctionDecl *Function,
2014 DeclAccessPair FoundDecl,
2015 ArrayRef<Expr *> Args,
2016 OverloadCandidateSet& CandidateSet,
2017 bool SuppressUserConversions = false,
2018 bool PartialOverloading = false,
2019 bool AllowExplicit = false);
2020 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2021 ArrayRef<Expr *> Args,
2022 OverloadCandidateSet& CandidateSet,
2023 bool SuppressUserConversions = false,
2024 TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
2025 void AddMethodCandidate(DeclAccessPair FoundDecl,
2026 QualType ObjectType,
2027 Expr::Classification ObjectClassification,
2028 ArrayRef<Expr *> Args,
2029 OverloadCandidateSet& CandidateSet,
2030 bool SuppressUserConversion = false);
2031 void AddMethodCandidate(CXXMethodDecl *Method,
2032 DeclAccessPair FoundDecl,
2033 CXXRecordDecl *ActingContext, QualType ObjectType,
2034 Expr::Classification ObjectClassification,
2035 ArrayRef<Expr *> Args,
2036 OverloadCandidateSet& CandidateSet,
2037 bool SuppressUserConversions = false);
2038 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2039 DeclAccessPair FoundDecl,
2040 CXXRecordDecl *ActingContext,
2041 TemplateArgumentListInfo *ExplicitTemplateArgs,
2042 QualType ObjectType,
2043 Expr::Classification ObjectClassification,
2044 ArrayRef<Expr *> Args,
2045 OverloadCandidateSet& CandidateSet,
2046 bool SuppressUserConversions = false);
2047 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2048 DeclAccessPair FoundDecl,
2049 TemplateArgumentListInfo *ExplicitTemplateArgs,
2050 ArrayRef<Expr *> Args,
2051 OverloadCandidateSet& CandidateSet,
2052 bool SuppressUserConversions = false);
2053 void AddConversionCandidate(CXXConversionDecl *Conversion,
2054 DeclAccessPair FoundDecl,
2055 CXXRecordDecl *ActingContext,
2056 Expr *From, QualType ToType,
2057 OverloadCandidateSet& CandidateSet);
2058 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2059 DeclAccessPair FoundDecl,
2060 CXXRecordDecl *ActingContext,
2061 Expr *From, QualType ToType,
2062 OverloadCandidateSet &CandidateSet);
2063 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2064 DeclAccessPair FoundDecl,
2065 CXXRecordDecl *ActingContext,
2066 const FunctionProtoType *Proto,
2067 Expr *Object, ArrayRef<Expr *> Args,
2068 OverloadCandidateSet& CandidateSet);
2069 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2070 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2071 OverloadCandidateSet& CandidateSet,
2072 SourceRange OpRange = SourceRange());
2073 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2074 ArrayRef<Expr *> Args,
2075 OverloadCandidateSet& CandidateSet,
2076 bool IsAssignmentOperator = false,
2077 unsigned NumContextualBoolArguments = 0);
2078 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2079 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2080 OverloadCandidateSet& CandidateSet);
2081 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2082 bool Operator, SourceLocation Loc,
2083 ArrayRef<Expr *> Args,
2084 TemplateArgumentListInfo *ExplicitTemplateArgs,
2085 OverloadCandidateSet& CandidateSet,
2086 bool PartialOverloading = false);
2088 // Emit as a 'note' the specific overload candidate
2089 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2091 // Emit as a series of 'note's all template and non-templates
2092 // identified by the expression Expr
2093 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2095 // [PossiblyAFunctionType] --> [Return]
2096 // NonFunctionType --> NonFunctionType
2098 // R (*)(A) --> R (A)
2099 // R (&)(A) --> R (A)
2100 // R (S::*)(A) --> R (A)
2101 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2104 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2105 QualType TargetType,
2107 DeclAccessPair &Found,
2108 bool *pHadMultipleCandidates = 0);
2110 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2111 bool Complain = false,
2112 DeclAccessPair* Found = 0);
2114 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2115 ExprResult &SrcExpr,
2116 bool DoFunctionPointerConverion = false,
2117 bool Complain = false,
2118 const SourceRange& OpRangeForComplaining = SourceRange(),
2119 QualType DestTypeForComplaining = QualType(),
2120 unsigned DiagIDForComplaining = 0);
2123 Expr *FixOverloadedFunctionReference(Expr *E,
2124 DeclAccessPair FoundDecl,
2126 ExprResult FixOverloadedFunctionReference(ExprResult,
2127 DeclAccessPair FoundDecl,
2130 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2131 ArrayRef<Expr *> Args,
2132 OverloadCandidateSet &CandidateSet,
2133 bool PartialOverloading = false);
2135 // An enum used to represent the different possible results of building a
2136 // range-based for loop.
2137 enum ForRangeStatus {
2139 FRS_NoViableFunction,
2140 FRS_DiagnosticIssued
2143 // An enum to represent whether something is dealing with a call to begin()
2144 // or a call to end() in a range-based for loop.
2145 enum BeginEndFunction {
2150 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2151 SourceLocation RangeLoc,
2153 BeginEndFunction BEF,
2154 const DeclarationNameInfo &NameInfo,
2155 LookupResult &MemberLookup,
2156 OverloadCandidateSet *CandidateSet,
2157 Expr *Range, ExprResult *CallExpr);
2159 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2160 UnresolvedLookupExpr *ULE,
2161 SourceLocation LParenLoc,
2162 Expr **Args, unsigned NumArgs,
2163 SourceLocation RParenLoc,
2165 bool AllowTypoCorrection=true);
2167 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2168 Expr **Args, unsigned NumArgs,
2169 SourceLocation RParenLoc,
2170 OverloadCandidateSet *CandidateSet,
2171 ExprResult *Result);
2173 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2175 const UnresolvedSetImpl &Fns,
2178 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2180 const UnresolvedSetImpl &Fns,
2181 Expr *LHS, Expr *RHS);
2183 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2184 SourceLocation RLoc,
2185 Expr *Base,Expr *Idx);
2188 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2189 SourceLocation LParenLoc, Expr **Args,
2190 unsigned NumArgs, SourceLocation RParenLoc);
2192 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2193 Expr **Args, unsigned NumArgs,
2194 SourceLocation RParenLoc);
2196 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2197 SourceLocation OpLoc);
2199 /// CheckCallReturnType - Checks that a call expression's return type is
2200 /// complete. Returns true on failure. The location passed in is the location
2201 /// that best represents the call.
2202 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2203 CallExpr *CE, FunctionDecl *FD);
2205 /// Helpers for dealing with blocks and functions.
2206 bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd,
2207 bool CheckParameterNames);
2208 void CheckCXXDefaultArguments(FunctionDecl *FD);
2209 void CheckExtraCXXDefaultArguments(Declarator &D);
2210 Scope *getNonFieldDeclScope(Scope *S);
2212 /// \name Name lookup
2214 /// These routines provide name lookup that is used during semantic
2215 /// analysis to resolve the various kinds of names (identifiers,
2216 /// overloaded operator names, constructor names, etc.) into zero or
2217 /// more declarations within a particular scope. The major entry
2218 /// points are LookupName, which performs unqualified name lookup,
2219 /// and LookupQualifiedName, which performs qualified name lookup.
2221 /// All name lookup is performed based on some specific criteria,
2222 /// which specify what names will be visible to name lookup and how
2223 /// far name lookup should work. These criteria are important both
2224 /// for capturing language semantics (certain lookups will ignore
2225 /// certain names, for example) and for performance, since name
2226 /// lookup is often a bottleneck in the compilation of C++. Name
2227 /// lookup criteria is specified via the LookupCriteria enumeration.
2229 /// The results of name lookup can vary based on the kind of name
2230 /// lookup performed, the current language, and the translation
2231 /// unit. In C, for example, name lookup will either return nothing
2232 /// (no entity found) or a single declaration. In C++, name lookup
2233 /// can additionally refer to a set of overloaded functions or
2234 /// result in an ambiguity. All of the possible results of name
2235 /// lookup are captured by the LookupResult class, which provides
2236 /// the ability to distinguish among them.
2239 /// @brief Describes the kind of name lookup to perform.
2240 enum LookupNameKind {
2241 /// Ordinary name lookup, which finds ordinary names (functions,
2242 /// variables, typedefs, etc.) in C and most kinds of names
2243 /// (functions, variables, members, types, etc.) in C++.
2244 LookupOrdinaryName = 0,
2245 /// Tag name lookup, which finds the names of enums, classes,
2246 /// structs, and unions.
2248 /// Label name lookup.
2250 /// Member name lookup, which finds the names of
2251 /// class/struct/union members.
2253 /// Look up of an operator name (e.g., operator+) for use with
2254 /// operator overloading. This lookup is similar to ordinary name
2255 /// lookup, but will ignore any declarations that are class members.
2257 /// Look up of a name that precedes the '::' scope resolution
2258 /// operator in C++. This lookup completely ignores operator, object,
2259 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2260 LookupNestedNameSpecifierName,
2261 /// Look up a namespace name within a C++ using directive or
2262 /// namespace alias definition, ignoring non-namespace names (C++
2263 /// [basic.lookup.udir]p1).
2264 LookupNamespaceName,
2265 /// Look up all declarations in a scope with the given name,
2266 /// including resolved using declarations. This is appropriate
2267 /// for checking redeclarations for a using declaration.
2268 LookupUsingDeclName,
2269 /// Look up an ordinary name that is going to be redeclared as a
2270 /// name with linkage. This lookup ignores any declarations that
2271 /// are outside of the current scope unless they have linkage. See
2272 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2273 LookupRedeclarationWithLinkage,
2274 /// Look up the name of an Objective-C protocol.
2275 LookupObjCProtocolName,
2276 /// Look up implicit 'self' parameter of an objective-c method.
2277 LookupObjCImplicitSelfParam,
2278 /// \brief Look up any declaration with any name.
2282 /// \brief Specifies whether (or how) name lookup is being performed for a
2283 /// redeclaration (vs. a reference).
2284 enum RedeclarationKind {
2285 /// \brief The lookup is a reference to this name that is not for the
2286 /// purpose of redeclaring the name.
2287 NotForRedeclaration = 0,
2288 /// \brief The lookup results will be used for redeclaration of a name,
2289 /// if an entity by that name already exists.
2293 /// \brief The possible outcomes of name lookup for a literal operator.
2294 enum LiteralOperatorLookupResult {
2295 /// \brief The lookup resulted in an error.
2297 /// \brief The lookup found a single 'cooked' literal operator, which
2298 /// expects a normal literal to be built and passed to it.
2300 /// \brief The lookup found a single 'raw' literal operator, which expects
2301 /// a string literal containing the spelling of the literal token.
2303 /// \brief The lookup found an overload set of literal operator templates,
2304 /// which expect the characters of the spelling of the literal token to be
2305 /// passed as a non-type template argument pack.
2309 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2310 CXXSpecialMember SM,
2318 bool CppLookupName(LookupResult &R, Scope *S);
2320 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2322 // The boolean value will be true to indicate that the namespace was loaded
2323 // from an AST/PCH file, or false otherwise.
2324 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2326 /// \brief Whether we have already loaded known namespaces from an extenal
2328 bool LoadedExternalKnownNamespaces;
2331 /// \brief Look up a name, looking for a single declaration. Return
2332 /// null if the results were absent, ambiguous, or overloaded.
2334 /// It is preferable to use the elaborated form and explicitly handle
2335 /// ambiguity and overloaded.
2336 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2338 LookupNameKind NameKind,
2339 RedeclarationKind Redecl
2340 = NotForRedeclaration);
2341 bool LookupName(LookupResult &R, Scope *S,
2342 bool AllowBuiltinCreation = false);
2343 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2344 bool InUnqualifiedLookup = false);
2345 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2346 bool AllowBuiltinCreation = false,
2347 bool EnteringContext = false);
2348 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2349 RedeclarationKind Redecl
2350 = NotForRedeclaration);
2352 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2353 QualType T1, QualType T2,
2354 UnresolvedSetImpl &Functions);
2356 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2357 SourceLocation GnuLabelLoc = SourceLocation());
2359 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2360 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2361 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2363 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2364 bool RValueThis, unsigned ThisQuals);
2365 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2367 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2368 bool RValueThis, unsigned ThisQuals);
2369 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2371 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2372 ArrayRef<QualType> ArgTys,
2373 bool AllowRawAndTemplate);
2374 bool isKnownName(StringRef name);
2376 void ArgumentDependentLookup(DeclarationName Name, bool Operator,
2378 ArrayRef<Expr *> Args,
2379 ADLResult &Functions);
2381 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2382 VisibleDeclConsumer &Consumer,
2383 bool IncludeGlobalScope = true);
2384 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2385 VisibleDeclConsumer &Consumer,
2386 bool IncludeGlobalScope = true);
2388 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2389 Sema::LookupNameKind LookupKind,
2390 Scope *S, CXXScopeSpec *SS,
2391 CorrectionCandidateCallback &CCC,
2392 DeclContext *MemberContext = 0,
2393 bool EnteringContext = false,
2394 const ObjCObjectPointerType *OPT = 0);
2396 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2397 ArrayRef<Expr *> Args,
2398 AssociatedNamespaceSet &AssociatedNamespaces,
2399 AssociatedClassSet &AssociatedClasses);
2401 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2402 bool ConsiderLinkage,
2403 bool ExplicitInstantiationOrSpecialization);
2405 bool DiagnoseAmbiguousLookup(LookupResult &Result);
2408 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2409 SourceLocation IdLoc,
2410 bool TypoCorrection = false);
2411 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2412 Scope *S, bool ForRedeclaration,
2413 SourceLocation Loc);
2414 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2416 void AddKnownFunctionAttributes(FunctionDecl *FD);
2418 // More parsing and symbol table subroutines.
2420 void ProcessPragmaWeak(Scope *S, Decl *D);
2421 // Decl attributes - this routine is the top level dispatcher.
2422 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
2423 bool NonInheritable = true,
2424 bool Inheritable = true);
2425 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2426 bool NonInheritable = true,
2427 bool Inheritable = true,
2428 bool IncludeCXX11Attributes = true);
2429 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2430 const AttributeList *AttrList);
2432 void checkUnusedDeclAttributes(Declarator &D);
2434 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2435 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2436 const FunctionDecl *FD = 0);
2437 bool CheckNoReturnAttr(const AttributeList &attr);
2438 void CheckAlignasUnderalignment(Decl *D);
2440 /// \brief Stmt attributes - this routine is the top level dispatcher.
2441 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2444 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
2445 bool &IncompleteImpl, unsigned DiagID);
2446 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2447 ObjCMethodDecl *MethodDecl,
2448 bool IsProtocolMethodDecl);
2450 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2451 ObjCMethodDecl *Overridden,
2452 bool IsProtocolMethodDecl);
2454 /// WarnExactTypedMethods - This routine issues a warning if method
2455 /// implementation declaration matches exactly that of its declaration.
2456 void WarnExactTypedMethods(ObjCMethodDecl *Method,
2457 ObjCMethodDecl *MethodDecl,
2458 bool IsProtocolMethodDecl);
2460 bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl,
2461 ObjCInterfaceDecl *IDecl);
2463 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2464 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2466 /// CheckProtocolMethodDefs - This routine checks unimplemented
2467 /// methods declared in protocol, and those referenced by it.
2468 void CheckProtocolMethodDefs(SourceLocation ImpLoc,
2469 ObjCProtocolDecl *PDecl,
2470 bool& IncompleteImpl,
2471 const SelectorSet &InsMap,
2472 const SelectorSet &ClsMap,
2473 ObjCContainerDecl *CDecl);
2475 /// CheckImplementationIvars - This routine checks if the instance variables
2476 /// listed in the implelementation match those listed in the interface.
2477 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2478 ObjCIvarDecl **Fields, unsigned nIvars,
2479 SourceLocation Loc);
2481 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2482 /// remains unimplemented in the class or category \@implementation.
2483 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2484 ObjCContainerDecl* IDecl,
2485 bool IncompleteImpl = false);
2487 /// DiagnoseUnimplementedProperties - This routine warns on those properties
2488 /// which must be implemented by this implementation.
2489 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2490 ObjCContainerDecl *CDecl);
2492 /// DefaultSynthesizeProperties - This routine default synthesizes all
2493 /// properties which must be synthesized in the class's \@implementation.
2494 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2495 ObjCInterfaceDecl *IDecl);
2496 void DefaultSynthesizeProperties(Scope *S, Decl *D);
2498 /// CollectImmediateProperties - This routine collects all properties in
2499 /// the class and its conforming protocols; but not those it its super class.
2500 void CollectImmediateProperties(ObjCContainerDecl *CDecl,
2501 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
2502 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
2504 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
2505 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
2506 /// declared in class 'IFace'.
2507 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
2508 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
2510 /// Called by ActOnProperty to handle \@property declarations in
2511 /// class extensions.
2512 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
2513 SourceLocation AtLoc,
2514 SourceLocation LParenLoc,
2515 FieldDeclarator &FD,
2518 const bool isAssign,
2519 const bool isReadWrite,
2520 const unsigned Attributes,
2521 const unsigned AttributesAsWritten,
2522 bool *isOverridingProperty,
2524 tok::ObjCKeywordKind MethodImplKind);
2526 /// Called by ActOnProperty and HandlePropertyInClassExtension to
2527 /// handle creating the ObjcPropertyDecl for a category or \@interface.
2528 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
2529 ObjCContainerDecl *CDecl,
2530 SourceLocation AtLoc,
2531 SourceLocation LParenLoc,
2532 FieldDeclarator &FD,
2535 const bool isAssign,
2536 const bool isReadWrite,
2537 const unsigned Attributes,
2538 const unsigned AttributesAsWritten,
2540 tok::ObjCKeywordKind MethodImplKind,
2541 DeclContext *lexicalDC = 0);
2543 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
2544 /// warning) when atomic property has one but not the other user-declared
2545 /// setter or getter.
2546 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
2547 ObjCContainerDecl* IDecl);
2549 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
2551 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
2553 enum MethodMatchStrategy {
2558 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
2559 /// true, or false, accordingly.
2560 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
2561 const ObjCMethodDecl *PrevMethod,
2562 MethodMatchStrategy strategy = MMS_strict);
2564 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2565 /// or protocol against those declared in their implementations.
2566 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2567 const SelectorSet &ClsMap,
2568 SelectorSet &InsMapSeen,
2569 SelectorSet &ClsMapSeen,
2570 ObjCImplDecl* IMPDecl,
2571 ObjCContainerDecl* IDecl,
2572 bool &IncompleteImpl,
2573 bool ImmediateClass,
2574 bool WarnCategoryMethodImpl=false);
2576 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2577 /// category matches with those implemented in its primary class and
2578 /// warns each time an exact match is found.
2579 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2581 /// \brief Add the given method to the list of globally-known methods.
2582 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
2585 /// AddMethodToGlobalPool - Add an instance or factory method to the global
2586 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2587 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2589 /// LookupMethodInGlobalPool - Returns the instance or factory method and
2590 /// optionally warns if there are multiple signatures.
2591 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2592 bool receiverIdOrClass,
2593 bool warn, bool instance);
2596 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
2597 /// unit are added to a global pool. This allows us to efficiently associate
2598 /// a selector with a method declaraation for purposes of typechecking
2599 /// messages sent to "id" (where the class of the object is unknown).
2600 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2601 AddMethodToGlobalPool(Method, impl, /*instance*/true);
2604 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
2605 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2606 AddMethodToGlobalPool(Method, impl, /*instance*/false);
2609 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
2611 void AddAnyMethodToGlobalPool(Decl *D);
2613 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
2614 /// there are multiple signatures.
2615 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
2616 bool receiverIdOrClass=false,
2618 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2619 warn, /*instance*/true);
2622 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
2623 /// there are multiple signatures.
2624 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
2625 bool receiverIdOrClass=false,
2627 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2628 warn, /*instance*/false);
2631 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
2633 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
2635 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2637 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2638 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
2640 //===--------------------------------------------------------------------===//
2641 // Statement Parsing Callbacks: SemaStmt.cpp.
2645 FullExprArg(Sema &actions) : E(0) { }
2647 // FIXME: The const_cast here is ugly. RValue references would make this
2648 // much nicer (or we could duplicate a bunch of the move semantics
2649 // emulation code from Ownership.h).
2650 FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2652 ExprResult release() {
2656 Expr *get() const { return E; }
2658 Expr *operator->() {
2663 // FIXME: No need to make the entire Sema class a friend when it's just
2664 // Sema::MakeFullExpr that needs access to the constructor below.
2667 explicit FullExprArg(Expr *expr) : E(expr) {}
2672 FullExprArg MakeFullExpr(Expr *Arg) {
2673 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
2675 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
2676 return FullExprArg(ActOnFinishFullExpr(Arg, CC).release());
2678 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
2680 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
2681 /*DiscardedValue*/ true);
2682 return FullExprArg(FE.release());
2685 StmtResult ActOnExprStmt(ExprResult Arg);
2686 StmtResult ActOnExprStmtError();
2688 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
2689 bool HasLeadingEmptyMacro = false);
2691 void ActOnStartOfCompoundStmt();
2692 void ActOnFinishOfCompoundStmt();
2693 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
2697 /// \brief A RAII object to enter scope of a compound statement.
2698 class CompoundScopeRAII {
2700 CompoundScopeRAII(Sema &S): S(S) {
2701 S.ActOnStartOfCompoundStmt();
2704 ~CompoundScopeRAII() {
2705 S.ActOnFinishOfCompoundStmt();
2712 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
2713 SourceLocation StartLoc,
2714 SourceLocation EndLoc);
2715 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
2716 StmtResult ActOnForEachLValueExpr(Expr *E);
2717 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
2718 SourceLocation DotDotDotLoc, Expr *RHSVal,
2719 SourceLocation ColonLoc);
2720 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
2722 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
2723 SourceLocation ColonLoc,
2724 Stmt *SubStmt, Scope *CurScope);
2725 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
2726 SourceLocation ColonLoc, Stmt *SubStmt);
2728 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
2729 ArrayRef<const Attr*> Attrs,
2732 StmtResult ActOnIfStmt(SourceLocation IfLoc,
2733 FullExprArg CondVal, Decl *CondVar,
2735 SourceLocation ElseLoc, Stmt *ElseVal);
2736 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
2739 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
2740 Stmt *Switch, Stmt *Body);
2741 StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
2743 Decl *CondVar, Stmt *Body);
2744 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
2745 SourceLocation WhileLoc,
2746 SourceLocation CondLParen, Expr *Cond,
2747 SourceLocation CondRParen);
2749 StmtResult ActOnForStmt(SourceLocation ForLoc,
2750 SourceLocation LParenLoc,
2751 Stmt *First, FullExprArg Second,
2754 SourceLocation RParenLoc,
2756 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
2758 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
2759 Stmt *First, Expr *collection,
2760 SourceLocation RParenLoc);
2761 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
2763 enum BuildForRangeKind {
2764 /// Initial building of a for-range statement.
2766 /// Instantiation or recovery rebuild of a for-range statement. Don't
2767 /// attempt any typo-correction.
2769 /// Determining whether a for-range statement could be built. Avoid any
2770 /// unnecessary or irreversible actions.
2774 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
2775 SourceLocation ColonLoc, Expr *Collection,
2776 SourceLocation RParenLoc,
2777 BuildForRangeKind Kind);
2778 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
2779 SourceLocation ColonLoc,
2780 Stmt *RangeDecl, Stmt *BeginEndDecl,
2781 Expr *Cond, Expr *Inc,
2783 SourceLocation RParenLoc,
2784 BuildForRangeKind Kind);
2785 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
2787 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
2788 SourceLocation LabelLoc,
2789 LabelDecl *TheDecl);
2790 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
2791 SourceLocation StarLoc,
2793 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
2794 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
2796 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
2797 CapturedRegionKind Kind, unsigned NumParams);
2798 StmtResult ActOnCapturedRegionEnd(Stmt *S);
2799 void ActOnCapturedRegionError();
2800 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
2802 unsigned NumParams);
2803 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
2804 bool AllowFunctionParameters);
2806 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2807 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2809 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2810 bool IsVolatile, unsigned NumOutputs,
2811 unsigned NumInputs, IdentifierInfo **Names,
2812 MultiExprArg Constraints, MultiExprArg Exprs,
2813 Expr *AsmString, MultiExprArg Clobbers,
2814 SourceLocation RParenLoc);
2816 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
2817 SourceLocation TemplateKWLoc,
2819 InlineAsmIdentifierInfo &Info,
2820 bool IsUnevaluatedContext);
2821 bool LookupInlineAsmField(StringRef Base, StringRef Member,
2822 unsigned &Offset, SourceLocation AsmLoc);
2823 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
2824 ArrayRef<Token> AsmToks,
2825 StringRef AsmString,
2826 unsigned NumOutputs, unsigned NumInputs,
2827 ArrayRef<StringRef> Constraints,
2828 ArrayRef<StringRef> Clobbers,
2829 ArrayRef<Expr*> Exprs,
2830 SourceLocation EndLoc);
2832 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
2833 SourceLocation StartLoc,
2834 SourceLocation IdLoc, IdentifierInfo *Id,
2835 bool Invalid = false);
2837 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
2839 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
2840 Decl *Parm, Stmt *Body);
2842 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
2844 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2845 MultiStmtArg Catch, Stmt *Finally);
2847 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
2848 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2850 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
2852 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
2856 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
2858 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
2859 SourceLocation StartLoc,
2860 SourceLocation IdLoc,
2861 IdentifierInfo *Id);
2863 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
2865 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
2866 Decl *ExDecl, Stmt *HandlerBlock);
2867 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2868 MultiStmtArg Handlers);
2870 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
2871 SourceLocation TryLoc,
2875 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
2879 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
2882 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
2884 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
2886 /// \brief If it's a file scoped decl that must warn if not used, keep track
2888 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
2890 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
2891 /// whose result is unused, warn.
2892 void DiagnoseUnusedExprResult(const Stmt *S);
2893 void DiagnoseUnusedDecl(const NamedDecl *ND);
2895 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2896 /// statement as a \p Body, and it is located on the same line.
2898 /// This helps prevent bugs due to typos, such as:
2901 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
2905 /// Warn if a for/while loop statement \p S, which is followed by
2906 /// \p PossibleBody, has a suspicious null statement as a body.
2907 void DiagnoseEmptyLoopBody(const Stmt *S,
2908 const Stmt *PossibleBody);
2910 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
2911 return DelayedDiagnostics.push(pool);
2913 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
2915 typedef ProcessingContextState ParsingClassState;
2916 ParsingClassState PushParsingClass() {
2917 return DelayedDiagnostics.pushUndelayed();
2919 void PopParsingClass(ParsingClassState state) {
2920 DelayedDiagnostics.popUndelayed(state);
2923 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
2925 void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
2927 const ObjCInterfaceDecl *UnknownObjCClass,
2928 const ObjCPropertyDecl *ObjCProperty);
2930 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2932 bool makeUnavailableInSystemHeader(SourceLocation loc,
2935 //===--------------------------------------------------------------------===//
2936 // Expression Parsing Callbacks: SemaExpr.cpp.
2938 bool CanUseDecl(NamedDecl *D);
2939 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
2940 const ObjCInterfaceDecl *UnknownObjCClass=0);
2941 void NoteDeletedFunction(FunctionDecl *FD);
2942 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
2943 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
2944 ObjCMethodDecl *Getter,
2945 SourceLocation Loc);
2946 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
2947 Expr **Args, unsigned NumArgs);
2949 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
2950 Decl *LambdaContextDecl = 0,
2951 bool IsDecltype = false);
2952 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
2953 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
2954 ReuseLambdaContextDecl_t,
2955 bool IsDecltype = false);
2956 void PopExpressionEvaluationContext();
2958 void DiscardCleanupsInEvaluationContext();
2960 ExprResult TransformToPotentiallyEvaluated(Expr *E);
2961 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
2963 ExprResult ActOnConstantExpression(ExprResult Res);
2965 // Functions for marking a declaration referenced. These functions also
2966 // contain the relevant logic for marking if a reference to a function or
2967 // variable is an odr-use (in the C++11 sense). There are separate variants
2968 // for expressions referring to a decl; these exist because odr-use marking
2969 // needs to be delayed for some constant variables when we build one of the
2970 // named expressions.
2971 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
2972 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func);
2973 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
2974 void MarkDeclRefReferenced(DeclRefExpr *E);
2975 void MarkMemberReferenced(MemberExpr *E);
2977 void UpdateMarkingForLValueToRValue(Expr *E);
2978 void CleanupVarDeclMarking();
2980 enum TryCaptureKind {
2981 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
2984 /// \brief Try to capture the given variable.
2986 /// \param Var The variable to capture.
2988 /// \param Loc The location at which the capture occurs.
2990 /// \param Kind The kind of capture, which may be implicit (for either a
2991 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
2993 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
2994 /// an explicit lambda capture.
2996 /// \param BuildAndDiagnose Whether we are actually supposed to add the
2997 /// captures or diagnose errors. If false, this routine merely check whether
2998 /// the capture can occur without performing the capture itself or complaining
2999 /// if the variable cannot be captured.
3001 /// \param CaptureType Will be set to the type of the field used to capture
3002 /// this variable in the innermost block or lambda. Only valid when the
3003 /// variable can be captured.
3005 /// \param DeclRefType Will be set to the type of a reference to the capture
3006 /// from within the current scope. Only valid when the variable can be
3009 /// \returns true if an error occurred (i.e., the variable cannot be
3010 /// captured) and false if the capture succeeded.
3011 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3012 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3013 QualType &CaptureType,
3014 QualType &DeclRefType);
3016 /// \brief Try to capture the given variable.
3017 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3018 TryCaptureKind Kind = TryCapture_Implicit,
3019 SourceLocation EllipsisLoc = SourceLocation());
3021 /// \brief Given a variable, determine the type that a reference to that
3022 /// variable will have in the given scope.
3023 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3025 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3026 void MarkDeclarationsReferencedInExpr(Expr *E,
3027 bool SkipLocalVariables = false);
3029 /// \brief Try to recover by turning the given expression into a
3030 /// call. Returns true if recovery was attempted or an error was
3031 /// emitted; this may also leave the ExprResult invalid.
3032 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3033 bool ForceComplain = false,
3034 bool (*IsPlausibleResult)(QualType) = 0);
3036 /// \brief Figure out if an expression could be turned into a call.
3037 bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
3038 UnresolvedSetImpl &NonTemplateOverloads);
3040 /// \brief Conditionally issue a diagnostic based on the current
3041 /// evaluation context.
3043 /// \param Statement If Statement is non-null, delay reporting the
3044 /// diagnostic until the function body is parsed, and then do a basic
3045 /// reachability analysis to determine if the statement is reachable.
3046 /// If it is unreachable, the diagnostic will not be emitted.
3047 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3048 const PartialDiagnostic &PD);
3050 // Primary Expressions.
3051 SourceRange getExprRange(Expr *E) const;
3053 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
3054 SourceLocation TemplateKWLoc,
3056 bool HasTrailingLParen, bool IsAddressOfOperand,
3057 CorrectionCandidateCallback *CCC = 0);
3059 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3060 TemplateArgumentListInfo &Buffer,
3061 DeclarationNameInfo &NameInfo,
3062 const TemplateArgumentListInfo *&TemplateArgs);
3064 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3065 CorrectionCandidateCallback &CCC,
3066 TemplateArgumentListInfo *ExplicitTemplateArgs = 0,
3067 ArrayRef<Expr *> Args = None);
3069 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3071 bool AllowBuiltinCreation=false);
3073 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3074 SourceLocation TemplateKWLoc,
3075 const DeclarationNameInfo &NameInfo,
3076 bool isAddressOfOperand,
3077 const TemplateArgumentListInfo *TemplateArgs);
3079 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3082 const CXXScopeSpec *SS = 0);
3083 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3085 const DeclarationNameInfo &NameInfo,
3086 const CXXScopeSpec *SS = 0,
3087 NamedDecl *FoundD = 0);
3089 BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
3090 SourceLocation nameLoc,
3091 IndirectFieldDecl *indirectField,
3092 Expr *baseObjectExpr = 0,
3093 SourceLocation opLoc = SourceLocation());
3094 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3095 SourceLocation TemplateKWLoc,
3097 const TemplateArgumentListInfo *TemplateArgs);
3098 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3099 SourceLocation TemplateKWLoc,
3101 const TemplateArgumentListInfo *TemplateArgs,
3102 bool IsDefiniteInstance);
3103 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3104 const LookupResult &R,
3105 bool HasTrailingLParen);
3107 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3108 const DeclarationNameInfo &NameInfo,
3109 bool IsAddressOfOperand);
3110 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3111 SourceLocation TemplateKWLoc,
3112 const DeclarationNameInfo &NameInfo,
3113 const TemplateArgumentListInfo *TemplateArgs);
3115 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3118 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3119 const DeclarationNameInfo &NameInfo,
3120 NamedDecl *D, NamedDecl *FoundD = 0);
3122 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3123 DeclarationNameInfo &SuffixInfo,
3124 ArrayRef<Expr*> Args,
3125 SourceLocation LitEndLoc,
3126 TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
3128 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3129 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3130 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0);
3131 ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0);
3132 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3133 ExprResult ActOnParenListExpr(SourceLocation L,
3137 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3138 /// fragments (e.g. "foo" "bar" L"baz").
3139 ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
3140 Scope *UDLScope = 0);
3142 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3143 SourceLocation DefaultLoc,
3144 SourceLocation RParenLoc,
3145 Expr *ControllingExpr,
3146 MultiTypeArg ArgTypes,
3147 MultiExprArg ArgExprs);
3148 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3149 SourceLocation DefaultLoc,
3150 SourceLocation RParenLoc,
3151 Expr *ControllingExpr,
3152 TypeSourceInfo **Types,
3154 unsigned NumAssocs);
3156 // Binary/Unary Operators. 'Tok' is the token for the operator.
3157 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3159 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3160 UnaryOperatorKind Opc, Expr *Input);
3161 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3162 tok::TokenKind Op, Expr *Input);
3164 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3165 SourceLocation OpLoc,
3166 UnaryExprOrTypeTrait ExprKind,
3168 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3169 UnaryExprOrTypeTrait ExprKind);
3171 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3172 UnaryExprOrTypeTrait ExprKind,
3173 bool IsType, void *TyOrEx,
3174 const SourceRange &ArgRange);
3176 ExprResult CheckPlaceholderExpr(Expr *E);
3177 bool CheckVecStepExpr(Expr *E);
3179 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3180 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3181 SourceRange ExprRange,
3182 UnaryExprOrTypeTrait ExprKind);
3183 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3184 SourceLocation OpLoc,
3185 IdentifierInfo &Name,
3186 SourceLocation NameLoc,
3187 SourceLocation RParenLoc);
3188 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3189 tok::TokenKind Kind, Expr *Input);
3191 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3192 Expr *Idx, SourceLocation RLoc);
3193 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3194 Expr *Idx, SourceLocation RLoc);
3196 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3197 SourceLocation OpLoc, bool IsArrow,
3199 SourceLocation TemplateKWLoc,
3200 NamedDecl *FirstQualifierInScope,
3201 const DeclarationNameInfo &NameInfo,
3202 const TemplateArgumentListInfo *TemplateArgs);
3204 // This struct is for use by ActOnMemberAccess to allow
3205 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3206 // changing the access operator from a '.' to a '->' (to see if that is the
3207 // change needed to fix an error about an unknown member, e.g. when the class
3208 // defines a custom operator->).
3209 struct ActOnMemberAccessExtraArgs {
3213 bool HasTrailingLParen;
3216 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3217 SourceLocation OpLoc, bool IsArrow,
3218 const CXXScopeSpec &SS,
3219 SourceLocation TemplateKWLoc,
3220 NamedDecl *FirstQualifierInScope,
3222 const TemplateArgumentListInfo *TemplateArgs,
3223 bool SuppressQualifierCheck = false,
3224 ActOnMemberAccessExtraArgs *ExtraArgs = 0);
3226 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3227 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
3228 bool &IsArrow, SourceLocation OpLoc,
3231 bool HasTemplateArgs);
3233 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3234 const CXXScopeSpec &SS,
3235 const LookupResult &R);
3237 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3238 bool IsArrow, SourceLocation OpLoc,
3239 const CXXScopeSpec &SS,
3240 SourceLocation TemplateKWLoc,
3241 NamedDecl *FirstQualifierInScope,
3242 const DeclarationNameInfo &NameInfo,
3243 const TemplateArgumentListInfo *TemplateArgs);
3245 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3246 SourceLocation OpLoc,
3247 tok::TokenKind OpKind,
3249 SourceLocation TemplateKWLoc,
3250 UnqualifiedId &Member,
3252 bool HasTrailingLParen);
3254 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3255 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3256 FunctionDecl *FDecl,
3257 const FunctionProtoType *Proto,
3258 Expr **Args, unsigned NumArgs,
3259 SourceLocation RParenLoc,
3260 bool ExecConfig = false);
3261 void CheckStaticArrayArgument(SourceLocation CallLoc,
3263 const Expr *ArgExpr);
3265 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3266 /// This provides the location of the left/right parens and a list of comma
3268 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3269 MultiExprArg ArgExprs, SourceLocation RParenLoc,
3270 Expr *ExecConfig = 0, bool IsExecConfig = false);
3271 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3272 SourceLocation LParenLoc,
3273 Expr **Args, unsigned NumArgs,
3274 SourceLocation RParenLoc,
3276 bool IsExecConfig = false);
3278 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3279 MultiExprArg ExecConfig,
3280 SourceLocation GGGLoc);
3282 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3283 Declarator &D, ParsedType &Ty,
3284 SourceLocation RParenLoc, Expr *CastExpr);
3285 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3287 SourceLocation RParenLoc,
3289 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3291 /// \brief Build an altivec or OpenCL literal.
3292 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3293 SourceLocation RParenLoc, Expr *E,
3294 TypeSourceInfo *TInfo);
3296 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3298 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3300 SourceLocation RParenLoc,
3303 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3304 TypeSourceInfo *TInfo,
3305 SourceLocation RParenLoc,
3308 ExprResult ActOnInitList(SourceLocation LBraceLoc,
3309 MultiExprArg InitArgList,
3310 SourceLocation RBraceLoc);
3312 ExprResult ActOnDesignatedInitializer(Designation &Desig,
3317 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3318 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3319 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3320 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3321 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3322 Expr *LHSExpr, Expr *RHSExpr);
3324 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
3325 /// in the case of a the GNU conditional expr extension.
3326 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3327 SourceLocation ColonLoc,
3328 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3330 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3331 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3332 LabelDecl *TheDecl);
3334 void ActOnStartStmtExpr();
3335 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3336 SourceLocation RPLoc); // "({..})"
3337 void ActOnStmtExprError();
3339 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3340 struct OffsetOfComponent {
3341 SourceLocation LocStart, LocEnd;
3342 bool isBrackets; // true if [expr], false if .ident
3344 IdentifierInfo *IdentInfo;
3349 /// __builtin_offsetof(type, a.b[123][456].c)
3350 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3351 TypeSourceInfo *TInfo,
3352 OffsetOfComponent *CompPtr,
3353 unsigned NumComponents,
3354 SourceLocation RParenLoc);
3355 ExprResult ActOnBuiltinOffsetOf(Scope *S,
3356 SourceLocation BuiltinLoc,
3357 SourceLocation TypeLoc,
3358 ParsedType ParsedArgTy,
3359 OffsetOfComponent *CompPtr,
3360 unsigned NumComponents,
3361 SourceLocation RParenLoc);
3363 // __builtin_choose_expr(constExpr, expr1, expr2)
3364 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3365 Expr *CondExpr, Expr *LHSExpr,
3366 Expr *RHSExpr, SourceLocation RPLoc);
3368 // __builtin_va_arg(expr, type)
3369 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3370 SourceLocation RPLoc);
3371 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3372 TypeSourceInfo *TInfo, SourceLocation RPLoc);
3375 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3377 bool CheckCaseExpression(Expr *E);
3379 /// \brief Describes the result of an "if-exists" condition check.
3380 enum IfExistsResult {
3381 /// \brief The symbol exists.
3384 /// \brief The symbol does not exist.
3387 /// \brief The name is a dependent name, so the results will differ
3388 /// from one instantiation to the next.
3391 /// \brief An error occurred.
3396 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3397 const DeclarationNameInfo &TargetNameInfo);
3400 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3401 bool IsIfExists, CXXScopeSpec &SS,
3402 UnqualifiedId &Name);
3404 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3406 NestedNameSpecifierLoc QualifierLoc,
3407 DeclarationNameInfo NameInfo,
3409 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3411 CXXScopeSpec &SS, UnqualifiedId &Name,
3414 //===------------------------- "Block" Extension ------------------------===//
3416 /// ActOnBlockStart - This callback is invoked when a block literal is
3418 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3420 /// ActOnBlockArguments - This callback allows processing of block arguments.
3421 /// If there are no arguments, this is still invoked.
3422 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3425 /// ActOnBlockError - If there is an error parsing a block, this callback
3426 /// is invoked to pop the information about the block from the action impl.
3427 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3429 /// ActOnBlockStmtExpr - This is called when the body of a block statement
3430 /// literal was successfully completed. ^(int x){...}
3431 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3434 //===---------------------------- OpenCL Features -----------------------===//
3436 /// __builtin_astype(...)
3437 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3438 SourceLocation BuiltinLoc,
3439 SourceLocation RParenLoc);
3441 //===---------------------------- C++ Features --------------------------===//
3443 // Act on C++ namespaces
3444 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3445 SourceLocation NamespaceLoc,
3446 SourceLocation IdentLoc,
3447 IdentifierInfo *Ident,
3448 SourceLocation LBrace,
3449 AttributeList *AttrList);
3450 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3452 NamespaceDecl *getStdNamespace() const;
3453 NamespaceDecl *getOrCreateStdNamespace();
3455 CXXRecordDecl *getStdBadAlloc() const;
3457 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3458 /// it is and Element is not NULL, assigns the element type to Element.
3459 bool isStdInitializerList(QualType Ty, QualType *Element);
3461 /// \brief Looks for the std::initializer_list template and instantiates it
3462 /// with Element, or emits an error if it's not found.
3464 /// \returns The instantiated template, or null on error.
3465 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3467 /// \brief Determine whether Ctor is an initializer-list constructor, as
3468 /// defined in [dcl.init.list]p2.
3469 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3471 Decl *ActOnUsingDirective(Scope *CurScope,
3472 SourceLocation UsingLoc,
3473 SourceLocation NamespcLoc,
3475 SourceLocation IdentLoc,
3476 IdentifierInfo *NamespcName,
3477 AttributeList *AttrList);
3479 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3481 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3482 SourceLocation NamespaceLoc,
3483 SourceLocation AliasLoc,
3484 IdentifierInfo *Alias,
3486 SourceLocation IdentLoc,
3487 IdentifierInfo *Ident);
3489 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3490 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3491 const LookupResult &PreviousDecls);
3492 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3495 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3497 const CXXScopeSpec &SS,
3498 SourceLocation NameLoc,
3499 const LookupResult &Previous);
3500 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3501 const CXXScopeSpec &SS,
3502 SourceLocation NameLoc);
3504 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3505 SourceLocation UsingLoc,
3507 const DeclarationNameInfo &NameInfo,
3508 AttributeList *AttrList,
3509 bool IsInstantiation,
3511 SourceLocation TypenameLoc);
3513 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3515 Decl *ActOnUsingDeclaration(Scope *CurScope,
3517 bool HasUsingKeyword,
3518 SourceLocation UsingLoc,
3520 UnqualifiedId &Name,
3521 AttributeList *AttrList,
3523 SourceLocation TypenameLoc);
3524 Decl *ActOnAliasDeclaration(Scope *CurScope,
3526 MultiTemplateParamsArg TemplateParams,
3527 SourceLocation UsingLoc,
3528 UnqualifiedId &Name,
3529 AttributeList *AttrList,
3532 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3533 /// including handling of its default argument expressions.
3535 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3537 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3538 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3539 bool HadMultipleCandidates, bool IsListInitialization,
3540 bool RequiresZeroInit, unsigned ConstructKind,
3541 SourceRange ParenRange);
3543 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3544 // the constructor can be elidable?
3546 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3547 CXXConstructorDecl *Constructor, bool Elidable,
3548 MultiExprArg Exprs, bool HadMultipleCandidates,
3549 bool IsListInitialization, bool RequiresZeroInit,
3550 unsigned ConstructKind, SourceRange ParenRange);
3552 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3553 /// the default expr if needed.
3554 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3556 ParmVarDecl *Param);
3558 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3559 /// constructed variable.
3560 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3562 /// \brief Helper class that collects exception specifications for
3563 /// implicitly-declared special member functions.
3564 class ImplicitExceptionSpecification {
3565 // Pointer to allow copying
3567 // We order exception specifications thus:
3568 // noexcept is the most restrictive, but is only used in C++11.
3569 // throw() comes next.
3570 // Then a throw(collected exceptions)
3571 // Finally no specification, which is expressed as noexcept(false).
3572 // throw(...) is used instead if any called function uses it.
3573 ExceptionSpecificationType ComputedEST;
3574 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3575 SmallVector<QualType, 4> Exceptions;
3577 void ClearExceptions() {
3578 ExceptionsSeen.clear();
3583 explicit ImplicitExceptionSpecification(Sema &Self)
3584 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
3585 if (!Self.getLangOpts().CPlusPlus11)
3586 ComputedEST = EST_DynamicNone;
3589 /// \brief Get the computed exception specification type.
3590 ExceptionSpecificationType getExceptionSpecType() const {
3591 assert(ComputedEST != EST_ComputedNoexcept &&
3592 "noexcept(expr) should not be a possible result");
3596 /// \brief The number of exceptions in the exception specification.
3597 unsigned size() const { return Exceptions.size(); }
3599 /// \brief The set of exceptions in the exception specification.
3600 const QualType *data() const { return Exceptions.data(); }
3602 /// \brief Integrate another called method into the collected data.
3603 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
3605 /// \brief Integrate an invoked expression into the collected data.
3606 void CalledExpr(Expr *E);
3608 /// \brief Overwrite an EPI's exception specification with this
3609 /// computed exception specification.
3610 void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const {
3611 EPI.ExceptionSpecType = getExceptionSpecType();
3612 if (EPI.ExceptionSpecType == EST_Dynamic) {
3613 EPI.NumExceptions = size();
3614 EPI.Exceptions = data();
3615 } else if (EPI.ExceptionSpecType == EST_None) {
3616 /// C++11 [except.spec]p14:
3617 /// The exception-specification is noexcept(false) if the set of
3618 /// potential exceptions of the special member function contains "any"
3619 EPI.ExceptionSpecType = EST_ComputedNoexcept;
3620 EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
3621 tok::kw_false).take();
3624 FunctionProtoType::ExtProtoInfo getEPI() const {
3625 FunctionProtoType::ExtProtoInfo EPI;
3631 /// \brief Determine what sort of exception specification a defaulted
3632 /// copy constructor of a class will have.
3633 ImplicitExceptionSpecification
3634 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
3637 /// \brief Determine what sort of exception specification a defaulted
3638 /// default constructor of a class will have, and whether the parameter
3640 ImplicitExceptionSpecification
3641 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
3643 /// \brief Determine what sort of exception specification a defautled
3644 /// copy assignment operator of a class will have, and whether the
3645 /// parameter will be const.
3646 ImplicitExceptionSpecification
3647 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
3649 /// \brief Determine what sort of exception specification a defaulted move
3650 /// constructor of a class will have.
3651 ImplicitExceptionSpecification
3652 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
3654 /// \brief Determine what sort of exception specification a defaulted move
3655 /// assignment operator of a class will have.
3656 ImplicitExceptionSpecification
3657 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
3659 /// \brief Determine what sort of exception specification a defaulted
3660 /// destructor of a class will have.
3661 ImplicitExceptionSpecification
3662 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
3664 /// \brief Determine what sort of exception specification an inheriting
3665 /// constructor of a class will have.
3666 ImplicitExceptionSpecification
3667 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
3669 /// \brief Evaluate the implicit exception specification for a defaulted
3670 /// special member function.
3671 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
3673 /// \brief Check the given exception-specification and update the
3674 /// extended prototype information with the results.
3675 void checkExceptionSpecification(ExceptionSpecificationType EST,
3676 ArrayRef<ParsedType> DynamicExceptions,
3677 ArrayRef<SourceRange> DynamicExceptionRanges,
3679 SmallVectorImpl<QualType> &Exceptions,
3680 FunctionProtoType::ExtProtoInfo &EPI);
3682 /// \brief Determine if a special member function should have a deleted
3683 /// definition when it is defaulted.
3684 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
3685 bool Diagnose = false);
3687 /// \brief Declare the implicit default constructor for the given class.
3689 /// \param ClassDecl The class declaration into which the implicit
3690 /// default constructor will be added.
3692 /// \returns The implicitly-declared default constructor.
3693 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
3694 CXXRecordDecl *ClassDecl);
3696 /// DefineImplicitDefaultConstructor - Checks for feasibility of
3697 /// defining this constructor as the default constructor.
3698 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3699 CXXConstructorDecl *Constructor);
3701 /// \brief Declare the implicit destructor for the given class.
3703 /// \param ClassDecl The class declaration into which the implicit
3704 /// destructor will be added.
3706 /// \returns The implicitly-declared destructor.
3707 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
3709 /// DefineImplicitDestructor - Checks for feasibility of
3710 /// defining this destructor as the default destructor.
3711 void DefineImplicitDestructor(SourceLocation CurrentLocation,
3712 CXXDestructorDecl *Destructor);
3714 /// \brief Build an exception spec for destructors that don't have one.
3716 /// C++11 says that user-defined destructors with no exception spec get one
3717 /// that looks as if the destructor was implicitly declared.
3718 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
3719 CXXDestructorDecl *Destructor);
3721 /// \brief Declare all inheriting constructors for the given class.
3723 /// \param ClassDecl The class declaration into which the inheriting
3724 /// constructors will be added.
3725 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
3727 /// \brief Define the specified inheriting constructor.
3728 void DefineInheritingConstructor(SourceLocation UseLoc,
3729 CXXConstructorDecl *Constructor);
3731 /// \brief Declare the implicit copy constructor for the given class.
3733 /// \param ClassDecl The class declaration into which the implicit
3734 /// copy constructor will be added.
3736 /// \returns The implicitly-declared copy constructor.
3737 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
3739 /// DefineImplicitCopyConstructor - Checks for feasibility of
3740 /// defining this constructor as the copy constructor.
3741 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3742 CXXConstructorDecl *Constructor);
3744 /// \brief Declare the implicit move constructor for the given class.
3746 /// \param ClassDecl The Class declaration into which the implicit
3747 /// move constructor will be added.
3749 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3751 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3753 /// DefineImplicitMoveConstructor - Checks for feasibility of
3754 /// defining this constructor as the move constructor.
3755 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3756 CXXConstructorDecl *Constructor);
3758 /// \brief Declare the implicit copy assignment operator for the given class.
3760 /// \param ClassDecl The class declaration into which the implicit
3761 /// copy assignment operator will be added.
3763 /// \returns The implicitly-declared copy assignment operator.
3764 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3766 /// \brief Defines an implicitly-declared copy assignment operator.
3767 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3768 CXXMethodDecl *MethodDecl);
3770 /// \brief Declare the implicit move assignment operator for the given class.
3772 /// \param ClassDecl The Class declaration into which the implicit
3773 /// move assignment operator will be added.
3775 /// \returns The implicitly-declared move assignment operator, or NULL if it
3776 /// wasn't declared.
3777 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3779 /// \brief Defines an implicitly-declared move assignment operator.
3780 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3781 CXXMethodDecl *MethodDecl);
3783 /// \brief Force the declaration of any implicitly-declared members of this
3785 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3787 /// \brief Determine whether the given function is an implicitly-deleted
3788 /// special member function.
3789 bool isImplicitlyDeleted(FunctionDecl *FD);
3791 /// \brief Check whether 'this' shows up in the type of a static member
3792 /// function after the (naturally empty) cv-qualifier-seq would be.
3794 /// \returns true if an error occurred.
3795 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
3797 /// \brief Whether this' shows up in the exception specification of a static
3798 /// member function.
3799 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
3801 /// \brief Check whether 'this' shows up in the attributes of the given
3802 /// static member function.
3804 /// \returns true if an error occurred.
3805 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
3807 /// MaybeBindToTemporary - If the passed in expression has a record type with
3808 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3809 /// it simply returns the passed in expression.
3810 ExprResult MaybeBindToTemporary(Expr *E);
3812 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3813 MultiExprArg ArgsPtr,
3815 SmallVectorImpl<Expr*> &ConvertedArgs,
3816 bool AllowExplicit = false,
3817 bool IsListInitialization = false);
3819 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
3820 SourceLocation NameLoc,
3821 IdentifierInfo &Name);
3823 ParsedType getDestructorName(SourceLocation TildeLoc,
3824 IdentifierInfo &II, SourceLocation NameLoc,
3825 Scope *S, CXXScopeSpec &SS,
3826 ParsedType ObjectType,
3827 bool EnteringContext);
3829 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
3831 // Checks that reinterpret casts don't have undefined behavior.
3832 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
3833 bool IsDereference, SourceRange Range);
3835 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
3836 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
3837 tok::TokenKind Kind,
3838 SourceLocation LAngleBracketLoc,
3840 SourceLocation RAngleBracketLoc,
3841 SourceLocation LParenLoc,
3843 SourceLocation RParenLoc);
3845 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
3846 tok::TokenKind Kind,
3849 SourceRange AngleBrackets,
3850 SourceRange Parens);
3852 ExprResult BuildCXXTypeId(QualType TypeInfoType,
3853 SourceLocation TypeidLoc,
3854 TypeSourceInfo *Operand,
3855 SourceLocation RParenLoc);
3856 ExprResult BuildCXXTypeId(QualType TypeInfoType,
3857 SourceLocation TypeidLoc,
3859 SourceLocation RParenLoc);
3861 /// ActOnCXXTypeid - Parse typeid( something ).
3862 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
3863 SourceLocation LParenLoc, bool isType,
3865 SourceLocation RParenLoc);
3867 ExprResult BuildCXXUuidof(QualType TypeInfoType,
3868 SourceLocation TypeidLoc,
3869 TypeSourceInfo *Operand,
3870 SourceLocation RParenLoc);
3871 ExprResult BuildCXXUuidof(QualType TypeInfoType,
3872 SourceLocation TypeidLoc,
3874 SourceLocation RParenLoc);
3876 /// ActOnCXXUuidof - Parse __uuidof( something ).
3877 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
3878 SourceLocation LParenLoc, bool isType,
3880 SourceLocation RParenLoc);
3883 //// ActOnCXXThis - Parse 'this' pointer.
3884 ExprResult ActOnCXXThis(SourceLocation loc);
3886 /// \brief Try to retrieve the type of the 'this' pointer.
3888 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
3889 QualType getCurrentThisType();
3891 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
3892 /// current context not being a non-static member function. In such cases,
3893 /// this provides the type used for 'this'.
3894 QualType CXXThisTypeOverride;
3896 /// \brief RAII object used to temporarily allow the C++ 'this' expression
3897 /// to be used, with the given qualifiers on the current class type.
3898 class CXXThisScopeRAII {
3900 QualType OldCXXThisTypeOverride;
3904 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
3905 /// using the given declaration (which is either a class template or a
3906 /// class) along with the given qualifiers.
3907 /// along with the qualifiers placed on '*this'.
3908 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
3909 bool Enabled = true);
3911 ~CXXThisScopeRAII();
3914 /// \brief Make sure the value of 'this' is actually available in the current
3915 /// context, if it is a potentially evaluated context.
3917 /// \param Loc The location at which the capture of 'this' occurs.
3919 /// \param Explicit Whether 'this' is explicitly captured in a lambda
3921 void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false);
3923 /// \brief Determine whether the given type is the type of *this that is used
3924 /// outside of the body of a member function for a type that is currently
3926 bool isThisOutsideMemberFunctionBody(QualType BaseType);
3928 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
3929 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3932 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
3933 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3935 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
3936 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
3938 //// ActOnCXXThrow - Parse throw expressions.
3939 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
3940 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
3941 bool IsThrownVarInScope);
3942 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
3943 bool IsThrownVarInScope);
3945 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
3946 /// Can be interpreted either as function-style casting ("int(x)")
3947 /// or class type construction ("ClassType(x,y,z)")
3948 /// or creation of a value-initialized type ("int()").
3949 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
3950 SourceLocation LParenLoc,
3952 SourceLocation RParenLoc);
3954 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
3955 SourceLocation LParenLoc,
3957 SourceLocation RParenLoc);
3959 /// ActOnCXXNew - Parsed a C++ 'new' expression.
3960 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
3961 SourceLocation PlacementLParen,
3962 MultiExprArg PlacementArgs,
3963 SourceLocation PlacementRParen,
3964 SourceRange TypeIdParens, Declarator &D,
3966 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
3967 SourceLocation PlacementLParen,
3968 MultiExprArg PlacementArgs,
3969 SourceLocation PlacementRParen,
3970 SourceRange TypeIdParens,
3972 TypeSourceInfo *AllocTypeInfo,
3974 SourceRange DirectInitRange,
3976 bool TypeMayContainAuto = true);
3978 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
3980 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
3981 bool UseGlobal, QualType AllocType, bool IsArray,
3982 Expr **PlaceArgs, unsigned NumPlaceArgs,
3983 FunctionDecl *&OperatorNew,
3984 FunctionDecl *&OperatorDelete);
3985 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
3986 DeclarationName Name, Expr** Args,
3987 unsigned NumArgs, DeclContext *Ctx,
3988 bool AllowMissing, FunctionDecl *&Operator,
3989 bool Diagnose = true);
3990 void DeclareGlobalNewDelete();
3991 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
3993 bool addMallocAttr = false);
3995 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3996 DeclarationName Name, FunctionDecl* &Operator,
3997 bool Diagnose = true);
3999 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4000 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4001 bool UseGlobal, bool ArrayForm,
4004 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4005 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4006 SourceLocation StmtLoc,
4007 bool ConvertToBoolean);
4009 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4010 Expr *Operand, SourceLocation RParen);
4011 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4012 SourceLocation RParen);
4014 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
4015 /// pseudo-functions.
4016 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
4017 SourceLocation KWLoc,
4019 SourceLocation RParen);
4021 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
4022 SourceLocation KWLoc,
4024 SourceLocation RParen);
4026 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
4027 /// pseudo-functions.
4028 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
4029 SourceLocation KWLoc,
4032 SourceLocation RParen);
4034 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
4035 SourceLocation KWLoc,
4036 TypeSourceInfo *LhsT,
4037 TypeSourceInfo *RhsT,
4038 SourceLocation RParen);
4040 /// \brief Parsed one of the type trait support pseudo-functions.
4041 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4042 ArrayRef<ParsedType> Args,
4043 SourceLocation RParenLoc);
4044 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4045 ArrayRef<TypeSourceInfo *> Args,
4046 SourceLocation RParenLoc);
4048 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4049 /// pseudo-functions.
4050 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4051 SourceLocation KWLoc,
4054 SourceLocation RParen);
4056 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4057 SourceLocation KWLoc,
4058 TypeSourceInfo *TSInfo,
4060 SourceLocation RParen);
4062 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4063 /// pseudo-functions.
4064 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4065 SourceLocation KWLoc,
4067 SourceLocation RParen);
4069 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4070 SourceLocation KWLoc,
4072 SourceLocation RParen);
4074 ExprResult ActOnStartCXXMemberReference(Scope *S,
4076 SourceLocation OpLoc,
4077 tok::TokenKind OpKind,
4078 ParsedType &ObjectType,
4079 bool &MayBePseudoDestructor);
4081 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
4083 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4084 SourceLocation OpLoc,
4085 tok::TokenKind OpKind,
4086 const CXXScopeSpec &SS,
4087 TypeSourceInfo *ScopeType,
4088 SourceLocation CCLoc,
4089 SourceLocation TildeLoc,
4090 PseudoDestructorTypeStorage DestroyedType,
4091 bool HasTrailingLParen);
4093 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4094 SourceLocation OpLoc,
4095 tok::TokenKind OpKind,
4097 UnqualifiedId &FirstTypeName,
4098 SourceLocation CCLoc,
4099 SourceLocation TildeLoc,
4100 UnqualifiedId &SecondTypeName,
4101 bool HasTrailingLParen);
4103 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4104 SourceLocation OpLoc,
4105 tok::TokenKind OpKind,
4106 SourceLocation TildeLoc,
4108 bool HasTrailingLParen);
4110 /// MaybeCreateExprWithCleanups - If the current full-expression
4111 /// requires any cleanups, surround it with a ExprWithCleanups node.
4112 /// Otherwise, just returns the passed-in expression.
4113 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4114 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4115 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4117 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4118 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4119 : SourceLocation());
4121 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4122 bool DiscardedValue = false,
4123 bool IsConstexpr = false);
4124 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4126 // Marks SS invalid if it represents an incomplete type.
4127 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4129 DeclContext *computeDeclContext(QualType T);
4130 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4131 bool EnteringContext = false);
4132 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4133 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4134 bool isUnknownSpecialization(const CXXScopeSpec &SS);
4136 /// \brief The parser has parsed a global nested-name-specifier '::'.
4138 /// \param S The scope in which this nested-name-specifier occurs.
4140 /// \param CCLoc The location of the '::'.
4142 /// \param SS The nested-name-specifier, which will be updated in-place
4143 /// to reflect the parsed nested-name-specifier.
4145 /// \returns true if an error occurred, false otherwise.
4146 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
4149 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
4150 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4152 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4153 SourceLocation IdLoc,
4155 ParsedType ObjectType);
4157 bool BuildCXXNestedNameSpecifier(Scope *S,
4158 IdentifierInfo &Identifier,
4159 SourceLocation IdentifierLoc,
4160 SourceLocation CCLoc,
4161 QualType ObjectType,
4162 bool EnteringContext,
4164 NamedDecl *ScopeLookupResult,
4165 bool ErrorRecoveryLookup);
4167 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4169 /// \param S The scope in which this nested-name-specifier occurs.
4171 /// \param Identifier The identifier preceding the '::'.
4173 /// \param IdentifierLoc The location of the identifier.
4175 /// \param CCLoc The location of the '::'.
4177 /// \param ObjectType The type of the object, if we're parsing
4178 /// nested-name-specifier in a member access expression.
4180 /// \param EnteringContext Whether we're entering the context nominated by
4181 /// this nested-name-specifier.
4183 /// \param SS The nested-name-specifier, which is both an input
4184 /// parameter (the nested-name-specifier before this type) and an
4185 /// output parameter (containing the full nested-name-specifier,
4186 /// including this new type).
4188 /// \returns true if an error occurred, false otherwise.
4189 bool ActOnCXXNestedNameSpecifier(Scope *S,
4190 IdentifierInfo &Identifier,
4191 SourceLocation IdentifierLoc,
4192 SourceLocation CCLoc,
4193 ParsedType ObjectType,
4194 bool EnteringContext,
4197 ExprResult ActOnDecltypeExpression(Expr *E);
4199 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4201 SourceLocation ColonColonLoc);
4203 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4204 IdentifierInfo &Identifier,
4205 SourceLocation IdentifierLoc,
4206 SourceLocation ColonLoc,
4207 ParsedType ObjectType,
4208 bool EnteringContext);
4210 /// \brief The parser has parsed a nested-name-specifier
4211 /// 'template[opt] template-name < template-args >::'.
4213 /// \param S The scope in which this nested-name-specifier occurs.
4215 /// \param SS The nested-name-specifier, which is both an input
4216 /// parameter (the nested-name-specifier before this type) and an
4217 /// output parameter (containing the full nested-name-specifier,
4218 /// including this new type).
4220 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4221 /// \param TemplateName the template name.
4222 /// \param TemplateNameLoc The location of the template name.
4223 /// \param LAngleLoc The location of the opening angle bracket ('<').
4224 /// \param TemplateArgs The template arguments.
4225 /// \param RAngleLoc The location of the closing angle bracket ('>').
4226 /// \param CCLoc The location of the '::'.
4228 /// \param EnteringContext Whether we're entering the context of the
4229 /// nested-name-specifier.
4232 /// \returns true if an error occurred, false otherwise.
4233 bool ActOnCXXNestedNameSpecifier(Scope *S,
4235 SourceLocation TemplateKWLoc,
4236 TemplateTy TemplateName,
4237 SourceLocation TemplateNameLoc,
4238 SourceLocation LAngleLoc,
4239 ASTTemplateArgsPtr TemplateArgs,
4240 SourceLocation RAngleLoc,
4241 SourceLocation CCLoc,
4242 bool EnteringContext);
4244 /// \brief Given a C++ nested-name-specifier, produce an annotation value
4245 /// that the parser can use later to reconstruct the given
4246 /// nested-name-specifier.
4248 /// \param SS A nested-name-specifier.
4250 /// \returns A pointer containing all of the information in the
4251 /// nested-name-specifier \p SS.
4252 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4254 /// \brief Given an annotation pointer for a nested-name-specifier, restore
4255 /// the nested-name-specifier structure.
4257 /// \param Annotation The annotation pointer, produced by
4258 /// \c SaveNestedNameSpecifierAnnotation().
4260 /// \param AnnotationRange The source range corresponding to the annotation.
4262 /// \param SS The nested-name-specifier that will be updated with the contents
4263 /// of the annotation pointer.
4264 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4265 SourceRange AnnotationRange,
4268 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4270 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4271 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4272 /// After this method is called, according to [C++ 3.4.3p3], names should be
4273 /// looked up in the declarator-id's scope, until the declarator is parsed and
4274 /// ActOnCXXExitDeclaratorScope is called.
4275 /// The 'SS' should be a non-empty valid CXXScopeSpec.
4276 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4278 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4279 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4280 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4281 /// Used to indicate that names should revert to being looked up in the
4283 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4285 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4286 /// initializer for the declaration 'Dcl'.
4287 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4288 /// static data member of class X, names should be looked up in the scope of
4290 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4292 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4293 /// initializer for the declaration 'Dcl'.
4294 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4296 /// \brief Create a new lambda closure type.
4297 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4298 TypeSourceInfo *Info,
4299 bool KnownDependent);
4301 /// \brief Start the definition of a lambda expression.
4302 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4303 SourceRange IntroducerRange,
4304 TypeSourceInfo *MethodType,
4305 SourceLocation EndLoc,
4306 ArrayRef<ParmVarDecl *> Params);
4308 /// \brief Introduce the scope for a lambda expression.
4309 sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator,
4310 SourceRange IntroducerRange,
4311 LambdaCaptureDefault CaptureDefault,
4312 bool ExplicitParams,
4313 bool ExplicitResultType,
4316 /// \brief Note that we have finished the explicit captures for the
4318 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4320 /// \brief Introduce the lambda parameters into scope.
4321 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4323 /// \brief Deduce a block or lambda's return type based on the return
4324 /// statements present in the body.
4325 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4327 /// ActOnStartOfLambdaDefinition - This is called just before we start
4328 /// parsing the body of a lambda; it analyzes the explicit captures and
4329 /// arguments, and sets up various data-structures for the body of the
4331 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4332 Declarator &ParamInfo, Scope *CurScope);
4334 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4335 /// is invoked to pop the information about the lambda.
4336 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4337 bool IsInstantiation = false);
4339 /// ActOnLambdaExpr - This is called when the body of a lambda expression
4340 /// was successfully completed.
4341 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4343 bool IsInstantiation = false);
4345 /// \brief Define the "body" of the conversion from a lambda object to a
4346 /// function pointer.
4348 /// This routine doesn't actually define a sensible body; rather, it fills
4349 /// in the initialization expression needed to copy the lambda object into
4350 /// the block, and IR generation actually generates the real body of the
4351 /// block pointer conversion.
4352 void DefineImplicitLambdaToFunctionPointerConversion(
4353 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4355 /// \brief Define the "body" of the conversion from a lambda object to a
4358 /// This routine doesn't actually define a sensible body; rather, it fills
4359 /// in the initialization expression needed to copy the lambda object into
4360 /// the block, and IR generation actually generates the real body of the
4361 /// block pointer conversion.
4362 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4363 CXXConversionDecl *Conv);
4365 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4366 SourceLocation ConvLocation,
4367 CXXConversionDecl *Conv,
4370 // ParseObjCStringLiteral - Parse Objective-C string literals.
4371 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4373 unsigned NumStrings);
4375 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4377 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4378 /// numeric literal expression. Type of the expression will be "NSNumber *"
4379 /// or "id" if NSNumber is unavailable.
4380 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4381 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4383 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4385 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4386 /// '@' prefixed parenthesized expression. The type of the expression will
4387 /// either be "NSNumber *" or "NSString *" depending on the type of
4388 /// ValueType, which is allowed to be a built-in numeric type or
4389 /// "char *" or "const char *".
4390 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4392 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4394 ObjCMethodDecl *getterMethod,
4395 ObjCMethodDecl *setterMethod);
4397 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4398 ObjCDictionaryElement *Elements,
4399 unsigned NumElements);
4401 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4402 TypeSourceInfo *EncodedTypeInfo,
4403 SourceLocation RParenLoc);
4404 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4405 CXXConversionDecl *Method,
4406 bool HadMultipleCandidates);
4408 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4409 SourceLocation EncodeLoc,
4410 SourceLocation LParenLoc,
4412 SourceLocation RParenLoc);
4414 /// ParseObjCSelectorExpression - Build selector expression for \@selector
4415 ExprResult ParseObjCSelectorExpression(Selector Sel,
4416 SourceLocation AtLoc,
4417 SourceLocation SelLoc,
4418 SourceLocation LParenLoc,
4419 SourceLocation RParenLoc);
4421 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4422 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4423 SourceLocation AtLoc,
4424 SourceLocation ProtoLoc,
4425 SourceLocation LParenLoc,
4426 SourceLocation ProtoIdLoc,
4427 SourceLocation RParenLoc);
4429 //===--------------------------------------------------------------------===//
4432 Decl *ActOnStartLinkageSpecification(Scope *S,
4433 SourceLocation ExternLoc,
4434 SourceLocation LangLoc,
4436 SourceLocation LBraceLoc);
4437 Decl *ActOnFinishLinkageSpecification(Scope *S,
4439 SourceLocation RBraceLoc);
4442 //===--------------------------------------------------------------------===//
4445 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4446 const CXXScopeSpec *SS = 0);
4448 bool ActOnAccessSpecifier(AccessSpecifier Access,
4449 SourceLocation ASLoc,
4450 SourceLocation ColonLoc,
4451 AttributeList *Attrs = 0);
4453 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4455 MultiTemplateParamsArg TemplateParameterLists,
4456 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4457 InClassInitStyle InitStyle);
4458 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
4461 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4464 IdentifierInfo *MemberOrBase,
4465 ParsedType TemplateTypeTy,
4467 SourceLocation IdLoc,
4468 SourceLocation LParenLoc,
4469 Expr **Args, unsigned NumArgs,
4470 SourceLocation RParenLoc,
4471 SourceLocation EllipsisLoc);
4473 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4476 IdentifierInfo *MemberOrBase,
4477 ParsedType TemplateTypeTy,
4479 SourceLocation IdLoc,
4481 SourceLocation EllipsisLoc);
4483 MemInitResult BuildMemInitializer(Decl *ConstructorD,
4486 IdentifierInfo *MemberOrBase,
4487 ParsedType TemplateTypeTy,
4489 SourceLocation IdLoc,
4491 SourceLocation EllipsisLoc);
4493 MemInitResult BuildMemberInitializer(ValueDecl *Member,
4495 SourceLocation IdLoc);
4497 MemInitResult BuildBaseInitializer(QualType BaseType,
4498 TypeSourceInfo *BaseTInfo,
4500 CXXRecordDecl *ClassDecl,
4501 SourceLocation EllipsisLoc);
4503 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
4505 CXXRecordDecl *ClassDecl);
4507 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4508 CXXCtorInitializer *Initializer);
4510 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4511 ArrayRef<CXXCtorInitializer *> Initializers = None);
4513 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
4516 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4517 /// mark all the non-trivial destructors of its members and bases as
4519 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
4520 CXXRecordDecl *Record);
4522 /// \brief The list of classes whose vtables have been used within
4523 /// this translation unit, and the source locations at which the
4524 /// first use occurred.
4525 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
4527 /// \brief The list of vtables that are required but have not yet been
4529 SmallVector<VTableUse, 16> VTableUses;
4531 /// \brief The set of classes whose vtables have been used within
4532 /// this translation unit, and a bit that will be true if the vtable is
4533 /// required to be emitted (otherwise, it should be emitted only if needed
4534 /// by code generation).
4535 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4537 /// \brief Load any externally-stored vtable uses.
4538 void LoadExternalVTableUses();
4540 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
4541 &ExternalSemaSource::ReadDynamicClasses, 2, 2>
4544 /// \brief A list of all of the dynamic classes in this translation
4546 DynamicClassesType DynamicClasses;
4548 /// \brief Note that the vtable for the given class was used at the
4550 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
4551 bool DefinitionRequired = false);
4553 /// \brief Mark the exception specifications of all virtual member functions
4554 /// in the given class as needed.
4555 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
4556 const CXXRecordDecl *RD);
4558 /// MarkVirtualMembersReferenced - Will mark all members of the given
4559 /// CXXRecordDecl referenced.
4560 void MarkVirtualMembersReferenced(SourceLocation Loc,
4561 const CXXRecordDecl *RD);
4563 /// \brief Define all of the vtables that have been used in this
4564 /// translation unit and reference any virtual members used by those
4567 /// \returns true if any work was done, false otherwise.
4568 bool DefineUsedVTables();
4570 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
4572 void ActOnMemInitializers(Decl *ConstructorDecl,
4573 SourceLocation ColonLoc,
4574 ArrayRef<CXXCtorInitializer*> MemInits,
4577 void CheckCompletedCXXClass(CXXRecordDecl *Record);
4578 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4580 SourceLocation LBrac,
4581 SourceLocation RBrac,
4582 AttributeList *AttrList);
4583 void ActOnFinishCXXMemberDecls();
4585 void ActOnReenterTemplateScope(Scope *S, Decl *Template);
4586 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
4587 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
4588 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4589 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4590 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
4591 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4592 void ActOnFinishDelayedMemberInitializers(Decl *Record);
4593 void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
4594 bool IsInsideALocalClassWithinATemplateFunction();
4596 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4598 Expr *AssertMessageExpr,
4599 SourceLocation RParenLoc);
4600 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4602 StringLiteral *AssertMessageExpr,
4603 SourceLocation RParenLoc,
4606 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
4607 SourceLocation FriendLoc,
4608 TypeSourceInfo *TSInfo);
4609 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4610 MultiTemplateParamsArg TemplateParams);
4611 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
4612 MultiTemplateParamsArg TemplateParams);
4614 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
4616 void CheckConstructor(CXXConstructorDecl *Constructor);
4617 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
4619 bool CheckDestructor(CXXDestructorDecl *Destructor);
4620 void CheckConversionDeclarator(Declarator &D, QualType &R,
4622 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4624 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
4625 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
4626 const FunctionProtoType *T);
4627 void CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
4629 //===--------------------------------------------------------------------===//
4630 // C++ Derived Classes
4633 /// ActOnBaseSpecifier - Parsed a base specifier
4634 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4635 SourceRange SpecifierRange,
4636 bool Virtual, AccessSpecifier Access,
4637 TypeSourceInfo *TInfo,
4638 SourceLocation EllipsisLoc);
4640 BaseResult ActOnBaseSpecifier(Decl *classdecl,
4641 SourceRange SpecifierRange,
4642 ParsedAttributes &Attrs,
4643 bool Virtual, AccessSpecifier Access,
4644 ParsedType basetype,
4645 SourceLocation BaseLoc,
4646 SourceLocation EllipsisLoc);
4648 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4650 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4653 bool IsDerivedFrom(QualType Derived, QualType Base);
4654 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4656 // FIXME: I don't like this name.
4657 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
4659 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
4661 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4662 SourceLocation Loc, SourceRange Range,
4663 CXXCastPath *BasePath = 0,
4664 bool IgnoreAccess = false);
4665 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4666 unsigned InaccessibleBaseID,
4667 unsigned AmbigiousBaseConvID,
4668 SourceLocation Loc, SourceRange Range,
4669 DeclarationName Name,
4670 CXXCastPath *BasePath);
4672 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
4674 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4675 const CXXMethodDecl *Old);
4677 /// CheckOverridingFunctionReturnType - Checks whether the return types are
4678 /// covariant, according to C++ [class.virtual]p5.
4679 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4680 const CXXMethodDecl *Old);
4682 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
4683 /// spec is a subset of base spec.
4684 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4685 const CXXMethodDecl *Old);
4687 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
4689 /// CheckOverrideControl - Check C++11 override control semantics.
4690 void CheckOverrideControl(Decl *D);
4692 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
4693 /// overrides a virtual member function marked 'final', according to
4694 /// C++11 [class.virtual]p4.
4695 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
4696 const CXXMethodDecl *Old);
4699 //===--------------------------------------------------------------------===//
4700 // C++ Access Control
4710 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
4711 NamedDecl *PrevMemberDecl,
4712 AccessSpecifier LexicalAS);
4714 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
4715 DeclAccessPair FoundDecl);
4716 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
4717 DeclAccessPair FoundDecl);
4718 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
4719 SourceRange PlacementRange,
4720 CXXRecordDecl *NamingClass,
4721 DeclAccessPair FoundDecl,
4722 bool Diagnose = true);
4723 AccessResult CheckConstructorAccess(SourceLocation Loc,
4724 CXXConstructorDecl *D,
4725 const InitializedEntity &Entity,
4726 AccessSpecifier Access,
4727 bool IsCopyBindingRefToTemp = false);
4728 AccessResult CheckConstructorAccess(SourceLocation Loc,
4729 CXXConstructorDecl *D,
4730 const InitializedEntity &Entity,
4731 AccessSpecifier Access,
4732 const PartialDiagnostic &PDiag);
4733 AccessResult CheckDestructorAccess(SourceLocation Loc,
4734 CXXDestructorDecl *Dtor,
4735 const PartialDiagnostic &PDiag,
4736 QualType objectType = QualType());
4737 AccessResult CheckFriendAccess(NamedDecl *D);
4738 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
4741 DeclAccessPair FoundDecl);
4742 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
4743 DeclAccessPair FoundDecl);
4744 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
4745 QualType Base, QualType Derived,
4746 const CXXBasePath &Path,
4748 bool ForceCheck = false,
4749 bool ForceUnprivileged = false);
4750 void CheckLookupAccess(const LookupResult &R);
4751 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
4752 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
4753 AccessSpecifier access,
4754 QualType objectType);
4756 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
4757 const MultiLevelTemplateArgumentList &TemplateArgs);
4758 void PerformDependentDiagnostics(const DeclContext *Pattern,
4759 const MultiLevelTemplateArgumentList &TemplateArgs);
4761 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4763 /// \brief When true, access checking violations are treated as SFINAE
4764 /// failures rather than hard errors.
4765 bool AccessCheckingSFINAE;
4767 enum AbstractDiagSelID {
4771 AbstractVariableType,
4777 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4778 TypeDiagnoser &Diagnoser);
4779 template<typename T1>
4780 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4783 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
4784 return RequireNonAbstractType(Loc, T, Diagnoser);
4787 template<typename T1, typename T2>
4788 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4790 const T1 &Arg1, const T2 &Arg2) {
4791 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
4792 return RequireNonAbstractType(Loc, T, Diagnoser);
4795 template<typename T1, typename T2, typename T3>
4796 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4798 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
4799 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
4800 return RequireNonAbstractType(Loc, T, Diagnoser);
4803 void DiagnoseAbstractType(const CXXRecordDecl *RD);
4805 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
4806 AbstractDiagSelID SelID = AbstractNone);
4808 //===--------------------------------------------------------------------===//
4809 // C++ Overloaded Operators [C++ 13.5]
4812 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
4814 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
4816 //===--------------------------------------------------------------------===//
4817 // C++ Templates [C++ 14]
4819 void FilterAcceptableTemplateNames(LookupResult &R,
4820 bool AllowFunctionTemplates = true);
4821 bool hasAnyAcceptableTemplateNames(LookupResult &R,
4822 bool AllowFunctionTemplates = true);
4824 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
4825 QualType ObjectType, bool EnteringContext,
4826 bool &MemberOfUnknownSpecialization);
4828 TemplateNameKind isTemplateName(Scope *S,
4830 bool hasTemplateKeyword,
4831 UnqualifiedId &Name,
4832 ParsedType ObjectType,
4833 bool EnteringContext,
4834 TemplateTy &Template,
4835 bool &MemberOfUnknownSpecialization);
4837 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
4838 SourceLocation IILoc,
4840 const CXXScopeSpec *SS,
4841 TemplateTy &SuggestedTemplate,
4842 TemplateNameKind &SuggestedKind);
4844 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
4845 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
4847 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
4848 SourceLocation EllipsisLoc,
4849 SourceLocation KeyLoc,
4850 IdentifierInfo *ParamName,
4851 SourceLocation ParamNameLoc,
4852 unsigned Depth, unsigned Position,
4853 SourceLocation EqualLoc,
4854 ParsedType DefaultArg);
4856 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
4857 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
4860 SourceLocation EqualLoc,
4862 Decl *ActOnTemplateTemplateParameter(Scope *S,
4863 SourceLocation TmpLoc,
4864 TemplateParameterList *Params,
4865 SourceLocation EllipsisLoc,
4866 IdentifierInfo *ParamName,
4867 SourceLocation ParamNameLoc,
4870 SourceLocation EqualLoc,
4871 ParsedTemplateArgument DefaultArg);
4873 TemplateParameterList *
4874 ActOnTemplateParameterList(unsigned Depth,
4875 SourceLocation ExportLoc,
4876 SourceLocation TemplateLoc,
4877 SourceLocation LAngleLoc,
4878 Decl **Params, unsigned NumParams,
4879 SourceLocation RAngleLoc);
4881 /// \brief The context in which we are checking a template parameter
4883 enum TemplateParamListContext {
4885 TPC_FunctionTemplate,
4886 TPC_ClassTemplateMember,
4887 TPC_FriendFunctionTemplate,
4888 TPC_FriendFunctionTemplateDefinition,
4889 TPC_TypeAliasTemplate
4892 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
4893 TemplateParameterList *OldParams,
4894 TemplateParamListContext TPC);
4895 TemplateParameterList *
4896 MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
4897 SourceLocation DeclLoc,
4898 const CXXScopeSpec &SS,
4899 TemplateParameterList **ParamLists,
4900 unsigned NumParamLists,
4902 bool &IsExplicitSpecialization,
4905 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
4906 SourceLocation KWLoc, CXXScopeSpec &SS,
4907 IdentifierInfo *Name, SourceLocation NameLoc,
4908 AttributeList *Attr,
4909 TemplateParameterList *TemplateParams,
4911 SourceLocation ModulePrivateLoc,
4912 unsigned NumOuterTemplateParamLists,
4913 TemplateParameterList **OuterTemplateParamLists);
4915 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
4916 TemplateArgumentListInfo &Out);
4918 void NoteAllFoundTemplates(TemplateName Name);
4920 QualType CheckTemplateIdType(TemplateName Template,
4921 SourceLocation TemplateLoc,
4922 TemplateArgumentListInfo &TemplateArgs);
4925 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4926 TemplateTy Template, SourceLocation TemplateLoc,
4927 SourceLocation LAngleLoc,
4928 ASTTemplateArgsPtr TemplateArgs,
4929 SourceLocation RAngleLoc,
4930 bool IsCtorOrDtorName = false);
4932 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
4933 /// such as \c class T::template apply<U>.
4934 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
4935 TypeSpecifierType TagSpec,
4936 SourceLocation TagLoc,
4938 SourceLocation TemplateKWLoc,
4939 TemplateTy TemplateD,
4940 SourceLocation TemplateLoc,
4941 SourceLocation LAngleLoc,
4942 ASTTemplateArgsPtr TemplateArgsIn,
4943 SourceLocation RAngleLoc);
4946 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
4947 SourceLocation TemplateKWLoc,
4950 const TemplateArgumentListInfo *TemplateArgs);
4952 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4953 SourceLocation TemplateKWLoc,
4954 const DeclarationNameInfo &NameInfo,
4955 const TemplateArgumentListInfo *TemplateArgs);
4957 TemplateNameKind ActOnDependentTemplateName(Scope *S,
4959 SourceLocation TemplateKWLoc,
4960 UnqualifiedId &Name,
4961 ParsedType ObjectType,
4962 bool EnteringContext,
4963 TemplateTy &Template);
4966 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
4967 SourceLocation KWLoc,
4968 SourceLocation ModulePrivateLoc,
4970 TemplateTy Template,
4971 SourceLocation TemplateNameLoc,
4972 SourceLocation LAngleLoc,
4973 ASTTemplateArgsPtr TemplateArgs,
4974 SourceLocation RAngleLoc,
4975 AttributeList *Attr,
4976 MultiTemplateParamsArg TemplateParameterLists);
4978 Decl *ActOnTemplateDeclarator(Scope *S,
4979 MultiTemplateParamsArg TemplateParameterLists,
4982 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4983 MultiTemplateParamsArg TemplateParameterLists,
4987 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4988 TemplateSpecializationKind NewTSK,
4989 NamedDecl *PrevDecl,
4990 TemplateSpecializationKind PrevTSK,
4991 SourceLocation PrevPtOfInstantiation,
4994 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4995 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4996 LookupResult &Previous);
4998 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4999 TemplateArgumentListInfo *ExplicitTemplateArgs,
5000 LookupResult &Previous);
5001 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5004 ActOnExplicitInstantiation(Scope *S,
5005 SourceLocation ExternLoc,
5006 SourceLocation TemplateLoc,
5008 SourceLocation KWLoc,
5009 const CXXScopeSpec &SS,
5010 TemplateTy Template,
5011 SourceLocation TemplateNameLoc,
5012 SourceLocation LAngleLoc,
5013 ASTTemplateArgsPtr TemplateArgs,
5014 SourceLocation RAngleLoc,
5015 AttributeList *Attr);
5018 ActOnExplicitInstantiation(Scope *S,
5019 SourceLocation ExternLoc,
5020 SourceLocation TemplateLoc,
5022 SourceLocation KWLoc,
5024 IdentifierInfo *Name,
5025 SourceLocation NameLoc,
5026 AttributeList *Attr);
5028 DeclResult ActOnExplicitInstantiation(Scope *S,
5029 SourceLocation ExternLoc,
5030 SourceLocation TemplateLoc,
5034 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5035 SourceLocation TemplateLoc,
5036 SourceLocation RAngleLoc,
5038 SmallVectorImpl<TemplateArgument> &Converted);
5040 /// \brief Specifies the context in which a particular template
5041 /// argument is being checked.
5042 enum CheckTemplateArgumentKind {
5043 /// \brief The template argument was specified in the code or was
5044 /// instantiated with some deduced template arguments.
5047 /// \brief The template argument was deduced via template argument
5051 /// \brief The template argument was deduced from an array bound
5052 /// via template argument deduction.
5053 CTAK_DeducedFromArrayBound
5056 bool CheckTemplateArgument(NamedDecl *Param,
5057 const TemplateArgumentLoc &Arg,
5058 NamedDecl *Template,
5059 SourceLocation TemplateLoc,
5060 SourceLocation RAngleLoc,
5061 unsigned ArgumentPackIndex,
5062 SmallVectorImpl<TemplateArgument> &Converted,
5063 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5065 /// \brief Check that the given template arguments can be be provided to
5066 /// the given template, converting the arguments along the way.
5068 /// \param Template The template to which the template arguments are being
5071 /// \param TemplateLoc The location of the template name in the source.
5073 /// \param TemplateArgs The list of template arguments. If the template is
5074 /// a template template parameter, this function may extend the set of
5075 /// template arguments to also include substituted, defaulted template
5078 /// \param PartialTemplateArgs True if the list of template arguments is
5079 /// intentionally partial, e.g., because we're checking just the initial
5080 /// set of template arguments.
5082 /// \param Converted Will receive the converted, canonicalized template
5086 /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate
5087 /// when the template arguments contain a pack expansion that is being
5088 /// expanded into a fixed parameter list.
5090 /// \returns True if an error occurred, false otherwise.
5091 bool CheckTemplateArgumentList(TemplateDecl *Template,
5092 SourceLocation TemplateLoc,
5093 TemplateArgumentListInfo &TemplateArgs,
5094 bool PartialTemplateArgs,
5095 SmallVectorImpl<TemplateArgument> &Converted,
5096 bool *ExpansionIntoFixedList = 0);
5098 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5099 const TemplateArgumentLoc &Arg,
5100 SmallVectorImpl<TemplateArgument> &Converted);
5102 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5103 TypeSourceInfo *Arg);
5104 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5105 QualType InstantiatedParamType, Expr *Arg,
5106 TemplateArgument &Converted,
5107 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5108 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5109 const TemplateArgumentLoc &Arg,
5110 unsigned ArgumentPackIndex);
5113 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5115 SourceLocation Loc);
5117 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5118 SourceLocation Loc);
5120 /// \brief Enumeration describing how template parameter lists are compared
5122 enum TemplateParameterListEqualKind {
5123 /// \brief We are matching the template parameter lists of two templates
5124 /// that might be redeclarations.
5127 /// template<typename T> struct X;
5128 /// template<typename T> struct X;
5132 /// \brief We are matching the template parameter lists of two template
5133 /// template parameters as part of matching the template parameter lists
5134 /// of two templates that might be redeclarations.
5137 /// template<template<int I> class TT> struct X;
5138 /// template<template<int Value> class Other> struct X;
5140 TPL_TemplateTemplateParmMatch,
5142 /// \brief We are matching the template parameter lists of a template
5143 /// template argument against the template parameter lists of a template
5144 /// template parameter.
5147 /// template<template<int Value> class Metafun> struct X;
5148 /// template<int Value> struct integer_c;
5149 /// X<integer_c> xic;
5151 TPL_TemplateTemplateArgumentMatch
5154 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5155 TemplateParameterList *Old,
5157 TemplateParameterListEqualKind Kind,
5158 SourceLocation TemplateArgLoc
5159 = SourceLocation());
5161 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5163 /// \brief Called when the parser has parsed a C++ typename
5164 /// specifier, e.g., "typename T::type".
5166 /// \param S The scope in which this typename type occurs.
5167 /// \param TypenameLoc the location of the 'typename' keyword
5168 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5169 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5170 /// \param IdLoc the location of the identifier.
5172 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5173 const CXXScopeSpec &SS, const IdentifierInfo &II,
5174 SourceLocation IdLoc);
5176 /// \brief Called when the parser has parsed a C++ typename
5177 /// specifier that ends in a template-id, e.g.,
5178 /// "typename MetaFun::template apply<T1, T2>".
5180 /// \param S The scope in which this typename type occurs.
5181 /// \param TypenameLoc the location of the 'typename' keyword
5182 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5183 /// \param TemplateLoc the location of the 'template' keyword, if any.
5184 /// \param TemplateName The template name.
5185 /// \param TemplateNameLoc The location of the template name.
5186 /// \param LAngleLoc The location of the opening angle bracket ('<').
5187 /// \param TemplateArgs The template arguments.
5188 /// \param RAngleLoc The location of the closing angle bracket ('>').
5190 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5191 const CXXScopeSpec &SS,
5192 SourceLocation TemplateLoc,
5193 TemplateTy TemplateName,
5194 SourceLocation TemplateNameLoc,
5195 SourceLocation LAngleLoc,
5196 ASTTemplateArgsPtr TemplateArgs,
5197 SourceLocation RAngleLoc);
5199 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5200 SourceLocation KeywordLoc,
5201 NestedNameSpecifierLoc QualifierLoc,
5202 const IdentifierInfo &II,
5203 SourceLocation IILoc);
5205 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5207 DeclarationName Name);
5208 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5210 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5211 bool RebuildTemplateParamsInCurrentInstantiation(
5212 TemplateParameterList *Params);
5215 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5216 const TemplateArgumentList &Args);
5219 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5220 const TemplateArgument *Args,
5223 //===--------------------------------------------------------------------===//
5224 // C++ Variadic Templates (C++0x [temp.variadic])
5225 //===--------------------------------------------------------------------===//
5227 /// \brief The context in which an unexpanded parameter pack is
5228 /// being diagnosed.
5230 /// Note that the values of this enumeration line up with the first
5231 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5232 enum UnexpandedParameterPackContext {
5233 /// \brief An arbitrary expression.
5234 UPPC_Expression = 0,
5236 /// \brief The base type of a class type.
5239 /// \brief The type of an arbitrary declaration.
5240 UPPC_DeclarationType,
5242 /// \brief The type of a data member.
5243 UPPC_DataMemberType,
5245 /// \brief The size of a bit-field.
5248 /// \brief The expression in a static assertion.
5249 UPPC_StaticAssertExpression,
5251 /// \brief The fixed underlying type of an enumeration.
5252 UPPC_FixedUnderlyingType,
5254 /// \brief The enumerator value.
5255 UPPC_EnumeratorValue,
5257 /// \brief A using declaration.
5258 UPPC_UsingDeclaration,
5260 /// \brief A friend declaration.
5261 UPPC_FriendDeclaration,
5263 /// \brief A declaration qualifier.
5264 UPPC_DeclarationQualifier,
5266 /// \brief An initializer.
5269 /// \brief A default argument.
5270 UPPC_DefaultArgument,
5272 /// \brief The type of a non-type template parameter.
5273 UPPC_NonTypeTemplateParameterType,
5275 /// \brief The type of an exception.
5278 /// \brief Partial specialization.
5279 UPPC_PartialSpecialization,
5281 /// \brief Microsoft __if_exists.
5284 /// \brief Microsoft __if_not_exists.
5287 /// \brief Lambda expression.
5290 /// \brief Block expression,
5294 /// \brief Diagnose unexpanded parameter packs.
5296 /// \param Loc The location at which we should emit the diagnostic.
5298 /// \param UPPC The context in which we are diagnosing unexpanded
5299 /// parameter packs.
5301 /// \param Unexpanded the set of unexpanded parameter packs.
5303 /// \returns true if an error occurred, false otherwise.
5304 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5305 UnexpandedParameterPackContext UPPC,
5306 ArrayRef<UnexpandedParameterPack> Unexpanded);
5308 /// \brief If the given type contains an unexpanded parameter pack,
5309 /// diagnose the error.
5311 /// \param Loc The source location where a diagnostc should be emitted.
5313 /// \param T The type that is being checked for unexpanded parameter
5316 /// \returns true if an error occurred, false otherwise.
5317 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5318 UnexpandedParameterPackContext UPPC);
5320 /// \brief If the given expression contains an unexpanded parameter
5321 /// pack, diagnose the error.
5323 /// \param E The expression that is being checked for unexpanded
5324 /// parameter packs.
5326 /// \returns true if an error occurred, false otherwise.
5327 bool DiagnoseUnexpandedParameterPack(Expr *E,
5328 UnexpandedParameterPackContext UPPC = UPPC_Expression);
5330 /// \brief If the given nested-name-specifier contains an unexpanded
5331 /// parameter pack, diagnose the error.
5333 /// \param SS The nested-name-specifier that is being checked for
5334 /// unexpanded parameter packs.
5336 /// \returns true if an error occurred, false otherwise.
5337 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5338 UnexpandedParameterPackContext UPPC);
5340 /// \brief If the given name contains an unexpanded parameter pack,
5341 /// diagnose the error.
5343 /// \param NameInfo The name (with source location information) that
5344 /// is being checked for unexpanded parameter packs.
5346 /// \returns true if an error occurred, false otherwise.
5347 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5348 UnexpandedParameterPackContext UPPC);
5350 /// \brief If the given template name contains an unexpanded parameter pack,
5351 /// diagnose the error.
5353 /// \param Loc The location of the template name.
5355 /// \param Template The template name that is being checked for unexpanded
5356 /// parameter packs.
5358 /// \returns true if an error occurred, false otherwise.
5359 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5360 TemplateName Template,
5361 UnexpandedParameterPackContext UPPC);
5363 /// \brief If the given template argument contains an unexpanded parameter
5364 /// pack, diagnose the error.
5366 /// \param Arg The template argument that is being checked for unexpanded
5367 /// parameter packs.
5369 /// \returns true if an error occurred, false otherwise.
5370 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5371 UnexpandedParameterPackContext UPPC);
5373 /// \brief Collect the set of unexpanded parameter packs within the given
5374 /// template argument.
5376 /// \param Arg The template argument that will be traversed to find
5377 /// unexpanded parameter packs.
5378 void collectUnexpandedParameterPacks(TemplateArgument Arg,
5379 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5381 /// \brief Collect the set of unexpanded parameter packs within the given
5382 /// template argument.
5384 /// \param Arg The template argument that will be traversed to find
5385 /// unexpanded parameter packs.
5386 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5387 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5389 /// \brief Collect the set of unexpanded parameter packs within the given
5392 /// \param T The type that will be traversed to find
5393 /// unexpanded parameter packs.
5394 void collectUnexpandedParameterPacks(QualType T,
5395 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5397 /// \brief Collect the set of unexpanded parameter packs within the given
5400 /// \param TL The type that will be traversed to find
5401 /// unexpanded parameter packs.
5402 void collectUnexpandedParameterPacks(TypeLoc TL,
5403 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5405 /// \brief Collect the set of unexpanded parameter packs within the given
5406 /// nested-name-specifier.
5408 /// \param SS The nested-name-specifier that will be traversed to find
5409 /// unexpanded parameter packs.
5410 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5411 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5413 /// \brief Collect the set of unexpanded parameter packs within the given
5416 /// \param NameInfo The name that will be traversed to find
5417 /// unexpanded parameter packs.
5418 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5419 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5421 /// \brief Invoked when parsing a template argument followed by an
5422 /// ellipsis, which creates a pack expansion.
5424 /// \param Arg The template argument preceding the ellipsis, which
5425 /// may already be invalid.
5427 /// \param EllipsisLoc The location of the ellipsis.
5428 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5429 SourceLocation EllipsisLoc);
5431 /// \brief Invoked when parsing a type followed by an ellipsis, which
5432 /// creates a pack expansion.
5434 /// \param Type The type preceding the ellipsis, which will become
5435 /// the pattern of the pack expansion.
5437 /// \param EllipsisLoc The location of the ellipsis.
5438 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5440 /// \brief Construct a pack expansion type from the pattern of the pack
5442 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5443 SourceLocation EllipsisLoc,
5444 Optional<unsigned> NumExpansions);
5446 /// \brief Construct a pack expansion type from the pattern of the pack
5448 QualType CheckPackExpansion(QualType Pattern,
5449 SourceRange PatternRange,
5450 SourceLocation EllipsisLoc,
5451 Optional<unsigned> NumExpansions);
5453 /// \brief Invoked when parsing an expression followed by an ellipsis, which
5454 /// creates a pack expansion.
5456 /// \param Pattern The expression preceding the ellipsis, which will become
5457 /// the pattern of the pack expansion.
5459 /// \param EllipsisLoc The location of the ellipsis.
5460 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5462 /// \brief Invoked when parsing an expression followed by an ellipsis, which
5463 /// creates a pack expansion.
5465 /// \param Pattern The expression preceding the ellipsis, which will become
5466 /// the pattern of the pack expansion.
5468 /// \param EllipsisLoc The location of the ellipsis.
5469 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
5470 Optional<unsigned> NumExpansions);
5472 /// \brief Determine whether we could expand a pack expansion with the
5473 /// given set of parameter packs into separate arguments by repeatedly
5474 /// transforming the pattern.
5476 /// \param EllipsisLoc The location of the ellipsis that identifies the
5479 /// \param PatternRange The source range that covers the entire pattern of
5480 /// the pack expansion.
5482 /// \param Unexpanded The set of unexpanded parameter packs within the
5485 /// \param ShouldExpand Will be set to \c true if the transformer should
5486 /// expand the corresponding pack expansions into separate arguments. When
5487 /// set, \c NumExpansions must also be set.
5489 /// \param RetainExpansion Whether the caller should add an unexpanded
5490 /// pack expansion after all of the expanded arguments. This is used
5491 /// when extending explicitly-specified template argument packs per
5492 /// C++0x [temp.arg.explicit]p9.
5494 /// \param NumExpansions The number of separate arguments that will be in
5495 /// the expanded form of the corresponding pack expansion. This is both an
5496 /// input and an output parameter, which can be set by the caller if the
5497 /// number of expansions is known a priori (e.g., due to a prior substitution)
5498 /// and will be set by the callee when the number of expansions is known.
5499 /// The callee must set this value when \c ShouldExpand is \c true; it may
5500 /// set this value in other cases.
5502 /// \returns true if an error occurred (e.g., because the parameter packs
5503 /// are to be instantiated with arguments of different lengths), false
5504 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
5506 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
5507 SourceRange PatternRange,
5508 ArrayRef<UnexpandedParameterPack> Unexpanded,
5509 const MultiLevelTemplateArgumentList &TemplateArgs,
5511 bool &RetainExpansion,
5512 Optional<unsigned> &NumExpansions);
5514 /// \brief Determine the number of arguments in the given pack expansion
5517 /// This routine assumes that the number of arguments in the expansion is
5518 /// consistent across all of the unexpanded parameter packs in its pattern.
5520 /// Returns an empty Optional if the type can't be expanded.
5521 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
5522 const MultiLevelTemplateArgumentList &TemplateArgs);
5524 /// \brief Determine whether the given declarator contains any unexpanded
5525 /// parameter packs.
5527 /// This routine is used by the parser to disambiguate function declarators
5528 /// with an ellipsis prior to the ')', e.g.,
5534 /// To determine whether we have an (unnamed) function parameter pack or
5535 /// a variadic function.
5537 /// \returns true if the declarator contains any unexpanded parameter packs,
5538 /// false otherwise.
5539 bool containsUnexpandedParameterPacks(Declarator &D);
5541 //===--------------------------------------------------------------------===//
5542 // C++ Template Argument Deduction (C++ [temp.deduct])
5543 //===--------------------------------------------------------------------===//
5545 /// \brief Describes the result of template argument deduction.
5547 /// The TemplateDeductionResult enumeration describes the result of
5548 /// template argument deduction, as returned from
5549 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
5550 /// structure provides additional information about the results of
5551 /// template argument deduction, e.g., the deduced template argument
5552 /// list (if successful) or the specific template parameters or
5553 /// deduced arguments that were involved in the failure.
5554 enum TemplateDeductionResult {
5555 /// \brief Template argument deduction was successful.
5557 /// \brief The declaration was invalid; do nothing.
5559 /// \brief Template argument deduction exceeded the maximum template
5560 /// instantiation depth (which has already been diagnosed).
5561 TDK_InstantiationDepth,
5562 /// \brief Template argument deduction did not deduce a value
5563 /// for every template parameter.
5565 /// \brief Template argument deduction produced inconsistent
5566 /// deduced values for the given template parameter.
5568 /// \brief Template argument deduction failed due to inconsistent
5569 /// cv-qualifiers on a template parameter type that would
5570 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
5571 /// but were given a non-const "X".
5573 /// \brief Substitution of the deduced template argument values
5574 /// resulted in an error.
5575 TDK_SubstitutionFailure,
5576 /// \brief A non-depnedent component of the parameter did not match the
5577 /// corresponding component of the argument.
5578 TDK_NonDeducedMismatch,
5579 /// \brief When performing template argument deduction for a function
5580 /// template, there were too many call arguments.
5581 TDK_TooManyArguments,
5582 /// \brief When performing template argument deduction for a function
5583 /// template, there were too few call arguments.
5584 TDK_TooFewArguments,
5585 /// \brief The explicitly-specified template arguments were not valid
5586 /// template arguments for the given template.
5587 TDK_InvalidExplicitArguments,
5588 /// \brief The arguments included an overloaded function name that could
5589 /// not be resolved to a suitable function.
5590 TDK_FailedOverloadResolution,
5591 /// \brief Deduction failed; that's all we know.
5592 TDK_MiscellaneousDeductionFailure
5595 TemplateDeductionResult
5596 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
5597 const TemplateArgumentList &TemplateArgs,
5598 sema::TemplateDeductionInfo &Info);
5600 TemplateDeductionResult
5601 SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5602 TemplateArgumentListInfo &ExplicitTemplateArgs,
5603 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5604 SmallVectorImpl<QualType> &ParamTypes,
5605 QualType *FunctionType,
5606 sema::TemplateDeductionInfo &Info);
5608 /// brief A function argument from which we performed template argument
5609 // deduction for a call.
5610 struct OriginalCallArg {
5611 OriginalCallArg(QualType OriginalParamType,
5613 QualType OriginalArgType)
5614 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
5615 OriginalArgType(OriginalArgType) { }
5617 QualType OriginalParamType;
5619 QualType OriginalArgType;
5622 TemplateDeductionResult
5623 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
5624 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5625 unsigned NumExplicitlySpecified,
5626 FunctionDecl *&Specialization,
5627 sema::TemplateDeductionInfo &Info,
5628 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
5630 TemplateDeductionResult
5631 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5632 TemplateArgumentListInfo *ExplicitTemplateArgs,
5633 ArrayRef<Expr *> Args,
5634 FunctionDecl *&Specialization,
5635 sema::TemplateDeductionInfo &Info);
5637 TemplateDeductionResult
5638 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5639 TemplateArgumentListInfo *ExplicitTemplateArgs,
5640 QualType ArgFunctionType,
5641 FunctionDecl *&Specialization,
5642 sema::TemplateDeductionInfo &Info,
5643 bool InOverloadResolution = false);
5645 TemplateDeductionResult
5646 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5648 CXXConversionDecl *&Specialization,
5649 sema::TemplateDeductionInfo &Info);
5651 TemplateDeductionResult
5652 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5653 TemplateArgumentListInfo *ExplicitTemplateArgs,
5654 FunctionDecl *&Specialization,
5655 sema::TemplateDeductionInfo &Info,
5656 bool InOverloadResolution = false);
5658 /// \brief Result type of DeduceAutoType.
5659 enum DeduceAutoResult {
5662 DAR_FailedAlreadyDiagnosed
5665 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
5667 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
5669 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
5670 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
5671 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
5672 bool Diagnose = true);
5674 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
5675 SourceLocation ReturnLoc,
5676 Expr *&RetExpr, AutoType *AT);
5678 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
5679 FunctionTemplateDecl *FT2,
5681 TemplatePartialOrderingContext TPOC,
5682 unsigned NumCallArguments);
5683 UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
5684 UnresolvedSetIterator SEnd,
5685 TemplatePartialOrderingContext TPOC,
5686 unsigned NumCallArguments,
5688 const PartialDiagnostic &NoneDiag,
5689 const PartialDiagnostic &AmbigDiag,
5690 const PartialDiagnostic &CandidateDiag,
5691 bool Complain = true,
5692 QualType TargetType = QualType());
5694 ClassTemplatePartialSpecializationDecl *
5695 getMoreSpecializedPartialSpecialization(
5696 ClassTemplatePartialSpecializationDecl *PS1,
5697 ClassTemplatePartialSpecializationDecl *PS2,
5698 SourceLocation Loc);
5700 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5703 llvm::SmallBitVector &Used);
5704 void MarkDeducedTemplateParameters(
5705 const FunctionTemplateDecl *FunctionTemplate,
5706 llvm::SmallBitVector &Deduced) {
5707 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
5709 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
5710 const FunctionTemplateDecl *FunctionTemplate,
5711 llvm::SmallBitVector &Deduced);
5713 //===--------------------------------------------------------------------===//
5714 // C++ Template Instantiation
5717 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
5718 const TemplateArgumentList *Innermost = 0,
5719 bool RelativeToPrimary = false,
5720 const FunctionDecl *Pattern = 0);
5722 /// \brief A template instantiation that is currently in progress.
5723 struct ActiveTemplateInstantiation {
5724 /// \brief The kind of template instantiation we are performing
5725 enum InstantiationKind {
5726 /// We are instantiating a template declaration. The entity is
5727 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
5728 TemplateInstantiation,
5730 /// We are instantiating a default argument for a template
5731 /// parameter. The Entity is the template, and
5732 /// TemplateArgs/NumTemplateArguments provides the template
5733 /// arguments as specified.
5734 /// FIXME: Use a TemplateArgumentList
5735 DefaultTemplateArgumentInstantiation,
5737 /// We are instantiating a default argument for a function.
5738 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
5739 /// provides the template arguments as specified.
5740 DefaultFunctionArgumentInstantiation,
5742 /// We are substituting explicit template arguments provided for
5743 /// a function template. The entity is a FunctionTemplateDecl.
5744 ExplicitTemplateArgumentSubstitution,
5746 /// We are substituting template argument determined as part of
5747 /// template argument deduction for either a class template
5748 /// partial specialization or a function template. The
5749 /// Entity is either a ClassTemplatePartialSpecializationDecl or
5750 /// a FunctionTemplateDecl.
5751 DeducedTemplateArgumentSubstitution,
5753 /// We are substituting prior template arguments into a new
5754 /// template parameter. The template parameter itself is either a
5755 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
5756 PriorTemplateArgumentSubstitution,
5758 /// We are checking the validity of a default template argument that
5759 /// has been used when naming a template-id.
5760 DefaultTemplateArgumentChecking,
5762 /// We are instantiating the exception specification for a function
5763 /// template which was deferred until it was needed.
5764 ExceptionSpecInstantiation
5767 /// \brief The point of instantiation within the source code.
5768 SourceLocation PointOfInstantiation;
5770 /// \brief The template (or partial specialization) in which we are
5771 /// performing the instantiation, for substitutions of prior template
5773 NamedDecl *Template;
5775 /// \brief The entity that is being instantiated.
5778 /// \brief The list of template arguments we are substituting, if they
5779 /// are not part of the entity.
5780 const TemplateArgument *TemplateArgs;
5782 /// \brief The number of template arguments in TemplateArgs.
5783 unsigned NumTemplateArgs;
5785 /// \brief The template deduction info object associated with the
5786 /// substitution or checking of explicit or deduced template arguments.
5787 sema::TemplateDeductionInfo *DeductionInfo;
5789 /// \brief The source range that covers the construct that cause
5790 /// the instantiation, e.g., the template-id that causes a class
5791 /// template instantiation.
5792 SourceRange InstantiationRange;
5794 ActiveTemplateInstantiation()
5795 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
5796 NumTemplateArgs(0), DeductionInfo(0) {}
5798 /// \brief Determines whether this template is an actual instantiation
5799 /// that should be counted toward the maximum instantiation depth.
5800 bool isInstantiationRecord() const;
5802 friend bool operator==(const ActiveTemplateInstantiation &X,
5803 const ActiveTemplateInstantiation &Y) {
5804 if (X.Kind != Y.Kind)
5807 if (X.Entity != Y.Entity)
5811 case TemplateInstantiation:
5812 case ExceptionSpecInstantiation:
5815 case PriorTemplateArgumentSubstitution:
5816 case DefaultTemplateArgumentChecking:
5817 if (X.Template != Y.Template)
5822 case DefaultTemplateArgumentInstantiation:
5823 case ExplicitTemplateArgumentSubstitution:
5824 case DeducedTemplateArgumentSubstitution:
5825 case DefaultFunctionArgumentInstantiation:
5826 return X.TemplateArgs == Y.TemplateArgs;
5830 llvm_unreachable("Invalid InstantiationKind!");
5833 friend bool operator!=(const ActiveTemplateInstantiation &X,
5834 const ActiveTemplateInstantiation &Y) {
5839 /// \brief List of active template instantiations.
5841 /// This vector is treated as a stack. As one template instantiation
5842 /// requires another template instantiation, additional
5843 /// instantiations are pushed onto the stack up to a
5844 /// user-configurable limit LangOptions::InstantiationDepth.
5845 SmallVector<ActiveTemplateInstantiation, 16>
5846 ActiveTemplateInstantiations;
5848 /// \brief Whether we are in a SFINAE context that is not associated with
5849 /// template instantiation.
5851 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
5852 /// of a template instantiation or template argument deduction.
5853 bool InNonInstantiationSFINAEContext;
5855 /// \brief The number of ActiveTemplateInstantiation entries in
5856 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
5857 /// therefore, should not be counted as part of the instantiation depth.
5858 unsigned NonInstantiationEntries;
5860 /// \brief The last template from which a template instantiation
5861 /// error or warning was produced.
5863 /// This value is used to suppress printing of redundant template
5864 /// instantiation backtraces when there are multiple errors in the
5865 /// same instantiation. FIXME: Does this belong in Sema? It's tough
5866 /// to implement it anywhere else.
5867 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
5869 /// \brief The current index into pack expansion arguments that will be
5870 /// used for substitution of parameter packs.
5872 /// The pack expansion index will be -1 to indicate that parameter packs
5873 /// should be instantiated as themselves. Otherwise, the index specifies
5874 /// which argument within the parameter pack will be used for substitution.
5875 int ArgumentPackSubstitutionIndex;
5877 /// \brief RAII object used to change the argument pack substitution index
5878 /// within a \c Sema object.
5880 /// See \c ArgumentPackSubstitutionIndex for more information.
5881 class ArgumentPackSubstitutionIndexRAII {
5883 int OldSubstitutionIndex;
5886 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
5887 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
5888 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
5891 ~ArgumentPackSubstitutionIndexRAII() {
5892 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
5896 friend class ArgumentPackSubstitutionRAII;
5898 /// \brief The stack of calls expression undergoing template instantiation.
5900 /// The top of this stack is used by a fixit instantiating unresolved
5901 /// function calls to fix the AST to match the textual change it prints.
5902 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
5904 /// \brief For each declaration that involved template argument deduction, the
5905 /// set of diagnostics that were suppressed during that template argument
5908 /// FIXME: Serialize this structure to the AST file.
5909 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
5910 SuppressedDiagnostics;
5912 /// \brief A stack object to be created when performing template
5915 /// Construction of an object of type \c InstantiatingTemplate
5916 /// pushes the current instantiation onto the stack of active
5917 /// instantiations. If the size of this stack exceeds the maximum
5918 /// number of recursive template instantiations, construction
5919 /// produces an error and evaluates true.
5921 /// Destruction of this object will pop the named instantiation off
5923 struct InstantiatingTemplate {
5924 /// \brief Note that we are instantiating a class template,
5925 /// function template, or a member thereof.
5926 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5928 SourceRange InstantiationRange = SourceRange());
5930 struct ExceptionSpecification {};
5931 /// \brief Note that we are instantiating an exception specification
5932 /// of a function template.
5933 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5934 FunctionDecl *Entity, ExceptionSpecification,
5935 SourceRange InstantiationRange = SourceRange());
5937 /// \brief Note that we are instantiating a default argument in a
5939 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5940 TemplateDecl *Template,
5941 ArrayRef<TemplateArgument> TemplateArgs,
5942 SourceRange InstantiationRange = SourceRange());
5944 /// \brief Note that we are instantiating a default argument in a
5946 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5947 FunctionTemplateDecl *FunctionTemplate,
5948 ArrayRef<TemplateArgument> TemplateArgs,
5949 ActiveTemplateInstantiation::InstantiationKind Kind,
5950 sema::TemplateDeductionInfo &DeductionInfo,
5951 SourceRange InstantiationRange = SourceRange());
5953 /// \brief Note that we are instantiating as part of template
5954 /// argument deduction for a class template partial
5956 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5957 ClassTemplatePartialSpecializationDecl *PartialSpec,
5958 ArrayRef<TemplateArgument> TemplateArgs,
5959 sema::TemplateDeductionInfo &DeductionInfo,
5960 SourceRange InstantiationRange = SourceRange());
5962 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5964 ArrayRef<TemplateArgument> TemplateArgs,
5965 SourceRange InstantiationRange = SourceRange());
5967 /// \brief Note that we are substituting prior template arguments into a
5968 /// non-type or template template parameter.
5969 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5970 NamedDecl *Template,
5971 NonTypeTemplateParmDecl *Param,
5972 ArrayRef<TemplateArgument> TemplateArgs,
5973 SourceRange InstantiationRange);
5975 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5976 NamedDecl *Template,
5977 TemplateTemplateParmDecl *Param,
5978 ArrayRef<TemplateArgument> TemplateArgs,
5979 SourceRange InstantiationRange);
5981 /// \brief Note that we are checking the default template argument
5982 /// against the template parameter for a given template-id.
5983 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5984 TemplateDecl *Template,
5986 ArrayRef<TemplateArgument> TemplateArgs,
5987 SourceRange InstantiationRange);
5990 /// \brief Note that we have finished instantiating this template.
5993 ~InstantiatingTemplate() { Clear(); }
5995 /// \brief Determines whether we have exceeded the maximum
5996 /// recursive template instantiations.
5997 operator bool() const { return Invalid; }
6002 bool SavedInNonInstantiationSFINAEContext;
6003 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6004 SourceRange InstantiationRange);
6006 InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6008 InstantiatingTemplate&
6009 operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6012 void PrintInstantiationStack();
6014 /// \brief Determines whether we are currently in a context where
6015 /// template argument substitution failures are not considered
6018 /// \returns An empty \c Optional if we're not in a SFINAE context.
6019 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6020 /// template-deduction context object, which can be used to capture
6021 /// diagnostics that will be suppressed.
6022 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6024 /// \brief Determines whether we are currently in a context that
6025 /// is not evaluated as per C++ [expr] p5.
6026 bool isUnevaluatedContext() const {
6027 assert(!ExprEvalContexts.empty() &&
6028 "Must be in an expression evaluation context");
6029 return ExprEvalContexts.back().isUnevaluated();
6032 /// \brief RAII class used to determine whether SFINAE has
6033 /// trapped any errors that occur during template argument
6037 unsigned PrevSFINAEErrors;
6038 bool PrevInNonInstantiationSFINAEContext;
6039 bool PrevAccessCheckingSFINAE;
6042 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6043 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6044 PrevInNonInstantiationSFINAEContext(
6045 SemaRef.InNonInstantiationSFINAEContext),
6046 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6048 if (!SemaRef.isSFINAEContext())
6049 SemaRef.InNonInstantiationSFINAEContext = true;
6050 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6054 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6055 SemaRef.InNonInstantiationSFINAEContext
6056 = PrevInNonInstantiationSFINAEContext;
6057 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6060 /// \brief Determine whether any SFINAE errors have been trapped.
6061 bool hasErrorOccurred() const {
6062 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6066 /// \brief The current instantiation scope used to store local
6068 LocalInstantiationScope *CurrentInstantiationScope;
6070 /// \brief The number of typos corrected by CorrectTypo.
6071 unsigned TyposCorrected;
6073 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
6074 UnqualifiedTyposCorrectedMap;
6076 /// \brief A cache containing the results of typo correction for unqualified
6079 /// The string is the string that we corrected to (which may be empty, if
6080 /// there was no correction), while the boolean will be true when the
6081 /// string represents a keyword.
6082 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
6084 /// \brief Worker object for performing CFG-based warnings.
6085 sema::AnalysisBasedWarnings AnalysisWarnings;
6087 /// \brief An entity for which implicit template instantiation is required.
6089 /// The source location associated with the declaration is the first place in
6090 /// the source code where the declaration was "used". It is not necessarily
6091 /// the point of instantiation (which will be either before or after the
6092 /// namespace-scope declaration that triggered this implicit instantiation),
6093 /// However, it is the location that diagnostics should generally refer to,
6094 /// because users will need to know what code triggered the instantiation.
6095 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6097 /// \brief The queue of implicit template instantiations that are required
6098 /// but have not yet been performed.
6099 std::deque<PendingImplicitInstantiation> PendingInstantiations;
6101 /// \brief The queue of implicit template instantiations that are required
6102 /// and must be performed within the current local scope.
6104 /// This queue is only used for member functions of local classes in
6105 /// templates, which must be instantiated in the same scope as their
6106 /// enclosing function, so that they can reference function-local
6107 /// types, static variables, enumerators, etc.
6108 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6110 void PerformPendingInstantiations(bool LocalOnly = false);
6112 TypeSourceInfo *SubstType(TypeSourceInfo *T,
6113 const MultiLevelTemplateArgumentList &TemplateArgs,
6114 SourceLocation Loc, DeclarationName Entity);
6116 QualType SubstType(QualType T,
6117 const MultiLevelTemplateArgumentList &TemplateArgs,
6118 SourceLocation Loc, DeclarationName Entity);
6120 TypeSourceInfo *SubstType(TypeLoc TL,
6121 const MultiLevelTemplateArgumentList &TemplateArgs,
6122 SourceLocation Loc, DeclarationName Entity);
6124 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6125 const MultiLevelTemplateArgumentList &TemplateArgs,
6127 DeclarationName Entity,
6128 CXXRecordDecl *ThisContext,
6129 unsigned ThisTypeQuals);
6130 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6131 const MultiLevelTemplateArgumentList &TemplateArgs,
6132 int indexAdjustment,
6133 Optional<unsigned> NumExpansions,
6134 bool ExpectParameterPack);
6135 bool SubstParmTypes(SourceLocation Loc,
6136 ParmVarDecl **Params, unsigned NumParams,
6137 const MultiLevelTemplateArgumentList &TemplateArgs,
6138 SmallVectorImpl<QualType> &ParamTypes,
6139 SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
6140 ExprResult SubstExpr(Expr *E,
6141 const MultiLevelTemplateArgumentList &TemplateArgs);
6143 /// \brief Substitute the given template arguments into a list of
6144 /// expressions, expanding pack expansions if required.
6146 /// \param Exprs The list of expressions to substitute into.
6148 /// \param NumExprs The number of expressions in \p Exprs.
6150 /// \param IsCall Whether this is some form of call, in which case
6151 /// default arguments will be dropped.
6153 /// \param TemplateArgs The set of template arguments to substitute.
6155 /// \param Outputs Will receive all of the substituted arguments.
6157 /// \returns true if an error occurred, false otherwise.
6158 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6159 const MultiLevelTemplateArgumentList &TemplateArgs,
6160 SmallVectorImpl<Expr *> &Outputs);
6162 StmtResult SubstStmt(Stmt *S,
6163 const MultiLevelTemplateArgumentList &TemplateArgs);
6165 Decl *SubstDecl(Decl *D, DeclContext *Owner,
6166 const MultiLevelTemplateArgumentList &TemplateArgs);
6168 ExprResult SubstInitializer(Expr *E,
6169 const MultiLevelTemplateArgumentList &TemplateArgs,
6170 bool CXXDirectInit);
6173 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6174 CXXRecordDecl *Pattern,
6175 const MultiLevelTemplateArgumentList &TemplateArgs);
6178 InstantiateClass(SourceLocation PointOfInstantiation,
6179 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6180 const MultiLevelTemplateArgumentList &TemplateArgs,
6181 TemplateSpecializationKind TSK,
6182 bool Complain = true);
6184 bool InstantiateEnum(SourceLocation PointOfInstantiation,
6185 EnumDecl *Instantiation, EnumDecl *Pattern,
6186 const MultiLevelTemplateArgumentList &TemplateArgs,
6187 TemplateSpecializationKind TSK);
6189 struct LateInstantiatedAttribute {
6190 const Attr *TmplAttr;
6191 LocalInstantiationScope *Scope;
6194 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6196 : TmplAttr(A), Scope(S), NewDecl(D)
6199 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6201 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6202 const Decl *Pattern, Decl *Inst,
6203 LateInstantiatedAttrVec *LateAttrs = 0,
6204 LocalInstantiationScope *OuterMostScope = 0);
6207 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6208 ClassTemplateSpecializationDecl *ClassTemplateSpec,
6209 TemplateSpecializationKind TSK,
6210 bool Complain = true);
6212 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6213 CXXRecordDecl *Instantiation,
6214 const MultiLevelTemplateArgumentList &TemplateArgs,
6215 TemplateSpecializationKind TSK);
6217 void InstantiateClassTemplateSpecializationMembers(
6218 SourceLocation PointOfInstantiation,
6219 ClassTemplateSpecializationDecl *ClassTemplateSpec,
6220 TemplateSpecializationKind TSK);
6222 NestedNameSpecifierLoc
6223 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
6224 const MultiLevelTemplateArgumentList &TemplateArgs);
6227 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
6228 const MultiLevelTemplateArgumentList &TemplateArgs);
6230 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
6232 const MultiLevelTemplateArgumentList &TemplateArgs);
6233 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
6234 TemplateArgumentListInfo &Result,
6235 const MultiLevelTemplateArgumentList &TemplateArgs);
6237 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
6238 FunctionDecl *Function);
6239 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
6240 FunctionDecl *Function,
6241 bool Recursive = false,
6242 bool DefinitionRequired = false);
6243 void InstantiateStaticDataMemberDefinition(
6244 SourceLocation PointOfInstantiation,
6246 bool Recursive = false,
6247 bool DefinitionRequired = false);
6249 void InstantiateMemInitializers(CXXConstructorDecl *New,
6250 const CXXConstructorDecl *Tmpl,
6251 const MultiLevelTemplateArgumentList &TemplateArgs);
6253 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6254 const MultiLevelTemplateArgumentList &TemplateArgs);
6255 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
6256 const MultiLevelTemplateArgumentList &TemplateArgs);
6258 // Objective-C declarations.
6259 enum ObjCContainerKind {
6266 OCK_CategoryImplementation
6268 ObjCContainerKind getObjCContainerKind() const;
6270 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
6271 IdentifierInfo *ClassName,
6272 SourceLocation ClassLoc,
6273 IdentifierInfo *SuperName,
6274 SourceLocation SuperLoc,
6275 Decl * const *ProtoRefs,
6276 unsigned NumProtoRefs,
6277 const SourceLocation *ProtoLocs,
6278 SourceLocation EndProtoLoc,
6279 AttributeList *AttrList);
6281 Decl *ActOnCompatibilityAlias(
6282 SourceLocation AtCompatibilityAliasLoc,
6283 IdentifierInfo *AliasName, SourceLocation AliasLocation,
6284 IdentifierInfo *ClassName, SourceLocation ClassLocation);
6286 bool CheckForwardProtocolDeclarationForCircularDependency(
6287 IdentifierInfo *PName,
6288 SourceLocation &PLoc, SourceLocation PrevLoc,
6289 const ObjCList<ObjCProtocolDecl> &PList);
6291 Decl *ActOnStartProtocolInterface(
6292 SourceLocation AtProtoInterfaceLoc,
6293 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6294 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6295 const SourceLocation *ProtoLocs,
6296 SourceLocation EndProtoLoc,
6297 AttributeList *AttrList);
6299 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6300 IdentifierInfo *ClassName,
6301 SourceLocation ClassLoc,
6302 IdentifierInfo *CategoryName,
6303 SourceLocation CategoryLoc,
6304 Decl * const *ProtoRefs,
6305 unsigned NumProtoRefs,
6306 const SourceLocation *ProtoLocs,
6307 SourceLocation EndProtoLoc);
6309 Decl *ActOnStartClassImplementation(
6310 SourceLocation AtClassImplLoc,
6311 IdentifierInfo *ClassName, SourceLocation ClassLoc,
6312 IdentifierInfo *SuperClassname,
6313 SourceLocation SuperClassLoc);
6315 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
6316 IdentifierInfo *ClassName,
6317 SourceLocation ClassLoc,
6318 IdentifierInfo *CatName,
6319 SourceLocation CatLoc);
6321 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
6322 ArrayRef<Decl *> Decls);
6324 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
6325 IdentifierInfo **IdentList,
6326 SourceLocation *IdentLocs,
6329 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
6330 const IdentifierLocPair *IdentList,
6332 AttributeList *attrList);
6334 void FindProtocolDeclaration(bool WarnOnDeclarations,
6335 const IdentifierLocPair *ProtocolId,
6336 unsigned NumProtocols,
6337 SmallVectorImpl<Decl *> &Protocols);
6339 /// Ensure attributes are consistent with type.
6340 /// \param [in, out] Attributes The attributes to check; they will
6341 /// be modified to be consistent with \p PropertyTy.
6342 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
6344 unsigned &Attributes,
6345 bool propertyInPrimaryClass);
6347 /// Process the specified property declaration and create decls for the
6348 /// setters and getters as needed.
6349 /// \param property The property declaration being processed
6350 /// \param CD The semantic container for the property
6351 /// \param redeclaredProperty Declaration for property if redeclared
6352 /// in class extension.
6353 /// \param lexicalDC Container for redeclaredProperty.
6354 void ProcessPropertyDecl(ObjCPropertyDecl *property,
6355 ObjCContainerDecl *CD,
6356 ObjCPropertyDecl *redeclaredProperty = 0,
6357 ObjCContainerDecl *lexicalDC = 0);
6360 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
6361 ObjCPropertyDecl *SuperProperty,
6362 const IdentifierInfo *Name);
6364 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
6365 ObjCInterfaceDecl *ID);
6367 void MatchOneProtocolPropertiesInClass(Decl *CDecl,
6368 ObjCProtocolDecl *PDecl);
6370 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
6371 Decl **allMethods = 0, unsigned allNum = 0,
6372 Decl **allProperties = 0, unsigned pNum = 0,
6373 DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
6375 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
6376 SourceLocation LParenLoc,
6377 FieldDeclarator &FD, ObjCDeclSpec &ODS,
6378 Selector GetterSel, Selector SetterSel,
6379 bool *OverridingProperty,
6380 tok::ObjCKeywordKind MethodImplKind,
6381 DeclContext *lexicalDC = 0);
6383 Decl *ActOnPropertyImplDecl(Scope *S,
6384 SourceLocation AtLoc,
6385 SourceLocation PropertyLoc,
6387 IdentifierInfo *PropertyId,
6388 IdentifierInfo *PropertyIvar,
6389 SourceLocation PropertyIvarLoc);
6391 enum ObjCSpecialMethodKind {
6397 OSMK_NonRetainingInit
6400 struct ObjCArgInfo {
6401 IdentifierInfo *Name;
6402 SourceLocation NameLoc;
6403 // The Type is null if no type was specified, and the DeclSpec is invalid
6406 ObjCDeclSpec DeclSpec;
6408 /// ArgAttrs - Attribute list for this argument.
6409 AttributeList *ArgAttrs;
6412 Decl *ActOnMethodDeclaration(
6414 SourceLocation BeginLoc, // location of the + or -.
6415 SourceLocation EndLoc, // location of the ; or {.
6416 tok::TokenKind MethodType,
6417 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
6418 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
6419 // optional arguments. The number of types/arguments is obtained
6420 // from the Sel.getNumArgs().
6421 ObjCArgInfo *ArgInfo,
6422 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
6423 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
6424 bool isVariadic, bool MethodDefinition);
6426 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
6427 const ObjCObjectPointerType *OPT,
6429 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
6432 bool CheckARCMethodDecl(ObjCMethodDecl *method);
6433 bool inferObjCARCLifetime(ValueDecl *decl);
6436 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
6438 SourceLocation OpLoc,
6439 DeclarationName MemberName,
6440 SourceLocation MemberLoc,
6441 SourceLocation SuperLoc, QualType SuperType,
6445 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
6446 IdentifierInfo &propertyName,
6447 SourceLocation receiverNameLoc,
6448 SourceLocation propertyNameLoc);
6450 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
6452 /// \brief Describes the kind of message expression indicated by a message
6453 /// send that starts with an identifier.
6454 enum ObjCMessageKind {
6455 /// \brief The message is sent to 'super'.
6457 /// \brief The message is an instance message.
6458 ObjCInstanceMessage,
6459 /// \brief The message is a class message, and the identifier is a type
6464 ObjCMessageKind getObjCMessageKind(Scope *S,
6465 IdentifierInfo *Name,
6466 SourceLocation NameLoc,
6468 bool HasTrailingDot,
6469 ParsedType &ReceiverType);
6471 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
6473 SourceLocation LBracLoc,
6474 ArrayRef<SourceLocation> SelectorLocs,
6475 SourceLocation RBracLoc,
6478 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
6479 QualType ReceiverType,
6480 SourceLocation SuperLoc,
6482 ObjCMethodDecl *Method,
6483 SourceLocation LBracLoc,
6484 ArrayRef<SourceLocation> SelectorLocs,
6485 SourceLocation RBracLoc,
6487 bool isImplicit = false);
6489 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
6490 bool isSuperReceiver,
6493 ObjCMethodDecl *Method,
6496 ExprResult ActOnClassMessage(Scope *S,
6497 ParsedType Receiver,
6499 SourceLocation LBracLoc,
6500 ArrayRef<SourceLocation> SelectorLocs,
6501 SourceLocation RBracLoc,
6504 ExprResult BuildInstanceMessage(Expr *Receiver,
6505 QualType ReceiverType,
6506 SourceLocation SuperLoc,
6508 ObjCMethodDecl *Method,
6509 SourceLocation LBracLoc,
6510 ArrayRef<SourceLocation> SelectorLocs,
6511 SourceLocation RBracLoc,
6513 bool isImplicit = false);
6515 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
6516 QualType ReceiverType,
6519 ObjCMethodDecl *Method,
6522 ExprResult ActOnInstanceMessage(Scope *S,
6525 SourceLocation LBracLoc,
6526 ArrayRef<SourceLocation> SelectorLocs,
6527 SourceLocation RBracLoc,
6530 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
6531 ObjCBridgeCastKind Kind,
6532 SourceLocation BridgeKeywordLoc,
6533 TypeSourceInfo *TSInfo,
6536 ExprResult ActOnObjCBridgedCast(Scope *S,
6537 SourceLocation LParenLoc,
6538 ObjCBridgeCastKind Kind,
6539 SourceLocation BridgeKeywordLoc,
6541 SourceLocation RParenLoc,
6544 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
6546 /// \brief Check whether the given new method is a valid override of the
6547 /// given overridden method, and set any properties that should be inherited.
6548 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
6549 const ObjCMethodDecl *Overridden);
6551 /// \brief Describes the compatibility of a result type with its method.
6552 enum ResultTypeCompatibilityKind {
6558 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
6559 ObjCInterfaceDecl *CurrentClass,
6560 ResultTypeCompatibilityKind RTC);
6562 enum PragmaOptionsAlignKind {
6563 POAK_Native, // #pragma options align=native
6564 POAK_Natural, // #pragma options align=natural
6565 POAK_Packed, // #pragma options align=packed
6566 POAK_Power, // #pragma options align=power
6567 POAK_Mac68k, // #pragma options align=mac68k
6568 POAK_Reset // #pragma options align=reset
6571 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
6572 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
6573 SourceLocation PragmaLoc);
6575 enum PragmaPackKind {
6576 PPK_Default, // #pragma pack([n])
6577 PPK_Show, // #pragma pack(show), only supported by MSVC.
6578 PPK_Push, // #pragma pack(push, [identifier], [n])
6579 PPK_Pop // #pragma pack(pop, [identifier], [n])
6582 enum PragmaMSStructKind {
6583 PMSST_OFF, // #pragms ms_struct off
6584 PMSST_ON // #pragms ms_struct on
6587 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
6588 void ActOnPragmaPack(PragmaPackKind Kind,
6589 IdentifierInfo *Name,
6591 SourceLocation PragmaLoc,
6592 SourceLocation LParenLoc,
6593 SourceLocation RParenLoc);
6595 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
6596 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
6598 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
6599 void ActOnPragmaUnused(const Token &Identifier,
6601 SourceLocation PragmaLoc);
6603 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
6604 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
6605 SourceLocation PragmaLoc);
6607 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6608 SourceLocation Loc);
6609 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
6611 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
6612 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
6613 SourceLocation PragmaLoc,
6614 SourceLocation WeakNameLoc);
6616 /// ActOnPragmaRedefineExtname - Called on well formed
6617 /// \#pragma redefine_extname oldname newname.
6618 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
6619 IdentifierInfo* AliasName,
6620 SourceLocation PragmaLoc,
6621 SourceLocation WeakNameLoc,
6622 SourceLocation AliasNameLoc);
6624 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
6625 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
6626 IdentifierInfo* AliasName,
6627 SourceLocation PragmaLoc,
6628 SourceLocation WeakNameLoc,
6629 SourceLocation AliasNameLoc);
6631 /// ActOnPragmaFPContract - Called on well formed
6632 /// \#pragma {STDC,OPENCL} FP_CONTRACT
6633 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
6635 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
6636 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
6637 void AddAlignmentAttributesForRecord(RecordDecl *RD);
6639 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
6640 void AddMsStructLayoutForRecord(RecordDecl *RD);
6642 /// FreePackedContext - Deallocate and null out PackContext.
6643 void FreePackedContext();
6645 /// PushNamespaceVisibilityAttr - Note that we've entered a
6646 /// namespace with a visibility attribute.
6647 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
6648 SourceLocation Loc);
6650 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
6651 /// add an appropriate visibility attribute.
6652 void AddPushedVisibilityAttribute(Decl *RD);
6654 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
6655 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
6656 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
6658 /// FreeVisContext - Deallocate and null out VisContext.
6659 void FreeVisContext();
6661 /// AddCFAuditedAttribute - Check whether we're currently within
6662 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
6663 /// the appropriate attribute.
6664 void AddCFAuditedAttribute(Decl *D);
6666 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
6667 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
6668 unsigned SpellingListIndex, bool IsPackExpansion);
6669 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
6670 unsigned SpellingListIndex, bool IsPackExpansion);
6672 // OpenMP directives and clauses.
6674 /// \brief Called on well-formed '#pragma omp threadprivate'.
6675 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
6678 ArrayRef<DeclarationNameInfo> IdList);
6679 /// \brief Build a new OpenMPThreadPrivateDecl and check its correctness.
6680 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
6682 ArrayRef<DeclRefExpr *> VarList);
6684 /// \brief The kind of conversion being performed.
6685 enum CheckedConversionKind {
6686 /// \brief An implicit conversion.
6687 CCK_ImplicitConversion,
6688 /// \brief A C-style cast.
6690 /// \brief A functional-style cast.
6692 /// \brief A cast other than a C-style cast.
6696 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
6697 /// cast. If there is already an implicit cast, merge into the existing one.
6698 /// If isLvalue, the result of the cast is an lvalue.
6699 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
6700 ExprValueKind VK = VK_RValue,
6701 const CXXCastPath *BasePath = 0,
6702 CheckedConversionKind CCK
6703 = CCK_ImplicitConversion);
6705 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
6706 /// to the conversion from scalar type ScalarTy to the Boolean type.
6707 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
6709 /// IgnoredValueConversions - Given that an expression's result is
6710 /// syntactically ignored, perform any conversions that are
6712 ExprResult IgnoredValueConversions(Expr *E);
6714 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
6715 // functions and arrays to their respective pointers (C99 6.3.2.1).
6716 ExprResult UsualUnaryConversions(Expr *E);
6718 // DefaultFunctionArrayConversion - converts functions and arrays
6719 // to their respective pointers (C99 6.3.2.1).
6720 ExprResult DefaultFunctionArrayConversion(Expr *E);
6722 // DefaultFunctionArrayLvalueConversion - converts functions and
6723 // arrays to their respective pointers and performs the
6724 // lvalue-to-rvalue conversion.
6725 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
6727 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
6728 // the operand. This is DefaultFunctionArrayLvalueConversion,
6729 // except that it assumes the operand isn't of function or array
6731 ExprResult DefaultLvalueConversion(Expr *E);
6733 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
6734 // do not have a prototype. Integer promotions are performed on each
6735 // argument, and arguments that have type float are promoted to double.
6736 ExprResult DefaultArgumentPromotion(Expr *E);
6738 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
6739 enum VariadicCallType {
6743 VariadicConstructor,
6744 VariadicDoesNotApply
6747 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
6748 const FunctionProtoType *Proto,
6751 // Used for determining in which context a type is allowed to be passed to a
6759 // Determines which VarArgKind fits an expression.
6760 VarArgKind isValidVarArgType(const QualType &Ty);
6762 /// GatherArgumentsForCall - Collector argument expressions for various
6763 /// form of call prototypes.
6764 bool GatherArgumentsForCall(SourceLocation CallLoc,
6765 FunctionDecl *FDecl,
6766 const FunctionProtoType *Proto,
6767 unsigned FirstProtoArg,
6768 Expr **Args, unsigned NumArgs,
6769 SmallVector<Expr *, 8> &AllArgs,
6770 VariadicCallType CallType = VariadicDoesNotApply,
6771 bool AllowExplicit = false,
6772 bool IsListInitialization = false);
6774 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
6775 // will create a runtime trap if the resulting type is not a POD type.
6776 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
6777 FunctionDecl *FDecl);
6779 /// Checks to see if the given expression is a valid argument to a variadic
6780 /// function, issuing a diagnostic and returning NULL if not.
6781 bool variadicArgumentPODCheck(const Expr *E, VariadicCallType CT);
6783 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
6784 // operands and then handles various conversions that are common to binary
6785 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
6786 // routine returns the first non-arithmetic type found. The client is
6787 // responsible for emitting appropriate error diagnostics.
6788 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
6789 bool IsCompAssign = false);
6791 /// AssignConvertType - All of the 'assignment' semantic checks return this
6792 /// enum to indicate whether the assignment was allowed. These checks are
6793 /// done for simple assignments, as well as initialization, return from
6794 /// function, argument passing, etc. The query is phrased in terms of a
6795 /// source and destination type.
6796 enum AssignConvertType {
6797 /// Compatible - the types are compatible according to the standard.
6800 /// PointerToInt - The assignment converts a pointer to an int, which we
6801 /// accept as an extension.
6804 /// IntToPointer - The assignment converts an int to a pointer, which we
6805 /// accept as an extension.
6808 /// FunctionVoidPointer - The assignment is between a function pointer and
6809 /// void*, which the standard doesn't allow, but we accept as an extension.
6810 FunctionVoidPointer,
6812 /// IncompatiblePointer - The assignment is between two pointers types that
6813 /// are not compatible, but we accept them as an extension.
6814 IncompatiblePointer,
6816 /// IncompatiblePointer - The assignment is between two pointers types which
6817 /// point to integers which have a different sign, but are otherwise
6818 /// identical. This is a subset of the above, but broken out because it's by
6819 /// far the most common case of incompatible pointers.
6820 IncompatiblePointerSign,
6822 /// CompatiblePointerDiscardsQualifiers - The assignment discards
6823 /// c/v/r qualifiers, which we accept as an extension.
6824 CompatiblePointerDiscardsQualifiers,
6826 /// IncompatiblePointerDiscardsQualifiers - The assignment
6827 /// discards qualifiers that we don't permit to be discarded,
6828 /// like address spaces.
6829 IncompatiblePointerDiscardsQualifiers,
6831 /// IncompatibleNestedPointerQualifiers - The assignment is between two
6832 /// nested pointer types, and the qualifiers other than the first two
6833 /// levels differ e.g. char ** -> const char **, but we accept them as an
6835 IncompatibleNestedPointerQualifiers,
6837 /// IncompatibleVectors - The assignment is between two vector types that
6838 /// have the same size, which we accept as an extension.
6839 IncompatibleVectors,
6841 /// IntToBlockPointer - The assignment converts an int to a block
6842 /// pointer. We disallow this.
6845 /// IncompatibleBlockPointer - The assignment is between two block
6846 /// pointers types that are not compatible.
6847 IncompatibleBlockPointer,
6849 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
6850 /// id type and something else (that is incompatible with it). For example,
6851 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
6852 IncompatibleObjCQualifiedId,
6854 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
6855 /// object with __weak qualifier.
6856 IncompatibleObjCWeakRef,
6858 /// Incompatible - We reject this conversion outright, it is invalid to
6859 /// represent it in the AST.
6863 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
6864 /// assignment conversion type specified by ConvTy. This returns true if the
6865 /// conversion was invalid or false if the conversion was accepted.
6866 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
6868 QualType DstType, QualType SrcType,
6869 Expr *SrcExpr, AssignmentAction Action,
6870 bool *Complained = 0);
6872 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
6873 /// integer not in the range of enum values.
6874 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
6877 /// CheckAssignmentConstraints - Perform type checking for assignment,
6878 /// argument passing, variable initialization, and function return values.
6880 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
6884 /// Check assignment constraints and prepare for a conversion of the
6885 /// RHS to the LHS type.
6886 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
6890 // CheckSingleAssignmentConstraints - Currently used by
6891 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
6892 // this routine performs the default function/array converions.
6893 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
6895 bool Diagnose = true);
6897 // \brief If the lhs type is a transparent union, check whether we
6898 // can initialize the transparent union with the given expression.
6899 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
6902 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
6904 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6906 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6907 AssignmentAction Action,
6908 bool AllowExplicit = false);
6909 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6910 AssignmentAction Action,
6912 ImplicitConversionSequence& ICS);
6913 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6914 const ImplicitConversionSequence& ICS,
6915 AssignmentAction Action,
6916 CheckedConversionKind CCK
6917 = CCK_ImplicitConversion);
6918 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6919 const StandardConversionSequence& SCS,
6920 AssignmentAction Action,
6921 CheckedConversionKind CCK);
6923 /// the following "Check" methods will return a valid/converted QualType
6924 /// or a null QualType (indicating an error diagnostic was issued).
6926 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
6927 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6929 QualType CheckPointerToMemberOperands( // C++ 5.5
6930 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
6931 SourceLocation OpLoc, bool isIndirect);
6932 QualType CheckMultiplyDivideOperands( // C99 6.5.5
6933 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
6935 QualType CheckRemainderOperands( // C99 6.5.5
6936 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6937 bool IsCompAssign = false);
6938 QualType CheckAdditionOperands( // C99 6.5.6
6939 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6940 QualType* CompLHSTy = 0);
6941 QualType CheckSubtractionOperands( // C99 6.5.6
6942 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6943 QualType* CompLHSTy = 0);
6944 QualType CheckShiftOperands( // C99 6.5.7
6945 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6946 bool IsCompAssign = false);
6947 QualType CheckCompareOperands( // C99 6.5.8/9
6948 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
6950 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
6951 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6952 bool IsCompAssign = false);
6953 QualType CheckLogicalOperands( // C99 6.5.[13,14]
6954 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
6955 // CheckAssignmentOperands is used for both simple and compound assignment.
6956 // For simple assignment, pass both expressions and a null converted type.
6957 // For compound assignment, pass both expressions and the converted type.
6958 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
6959 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
6961 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
6962 UnaryOperatorKind Opcode, Expr *Op);
6963 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
6964 BinaryOperatorKind Opcode,
6965 Expr *LHS, Expr *RHS);
6966 ExprResult checkPseudoObjectRValue(Expr *E);
6967 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
6969 QualType CheckConditionalOperands( // C99 6.5.15
6970 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
6971 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
6972 QualType CXXCheckConditionalOperands( // C++ 5.16
6973 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
6974 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
6975 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
6976 bool *NonStandardCompositeType = 0);
6977 QualType FindCompositePointerType(SourceLocation Loc,
6978 ExprResult &E1, ExprResult &E2,
6979 bool *NonStandardCompositeType = 0) {
6980 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
6981 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
6982 NonStandardCompositeType);
6988 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6989 SourceLocation QuestionLoc);
6991 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6992 SourceLocation QuestionLoc);
6994 /// type checking for vector binary operators.
6995 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6996 SourceLocation Loc, bool IsCompAssign);
6997 QualType GetSignedVectorType(QualType V);
6998 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
6999 SourceLocation Loc, bool isRelational);
7000 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7001 SourceLocation Loc);
7003 /// type checking declaration initializers (C99 6.7.8)
7004 bool CheckForConstantInitializer(Expr *e, QualType t);
7006 // type checking C++ declaration initializers (C++ [dcl.init]).
7008 /// ReferenceCompareResult - Expresses the result of comparing two
7009 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
7010 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
7011 enum ReferenceCompareResult {
7012 /// Ref_Incompatible - The two types are incompatible, so direct
7013 /// reference binding is not possible.
7014 Ref_Incompatible = 0,
7015 /// Ref_Related - The two types are reference-related, which means
7016 /// that their unqualified forms (T1 and T2) are either the same
7017 /// or T1 is a base class of T2.
7019 /// Ref_Compatible_With_Added_Qualification - The two types are
7020 /// reference-compatible with added qualification, meaning that
7021 /// they are reference-compatible and the qualifiers on T1 (cv1)
7022 /// are greater than the qualifiers on T2 (cv2).
7023 Ref_Compatible_With_Added_Qualification,
7024 /// Ref_Compatible - The two types are reference-compatible and
7025 /// have equivalent qualifiers (cv1 == cv2).
7029 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
7030 QualType T1, QualType T2,
7031 bool &DerivedToBase,
7032 bool &ObjCConversion,
7033 bool &ObjCLifetimeConversion);
7035 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7036 Expr *CastExpr, CastKind &CastKind,
7037 ExprValueKind &VK, CXXCastPath &Path);
7039 /// \brief Force an expression with unknown-type to an expression of the
7041 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7043 /// \brief Type-check an expression that's being passed to an
7044 /// __unknown_anytype parameter.
7045 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
7046 Expr *result, QualType ¶mType);
7048 // CheckVectorCast - check type constraints for vectors.
7049 // Since vectors are an extension, there are no C standard reference for this.
7050 // We allow casting between vectors and integer datatypes of the same size.
7051 // returns true if the cast is invalid
7052 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7055 // CheckExtVectorCast - check type constraints for extended vectors.
7056 // Since vectors are an extension, there are no C standard reference for this.
7057 // We allow casting between vectors and integer datatypes of the same size,
7058 // or vectors and the element type of that vector.
7059 // returns the cast expr
7060 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
7063 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
7064 SourceLocation LParenLoc,
7066 SourceLocation RParenLoc);
7068 enum ARCConversionResult { ACR_okay, ACR_unbridged };
7070 /// \brief Checks for invalid conversions and casts between
7071 /// retainable pointers and other pointer kinds.
7072 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
7073 QualType castType, Expr *&op,
7074 CheckedConversionKind CCK);
7076 Expr *stripARCUnbridgedCast(Expr *e);
7077 void diagnoseARCUnbridgedCast(Expr *e);
7079 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
7082 /// checkRetainCycles - Check whether an Objective-C message send
7083 /// might create an obvious retain cycle.
7084 void checkRetainCycles(ObjCMessageExpr *msg);
7085 void checkRetainCycles(Expr *receiver, Expr *argument);
7086 void checkRetainCycles(VarDecl *Var, Expr *Init);
7088 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
7089 /// to weak/__unsafe_unretained type.
7090 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
7092 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
7093 /// to weak/__unsafe_unretained expression.
7094 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
7096 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
7097 /// \param Method - May be null.
7098 /// \param [out] ReturnType - The return type of the send.
7099 /// \return true iff there were any incompatible types.
7100 bool CheckMessageArgumentTypes(QualType ReceiverType,
7101 Expr **Args, unsigned NumArgs, Selector Sel,
7102 ArrayRef<SourceLocation> SelectorLocs,
7103 ObjCMethodDecl *Method, bool isClassMessage,
7104 bool isSuperMessage,
7105 SourceLocation lbrac, SourceLocation rbrac,
7106 QualType &ReturnType, ExprValueKind &VK);
7108 /// \brief Determine the result of a message send expression based on
7109 /// the type of the receiver, the method expected to receive the message,
7110 /// and the form of the message send.
7111 QualType getMessageSendResultType(QualType ReceiverType,
7112 ObjCMethodDecl *Method,
7113 bool isClassMessage, bool isSuperMessage);
7115 /// \brief If the given expression involves a message send to a method
7116 /// with a related result type, emit a note describing what happened.
7117 void EmitRelatedResultTypeNote(const Expr *E);
7119 /// \brief Given that we had incompatible pointer types in a return
7120 /// statement, check whether we're in a method with a related result
7121 /// type, and if so, emit a note describing what happened.
7122 void EmitRelatedResultTypeNoteForReturn(QualType destType);
7124 /// CheckBooleanCondition - Diagnose problems involving the use of
7125 /// the given expression as a boolean condition (e.g. in an if
7126 /// statement). Also performs the standard function and array
7127 /// decays, possibly changing the input variable.
7129 /// \param Loc - A location associated with the condition, e.g. the
7131 /// \return true iff there were any errors
7132 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
7134 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7137 /// DiagnoseAssignmentAsCondition - Given that an expression is
7138 /// being used as a boolean condition, warn if it's an assignment.
7139 void DiagnoseAssignmentAsCondition(Expr *E);
7141 /// \brief Redundant parentheses over an equality comparison can indicate
7142 /// that the user intended an assignment used as condition.
7143 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7145 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
7146 ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
7148 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
7149 /// the specified width and sign. If an overflow occurs, detect it and emit
7150 /// the specified diagnostic.
7151 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
7152 unsigned NewWidth, bool NewSign,
7153 SourceLocation Loc, unsigned DiagID);
7155 /// Checks that the Objective-C declaration is declared in the global scope.
7156 /// Emits an error and marks the declaration as invalid if it's not declared
7157 /// in the global scope.
7158 bool CheckObjCDeclScope(Decl *D);
7160 /// \brief Abstract base class used for diagnosing integer constant
7161 /// expression violations.
7162 class VerifyICEDiagnoser {
7166 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
7168 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
7169 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
7170 virtual ~VerifyICEDiagnoser() { }
7173 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7174 /// and reports the appropriate diagnostics. Returns false on success.
7175 /// Can optionally return the value of the expression.
7176 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7177 VerifyICEDiagnoser &Diagnoser,
7178 bool AllowFold = true);
7179 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7181 bool AllowFold = true);
7182 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0);
7184 /// VerifyBitField - verifies that a bit field expression is an ICE and has
7185 /// the correct width, and that the field type is valid.
7186 /// Returns false on success.
7187 /// Can optionally return whether the bit-field is of width 0
7188 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
7189 QualType FieldTy, Expr *BitWidth,
7190 bool *ZeroWidth = 0);
7192 enum CUDAFunctionTarget {
7199 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
7201 bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
7202 CUDAFunctionTarget CalleeTarget);
7204 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
7205 return CheckCUDATarget(IdentifyCUDATarget(Caller),
7206 IdentifyCUDATarget(Callee));
7209 /// \name Code completion
7211 /// \brief Describes the context in which code completion occurs.
7212 enum ParserCompletionContext {
7213 /// \brief Code completion occurs at top-level or namespace context.
7215 /// \brief Code completion occurs within a class, struct, or union.
7217 /// \brief Code completion occurs within an Objective-C interface, protocol,
7220 /// \brief Code completion occurs within an Objective-C implementation or
7221 /// category implementation
7222 PCC_ObjCImplementation,
7223 /// \brief Code completion occurs within the list of instance variables
7224 /// in an Objective-C interface, protocol, category, or implementation.
7225 PCC_ObjCInstanceVariableList,
7226 /// \brief Code completion occurs following one or more template
7229 /// \brief Code completion occurs following one or more template
7230 /// headers within a class.
7232 /// \brief Code completion occurs within an expression.
7234 /// \brief Code completion occurs within a statement, which may
7235 /// also be an expression or a declaration.
7237 /// \brief Code completion occurs at the beginning of the
7238 /// initialization statement (or expression) in a for loop.
7240 /// \brief Code completion occurs within the condition of an if,
7241 /// while, switch, or for statement.
7243 /// \brief Code completion occurs within the body of a function on a
7244 /// recovery path, where we do not have a specific handle on our position
7246 PCC_RecoveryInFunction,
7247 /// \brief Code completion occurs where only a type is permitted.
7249 /// \brief Code completion occurs in a parenthesized expression, which
7250 /// might also be a type cast.
7251 PCC_ParenthesizedExpression,
7252 /// \brief Code completion occurs within a sequence of declaration
7253 /// specifiers within a function, method, or block.
7254 PCC_LocalDeclarationSpecifiers
7257 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
7258 void CodeCompleteOrdinaryName(Scope *S,
7259 ParserCompletionContext CompletionContext);
7260 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
7261 bool AllowNonIdentifiers,
7262 bool AllowNestedNameSpecifiers);
7264 struct CodeCompleteExpressionData;
7265 void CodeCompleteExpression(Scope *S,
7266 const CodeCompleteExpressionData &Data);
7267 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
7268 SourceLocation OpLoc,
7270 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
7271 void CodeCompleteTag(Scope *S, unsigned TagSpec);
7272 void CodeCompleteTypeQualifiers(DeclSpec &DS);
7273 void CodeCompleteCase(Scope *S);
7274 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
7275 void CodeCompleteInitializer(Scope *S, Decl *D);
7276 void CodeCompleteReturn(Scope *S);
7277 void CodeCompleteAfterIf(Scope *S);
7278 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
7280 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
7281 bool EnteringContext);
7282 void CodeCompleteUsing(Scope *S);
7283 void CodeCompleteUsingDirective(Scope *S);
7284 void CodeCompleteNamespaceDecl(Scope *S);
7285 void CodeCompleteNamespaceAliasDecl(Scope *S);
7286 void CodeCompleteOperatorName(Scope *S);
7287 void CodeCompleteConstructorInitializer(Decl *Constructor,
7288 CXXCtorInitializer** Initializers,
7289 unsigned NumInitializers);
7290 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7291 bool AfterAmpersand);
7293 void CodeCompleteObjCAtDirective(Scope *S);
7294 void CodeCompleteObjCAtVisibility(Scope *S);
7295 void CodeCompleteObjCAtStatement(Scope *S);
7296 void CodeCompleteObjCAtExpression(Scope *S);
7297 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
7298 void CodeCompleteObjCPropertyGetter(Scope *S);
7299 void CodeCompleteObjCPropertySetter(Scope *S);
7300 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7302 void CodeCompleteObjCMessageReceiver(Scope *S);
7303 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
7304 IdentifierInfo **SelIdents,
7305 unsigned NumSelIdents,
7306 bool AtArgumentExpression);
7307 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
7308 IdentifierInfo **SelIdents,
7309 unsigned NumSelIdents,
7310 bool AtArgumentExpression,
7311 bool IsSuper = false);
7312 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
7313 IdentifierInfo **SelIdents,
7314 unsigned NumSelIdents,
7315 bool AtArgumentExpression,
7316 ObjCInterfaceDecl *Super = 0);
7317 void CodeCompleteObjCForCollection(Scope *S,
7318 DeclGroupPtrTy IterationVar);
7319 void CodeCompleteObjCSelector(Scope *S,
7320 IdentifierInfo **SelIdents,
7321 unsigned NumSelIdents);
7322 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
7323 unsigned NumProtocols);
7324 void CodeCompleteObjCProtocolDecl(Scope *S);
7325 void CodeCompleteObjCInterfaceDecl(Scope *S);
7326 void CodeCompleteObjCSuperclass(Scope *S,
7327 IdentifierInfo *ClassName,
7328 SourceLocation ClassNameLoc);
7329 void CodeCompleteObjCImplementationDecl(Scope *S);
7330 void CodeCompleteObjCInterfaceCategory(Scope *S,
7331 IdentifierInfo *ClassName,
7332 SourceLocation ClassNameLoc);
7333 void CodeCompleteObjCImplementationCategory(Scope *S,
7334 IdentifierInfo *ClassName,
7335 SourceLocation ClassNameLoc);
7336 void CodeCompleteObjCPropertyDefinition(Scope *S);
7337 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
7338 IdentifierInfo *PropertyName);
7339 void CodeCompleteObjCMethodDecl(Scope *S,
7340 bool IsInstanceMethod,
7341 ParsedType ReturnType);
7342 void CodeCompleteObjCMethodDeclSelector(Scope *S,
7343 bool IsInstanceMethod,
7344 bool AtParameterName,
7345 ParsedType ReturnType,
7346 IdentifierInfo **SelIdents,
7347 unsigned NumSelIdents);
7348 void CodeCompletePreprocessorDirective(bool InConditional);
7349 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
7350 void CodeCompletePreprocessorMacroName(bool IsDefinition);
7351 void CodeCompletePreprocessorExpression();
7352 void CodeCompletePreprocessorMacroArgument(Scope *S,
7353 IdentifierInfo *Macro,
7354 MacroInfo *MacroInfo,
7356 void CodeCompleteNaturalLanguage();
7357 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7358 CodeCompletionTUInfo &CCTUInfo,
7359 SmallVectorImpl<CodeCompletionResult> &Results);
7362 //===--------------------------------------------------------------------===//
7363 // Extra semantic analysis beyond the C type system
7366 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
7367 unsigned ByteNo) const;
7370 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7371 const ArraySubscriptExpr *ASE=0,
7372 bool AllowOnePastEnd=true, bool IndexNegated=false);
7373 void CheckArrayAccess(const Expr *E);
7374 // Used to grab the relevant information from a FormatAttr and a
7375 // FunctionDeclaration.
7376 struct FormatStringInfo {
7378 unsigned FirstDataArg;
7382 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7383 FormatStringInfo *FSI);
7384 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
7385 const FunctionProtoType *Proto);
7386 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
7387 ArrayRef<const Expr *> Args);
7388 bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
7389 const FunctionProtoType *Proto);
7390 void CheckConstructorCall(FunctionDecl *FDecl,
7391 ArrayRef<const Expr *> Args,
7392 const FunctionProtoType *Proto,
7393 SourceLocation Loc);
7395 void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
7396 unsigned NumProtoArgs, bool IsMemberFunction,
7397 SourceLocation Loc, SourceRange Range,
7398 VariadicCallType CallType);
7401 bool CheckObjCString(Expr *Arg);
7403 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7404 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7405 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7407 bool SemaBuiltinVAStart(CallExpr *TheCall);
7408 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
7409 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
7412 // Used by C++ template instantiation.
7413 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
7416 bool SemaBuiltinPrefetch(CallExpr *TheCall);
7417 bool SemaBuiltinObjectSize(CallExpr *TheCall);
7418 bool SemaBuiltinLongjmp(CallExpr *TheCall);
7419 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
7420 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
7421 AtomicExpr::AtomicOp Op);
7422 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7423 llvm::APSInt &Result);
7425 enum FormatStringType {
7434 static FormatStringType GetFormatStringType(const FormatAttr *Format);
7436 enum StringLiteralCheckType {
7438 SLCT_UncheckedLiteral,
7442 StringLiteralCheckType checkFormatStringExpr(const Expr *E,
7443 ArrayRef<const Expr *> Args,
7445 unsigned format_idx,
7446 unsigned firstDataArg,
7447 FormatStringType Type,
7448 VariadicCallType CallType,
7449 bool inFunctionCall = true);
7451 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
7452 ArrayRef<const Expr *> Args, bool HasVAListArg,
7453 unsigned format_idx, unsigned firstDataArg,
7454 FormatStringType Type, bool inFunctionCall,
7455 VariadicCallType CallType);
7457 bool CheckFormatArguments(const FormatAttr *Format,
7458 ArrayRef<const Expr *> Args,
7460 VariadicCallType CallType,
7461 SourceLocation Loc, SourceRange Range);
7462 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
7463 bool HasVAListArg, unsigned format_idx,
7464 unsigned firstDataArg, FormatStringType Type,
7465 VariadicCallType CallType,
7466 SourceLocation Loc, SourceRange range);
7468 void CheckNonNullArguments(const NonNullAttr *NonNull,
7469 const Expr * const *ExprArgs,
7470 SourceLocation CallSiteLoc);
7472 void CheckMemaccessArguments(const CallExpr *Call,
7474 IdentifierInfo *FnName);
7476 void CheckStrlcpycatArguments(const CallExpr *Call,
7477 IdentifierInfo *FnName);
7479 void CheckStrncatArguments(const CallExpr *Call,
7480 IdentifierInfo *FnName);
7482 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
7483 SourceLocation ReturnLoc);
7484 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
7485 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
7486 void CheckForIntOverflow(Expr *E);
7487 void CheckUnsequencedOperations(Expr *E);
7489 /// \brief Perform semantic checks on a completed expression. This will either
7490 /// be a full-expression or a default argument expression.
7491 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
7492 bool IsConstexpr = false);
7494 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
7498 /// \brief Register a magic integral constant to be used as a type tag.
7499 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7500 uint64_t MagicValue, QualType Type,
7501 bool LayoutCompatible, bool MustBeNull);
7503 struct TypeTagData {
7506 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
7507 Type(Type), LayoutCompatible(LayoutCompatible),
7508 MustBeNull(MustBeNull)
7513 /// If true, \c Type should be compared with other expression's types for
7514 /// layout-compatibility.
7515 unsigned LayoutCompatible : 1;
7516 unsigned MustBeNull : 1;
7519 /// A pair of ArgumentKind identifier and magic value. This uniquely
7520 /// identifies the magic value.
7521 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
7524 /// \brief A map from magic value to type information.
7525 OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> >
7526 TypeTagForDatatypeMagicValues;
7528 /// \brief Peform checks on a call of a function with argument_with_type_tag
7529 /// or pointer_with_type_tag attributes.
7530 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7531 const Expr * const *ExprArgs);
7533 /// \brief The parser's current scope.
7535 /// The parser maintains this state here.
7538 mutable IdentifierInfo *Ident_super;
7541 friend class Parser;
7542 friend class InitializationSequence;
7543 friend class ASTReader;
7544 friend class ASTWriter;
7547 /// \brief Retrieve the parser's current scope.
7549 /// This routine must only be used when it is certain that semantic analysis
7550 /// and the parser are in precisely the same context, which is not the case
7551 /// when, e.g., we are performing any kind of template instantiation.
7552 /// Therefore, the only safe places to use this scope are in the parser
7553 /// itself and in routines directly invoked from the parser and *never* from
7554 /// template substitution or instantiation.
7555 Scope *getCurScope() const { return CurScope; }
7557 IdentifierInfo *getSuperIdentifier() const;
7559 Decl *getObjCDeclContext() const;
7561 DeclContext *getCurLexicalContext() const {
7562 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
7565 AvailabilityResult getCurContextAvailability() const;
7567 const DeclContext *getCurObjCLexicalContext() const {
7568 const DeclContext *DC = getCurLexicalContext();
7569 // A category implicitly has the attribute of the interface.
7570 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
7571 DC = CatD->getClassInterface();
7576 /// \brief RAII object that enters a new expression evaluation context.
7577 class EnterExpressionEvaluationContext {
7581 EnterExpressionEvaluationContext(Sema &Actions,
7582 Sema::ExpressionEvaluationContext NewContext,
7583 Decl *LambdaContextDecl = 0,
7584 bool IsDecltype = false)
7585 : Actions(Actions) {
7586 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
7589 EnterExpressionEvaluationContext(Sema &Actions,
7590 Sema::ExpressionEvaluationContext NewContext,
7591 Sema::ReuseLambdaContextDecl_t,
7592 bool IsDecltype = false)
7593 : Actions(Actions) {
7594 Actions.PushExpressionEvaluationContext(NewContext,
7595 Sema::ReuseLambdaContextDecl,
7599 ~EnterExpressionEvaluationContext() {
7600 Actions.PopExpressionEvaluationContext();
7604 } // end namespace clang