Sema.h revision 09df2b066221d869f17f4b5762405f111a65f983
1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
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/MangleNumberingContext.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"
50#include <deque>
51#include <string>
52#include <vector>
53
54namespace llvm {
55  class APSInt;
56  template <typename ValueT> struct DenseMapInfo;
57  template <typename ValueT, typename ValueInfoT> class DenseSet;
58  class SmallBitVector;
59}
60
61namespace clang {
62  class ADLResult;
63  class ASTConsumer;
64  class ASTContext;
65  class ASTMutationListener;
66  class ASTReader;
67  class ASTWriter;
68  class ArrayType;
69  class AttributeList;
70  class BlockDecl;
71  class CapturedDecl;
72  class CXXBasePath;
73  class CXXBasePaths;
74  class CXXBindTemporaryExpr;
75  typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
76  class CXXConstructorDecl;
77  class CXXConversionDecl;
78  class CXXDestructorDecl;
79  class CXXFieldCollector;
80  class CXXMemberCallExpr;
81  class CXXMethodDecl;
82  class CXXScopeSpec;
83  class CXXTemporary;
84  class CXXTryStmt;
85  class CallExpr;
86  class ClassTemplateDecl;
87  class ClassTemplatePartialSpecializationDecl;
88  class ClassTemplateSpecializationDecl;
89  class CodeCompleteConsumer;
90  class CodeCompletionAllocator;
91  class CodeCompletionTUInfo;
92  class CodeCompletionResult;
93  class Decl;
94  class DeclAccessPair;
95  class DeclContext;
96  class DeclRefExpr;
97  class DeclaratorDecl;
98  class DeducedTemplateArgument;
99  class DependentDiagnostic;
100  class DesignatedInitExpr;
101  class Designation;
102  class EnumConstantDecl;
103  class Expr;
104  class ExtVectorType;
105  class ExternalSemaSource;
106  class FormatAttr;
107  class FriendDecl;
108  class FunctionDecl;
109  class FunctionProtoType;
110  class FunctionTemplateDecl;
111  class ImplicitConversionSequence;
112  class InitListExpr;
113  class InitializationKind;
114  class InitializationSequence;
115  class InitializedEntity;
116  class IntegerLiteral;
117  class LabelStmt;
118  class LambdaExpr;
119  class LangOptions;
120  class LocalInstantiationScope;
121  class LookupResult;
122  class MacroInfo;
123  class MultiLevelTemplateArgumentList;
124  class NamedDecl;
125  class NonNullAttr;
126  class ObjCCategoryDecl;
127  class ObjCCategoryImplDecl;
128  class ObjCCompatibleAliasDecl;
129  class ObjCContainerDecl;
130  class ObjCImplDecl;
131  class ObjCImplementationDecl;
132  class ObjCInterfaceDecl;
133  class ObjCIvarDecl;
134  template <class T> class ObjCList;
135  class ObjCMessageExpr;
136  class ObjCMethodDecl;
137  class ObjCPropertyDecl;
138  class ObjCProtocolDecl;
139  class OMPThreadPrivateDecl;
140  class OverloadCandidateSet;
141  class OverloadExpr;
142  class ParenListExpr;
143  class ParmVarDecl;
144  class Preprocessor;
145  class PseudoDestructorTypeStorage;
146  class PseudoObjectExpr;
147  class QualType;
148  class StandardConversionSequence;
149  class Stmt;
150  class StringLiteral;
151  class SwitchStmt;
152  class TargetAttributesSema;
153  class TemplateArgument;
154  class TemplateArgumentList;
155  class TemplateArgumentLoc;
156  class TemplateDecl;
157  class TemplateParameterList;
158  class TemplatePartialOrderingContext;
159  class TemplateTemplateParmDecl;
160  class Token;
161  class TypeAliasDecl;
162  class TypedefDecl;
163  class TypedefNameDecl;
164  class TypeLoc;
165  class UnqualifiedId;
166  class UnresolvedLookupExpr;
167  class UnresolvedMemberExpr;
168  class UnresolvedSetImpl;
169  class UnresolvedSetIterator;
170  class UsingDecl;
171  class UsingShadowDecl;
172  class ValueDecl;
173  class VarDecl;
174  class VisibilityAttr;
175  class VisibleDeclConsumer;
176  class IndirectFieldDecl;
177
178namespace sema {
179  class AccessedEntity;
180  class BlockScopeInfo;
181  class CapturedRegionScopeInfo;
182  class CapturingScopeInfo;
183  class CompoundScopeInfo;
184  class DelayedDiagnostic;
185  class DelayedDiagnosticPool;
186  class FunctionScopeInfo;
187  class LambdaScopeInfo;
188  class PossiblyUnreachableDiag;
189  class TemplateDeductionInfo;
190}
191
192// FIXME: No way to easily map from TemplateTypeParmTypes to
193// TemplateTypeParmDecls, so we have this horrible PointerUnion.
194typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
195                  SourceLocation> UnexpandedParameterPack;
196
197/// Sema - This implements semantic analysis and AST building for C.
198class Sema {
199  Sema(const Sema &) LLVM_DELETED_FUNCTION;
200  void operator=(const Sema &) LLVM_DELETED_FUNCTION;
201  mutable const TargetAttributesSema* TheTargetAttributesSema;
202
203  ///\brief Source of additional semantic information.
204  ExternalSemaSource *ExternalSource;
205
206  ///\brief Whether Sema has generated a multiplexer and has to delete it.
207  bool isMultiplexExternalSource;
208
209  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
210
211  static bool
212  shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) {
213    // We are about to link these. It is now safe to compute the linkage of
214    // the new decl. If the new decl has external linkage, we will
215    // link it with the hidden decl (which also has external linkage) and
216    // it will keep having external linkage. If it has internal linkage, we
217    // will not link it. Since it has no previous decls, it will remain
218    // with internal linkage.
219    return !Old->isHidden() || New->isExternallyVisible();
220  }
221
222public:
223  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
224  typedef OpaquePtr<TemplateName> TemplateTy;
225  typedef OpaquePtr<QualType> TypeTy;
226
227  OpenCLOptions OpenCLFeatures;
228  FPOptions FPFeatures;
229
230  const LangOptions &LangOpts;
231  Preprocessor &PP;
232  ASTContext &Context;
233  ASTConsumer &Consumer;
234  DiagnosticsEngine &Diags;
235  SourceManager &SourceMgr;
236
237  /// \brief Flag indicating whether or not to collect detailed statistics.
238  bool CollectStats;
239
240  /// \brief Code-completion consumer.
241  CodeCompleteConsumer *CodeCompleter;
242
243  /// CurContext - This is the current declaration context of parsing.
244  DeclContext *CurContext;
245
246  /// \brief Generally null except when we temporarily switch decl contexts,
247  /// like in \see ActOnObjCTemporaryExitContainerContext.
248  DeclContext *OriginalLexicalContext;
249
250  /// VAListTagName - The declaration name corresponding to __va_list_tag.
251  /// This is used as part of a hack to omit that class from ADL results.
252  DeclarationName VAListTagName;
253
254  /// PackContext - Manages the stack for \#pragma pack. An alignment
255  /// of 0 indicates default alignment.
256  void *PackContext; // Really a "PragmaPackStack*"
257
258  bool MSStructPragmaOn; // True when \#pragma ms_struct on
259
260  /// VisContext - Manages the stack for \#pragma GCC visibility.
261  void *VisContext; // Really a "PragmaVisStack*"
262
263  /// \brief Flag indicating if Sema is building a recovery call expression.
264  ///
265  /// This flag is used to avoid building recovery call expressions
266  /// if Sema is already doing so, which would cause infinite recursions.
267  bool IsBuildingRecoveryCallExpr;
268
269  /// ExprNeedsCleanups - True if the current evaluation context
270  /// requires cleanups to be run at its conclusion.
271  bool ExprNeedsCleanups;
272
273  /// ExprCleanupObjects - This is the stack of objects requiring
274  /// cleanup that are created by the current full expression.  The
275  /// element type here is ExprWithCleanups::Object.
276  SmallVector<BlockDecl*, 8> ExprCleanupObjects;
277
278  llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
279
280  /// \brief Stack containing information about each of the nested
281  /// function, block, and method scopes that are currently active.
282  ///
283  /// This array is never empty.  Clients should ignore the first
284  /// element, which is used to cache a single FunctionScopeInfo
285  /// that's used to parse every top-level function.
286  SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
287
288  typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
289                     &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
290    ExtVectorDeclsType;
291
292  /// ExtVectorDecls - This is a list all the extended vector types. This allows
293  /// us to associate a raw vector type with one of the ext_vector type names.
294  /// This is only necessary for issuing pretty diagnostics.
295  ExtVectorDeclsType ExtVectorDecls;
296
297  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
298  OwningPtr<CXXFieldCollector> FieldCollector;
299
300  typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
301
302  /// \brief Set containing all declared private fields that are not used.
303  NamedDeclSetType UnusedPrivateFields;
304
305  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
306
307  /// PureVirtualClassDiagSet - a set of class declarations which we have
308  /// emitted a list of pure virtual functions. Used to prevent emitting the
309  /// same list more than once.
310  OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
311
312  /// ParsingInitForAutoVars - a set of declarations with auto types for which
313  /// we are currently parsing the initializer.
314  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
315
316  /// \brief A mapping from external names to the most recent
317  /// locally-scoped extern "C" declaration with that name.
318  ///
319  /// This map contains external declarations introduced in local
320  /// scopes, e.g.,
321  ///
322  /// \code
323  /// extern "C" void f() {
324  ///   void foo(int, int);
325  /// }
326  /// \endcode
327  ///
328  /// Here, the name "foo" will be associated with the declaration of
329  /// "foo" within f. This name is not visible outside of
330  /// "f". However, we still find it in two cases:
331  ///
332  ///   - If we are declaring another global or extern "C" entity with
333  ///     the name "foo", we can find "foo" as a previous declaration,
334  ///     so that the types of this external declaration can be checked
335  ///     for compatibility.
336  ///
337  ///   - If we would implicitly declare "foo" (e.g., due to a call to
338  ///     "foo" in C when no prototype or definition is visible), then
339  ///     we find this declaration of "foo" and complain that it is
340  ///     not visible.
341  llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls;
342
343  /// \brief Look for a locally scoped extern "C" declaration by the given name.
344  NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
345
346  typedef LazyVector<VarDecl *, ExternalSemaSource,
347                     &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
348    TentativeDefinitionsType;
349
350  /// \brief All the tentative definitions encountered in the TU.
351  TentativeDefinitionsType TentativeDefinitions;
352
353  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
354                     &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
355    UnusedFileScopedDeclsType;
356
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;
360
361  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
362                     &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
363    DelegatingCtorDeclsType;
364
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;
368
369  /// \brief All the destructors seen during a class definition that had their
370  /// exception spec computation delayed because it depended on an unparsed
371  /// exception spec.
372  SmallVector<CXXDestructorDecl*, 2> DelayedDestructorExceptionSpecs;
373
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;
380
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;
390
391  /// \brief Callback to the parser to parse templated functions when needed.
392  typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD);
393  LateTemplateParserCB *LateTemplateParser;
394  void *OpaqueParser;
395
396  void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
397    LateTemplateParser = LTP;
398    OpaqueParser = P;
399  }
400
401  class DelayedDiagnostics;
402
403  class DelayedDiagnosticsState {
404    sema::DelayedDiagnosticPool *SavedPool;
405    friend class Sema::DelayedDiagnostics;
406  };
407  typedef DelayedDiagnosticsState ParsingDeclState;
408  typedef DelayedDiagnosticsState ProcessingContextState;
409
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;
416
417  public:
418    DelayedDiagnostics() : CurPool(0) {}
419
420    /// Adds a delayed diagnostic.
421    void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
422
423    /// Determines whether diagnostics should be delayed.
424    bool shouldDelayDiagnostics() { return CurPool != 0; }
425
426    /// Returns the current delayed-diagnostics pool.
427    sema::DelayedDiagnosticPool *getCurrentPool() const {
428      return CurPool;
429    }
430
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;
436      CurPool = &pool;
437      return state;
438    }
439
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;
445    }
446
447    /// Enter a new scope where access and deprecation diagnostics are
448    /// not delayed.
449    DelayedDiagnosticsState pushUndelayed() {
450      DelayedDiagnosticsState state;
451      state.SavedPool = CurPool;
452      CurPool = 0;
453      return state;
454    }
455
456    /// Undo a previous pushUndelayed().
457    void popUndelayed(DelayedDiagnosticsState state) {
458      assert(CurPool == NULL);
459      CurPool = state.SavedPool;
460    }
461  } DelayedDiagnostics;
462
463  /// A RAII object to temporarily push a declaration context.
464  class ContextRAII {
465  private:
466    Sema &S;
467    DeclContext *SavedContext;
468    ProcessingContextState SavedContextState;
469    QualType SavedCXXThisTypeOverride;
470
471  public:
472    ContextRAII(Sema &S, DeclContext *ContextToPush)
473      : S(S), SavedContext(S.CurContext),
474        SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
475        SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
476    {
477      assert(ContextToPush && "pushing null context");
478      S.CurContext = ContextToPush;
479    }
480
481    void pop() {
482      if (!SavedContext) return;
483      S.CurContext = SavedContext;
484      S.DelayedDiagnostics.popUndelayed(SavedContextState);
485      S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
486      SavedContext = 0;
487    }
488
489    ~ContextRAII() {
490      pop();
491    }
492  };
493
494  /// \brief RAII object to handle the state changes required to synthesize
495  /// a function body.
496  class SynthesizedFunctionScope {
497    Sema &S;
498    Sema::ContextRAII SavedContext;
499
500  public:
501    SynthesizedFunctionScope(Sema &S, DeclContext *DC)
502      : S(S), SavedContext(S, DC)
503    {
504      S.PushFunctionScope();
505      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
506    }
507
508    ~SynthesizedFunctionScope() {
509      S.PopExpressionEvaluationContext();
510      S.PopFunctionScopeInfo();
511    }
512  };
513
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;
518
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;
524
525
526  /// \brief Load weak undeclared identifiers from the external source.
527  void LoadExternalWeakUndeclaredIdentifiers();
528
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;
535
536  IdentifierResolver IdResolver;
537
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.
541  Scope *TUScope;
542
543  /// \brief The C++ "std" namespace, where the standard library resides.
544  LazyDeclPtr StdNamespace;
545
546  /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
547  /// standard library.
548  LazyDeclPtr StdBadAlloc;
549
550  /// \brief The C++ "std::initializer_list" template, which is defined in
551  /// \<initializer_list>.
552  ClassTemplateDecl *StdInitializerList;
553
554  /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
555  RecordDecl *CXXTypeInfoDecl;
556
557  /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
558  RecordDecl *MSVCGuidDecl;
559
560  /// \brief Caches identifiers/selectors for NSFoundation APIs.
561  OwningPtr<NSAPI> NSAPIObj;
562
563  /// \brief The declaration of the Objective-C NSNumber class.
564  ObjCInterfaceDecl *NSNumberDecl;
565
566  /// \brief Pointer to NSNumber type (NSNumber *).
567  QualType NSNumberPointer;
568
569  /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
570  ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
571
572  /// \brief The declaration of the Objective-C NSString class.
573  ObjCInterfaceDecl *NSStringDecl;
574
575  /// \brief Pointer to NSString type (NSString *).
576  QualType NSStringPointer;
577
578  /// \brief The declaration of the stringWithUTF8String: method.
579  ObjCMethodDecl *StringWithUTF8StringMethod;
580
581  /// \brief The declaration of the Objective-C NSArray class.
582  ObjCInterfaceDecl *NSArrayDecl;
583
584  /// \brief The declaration of the arrayWithObjects:count: method.
585  ObjCMethodDecl *ArrayWithObjectsMethod;
586
587  /// \brief The declaration of the Objective-C NSDictionary class.
588  ObjCInterfaceDecl *NSDictionaryDecl;
589
590  /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
591  ObjCMethodDecl *DictionaryWithObjectsMethod;
592
593  /// \brief id<NSCopying> type.
594  QualType QIDNSCopying;
595
596  /// \brief will hold 'respondsToSelector:'
597  Selector RespondsToSelectorSel;
598
599  /// A flag to remember whether the implicit forms of operator new and delete
600  /// have been declared.
601  bool GlobalNewDeleteDeclared;
602
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;
606
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
614    /// run time.
615    Unevaluated,
616
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.
620    UnevaluatedAbstract,
621
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).
625    ConstantEvaluated,
626
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,
631
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.
635    ///
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
641  };
642
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;
648
649    /// \brief Whether the enclosing context needed a cleanup.
650    bool ParentNeedsCleanups;
651
652    /// \brief Whether we are in a decltype expression.
653    bool IsDecltype;
654
655    /// \brief The number of active cleanup objects when we entered
656    /// this expression evaluation context.
657    unsigned NumCleanupObjects;
658
659    llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
660
661    /// \brief The lambdas that are present within this context, if it
662    /// is indeed an unevaluated context.
663    SmallVector<LambdaExpr *, 2> Lambdas;
664
665    /// \brief The declaration that provides context for lambda expressions
666    /// and block literals if the normal declaration context does not
667    /// suffice, e.g., in a default function argument.
668    Decl *ManglingContextDecl;
669
670    /// \brief The context information used to mangle lambda expressions
671    /// and block literals within this context.
672    ///
673    /// This mangling information is allocated lazily, since most contexts
674    /// do not have lambda expressions or block literals.
675    IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
676
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;
680
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;
684
685    ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
686                                      unsigned NumCleanupObjects,
687                                      bool ParentNeedsCleanups,
688                                      Decl *ManglingContextDecl,
689                                      bool IsDecltype)
690      : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
691        IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
692        ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
693
694    /// \brief Retrieve the mangling numbering context, used to consistently
695    /// number constructs like lambdas for mangling.
696    MangleNumberingContext &getMangleNumberingContext() {
697      assert(ManglingContextDecl && "Need to have a context declaration");
698      if (!MangleNumbering)
699        MangleNumbering = new MangleNumberingContext;
700      return *MangleNumbering;
701    }
702
703    bool isUnevaluated() const {
704      return Context == Unevaluated || Context == UnevaluatedAbstract;
705    }
706  };
707
708  /// A stack of expression evaluation contexts.
709  SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
710
711  /// \brief Compute the mangling number context for a lambda expression or
712  /// block literal.
713  ///
714  /// \param DC - The DeclContext containing the lambda expression or
715  /// block literal.
716  /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
717  /// associated with the context, if relevant.
718  MangleNumberingContext *getCurrentMangleNumberContext(
719    const DeclContext *DC,
720    Decl *&ManglingContextDecl);
721
722
723  /// SpecialMemberOverloadResult - The overloading result for a special member
724  /// function.
725  ///
726  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
727  /// integer are used to determine whether overload resolution succeeded.
728  class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
729  public:
730    enum Kind {
731      NoMemberOrDeleted,
732      Ambiguous,
733      Success
734    };
735
736  private:
737    llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
738
739  public:
740    SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
741      : FastFoldingSetNode(ID)
742    {}
743
744    CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
745    void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
746
747    Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
748    void setKind(Kind K) { Pair.setInt(K); }
749  };
750
751  /// \brief A cache of special member function overload resolution results
752  /// for C++ records.
753  llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
754
755  /// \brief The kind of translation unit we are processing.
756  ///
757  /// When we're processing a complete translation unit, Sema will perform
758  /// end-of-translation-unit semantic tasks (such as creating
759  /// initializers for tentative definitions in C) once parsing has
760  /// completed. Modules and precompiled headers perform different kinds of
761  /// checks.
762  TranslationUnitKind TUKind;
763
764  llvm::BumpPtrAllocator BumpAlloc;
765
766  /// \brief The number of SFINAE diagnostics that have been trapped.
767  unsigned NumSFINAEErrors;
768
769  typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> >
770    UnparsedDefaultArgInstantiationsMap;
771
772  /// \brief A mapping from parameters with unparsed default arguments to the
773  /// set of instantiations of each parameter.
774  ///
775  /// This mapping is a temporary data structure used when parsing
776  /// nested class templates or nested classes of class templates,
777  /// where we might end up instantiating an inner class before the
778  /// default arguments of its methods have been parsed.
779  UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
780
781  // Contains the locations of the beginning of unparsed default
782  // argument locations.
783  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
784
785  /// UndefinedInternals - all the used, undefined objects which require a
786  /// definition in this translation unit.
787  llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
788
789  /// Obtain a sorted list of functions that are undefined but ODR-used.
790  void getUndefinedButUsed(
791    llvm::SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
792
793  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
794  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
795
796  /// Method Pool - allows efficient lookup when typechecking messages to "id".
797  /// We need to maintain a list, since selectors can have differing signatures
798  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
799  /// of selectors are "overloaded").
800  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
801  /// methods inside categories with a particular selector.
802  GlobalMethodPool MethodPool;
803
804  /// Method selectors used in a \@selector expression. Used for implementation
805  /// of -Wselector.
806  llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
807
808  /// Kinds of C++ special members.
809  enum CXXSpecialMember {
810    CXXDefaultConstructor,
811    CXXCopyConstructor,
812    CXXMoveConstructor,
813    CXXCopyAssignment,
814    CXXMoveAssignment,
815    CXXDestructor,
816    CXXInvalid
817  };
818
819  typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
820
821  /// The C++ special members which we are currently in the process of
822  /// declaring. If this process recursively triggers the declaration of the
823  /// same special member, we should act as if it is not yet declared.
824  llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
825
826  void ReadMethodPool(Selector Sel);
827
828  /// Private Helper predicate to check for 'self'.
829  bool isSelfExpr(Expr *RExpr);
830
831  /// \brief Cause the active diagnostic on the DiagosticsEngine to be
832  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
833  /// should not be used elsewhere.
834  void EmitCurrentDiagnostic(unsigned DiagID);
835
836  /// Records and restores the FP_CONTRACT state on entry/exit of compound
837  /// statements.
838  class FPContractStateRAII {
839  public:
840    FPContractStateRAII(Sema& S)
841      : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
842    ~FPContractStateRAII() {
843      S.FPFeatures.fp_contract = OldFPContractState;
844    }
845  private:
846    Sema& S;
847    bool OldFPContractState : 1;
848  };
849
850  typedef llvm::MCAsmParserSemaCallback::InlineAsmIdentifierInfo
851    InlineAsmIdentifierInfo;
852
853public:
854  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
855       TranslationUnitKind TUKind = TU_Complete,
856       CodeCompleteConsumer *CompletionConsumer = 0);
857  ~Sema();
858
859  /// \brief Perform initialization that occurs after the parser has been
860  /// initialized but before it parses anything.
861  void Initialize();
862
863  const LangOptions &getLangOpts() const { return LangOpts; }
864  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
865  FPOptions     &getFPOptions() { return FPFeatures; }
866
867  DiagnosticsEngine &getDiagnostics() const { return Diags; }
868  SourceManager &getSourceManager() const { return SourceMgr; }
869  const TargetAttributesSema &getTargetAttributesSema() const;
870  Preprocessor &getPreprocessor() const { return PP; }
871  ASTContext &getASTContext() const { return Context; }
872  ASTConsumer &getASTConsumer() const { return Consumer; }
873  ASTMutationListener *getASTMutationListener() const;
874  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
875
876  ///\brief Registers an external source. If an external source already exists,
877  /// creates a multiplex external source and appends to it.
878  ///
879  ///\param[in] E - A non-null external sema source.
880  ///
881  void addExternalSource(ExternalSemaSource *E);
882
883  void PrintStats() const;
884
885  /// \brief Helper class that creates diagnostics with optional
886  /// template instantiation stacks.
887  ///
888  /// This class provides a wrapper around the basic DiagnosticBuilder
889  /// class that emits diagnostics. SemaDiagnosticBuilder is
890  /// responsible for emitting the diagnostic (as DiagnosticBuilder
891  /// does) and, if the diagnostic comes from inside a template
892  /// instantiation, printing the template instantiation stack as
893  /// well.
894  class SemaDiagnosticBuilder : public DiagnosticBuilder {
895    Sema &SemaRef;
896    unsigned DiagID;
897
898  public:
899    SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
900      : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
901
902    ~SemaDiagnosticBuilder() {
903      // If we aren't active, there is nothing to do.
904      if (!isActive()) return;
905
906      // Otherwise, we need to emit the diagnostic. First flush the underlying
907      // DiagnosticBuilder data, and clear the diagnostic builder itself so it
908      // won't emit the diagnostic in its own destructor.
909      //
910      // This seems wasteful, in that as written the DiagnosticBuilder dtor will
911      // do its own needless checks to see if the diagnostic needs to be
912      // emitted. However, because we take care to ensure that the builder
913      // objects never escape, a sufficiently smart compiler will be able to
914      // eliminate that code.
915      FlushCounts();
916      Clear();
917
918      // Dispatch to Sema to emit the diagnostic.
919      SemaRef.EmitCurrentDiagnostic(DiagID);
920    }
921
922    /// Teach operator<< to produce an object of the correct type.
923    template<typename T>
924    friend const SemaDiagnosticBuilder &operator<<(
925        const SemaDiagnosticBuilder &Diag, const T &Value) {
926      const DiagnosticBuilder &BaseDiag = Diag;
927      BaseDiag << Value;
928      return Diag;
929    }
930  };
931
932  /// \brief Emit a diagnostic.
933  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
934    DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
935    return SemaDiagnosticBuilder(DB, *this, DiagID);
936  }
937
938  /// \brief Emit a partial diagnostic.
939  SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
940
941  /// \brief Build a partial diagnostic.
942  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
943
944  bool findMacroSpelling(SourceLocation &loc, StringRef name);
945
946  /// \brief Get a string to suggest for zero-initialization of a type.
947  std::string getFixItZeroInitializerForType(QualType T) const;
948  std::string getFixItZeroLiteralForType(QualType T) const;
949
950  ExprResult Owned(Expr* E) { return E; }
951  ExprResult Owned(ExprResult R) { return R; }
952  StmtResult Owned(Stmt* S) { return S; }
953
954  void ActOnEndOfTranslationUnit();
955
956  void CheckDelegatingCtorCycles();
957
958  Scope *getScopeForContext(DeclContext *Ctx);
959
960  void PushFunctionScope();
961  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
962  void PushLambdaScope(CXXRecordDecl *Lambda, CXXMethodDecl *CallOperator);
963  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
964                               RecordDecl *RD,
965                               CapturedRegionKind K);
966  void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP =0,
967                            const Decl *D = 0, const BlockExpr *blkExpr = 0);
968
969  sema::FunctionScopeInfo *getCurFunction() const {
970    return FunctionScopes.back();
971  }
972
973  template <typename ExprT>
974  void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
975    if (!isUnevaluatedContext())
976      getCurFunction()->recordUseOfWeak(E, IsRead);
977  }
978
979  void PushCompoundScope();
980  void PopCompoundScope();
981
982  sema::CompoundScopeInfo &getCurCompoundScope() const;
983
984  bool hasAnyUnrecoverableErrorsInThisFunction() const;
985
986  /// \brief Retrieve the current block, if any.
987  sema::BlockScopeInfo *getCurBlock();
988
989  /// \brief Retrieve the current lambda expression, if any.
990  sema::LambdaScopeInfo *getCurLambda();
991
992  /// \brief Retrieve the current captured region, if any.
993  sema::CapturedRegionScopeInfo *getCurCapturedRegion();
994
995  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
996  SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
997
998  void ActOnComment(SourceRange Comment);
999
1000  //===--------------------------------------------------------------------===//
1001  // Type Analysis / Processing: SemaType.cpp.
1002  //
1003
1004  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1005                              const DeclSpec *DS = 0);
1006  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1007                              const DeclSpec *DS = 0);
1008  QualType BuildPointerType(QualType T,
1009                            SourceLocation Loc, DeclarationName Entity);
1010  QualType BuildReferenceType(QualType T, bool LValueRef,
1011                              SourceLocation Loc, DeclarationName Entity);
1012  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1013                          Expr *ArraySize, unsigned Quals,
1014                          SourceRange Brackets, DeclarationName Entity);
1015  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1016                              SourceLocation AttrLoc);
1017
1018  bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1019
1020  /// \brief Build a function type.
1021  ///
1022  /// This routine checks the function type according to C++ rules and
1023  /// under the assumption that the result type and parameter types have
1024  /// just been instantiated from a template. It therefore duplicates
1025  /// some of the behavior of GetTypeForDeclarator, but in a much
1026  /// simpler form that is only suitable for this narrow use case.
1027  ///
1028  /// \param T The return type of the function.
1029  ///
1030  /// \param ParamTypes The parameter types of the function. This array
1031  /// will be modified to account for adjustments to the types of the
1032  /// function parameters.
1033  ///
1034  /// \param Loc The location of the entity whose type involves this
1035  /// function type or, if there is no such entity, the location of the
1036  /// type that will have function type.
1037  ///
1038  /// \param Entity The name of the entity that involves the function
1039  /// type, if known.
1040  ///
1041  /// \param EPI Extra information about the function type. Usually this will
1042  /// be taken from an existing function with the same prototype.
1043  ///
1044  /// \returns A suitable function type, if there are no errors. The
1045  /// unqualified type will always be a FunctionProtoType.
1046  /// Otherwise, returns a NULL type.
1047  QualType BuildFunctionType(QualType T,
1048                             llvm::MutableArrayRef<QualType> ParamTypes,
1049                             SourceLocation Loc, DeclarationName Entity,
1050                             const FunctionProtoType::ExtProtoInfo &EPI);
1051
1052  QualType BuildMemberPointerType(QualType T, QualType Class,
1053                                  SourceLocation Loc,
1054                                  DeclarationName Entity);
1055  QualType BuildBlockPointerType(QualType T,
1056                                 SourceLocation Loc, DeclarationName Entity);
1057  QualType BuildParenType(QualType T);
1058  QualType BuildAtomicType(QualType T, SourceLocation Loc);
1059
1060  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1061  TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1062  TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1063                                               TypeSourceInfo *ReturnTypeInfo);
1064
1065  /// \brief Package the given type and TSI into a ParsedType.
1066  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1067  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1068  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1069  static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
1070  CanThrowResult canThrow(const Expr *E);
1071  const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1072                                                const FunctionProtoType *FPT);
1073  bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1074  bool CheckDistantExceptionSpec(QualType T);
1075  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1076  bool CheckEquivalentExceptionSpec(
1077      const FunctionProtoType *Old, SourceLocation OldLoc,
1078      const FunctionProtoType *New, SourceLocation NewLoc);
1079  bool CheckEquivalentExceptionSpec(
1080      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1081      const FunctionProtoType *Old, SourceLocation OldLoc,
1082      const FunctionProtoType *New, SourceLocation NewLoc,
1083      bool *MissingExceptionSpecification = 0,
1084      bool *MissingEmptyExceptionSpecification = 0,
1085      bool AllowNoexceptAllMatchWithNoSpec = false,
1086      bool IsOperatorNew = false);
1087  bool CheckExceptionSpecSubset(
1088      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1089      const FunctionProtoType *Superset, SourceLocation SuperLoc,
1090      const FunctionProtoType *Subset, SourceLocation SubLoc);
1091  bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1092      const FunctionProtoType *Target, SourceLocation TargetLoc,
1093      const FunctionProtoType *Source, SourceLocation SourceLoc);
1094
1095  TypeResult ActOnTypeName(Scope *S, Declarator &D);
1096
1097  /// \brief The parser has parsed the context-sensitive type 'instancetype'
1098  /// in an Objective-C message declaration. Return the appropriate type.
1099  ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1100
1101  /// \brief Abstract class used to diagnose incomplete types.
1102  struct TypeDiagnoser {
1103    bool Suppressed;
1104
1105    TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1106
1107    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1108    virtual ~TypeDiagnoser() {}
1109  };
1110
1111  static int getPrintable(int I) { return I; }
1112  static unsigned getPrintable(unsigned I) { return I; }
1113  static bool getPrintable(bool B) { return B; }
1114  static const char * getPrintable(const char *S) { return S; }
1115  static StringRef getPrintable(StringRef S) { return S; }
1116  static const std::string &getPrintable(const std::string &S) { return S; }
1117  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1118    return II;
1119  }
1120  static DeclarationName getPrintable(DeclarationName N) { return N; }
1121  static QualType getPrintable(QualType T) { return T; }
1122  static SourceRange getPrintable(SourceRange R) { return R; }
1123  static SourceRange getPrintable(SourceLocation L) { return L; }
1124  static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); }
1125  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1126
1127  template<typename T1>
1128  class BoundTypeDiagnoser1 : public TypeDiagnoser {
1129    unsigned DiagID;
1130    const T1 &Arg1;
1131
1132  public:
1133    BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1)
1134      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { }
1135    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1136      if (Suppressed) return;
1137      S.Diag(Loc, DiagID) << getPrintable(Arg1) << T;
1138    }
1139
1140    virtual ~BoundTypeDiagnoser1() { }
1141  };
1142
1143  template<typename T1, typename T2>
1144  class BoundTypeDiagnoser2 : public TypeDiagnoser {
1145    unsigned DiagID;
1146    const T1 &Arg1;
1147    const T2 &Arg2;
1148
1149  public:
1150    BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1,
1151                                  const T2 &Arg2)
1152      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1153        Arg2(Arg2) { }
1154
1155    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1156      if (Suppressed) return;
1157      S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T;
1158    }
1159
1160    virtual ~BoundTypeDiagnoser2() { }
1161  };
1162
1163  template<typename T1, typename T2, typename T3>
1164  class BoundTypeDiagnoser3 : public TypeDiagnoser {
1165    unsigned DiagID;
1166    const T1 &Arg1;
1167    const T2 &Arg2;
1168    const T3 &Arg3;
1169
1170  public:
1171    BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1,
1172                                  const T2 &Arg2, const T3 &Arg3)
1173    : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1174      Arg2(Arg2), Arg3(Arg3) { }
1175
1176    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1177      if (Suppressed) return;
1178      S.Diag(Loc, DiagID)
1179        << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T;
1180    }
1181
1182    virtual ~BoundTypeDiagnoser3() { }
1183  };
1184
1185private:
1186  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1187                           TypeDiagnoser &Diagnoser);
1188public:
1189  bool RequireCompleteType(SourceLocation Loc, QualType T,
1190                           TypeDiagnoser &Diagnoser);
1191  bool RequireCompleteType(SourceLocation Loc, QualType T,
1192                           unsigned DiagID);
1193
1194  template<typename T1>
1195  bool RequireCompleteType(SourceLocation Loc, QualType T,
1196                           unsigned DiagID, const T1 &Arg1) {
1197    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1198    return RequireCompleteType(Loc, T, Diagnoser);
1199  }
1200
1201  template<typename T1, typename T2>
1202  bool RequireCompleteType(SourceLocation Loc, QualType T,
1203                           unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1204    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1205    return RequireCompleteType(Loc, T, Diagnoser);
1206  }
1207
1208  template<typename T1, typename T2, typename T3>
1209  bool RequireCompleteType(SourceLocation Loc, QualType T,
1210                           unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1211                           const T3 &Arg3) {
1212    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1213                                                        Arg3);
1214    return RequireCompleteType(Loc, T, Diagnoser);
1215  }
1216
1217  bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1218  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1219
1220  template<typename T1>
1221  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) {
1222    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1223    return RequireCompleteExprType(E, Diagnoser);
1224  }
1225
1226  template<typename T1, typename T2>
1227  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1228                               const T2 &Arg2) {
1229    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1230    return RequireCompleteExprType(E, Diagnoser);
1231  }
1232
1233  template<typename T1, typename T2, typename T3>
1234  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1235                               const T2 &Arg2, const T3 &Arg3) {
1236    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1237                                                        Arg3);
1238    return RequireCompleteExprType(E, Diagnoser);
1239  }
1240
1241  bool RequireLiteralType(SourceLocation Loc, QualType T,
1242                          TypeDiagnoser &Diagnoser);
1243  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1244
1245  template<typename T1>
1246  bool RequireLiteralType(SourceLocation Loc, QualType T,
1247                          unsigned DiagID, const T1 &Arg1) {
1248    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1249    return RequireLiteralType(Loc, T, Diagnoser);
1250  }
1251
1252  template<typename T1, typename T2>
1253  bool RequireLiteralType(SourceLocation Loc, QualType T,
1254                          unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1255    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1256    return RequireLiteralType(Loc, T, Diagnoser);
1257  }
1258
1259  template<typename T1, typename T2, typename T3>
1260  bool RequireLiteralType(SourceLocation Loc, QualType T,
1261                          unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1262                          const T3 &Arg3) {
1263    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1264                                                        Arg3);
1265    return RequireLiteralType(Loc, T, Diagnoser);
1266  }
1267
1268  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1269                             const CXXScopeSpec &SS, QualType T);
1270
1271  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1272  QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
1273  QualType BuildUnaryTransformType(QualType BaseType,
1274                                   UnaryTransformType::UTTKind UKind,
1275                                   SourceLocation Loc);
1276
1277  //===--------------------------------------------------------------------===//
1278  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1279  //
1280
1281  /// List of decls defined in a function prototype. This contains EnumConstants
1282  /// that incorrectly end up in translation unit scope because there is no
1283  /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1284  /// them into the FunctionDecl.
1285  std::vector<NamedDecl*> DeclsInPrototypeScope;
1286  /// Nonzero if we are currently parsing a function declarator. This is a counter
1287  /// as opposed to a boolean so we can deal with nested function declarators
1288  /// such as:
1289  ///     void f(void (*g)(), ...)
1290  unsigned InFunctionDeclarator;
1291
1292  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0);
1293
1294  void DiagnoseUseOfUnimplementedSelectors();
1295
1296  bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1297
1298  ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1299                         Scope *S, CXXScopeSpec *SS = 0,
1300                         bool isClassName = false,
1301                         bool HasTrailingDot = false,
1302                         ParsedType ObjectType = ParsedType(),
1303                         bool IsCtorOrDtorName = false,
1304                         bool WantNontrivialTypeSourceInfo = false,
1305                         IdentifierInfo **CorrectedII = 0);
1306  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1307  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1308  bool DiagnoseUnknownTypeName(IdentifierInfo *&II,
1309                               SourceLocation IILoc,
1310                               Scope *S,
1311                               CXXScopeSpec *SS,
1312                               ParsedType &SuggestedType);
1313
1314  /// \brief Describes the result of the name lookup and resolution performed
1315  /// by \c ClassifyName().
1316  enum NameClassificationKind {
1317    NC_Unknown,
1318    NC_Error,
1319    NC_Keyword,
1320    NC_Type,
1321    NC_Expression,
1322    NC_NestedNameSpecifier,
1323    NC_TypeTemplate,
1324    NC_FunctionTemplate
1325  };
1326
1327  class NameClassification {
1328    NameClassificationKind Kind;
1329    ExprResult Expr;
1330    TemplateName Template;
1331    ParsedType Type;
1332    const IdentifierInfo *Keyword;
1333
1334    explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1335
1336  public:
1337    NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1338
1339    NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1340
1341    NameClassification(const IdentifierInfo *Keyword)
1342      : Kind(NC_Keyword), Keyword(Keyword) { }
1343
1344    static NameClassification Error() {
1345      return NameClassification(NC_Error);
1346    }
1347
1348    static NameClassification Unknown() {
1349      return NameClassification(NC_Unknown);
1350    }
1351
1352    static NameClassification NestedNameSpecifier() {
1353      return NameClassification(NC_NestedNameSpecifier);
1354    }
1355
1356    static NameClassification TypeTemplate(TemplateName Name) {
1357      NameClassification Result(NC_TypeTemplate);
1358      Result.Template = Name;
1359      return Result;
1360    }
1361
1362    static NameClassification FunctionTemplate(TemplateName Name) {
1363      NameClassification Result(NC_FunctionTemplate);
1364      Result.Template = Name;
1365      return Result;
1366    }
1367
1368    NameClassificationKind getKind() const { return Kind; }
1369
1370    ParsedType getType() const {
1371      assert(Kind == NC_Type);
1372      return Type;
1373    }
1374
1375    ExprResult getExpression() const {
1376      assert(Kind == NC_Expression);
1377      return Expr;
1378    }
1379
1380    TemplateName getTemplateName() const {
1381      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
1382      return Template;
1383    }
1384
1385    TemplateNameKind getTemplateNameKind() const {
1386      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
1387      return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template;
1388    }
1389  };
1390
1391  /// \brief Perform name lookup on the given name, classifying it based on
1392  /// the results of name lookup and the following token.
1393  ///
1394  /// This routine is used by the parser to resolve identifiers and help direct
1395  /// parsing. When the identifier cannot be found, this routine will attempt
1396  /// to correct the typo and classify based on the resulting name.
1397  ///
1398  /// \param S The scope in which we're performing name lookup.
1399  ///
1400  /// \param SS The nested-name-specifier that precedes the name.
1401  ///
1402  /// \param Name The identifier. If typo correction finds an alternative name,
1403  /// this pointer parameter will be updated accordingly.
1404  ///
1405  /// \param NameLoc The location of the identifier.
1406  ///
1407  /// \param NextToken The token following the identifier. Used to help
1408  /// disambiguate the name.
1409  ///
1410  /// \param IsAddressOfOperand True if this name is the operand of a unary
1411  ///        address of ('&') expression, assuming it is classified as an
1412  ///        expression.
1413  ///
1414  /// \param CCC The correction callback, if typo correction is desired.
1415  NameClassification ClassifyName(Scope *S,
1416                                  CXXScopeSpec &SS,
1417                                  IdentifierInfo *&Name,
1418                                  SourceLocation NameLoc,
1419                                  const Token &NextToken,
1420                                  bool IsAddressOfOperand,
1421                                  CorrectionCandidateCallback *CCC = 0);
1422
1423  Decl *ActOnDeclarator(Scope *S, Declarator &D);
1424
1425  NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1426                              MultiTemplateParamsArg TemplateParameterLists);
1427  void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1428  bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1429  bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1430                                    DeclarationName Name,
1431                                    SourceLocation Loc);
1432  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1433  void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1434  void CheckShadow(Scope *S, VarDecl *D);
1435  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1436  void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1437  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1438                                    TypeSourceInfo *TInfo,
1439                                    LookupResult &Previous);
1440  NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1441                                  LookupResult &Previous, bool &Redeclaration);
1442  NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1443                                     TypeSourceInfo *TInfo,
1444                                     LookupResult &Previous,
1445                                     MultiTemplateParamsArg TemplateParamLists);
1446  // Returns true if the variable declaration is a redeclaration
1447  bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1448  void CheckVariableDeclarationType(VarDecl *NewVD);
1449  void CheckCompleteVariableDeclaration(VarDecl *var);
1450  void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1451  void ActOnStartFunctionDeclarator();
1452  void ActOnEndFunctionDeclarator();
1453  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1454                                     TypeSourceInfo *TInfo,
1455                                     LookupResult &Previous,
1456                                     MultiTemplateParamsArg TemplateParamLists,
1457                                     bool &AddToScope);
1458  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1459  void checkVoidParamDecl(ParmVarDecl *Param);
1460
1461  bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1462  bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1463
1464  void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1465  // Returns true if the function declaration is a redeclaration
1466  bool CheckFunctionDeclaration(Scope *S,
1467                                FunctionDecl *NewFD, LookupResult &Previous,
1468                                bool IsExplicitSpecialization);
1469  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1470  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1471  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1472                                          SourceLocation Loc,
1473                                          QualType T);
1474  ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1475                              SourceLocation NameLoc, IdentifierInfo *Name,
1476                              QualType T, TypeSourceInfo *TSInfo,
1477                              StorageClass SC);
1478  void ActOnParamDefaultArgument(Decl *param,
1479                                 SourceLocation EqualLoc,
1480                                 Expr *defarg);
1481  void ActOnParamUnparsedDefaultArgument(Decl *param,
1482                                         SourceLocation EqualLoc,
1483                                         SourceLocation ArgLoc);
1484  void ActOnParamDefaultArgumentError(Decl *param);
1485  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1486                               SourceLocation EqualLoc);
1487
1488  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1489                            bool TypeMayContainAuto);
1490  void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1491  void ActOnInitializerError(Decl *Dcl);
1492  void ActOnCXXForRangeDecl(Decl *D);
1493  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1494  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1495  void FinalizeDeclaration(Decl *D);
1496  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1497                                         ArrayRef<Decl *> Group);
1498  DeclGroupPtrTy BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
1499                                      bool TypeMayContainAuto = true);
1500
1501  /// Should be called on all declarations that might have attached
1502  /// documentation comments.
1503  void ActOnDocumentableDecl(Decl *D);
1504  void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1505
1506  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1507                                       SourceLocation LocAfterDecls);
1508  void CheckForFunctionRedefinition(FunctionDecl *FD);
1509  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1510  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1511  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1512  bool isObjCMethodDecl(Decl *D) {
1513    return D && isa<ObjCMethodDecl>(D);
1514  }
1515
1516  /// \brief Determine whether we can skip parsing the body of a function
1517  /// definition, assuming we don't care about analyzing its body or emitting
1518  /// code for that function.
1519  ///
1520  /// This will be \c false only if we may need the body of the function in
1521  /// order to parse the rest of the program (for instance, if it is
1522  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1523  bool canSkipFunctionBody(Decl *D);
1524
1525  void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1526  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1527  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1528  Decl *ActOnSkippedFunctionBody(Decl *Decl);
1529
1530  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1531  /// attribute for which parsing is delayed.
1532  void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1533
1534  /// \brief Diagnose any unused parameters in the given sequence of
1535  /// ParmVarDecl pointers.
1536  void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1537                                ParmVarDecl * const *End);
1538
1539  /// \brief Diagnose whether the size of parameters or return value of a
1540  /// function or obj-c method definition is pass-by-value and larger than a
1541  /// specified threshold.
1542  void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1543                                              ParmVarDecl * const *End,
1544                                              QualType ReturnTy,
1545                                              NamedDecl *D);
1546
1547  void DiagnoseInvalidJumps(Stmt *Body);
1548  Decl *ActOnFileScopeAsmDecl(Expr *expr,
1549                              SourceLocation AsmLoc,
1550                              SourceLocation RParenLoc);
1551
1552  /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1553  Decl *ActOnEmptyDeclaration(Scope *S,
1554                              AttributeList *AttrList,
1555                              SourceLocation SemiLoc);
1556
1557  /// \brief The parser has processed a module import declaration.
1558  ///
1559  /// \param AtLoc The location of the '@' symbol, if any.
1560  ///
1561  /// \param ImportLoc The location of the 'import' keyword.
1562  ///
1563  /// \param Path The module access path.
1564  DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1565                               ModuleIdPath Path);
1566
1567  /// \brief Create an implicit import of the given module at the given
1568  /// source location.
1569  ///
1570  /// This routine is typically used for error recovery, when the entity found
1571  /// by name lookup is actually hidden within a module that we know about but
1572  /// the user has forgotten to import.
1573  void createImplicitModuleImport(SourceLocation Loc, Module *Mod);
1574
1575  /// \brief Retrieve a suitable printing policy.
1576  PrintingPolicy getPrintingPolicy() const {
1577    return getPrintingPolicy(Context, PP);
1578  }
1579
1580  /// \brief Retrieve a suitable printing policy.
1581  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1582                                          const Preprocessor &PP);
1583
1584  /// Scope actions.
1585  void ActOnPopScope(SourceLocation Loc, Scope *S);
1586  void ActOnTranslationUnitScope(Scope *S);
1587
1588  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1589                                   DeclSpec &DS);
1590  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1591                                   DeclSpec &DS,
1592                                   MultiTemplateParamsArg TemplateParams,
1593                                   bool IsExplicitInstantiation = false);
1594
1595  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1596                                    AccessSpecifier AS,
1597                                    RecordDecl *Record);
1598
1599  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1600                                       RecordDecl *Record);
1601
1602  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1603                                    TagTypeKind NewTag, bool isDefinition,
1604                                    SourceLocation NewTagLoc,
1605                                    const IdentifierInfo &Name);
1606
1607  enum TagUseKind {
1608    TUK_Reference,   // Reference to a tag:  'struct foo *X;'
1609    TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
1610    TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
1611    TUK_Friend       // Friend declaration:  'friend struct foo;'
1612  };
1613
1614  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1615                 SourceLocation KWLoc, CXXScopeSpec &SS,
1616                 IdentifierInfo *Name, SourceLocation NameLoc,
1617                 AttributeList *Attr, AccessSpecifier AS,
1618                 SourceLocation ModulePrivateLoc,
1619                 MultiTemplateParamsArg TemplateParameterLists,
1620                 bool &OwnedDecl, bool &IsDependent,
1621                 SourceLocation ScopedEnumKWLoc,
1622                 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
1623
1624  Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1625                                unsigned TagSpec, SourceLocation TagLoc,
1626                                CXXScopeSpec &SS,
1627                                IdentifierInfo *Name, SourceLocation NameLoc,
1628                                AttributeList *Attr,
1629                                MultiTemplateParamsArg TempParamLists);
1630
1631  TypeResult ActOnDependentTag(Scope *S,
1632                               unsigned TagSpec,
1633                               TagUseKind TUK,
1634                               const CXXScopeSpec &SS,
1635                               IdentifierInfo *Name,
1636                               SourceLocation TagLoc,
1637                               SourceLocation NameLoc);
1638
1639  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1640                 IdentifierInfo *ClassName,
1641                 SmallVectorImpl<Decl *> &Decls);
1642  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1643                   Declarator &D, Expr *BitfieldWidth);
1644
1645  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1646                         Declarator &D, Expr *BitfieldWidth,
1647                         InClassInitStyle InitStyle,
1648                         AccessSpecifier AS);
1649  MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1650                                   SourceLocation DeclStart,
1651                                   Declarator &D, Expr *BitfieldWidth,
1652                                   InClassInitStyle InitStyle,
1653                                   AccessSpecifier AS,
1654                                   AttributeList *MSPropertyAttr);
1655
1656  FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1657                            TypeSourceInfo *TInfo,
1658                            RecordDecl *Record, SourceLocation Loc,
1659                            bool Mutable, Expr *BitfieldWidth,
1660                            InClassInitStyle InitStyle,
1661                            SourceLocation TSSL,
1662                            AccessSpecifier AS, NamedDecl *PrevDecl,
1663                            Declarator *D = 0);
1664
1665  bool CheckNontrivialField(FieldDecl *FD);
1666  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1667  bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1668                              bool Diagnose = false);
1669  CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1670  void ActOnLastBitfield(SourceLocation DeclStart,
1671                         SmallVectorImpl<Decl *> &AllIvarDecls);
1672  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1673                  Declarator &D, Expr *BitfieldWidth,
1674                  tok::ObjCKeywordKind visibility);
1675
1676  // This is used for both record definitions and ObjC interface declarations.
1677  void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1678                   ArrayRef<Decl *> Fields,
1679                   SourceLocation LBrac, SourceLocation RBrac,
1680                   AttributeList *AttrList);
1681
1682  /// ActOnTagStartDefinition - Invoked when we have entered the
1683  /// scope of a tag's definition (e.g., for an enumeration, class,
1684  /// struct, or union).
1685  void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1686
1687  Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1688
1689  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1690  /// C++ record definition's base-specifiers clause and are starting its
1691  /// member declarations.
1692  void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1693                                       SourceLocation FinalLoc,
1694                                       SourceLocation LBraceLoc);
1695
1696  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1697  /// the definition of a tag (enumeration, class, struct, or union).
1698  void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1699                                SourceLocation RBraceLoc);
1700
1701  void ActOnObjCContainerFinishDefinition();
1702
1703  /// \brief Invoked when we must temporarily exit the objective-c container
1704  /// scope for parsing/looking-up C constructs.
1705  ///
1706  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1707  void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1708  void ActOnObjCReenterContainerContext(DeclContext *DC);
1709
1710  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1711  /// error parsing the definition of a tag.
1712  void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1713
1714  EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1715                                      EnumConstantDecl *LastEnumConst,
1716                                      SourceLocation IdLoc,
1717                                      IdentifierInfo *Id,
1718                                      Expr *val);
1719  bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1720  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1721                              QualType EnumUnderlyingTy, const EnumDecl *Prev);
1722
1723  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1724                          SourceLocation IdLoc, IdentifierInfo *Id,
1725                          AttributeList *Attrs,
1726                          SourceLocation EqualLoc, Expr *Val);
1727  void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1728                     SourceLocation RBraceLoc, Decl *EnumDecl,
1729                     ArrayRef<Decl *> Elements,
1730                     Scope *S, AttributeList *Attr);
1731
1732  DeclContext *getContainingDC(DeclContext *DC);
1733
1734  /// Set the current declaration context until it gets popped.
1735  void PushDeclContext(Scope *S, DeclContext *DC);
1736  void PopDeclContext();
1737
1738  /// EnterDeclaratorContext - Used when we must lookup names in the context
1739  /// of a declarator's nested name specifier.
1740  void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1741  void ExitDeclaratorContext(Scope *S);
1742
1743  /// Push the parameters of D, which must be a function, into scope.
1744  void ActOnReenterFunctionContext(Scope* S, Decl* D);
1745  void ActOnExitFunctionContext();
1746
1747  DeclContext *getFunctionLevelDeclContext();
1748
1749  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1750  /// to the function decl for the function being parsed.  If we're currently
1751  /// in a 'block', this returns the containing context.
1752  FunctionDecl *getCurFunctionDecl();
1753
1754  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1755  /// the method decl for the method being parsed.  If we're currently
1756  /// in a 'block', this returns the containing context.
1757  ObjCMethodDecl *getCurMethodDecl();
1758
1759  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1760  /// or C function we're in, otherwise return null.  If we're currently
1761  /// in a 'block', this returns the containing context.
1762  NamedDecl *getCurFunctionOrMethodDecl();
1763
1764  /// Add this decl to the scope shadowed decl chains.
1765  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1766
1767  /// \brief Make the given externally-produced declaration visible at the
1768  /// top level scope.
1769  ///
1770  /// \param D The externally-produced declaration to push.
1771  ///
1772  /// \param Name The name of the externally-produced declaration.
1773  void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1774
1775  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1776  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1777  /// true if 'D' belongs to the given declaration context.
1778  ///
1779  /// \param ExplicitInstantiationOrSpecialization When true, we are checking
1780  /// whether the declaration is in scope for the purposes of explicit template
1781  /// instantiation or specialization. The default is false.
1782  bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0,
1783                     bool ExplicitInstantiationOrSpecialization = false);
1784
1785  /// Finds the scope corresponding to the given decl context, if it
1786  /// happens to be an enclosing scope.  Otherwise return NULL.
1787  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1788
1789  /// Subroutines of ActOnDeclarator().
1790  TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1791                                TypeSourceInfo *TInfo);
1792  bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
1793
1794  /// Attribute merging methods. Return true if a new attribute was added.
1795  AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1796                                          IdentifierInfo *Platform,
1797                                          VersionTuple Introduced,
1798                                          VersionTuple Deprecated,
1799                                          VersionTuple Obsoleted,
1800                                          bool IsUnavailable,
1801                                          StringRef Message,
1802                                          bool Override,
1803                                          unsigned AttrSpellingListIndex);
1804  TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1805                                       TypeVisibilityAttr::VisibilityType Vis,
1806                                              unsigned AttrSpellingListIndex);
1807  VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
1808                                      VisibilityAttr::VisibilityType Vis,
1809                                      unsigned AttrSpellingListIndex);
1810  DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
1811                                    unsigned AttrSpellingListIndex);
1812  DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
1813                                    unsigned AttrSpellingListIndex);
1814  FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, StringRef Format,
1815                              int FormatIdx, int FirstArg,
1816                              unsigned AttrSpellingListIndex);
1817  SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
1818                                unsigned AttrSpellingListIndex);
1819
1820  /// \brief Describes the kind of merge to perform for availability
1821  /// attributes (including "deprecated", "unavailable", and "availability").
1822  enum AvailabilityMergeKind {
1823    /// \brief Don't merge availability attributes at all.
1824    AMK_None,
1825    /// \brief Merge availability attributes for a redeclaration, which requires
1826    /// an exact match.
1827    AMK_Redeclaration,
1828    /// \brief Merge availability attributes for an override, which requires
1829    /// an exact match or a weakening of constraints.
1830    AMK_Override
1831  };
1832
1833  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
1834                           AvailabilityMergeKind AMK = AMK_Redeclaration);
1835  void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
1836  bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S);
1837  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
1838                                    Scope *S);
1839  void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
1840  void MergeVarDecl(VarDecl *New, LookupResult &OldDecls,
1841                    bool OldDeclsWereHidden);
1842  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool OldIsHidden);
1843  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
1844  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
1845
1846  // AssignmentAction - This is used by all the assignment diagnostic functions
1847  // to represent what is actually causing the operation
1848  enum AssignmentAction {
1849    AA_Assigning,
1850    AA_Passing,
1851    AA_Returning,
1852    AA_Converting,
1853    AA_Initializing,
1854    AA_Sending,
1855    AA_Casting
1856  };
1857
1858  /// C++ Overloading.
1859  enum OverloadKind {
1860    /// This is a legitimate overload: the existing declarations are
1861    /// functions or function templates with different signatures.
1862    Ovl_Overload,
1863
1864    /// This is not an overload because the signature exactly matches
1865    /// an existing declaration.
1866    Ovl_Match,
1867
1868    /// This is not an overload because the lookup results contain a
1869    /// non-function.
1870    Ovl_NonFunction
1871  };
1872  OverloadKind CheckOverload(Scope *S,
1873                             FunctionDecl *New,
1874                             const LookupResult &OldDecls,
1875                             NamedDecl *&OldDecl,
1876                             bool IsForUsingDecl);
1877  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
1878
1879  /// \brief Checks availability of the function depending on the current
1880  /// function context.Inside an unavailable function,unavailability is ignored.
1881  ///
1882  /// \returns true if \p FD is unavailable and current context is inside
1883  /// an available function, false otherwise.
1884  bool isFunctionConsideredUnavailable(FunctionDecl *FD);
1885
1886  ImplicitConversionSequence
1887  TryImplicitConversion(Expr *From, QualType ToType,
1888                        bool SuppressUserConversions,
1889                        bool AllowExplicit,
1890                        bool InOverloadResolution,
1891                        bool CStyle,
1892                        bool AllowObjCWritebackConversion);
1893
1894  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
1895  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
1896  bool IsComplexPromotion(QualType FromType, QualType ToType);
1897  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1898                           bool InOverloadResolution,
1899                           QualType& ConvertedType, bool &IncompatibleObjC);
1900  bool isObjCPointerConversion(QualType FromType, QualType ToType,
1901                               QualType& ConvertedType, bool &IncompatibleObjC);
1902  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
1903                                 QualType &ConvertedType);
1904  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
1905                                QualType& ConvertedType);
1906  bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1907                                const FunctionProtoType *NewType,
1908                                unsigned *ArgPos = 0);
1909  void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
1910                                  QualType FromType, QualType ToType);
1911
1912  CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
1913  bool CheckPointerConversion(Expr *From, QualType ToType,
1914                              CastKind &Kind,
1915                              CXXCastPath& BasePath,
1916                              bool IgnoreBaseAccess);
1917  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
1918                                 bool InOverloadResolution,
1919                                 QualType &ConvertedType);
1920  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
1921                                    CastKind &Kind,
1922                                    CXXCastPath &BasePath,
1923                                    bool IgnoreBaseAccess);
1924  bool IsQualificationConversion(QualType FromType, QualType ToType,
1925                                 bool CStyle, bool &ObjCLifetimeConversion);
1926  bool IsNoReturnConversion(QualType FromType, QualType ToType,
1927                            QualType &ResultTy);
1928  bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
1929  bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
1930
1931  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1932                                             const VarDecl *NRVOCandidate,
1933                                             QualType ResultType,
1934                                             Expr *Value,
1935                                             bool AllowNRVO = true);
1936
1937  bool CanPerformCopyInitialization(const InitializedEntity &Entity,
1938                                    ExprResult Init);
1939  ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
1940                                       SourceLocation EqualLoc,
1941                                       ExprResult Init,
1942                                       bool TopLevelOfInitList = false,
1943                                       bool AllowExplicit = false);
1944  ExprResult PerformObjectArgumentInitialization(Expr *From,
1945                                                 NestedNameSpecifier *Qualifier,
1946                                                 NamedDecl *FoundDecl,
1947                                                 CXXMethodDecl *Method);
1948
1949  ExprResult PerformContextuallyConvertToBool(Expr *From);
1950  ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
1951
1952  /// Contexts in which a converted constant expression is required.
1953  enum CCEKind {
1954    CCEK_CaseValue,   ///< Expression in a case label.
1955    CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
1956    CCEK_TemplateArg, ///< Value of a non-type template parameter.
1957    CCEK_NewExpr      ///< Constant expression in a noptr-new-declarator.
1958  };
1959  ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
1960                                              llvm::APSInt &Value, CCEKind CCE);
1961
1962  /// \brief Abstract base class used to perform a contextual implicit
1963  /// conversion from an expression to any type passing a filter.
1964  class ContextualImplicitConverter {
1965  public:
1966    bool Suppress;
1967    bool SuppressConversion;
1968
1969    ContextualImplicitConverter(bool Suppress = false,
1970                                bool SuppressConversion = false)
1971        : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
1972
1973    /// \brief Determine whether the specified type is a valid destination type
1974    /// for this conversion.
1975    virtual bool match(QualType T) = 0;
1976
1977    /// \brief Emits a diagnostic complaining that the expression does not have
1978    /// integral or enumeration type.
1979    virtual SemaDiagnosticBuilder
1980    diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
1981
1982    /// \brief Emits a diagnostic when the expression has incomplete class type.
1983    virtual SemaDiagnosticBuilder
1984    diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
1985
1986    /// \brief Emits a diagnostic when the only matching conversion function
1987    /// is explicit.
1988    virtual SemaDiagnosticBuilder diagnoseExplicitConv(
1989        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
1990
1991    /// \brief Emits a note for the explicit conversion function.
1992    virtual SemaDiagnosticBuilder
1993    noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
1994
1995    /// \brief Emits a diagnostic when there are multiple possible conversion
1996    /// functions.
1997    virtual SemaDiagnosticBuilder
1998    diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
1999
2000    /// \brief Emits a note for one of the candidate conversions.
2001    virtual SemaDiagnosticBuilder
2002    noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2003
2004    /// \brief Emits a diagnostic when we picked a conversion function
2005    /// (for cases when we are not allowed to pick a conversion function).
2006    virtual SemaDiagnosticBuilder diagnoseConversion(
2007        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2008
2009    virtual ~ContextualImplicitConverter() {}
2010  };
2011
2012  class ICEConvertDiagnoser : public ContextualImplicitConverter {
2013    bool AllowScopedEnumerations;
2014
2015  public:
2016    ICEConvertDiagnoser(bool AllowScopedEnumerations,
2017                        bool Suppress, bool SuppressConversion)
2018        : ContextualImplicitConverter(Suppress, SuppressConversion),
2019          AllowScopedEnumerations(AllowScopedEnumerations) {}
2020
2021    /// Match an integral or (possibly scoped) enumeration type.
2022    bool match(QualType T);
2023
2024    SemaDiagnosticBuilder
2025    diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) {
2026      return diagnoseNotInt(S, Loc, T);
2027    }
2028
2029    /// \brief Emits a diagnostic complaining that the expression does not have
2030    /// integral or enumeration type.
2031    virtual SemaDiagnosticBuilder
2032    diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2033  };
2034
2035  /// Perform a contextual implicit conversion.
2036  ExprResult PerformContextualImplicitConversion(
2037      SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2038
2039
2040  enum ObjCSubscriptKind {
2041    OS_Array,
2042    OS_Dictionary,
2043    OS_Error
2044  };
2045  ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2046
2047  // Note that LK_String is intentionally after the other literals, as
2048  // this is used for diagnostics logic.
2049  enum ObjCLiteralKind {
2050    LK_Array,
2051    LK_Dictionary,
2052    LK_Numeric,
2053    LK_Boxed,
2054    LK_String,
2055    LK_Block,
2056    LK_None
2057  };
2058  ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2059
2060  ExprResult PerformObjectMemberConversion(Expr *From,
2061                                           NestedNameSpecifier *Qualifier,
2062                                           NamedDecl *FoundDecl,
2063                                           NamedDecl *Member);
2064
2065  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2066  // TODO: make this is a typesafe union.
2067  typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
2068  typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2069
2070  void AddOverloadCandidate(FunctionDecl *Function,
2071                            DeclAccessPair FoundDecl,
2072                            ArrayRef<Expr *> Args,
2073                            OverloadCandidateSet& CandidateSet,
2074                            bool SuppressUserConversions = false,
2075                            bool PartialOverloading = false,
2076                            bool AllowExplicit = false);
2077  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2078                             ArrayRef<Expr *> Args,
2079                             OverloadCandidateSet& CandidateSet,
2080                             bool SuppressUserConversions = false,
2081                            TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
2082  void AddMethodCandidate(DeclAccessPair FoundDecl,
2083                          QualType ObjectType,
2084                          Expr::Classification ObjectClassification,
2085                          ArrayRef<Expr *> Args,
2086                          OverloadCandidateSet& CandidateSet,
2087                          bool SuppressUserConversion = false);
2088  void AddMethodCandidate(CXXMethodDecl *Method,
2089                          DeclAccessPair FoundDecl,
2090                          CXXRecordDecl *ActingContext, QualType ObjectType,
2091                          Expr::Classification ObjectClassification,
2092                          ArrayRef<Expr *> Args,
2093                          OverloadCandidateSet& CandidateSet,
2094                          bool SuppressUserConversions = false);
2095  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2096                                  DeclAccessPair FoundDecl,
2097                                  CXXRecordDecl *ActingContext,
2098                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2099                                  QualType ObjectType,
2100                                  Expr::Classification ObjectClassification,
2101                                  ArrayRef<Expr *> Args,
2102                                  OverloadCandidateSet& CandidateSet,
2103                                  bool SuppressUserConversions = false);
2104  void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2105                                    DeclAccessPair FoundDecl,
2106                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2107                                    ArrayRef<Expr *> Args,
2108                                    OverloadCandidateSet& CandidateSet,
2109                                    bool SuppressUserConversions = false);
2110  void AddConversionCandidate(CXXConversionDecl *Conversion,
2111                              DeclAccessPair FoundDecl,
2112                              CXXRecordDecl *ActingContext,
2113                              Expr *From, QualType ToType,
2114                              OverloadCandidateSet& CandidateSet);
2115  void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2116                                      DeclAccessPair FoundDecl,
2117                                      CXXRecordDecl *ActingContext,
2118                                      Expr *From, QualType ToType,
2119                                      OverloadCandidateSet &CandidateSet);
2120  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2121                             DeclAccessPair FoundDecl,
2122                             CXXRecordDecl *ActingContext,
2123                             const FunctionProtoType *Proto,
2124                             Expr *Object, ArrayRef<Expr *> Args,
2125                             OverloadCandidateSet& CandidateSet);
2126  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2127                                   SourceLocation OpLoc, ArrayRef<Expr *> Args,
2128                                   OverloadCandidateSet& CandidateSet,
2129                                   SourceRange OpRange = SourceRange());
2130  void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2131                           ArrayRef<Expr *> Args,
2132                           OverloadCandidateSet& CandidateSet,
2133                           bool IsAssignmentOperator = false,
2134                           unsigned NumContextualBoolArguments = 0);
2135  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2136                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
2137                                    OverloadCandidateSet& CandidateSet);
2138  void AddArgumentDependentLookupCandidates(DeclarationName Name,
2139                                            bool Operator, SourceLocation Loc,
2140                                            ArrayRef<Expr *> Args,
2141                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2142                                            OverloadCandidateSet& CandidateSet,
2143                                            bool PartialOverloading = false);
2144
2145  // Emit as a 'note' the specific overload candidate
2146  void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2147
2148  // Emit as a series of 'note's all template and non-templates
2149  // identified by the expression Expr
2150  void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2151
2152  // [PossiblyAFunctionType]  -->   [Return]
2153  // NonFunctionType --> NonFunctionType
2154  // R (A) --> R(A)
2155  // R (*)(A) --> R (A)
2156  // R (&)(A) --> R (A)
2157  // R (S::*)(A) --> R (A)
2158  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2159
2160  FunctionDecl *
2161  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2162                                     QualType TargetType,
2163                                     bool Complain,
2164                                     DeclAccessPair &Found,
2165                                     bool *pHadMultipleCandidates = 0);
2166
2167  FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2168                                                   bool Complain = false,
2169                                                   DeclAccessPair* Found = 0);
2170
2171  bool ResolveAndFixSingleFunctionTemplateSpecialization(
2172                      ExprResult &SrcExpr,
2173                      bool DoFunctionPointerConverion = false,
2174                      bool Complain = false,
2175                      const SourceRange& OpRangeForComplaining = SourceRange(),
2176                      QualType DestTypeForComplaining = QualType(),
2177                      unsigned DiagIDForComplaining = 0);
2178
2179
2180  Expr *FixOverloadedFunctionReference(Expr *E,
2181                                       DeclAccessPair FoundDecl,
2182                                       FunctionDecl *Fn);
2183  ExprResult FixOverloadedFunctionReference(ExprResult,
2184                                            DeclAccessPair FoundDecl,
2185                                            FunctionDecl *Fn);
2186
2187  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2188                                   ArrayRef<Expr *> Args,
2189                                   OverloadCandidateSet &CandidateSet,
2190                                   bool PartialOverloading = false);
2191
2192  // An enum used to represent the different possible results of building a
2193  // range-based for loop.
2194  enum ForRangeStatus {
2195    FRS_Success,
2196    FRS_NoViableFunction,
2197    FRS_DiagnosticIssued
2198  };
2199
2200  // An enum to represent whether something is dealing with a call to begin()
2201  // or a call to end() in a range-based for loop.
2202  enum BeginEndFunction {
2203    BEF_begin,
2204    BEF_end
2205  };
2206
2207  ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2208                                           SourceLocation RangeLoc,
2209                                           VarDecl *Decl,
2210                                           BeginEndFunction BEF,
2211                                           const DeclarationNameInfo &NameInfo,
2212                                           LookupResult &MemberLookup,
2213                                           OverloadCandidateSet *CandidateSet,
2214                                           Expr *Range, ExprResult *CallExpr);
2215
2216  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2217                                     UnresolvedLookupExpr *ULE,
2218                                     SourceLocation LParenLoc,
2219                                     MultiExprArg Args,
2220                                     SourceLocation RParenLoc,
2221                                     Expr *ExecConfig,
2222                                     bool AllowTypoCorrection=true);
2223
2224  bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2225                              MultiExprArg Args, SourceLocation RParenLoc,
2226                              OverloadCandidateSet *CandidateSet,
2227                              ExprResult *Result);
2228
2229  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2230                                     unsigned Opc,
2231                                     const UnresolvedSetImpl &Fns,
2232                                     Expr *input);
2233
2234  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2235                                   unsigned Opc,
2236                                   const UnresolvedSetImpl &Fns,
2237                                   Expr *LHS, Expr *RHS);
2238
2239  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2240                                                SourceLocation RLoc,
2241                                                Expr *Base,Expr *Idx);
2242
2243  ExprResult
2244  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2245                            SourceLocation LParenLoc,
2246                            MultiExprArg Args,
2247                            SourceLocation RParenLoc);
2248  ExprResult
2249  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2250                               MultiExprArg Args,
2251                               SourceLocation RParenLoc);
2252
2253  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2254                                      SourceLocation OpLoc);
2255
2256  /// CheckCallReturnType - Checks that a call expression's return type is
2257  /// complete. Returns true on failure. The location passed in is the location
2258  /// that best represents the call.
2259  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2260                           CallExpr *CE, FunctionDecl *FD);
2261
2262  /// Helpers for dealing with blocks and functions.
2263  bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
2264                                ParmVarDecl *const *ParamEnd,
2265                                bool CheckParameterNames);
2266  void CheckCXXDefaultArguments(FunctionDecl *FD);
2267  void CheckExtraCXXDefaultArguments(Declarator &D);
2268  Scope *getNonFieldDeclScope(Scope *S);
2269
2270  /// \name Name lookup
2271  ///
2272  /// These routines provide name lookup that is used during semantic
2273  /// analysis to resolve the various kinds of names (identifiers,
2274  /// overloaded operator names, constructor names, etc.) into zero or
2275  /// more declarations within a particular scope. The major entry
2276  /// points are LookupName, which performs unqualified name lookup,
2277  /// and LookupQualifiedName, which performs qualified name lookup.
2278  ///
2279  /// All name lookup is performed based on some specific criteria,
2280  /// which specify what names will be visible to name lookup and how
2281  /// far name lookup should work. These criteria are important both
2282  /// for capturing language semantics (certain lookups will ignore
2283  /// certain names, for example) and for performance, since name
2284  /// lookup is often a bottleneck in the compilation of C++. Name
2285  /// lookup criteria is specified via the LookupCriteria enumeration.
2286  ///
2287  /// The results of name lookup can vary based on the kind of name
2288  /// lookup performed, the current language, and the translation
2289  /// unit. In C, for example, name lookup will either return nothing
2290  /// (no entity found) or a single declaration. In C++, name lookup
2291  /// can additionally refer to a set of overloaded functions or
2292  /// result in an ambiguity. All of the possible results of name
2293  /// lookup are captured by the LookupResult class, which provides
2294  /// the ability to distinguish among them.
2295  //@{
2296
2297  /// @brief Describes the kind of name lookup to perform.
2298  enum LookupNameKind {
2299    /// Ordinary name lookup, which finds ordinary names (functions,
2300    /// variables, typedefs, etc.) in C and most kinds of names
2301    /// (functions, variables, members, types, etc.) in C++.
2302    LookupOrdinaryName = 0,
2303    /// Tag name lookup, which finds the names of enums, classes,
2304    /// structs, and unions.
2305    LookupTagName,
2306    /// Label name lookup.
2307    LookupLabel,
2308    /// Member name lookup, which finds the names of
2309    /// class/struct/union members.
2310    LookupMemberName,
2311    /// Look up of an operator name (e.g., operator+) for use with
2312    /// operator overloading. This lookup is similar to ordinary name
2313    /// lookup, but will ignore any declarations that are class members.
2314    LookupOperatorName,
2315    /// Look up of a name that precedes the '::' scope resolution
2316    /// operator in C++. This lookup completely ignores operator, object,
2317    /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2318    LookupNestedNameSpecifierName,
2319    /// Look up a namespace name within a C++ using directive or
2320    /// namespace alias definition, ignoring non-namespace names (C++
2321    /// [basic.lookup.udir]p1).
2322    LookupNamespaceName,
2323    /// Look up all declarations in a scope with the given name,
2324    /// including resolved using declarations.  This is appropriate
2325    /// for checking redeclarations for a using declaration.
2326    LookupUsingDeclName,
2327    /// Look up an ordinary name that is going to be redeclared as a
2328    /// name with linkage. This lookup ignores any declarations that
2329    /// are outside of the current scope unless they have linkage. See
2330    /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2331    LookupRedeclarationWithLinkage,
2332    /// Look up the name of an Objective-C protocol.
2333    LookupObjCProtocolName,
2334    /// Look up implicit 'self' parameter of an objective-c method.
2335    LookupObjCImplicitSelfParam,
2336    /// \brief Look up any declaration with any name.
2337    LookupAnyName
2338  };
2339
2340  /// \brief Specifies whether (or how) name lookup is being performed for a
2341  /// redeclaration (vs. a reference).
2342  enum RedeclarationKind {
2343    /// \brief The lookup is a reference to this name that is not for the
2344    /// purpose of redeclaring the name.
2345    NotForRedeclaration = 0,
2346    /// \brief The lookup results will be used for redeclaration of a name,
2347    /// if an entity by that name already exists.
2348    ForRedeclaration
2349  };
2350
2351  /// \brief The possible outcomes of name lookup for a literal operator.
2352  enum LiteralOperatorLookupResult {
2353    /// \brief The lookup resulted in an error.
2354    LOLR_Error,
2355    /// \brief The lookup found a single 'cooked' literal operator, which
2356    /// expects a normal literal to be built and passed to it.
2357    LOLR_Cooked,
2358    /// \brief The lookup found a single 'raw' literal operator, which expects
2359    /// a string literal containing the spelling of the literal token.
2360    LOLR_Raw,
2361    /// \brief The lookup found an overload set of literal operator templates,
2362    /// which expect the characters of the spelling of the literal token to be
2363    /// passed as a non-type template argument pack.
2364    LOLR_Template
2365  };
2366
2367  SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2368                                                   CXXSpecialMember SM,
2369                                                   bool ConstArg,
2370                                                   bool VolatileArg,
2371                                                   bool RValueThis,
2372                                                   bool ConstThis,
2373                                                   bool VolatileThis);
2374
2375private:
2376  bool CppLookupName(LookupResult &R, Scope *S);
2377
2378  // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2379  //
2380  // The boolean value will be true to indicate that the namespace was loaded
2381  // from an AST/PCH file, or false otherwise.
2382  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2383
2384  /// \brief Whether we have already loaded known namespaces from an extenal
2385  /// source.
2386  bool LoadedExternalKnownNamespaces;
2387
2388public:
2389  /// \brief Look up a name, looking for a single declaration.  Return
2390  /// null if the results were absent, ambiguous, or overloaded.
2391  ///
2392  /// It is preferable to use the elaborated form and explicitly handle
2393  /// ambiguity and overloaded.
2394  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2395                              SourceLocation Loc,
2396                              LookupNameKind NameKind,
2397                              RedeclarationKind Redecl
2398                                = NotForRedeclaration);
2399  bool LookupName(LookupResult &R, Scope *S,
2400                  bool AllowBuiltinCreation = false);
2401  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2402                           bool InUnqualifiedLookup = false);
2403  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2404                        bool AllowBuiltinCreation = false,
2405                        bool EnteringContext = false);
2406  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2407                                   RedeclarationKind Redecl
2408                                     = NotForRedeclaration);
2409
2410  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2411                                    QualType T1, QualType T2,
2412                                    UnresolvedSetImpl &Functions);
2413
2414  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2415                                 SourceLocation GnuLabelLoc = SourceLocation());
2416
2417  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2418  CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2419  CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2420                                               unsigned Quals);
2421  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2422                                         bool RValueThis, unsigned ThisQuals);
2423  CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2424                                              unsigned Quals);
2425  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2426                                        bool RValueThis, unsigned ThisQuals);
2427  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2428
2429  LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2430                                                    ArrayRef<QualType> ArgTys,
2431                                                    bool AllowRawAndTemplate);
2432  bool isKnownName(StringRef name);
2433
2434  void ArgumentDependentLookup(DeclarationName Name, bool Operator,
2435                               SourceLocation Loc,
2436                               ArrayRef<Expr *> Args,
2437                               ADLResult &Functions);
2438
2439  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2440                          VisibleDeclConsumer &Consumer,
2441                          bool IncludeGlobalScope = true);
2442  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2443                          VisibleDeclConsumer &Consumer,
2444                          bool IncludeGlobalScope = true);
2445
2446  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2447                             Sema::LookupNameKind LookupKind,
2448                             Scope *S, CXXScopeSpec *SS,
2449                             CorrectionCandidateCallback &CCC,
2450                             DeclContext *MemberContext = 0,
2451                             bool EnteringContext = false,
2452                             const ObjCObjectPointerType *OPT = 0);
2453
2454  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2455                                          ArrayRef<Expr *> Args,
2456                                   AssociatedNamespaceSet &AssociatedNamespaces,
2457                                   AssociatedClassSet &AssociatedClasses);
2458
2459  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2460                            bool ConsiderLinkage,
2461                            bool ExplicitInstantiationOrSpecialization);
2462
2463  bool DiagnoseAmbiguousLookup(LookupResult &Result);
2464  //@}
2465
2466  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2467                                          SourceLocation IdLoc,
2468                                          bool TypoCorrection = false);
2469  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2470                                 Scope *S, bool ForRedeclaration,
2471                                 SourceLocation Loc);
2472  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2473                                      Scope *S);
2474  void AddKnownFunctionAttributes(FunctionDecl *FD);
2475
2476  // More parsing and symbol table subroutines.
2477
2478  void ProcessPragmaWeak(Scope *S, Decl *D);
2479  // Decl attributes - this routine is the top level dispatcher.
2480  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
2481                             bool NonInheritable = true,
2482                             bool Inheritable = true);
2483  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2484                                bool NonInheritable = true,
2485                                bool Inheritable = true,
2486                                bool IncludeCXX11Attributes = true);
2487  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2488                                      const AttributeList *AttrList);
2489
2490  void checkUnusedDeclAttributes(Declarator &D);
2491
2492  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2493  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2494                            const FunctionDecl *FD = 0);
2495  bool CheckNoReturnAttr(const AttributeList &attr);
2496  void CheckAlignasUnderalignment(Decl *D);
2497
2498  /// \brief Stmt attributes - this routine is the top level dispatcher.
2499  StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2500                                   SourceRange Range);
2501
2502  void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
2503                           bool &IncompleteImpl, unsigned DiagID);
2504  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2505                                   ObjCMethodDecl *MethodDecl,
2506                                   bool IsProtocolMethodDecl);
2507
2508  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2509                                   ObjCMethodDecl *Overridden,
2510                                   bool IsProtocolMethodDecl);
2511
2512  /// WarnExactTypedMethods - This routine issues a warning if method
2513  /// implementation declaration matches exactly that of its declaration.
2514  void WarnExactTypedMethods(ObjCMethodDecl *Method,
2515                             ObjCMethodDecl *MethodDecl,
2516                             bool IsProtocolMethodDecl);
2517
2518  typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2519  typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2520
2521  /// CheckProtocolMethodDefs - This routine checks unimplemented
2522  /// methods declared in protocol, and those referenced by it.
2523  void CheckProtocolMethodDefs(SourceLocation ImpLoc,
2524                               ObjCProtocolDecl *PDecl,
2525                               bool& IncompleteImpl,
2526                               const SelectorSet &InsMap,
2527                               const SelectorSet &ClsMap,
2528                               ObjCContainerDecl *CDecl);
2529
2530  /// CheckImplementationIvars - This routine checks if the instance variables
2531  /// listed in the implelementation match those listed in the interface.
2532  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2533                                ObjCIvarDecl **Fields, unsigned nIvars,
2534                                SourceLocation Loc);
2535
2536  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2537  /// remains unimplemented in the class or category \@implementation.
2538  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2539                                 ObjCContainerDecl* IDecl,
2540                                 bool IncompleteImpl = false);
2541
2542  /// DiagnoseUnimplementedProperties - This routine warns on those properties
2543  /// which must be implemented by this implementation.
2544  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2545                                       ObjCContainerDecl *CDecl);
2546
2547  /// DefaultSynthesizeProperties - This routine default synthesizes all
2548  /// properties which must be synthesized in the class's \@implementation.
2549  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2550                                    ObjCInterfaceDecl *IDecl);
2551  void DefaultSynthesizeProperties(Scope *S, Decl *D);
2552
2553  /// CollectImmediateProperties - This routine collects all properties in
2554  /// the class and its conforming protocols; but not those it its super class.
2555  void CollectImmediateProperties(ObjCContainerDecl *CDecl,
2556            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
2557            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
2558
2559  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
2560  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
2561  /// declared in class 'IFace'.
2562  bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
2563                                      ObjCMethodDecl *Method, ObjCIvarDecl *IV);
2564
2565  /// Called by ActOnProperty to handle \@property declarations in
2566  /// class extensions.
2567  ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
2568                      SourceLocation AtLoc,
2569                      SourceLocation LParenLoc,
2570                      FieldDeclarator &FD,
2571                      Selector GetterSel,
2572                      Selector SetterSel,
2573                      const bool isAssign,
2574                      const bool isReadWrite,
2575                      const unsigned Attributes,
2576                      const unsigned AttributesAsWritten,
2577                      bool *isOverridingProperty,
2578                      TypeSourceInfo *T,
2579                      tok::ObjCKeywordKind MethodImplKind);
2580
2581  /// Called by ActOnProperty and HandlePropertyInClassExtension to
2582  /// handle creating the ObjcPropertyDecl for a category or \@interface.
2583  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
2584                                       ObjCContainerDecl *CDecl,
2585                                       SourceLocation AtLoc,
2586                                       SourceLocation LParenLoc,
2587                                       FieldDeclarator &FD,
2588                                       Selector GetterSel,
2589                                       Selector SetterSel,
2590                                       const bool isAssign,
2591                                       const bool isReadWrite,
2592                                       const unsigned Attributes,
2593                                       const unsigned AttributesAsWritten,
2594                                       TypeSourceInfo *T,
2595                                       tok::ObjCKeywordKind MethodImplKind,
2596                                       DeclContext *lexicalDC = 0);
2597
2598  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
2599  /// warning) when atomic property has one but not the other user-declared
2600  /// setter or getter.
2601  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
2602                                       ObjCContainerDecl* IDecl);
2603
2604  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
2605
2606  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
2607
2608  enum MethodMatchStrategy {
2609    MMS_loose,
2610    MMS_strict
2611  };
2612
2613  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
2614  /// true, or false, accordingly.
2615  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
2616                                  const ObjCMethodDecl *PrevMethod,
2617                                  MethodMatchStrategy strategy = MMS_strict);
2618
2619  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2620  /// or protocol against those declared in their implementations.
2621  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2622                                  const SelectorSet &ClsMap,
2623                                  SelectorSet &InsMapSeen,
2624                                  SelectorSet &ClsMapSeen,
2625                                  ObjCImplDecl* IMPDecl,
2626                                  ObjCContainerDecl* IDecl,
2627                                  bool &IncompleteImpl,
2628                                  bool ImmediateClass,
2629                                  bool WarnCategoryMethodImpl=false);
2630
2631  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2632  /// category matches with those implemented in its primary class and
2633  /// warns each time an exact match is found.
2634  void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2635
2636  /// \brief Add the given method to the list of globally-known methods.
2637  void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
2638
2639private:
2640  /// AddMethodToGlobalPool - Add an instance or factory method to the global
2641  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2642  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2643
2644  /// LookupMethodInGlobalPool - Returns the instance or factory method and
2645  /// optionally warns if there are multiple signatures.
2646  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2647                                           bool receiverIdOrClass,
2648                                           bool warn, bool instance);
2649
2650public:
2651  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
2652  /// unit are added to a global pool. This allows us to efficiently associate
2653  /// a selector with a method declaraation for purposes of typechecking
2654  /// messages sent to "id" (where the class of the object is unknown).
2655  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2656    AddMethodToGlobalPool(Method, impl, /*instance*/true);
2657  }
2658
2659  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
2660  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2661    AddMethodToGlobalPool(Method, impl, /*instance*/false);
2662  }
2663
2664  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
2665  /// pool.
2666  void AddAnyMethodToGlobalPool(Decl *D);
2667
2668  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
2669  /// there are multiple signatures.
2670  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
2671                                                   bool receiverIdOrClass=false,
2672                                                   bool warn=true) {
2673    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2674                                    warn, /*instance*/true);
2675  }
2676
2677  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
2678  /// there are multiple signatures.
2679  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
2680                                                  bool receiverIdOrClass=false,
2681                                                  bool warn=true) {
2682    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2683                                    warn, /*instance*/false);
2684  }
2685
2686  const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
2687                              QualType ObjectType=QualType());
2688
2689  /// DiagnoseMismatchedMethodsInGlobalPool - This routine goes through list of
2690  /// methods in global pool and issues diagnostic on identical selectors which
2691  /// have mismathched types.
2692  void DiagnoseMismatchedMethodsInGlobalPool();
2693
2694  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
2695  /// implementation.
2696  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
2697
2698  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2699  /// initialization.
2700  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2701                                  SmallVectorImpl<ObjCIvarDecl*> &Ivars);
2702
2703  //===--------------------------------------------------------------------===//
2704  // Statement Parsing Callbacks: SemaStmt.cpp.
2705public:
2706  class FullExprArg {
2707  public:
2708    FullExprArg(Sema &actions) : E(0) { }
2709
2710    // FIXME: The const_cast here is ugly. RValue references would make this
2711    // much nicer (or we could duplicate a bunch of the move semantics
2712    // emulation code from Ownership.h).
2713    FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2714
2715    ExprResult release() {
2716      return E;
2717    }
2718
2719    Expr *get() const { return E; }
2720
2721    Expr *operator->() {
2722      return E;
2723    }
2724
2725  private:
2726    // FIXME: No need to make the entire Sema class a friend when it's just
2727    // Sema::MakeFullExpr that needs access to the constructor below.
2728    friend class Sema;
2729
2730    explicit FullExprArg(Expr *expr) : E(expr) {}
2731
2732    Expr *E;
2733  };
2734
2735  FullExprArg MakeFullExpr(Expr *Arg) {
2736    return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
2737  }
2738  FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
2739    return FullExprArg(ActOnFinishFullExpr(Arg, CC).release());
2740  }
2741  FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
2742    ExprResult FE =
2743      ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
2744                          /*DiscardedValue*/ true);
2745    return FullExprArg(FE.release());
2746  }
2747
2748  StmtResult ActOnExprStmt(ExprResult Arg);
2749  StmtResult ActOnExprStmtError();
2750
2751  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
2752                           bool HasLeadingEmptyMacro = false);
2753
2754  void ActOnStartOfCompoundStmt();
2755  void ActOnFinishOfCompoundStmt();
2756  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
2757                                       MultiStmtArg Elts,
2758                                       bool isStmtExpr);
2759
2760  /// \brief A RAII object to enter scope of a compound statement.
2761  class CompoundScopeRAII {
2762  public:
2763    CompoundScopeRAII(Sema &S): S(S) {
2764      S.ActOnStartOfCompoundStmt();
2765    }
2766
2767    ~CompoundScopeRAII() {
2768      S.ActOnFinishOfCompoundStmt();
2769    }
2770
2771  private:
2772    Sema &S;
2773  };
2774
2775  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
2776                                   SourceLocation StartLoc,
2777                                   SourceLocation EndLoc);
2778  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
2779  StmtResult ActOnForEachLValueExpr(Expr *E);
2780  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
2781                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
2782                                   SourceLocation ColonLoc);
2783  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
2784
2785  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
2786                                      SourceLocation ColonLoc,
2787                                      Stmt *SubStmt, Scope *CurScope);
2788  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
2789                            SourceLocation ColonLoc, Stmt *SubStmt);
2790
2791  StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
2792                                 ArrayRef<const Attr*> Attrs,
2793                                 Stmt *SubStmt);
2794
2795  StmtResult ActOnIfStmt(SourceLocation IfLoc,
2796                         FullExprArg CondVal, Decl *CondVar,
2797                         Stmt *ThenVal,
2798                         SourceLocation ElseLoc, Stmt *ElseVal);
2799  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
2800                                            Expr *Cond,
2801                                            Decl *CondVar);
2802  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
2803                                           Stmt *Switch, Stmt *Body);
2804  StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
2805                            FullExprArg Cond,
2806                            Decl *CondVar, Stmt *Body);
2807  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
2808                                 SourceLocation WhileLoc,
2809                                 SourceLocation CondLParen, Expr *Cond,
2810                                 SourceLocation CondRParen);
2811
2812  StmtResult ActOnForStmt(SourceLocation ForLoc,
2813                          SourceLocation LParenLoc,
2814                          Stmt *First, FullExprArg Second,
2815                          Decl *SecondVar,
2816                          FullExprArg Third,
2817                          SourceLocation RParenLoc,
2818                          Stmt *Body);
2819  ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
2820                                           Expr *collection);
2821  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
2822                                        Stmt *First, Expr *collection,
2823                                        SourceLocation RParenLoc);
2824  StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
2825
2826  enum BuildForRangeKind {
2827    /// Initial building of a for-range statement.
2828    BFRK_Build,
2829    /// Instantiation or recovery rebuild of a for-range statement. Don't
2830    /// attempt any typo-correction.
2831    BFRK_Rebuild,
2832    /// Determining whether a for-range statement could be built. Avoid any
2833    /// unnecessary or irreversible actions.
2834    BFRK_Check
2835  };
2836
2837  StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
2838                                  SourceLocation ColonLoc, Expr *Collection,
2839                                  SourceLocation RParenLoc,
2840                                  BuildForRangeKind Kind);
2841  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
2842                                  SourceLocation ColonLoc,
2843                                  Stmt *RangeDecl, Stmt *BeginEndDecl,
2844                                  Expr *Cond, Expr *Inc,
2845                                  Stmt *LoopVarDecl,
2846                                  SourceLocation RParenLoc,
2847                                  BuildForRangeKind Kind);
2848  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
2849
2850  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
2851                           SourceLocation LabelLoc,
2852                           LabelDecl *TheDecl);
2853  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
2854                                   SourceLocation StarLoc,
2855                                   Expr *DestExp);
2856  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
2857  StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
2858
2859  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
2860                                CapturedRegionKind Kind, unsigned NumParams);
2861  StmtResult ActOnCapturedRegionEnd(Stmt *S);
2862  void ActOnCapturedRegionError();
2863  RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
2864                                           SourceLocation Loc,
2865                                           unsigned NumParams);
2866  const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
2867                                         bool AllowFunctionParameters);
2868
2869  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2870  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2871
2872  StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2873                             bool IsVolatile, unsigned NumOutputs,
2874                             unsigned NumInputs, IdentifierInfo **Names,
2875                             MultiExprArg Constraints, MultiExprArg Exprs,
2876                             Expr *AsmString, MultiExprArg Clobbers,
2877                             SourceLocation RParenLoc);
2878
2879  ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
2880                                       SourceLocation TemplateKWLoc,
2881                                       UnqualifiedId &Id,
2882                                       InlineAsmIdentifierInfo &Info,
2883                                       bool IsUnevaluatedContext);
2884  bool LookupInlineAsmField(StringRef Base, StringRef Member,
2885                            unsigned &Offset, SourceLocation AsmLoc);
2886  StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
2887                            ArrayRef<Token> AsmToks,
2888                            StringRef AsmString,
2889                            unsigned NumOutputs, unsigned NumInputs,
2890                            ArrayRef<StringRef> Constraints,
2891                            ArrayRef<StringRef> Clobbers,
2892                            ArrayRef<Expr*> Exprs,
2893                            SourceLocation EndLoc);
2894
2895  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
2896                                  SourceLocation StartLoc,
2897                                  SourceLocation IdLoc, IdentifierInfo *Id,
2898                                  bool Invalid = false);
2899
2900  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
2901
2902  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
2903                                  Decl *Parm, Stmt *Body);
2904
2905  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
2906
2907  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2908                                MultiStmtArg Catch, Stmt *Finally);
2909
2910  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
2911  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2912                                  Scope *CurScope);
2913  ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
2914                                            Expr *operand);
2915  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
2916                                         Expr *SynchExpr,
2917                                         Stmt *SynchBody);
2918
2919  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
2920
2921  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
2922                                     SourceLocation StartLoc,
2923                                     SourceLocation IdLoc,
2924                                     IdentifierInfo *Id);
2925
2926  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
2927
2928  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
2929                                Decl *ExDecl, Stmt *HandlerBlock);
2930  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2931                              MultiStmtArg Handlers);
2932
2933  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
2934                              SourceLocation TryLoc,
2935                              Stmt *TryBlock,
2936                              Stmt *Handler);
2937
2938  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
2939                                 Expr *FilterExpr,
2940                                 Stmt *Block);
2941
2942  StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
2943                                  Stmt *Block);
2944
2945  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
2946
2947  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
2948
2949  /// \brief If it's a file scoped decl that must warn if not used, keep track
2950  /// of it.
2951  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
2952
2953  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
2954  /// whose result is unused, warn.
2955  void DiagnoseUnusedExprResult(const Stmt *S);
2956  void DiagnoseUnusedDecl(const NamedDecl *ND);
2957
2958  /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2959  /// statement as a \p Body, and it is located on the same line.
2960  ///
2961  /// This helps prevent bugs due to typos, such as:
2962  ///     if (condition);
2963  ///       do_stuff();
2964  void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
2965                             const Stmt *Body,
2966                             unsigned DiagID);
2967
2968  /// Warn if a for/while loop statement \p S, which is followed by
2969  /// \p PossibleBody, has a suspicious null statement as a body.
2970  void DiagnoseEmptyLoopBody(const Stmt *S,
2971                             const Stmt *PossibleBody);
2972
2973  ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
2974    return DelayedDiagnostics.push(pool);
2975  }
2976  void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
2977
2978  typedef ProcessingContextState ParsingClassState;
2979  ParsingClassState PushParsingClass() {
2980    return DelayedDiagnostics.pushUndelayed();
2981  }
2982  void PopParsingClass(ParsingClassState state) {
2983    DelayedDiagnostics.popUndelayed(state);
2984  }
2985
2986  void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
2987
2988  void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
2989                              SourceLocation Loc,
2990                              const ObjCInterfaceDecl *UnknownObjCClass,
2991                              const ObjCPropertyDecl  *ObjCProperty);
2992
2993  void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2994
2995  bool makeUnavailableInSystemHeader(SourceLocation loc,
2996                                     StringRef message);
2997
2998  //===--------------------------------------------------------------------===//
2999  // Expression Parsing Callbacks: SemaExpr.cpp.
3000
3001  bool CanUseDecl(NamedDecl *D);
3002  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3003                         const ObjCInterfaceDecl *UnknownObjCClass=0);
3004  void NoteDeletedFunction(FunctionDecl *FD);
3005  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3006  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3007                                        ObjCMethodDecl *Getter,
3008                                        SourceLocation Loc);
3009  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3010                             ArrayRef<Expr *> Args);
3011
3012  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3013                                       Decl *LambdaContextDecl = 0,
3014                                       bool IsDecltype = false);
3015  enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3016  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3017                                       ReuseLambdaContextDecl_t,
3018                                       bool IsDecltype = false);
3019  void PopExpressionEvaluationContext();
3020
3021  void DiscardCleanupsInEvaluationContext();
3022
3023  ExprResult TransformToPotentiallyEvaluated(Expr *E);
3024  ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3025
3026  ExprResult ActOnConstantExpression(ExprResult Res);
3027
3028  // Functions for marking a declaration referenced.  These functions also
3029  // contain the relevant logic for marking if a reference to a function or
3030  // variable is an odr-use (in the C++11 sense).  There are separate variants
3031  // for expressions referring to a decl; these exist because odr-use marking
3032  // needs to be delayed for some constant variables when we build one of the
3033  // named expressions.
3034  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3035  void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func);
3036  void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3037  void MarkDeclRefReferenced(DeclRefExpr *E);
3038  void MarkMemberReferenced(MemberExpr *E);
3039
3040  void UpdateMarkingForLValueToRValue(Expr *E);
3041  void CleanupVarDeclMarking();
3042
3043  enum TryCaptureKind {
3044    TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3045  };
3046
3047  /// \brief Try to capture the given variable.
3048  ///
3049  /// \param Var The variable to capture.
3050  ///
3051  /// \param Loc The location at which the capture occurs.
3052  ///
3053  /// \param Kind The kind of capture, which may be implicit (for either a
3054  /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3055  ///
3056  /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3057  /// an explicit lambda capture.
3058  ///
3059  /// \param BuildAndDiagnose Whether we are actually supposed to add the
3060  /// captures or diagnose errors. If false, this routine merely check whether
3061  /// the capture can occur without performing the capture itself or complaining
3062  /// if the variable cannot be captured.
3063  ///
3064  /// \param CaptureType Will be set to the type of the field used to capture
3065  /// this variable in the innermost block or lambda. Only valid when the
3066  /// variable can be captured.
3067  ///
3068  /// \param DeclRefType Will be set to the type of a reference to the capture
3069  /// from within the current scope. Only valid when the variable can be
3070  /// captured.
3071  ///
3072  /// \returns true if an error occurred (i.e., the variable cannot be
3073  /// captured) and false if the capture succeeded.
3074  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3075                          SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3076                          QualType &CaptureType,
3077                          QualType &DeclRefType);
3078
3079  /// \brief Try to capture the given variable.
3080  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3081                          TryCaptureKind Kind = TryCapture_Implicit,
3082                          SourceLocation EllipsisLoc = SourceLocation());
3083
3084  /// \brief Given a variable, determine the type that a reference to that
3085  /// variable will have in the given scope.
3086  QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3087
3088  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3089  void MarkDeclarationsReferencedInExpr(Expr *E,
3090                                        bool SkipLocalVariables = false);
3091
3092  /// \brief Try to recover by turning the given expression into a
3093  /// call.  Returns true if recovery was attempted or an error was
3094  /// emitted; this may also leave the ExprResult invalid.
3095  bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3096                            bool ForceComplain = false,
3097                            bool (*IsPlausibleResult)(QualType) = 0);
3098
3099  /// \brief Figure out if an expression could be turned into a call.
3100  bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3101                     UnresolvedSetImpl &NonTemplateOverloads);
3102
3103  /// \brief Conditionally issue a diagnostic based on the current
3104  /// evaluation context.
3105  ///
3106  /// \param Statement If Statement is non-null, delay reporting the
3107  /// diagnostic until the function body is parsed, and then do a basic
3108  /// reachability analysis to determine if the statement is reachable.
3109  /// If it is unreachable, the diagnostic will not be emitted.
3110  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3111                           const PartialDiagnostic &PD);
3112
3113  // Primary Expressions.
3114  SourceRange getExprRange(Expr *E) const;
3115
3116  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
3117                               SourceLocation TemplateKWLoc,
3118                               UnqualifiedId &Id,
3119                               bool HasTrailingLParen, bool IsAddressOfOperand,
3120                               CorrectionCandidateCallback *CCC = 0,
3121                               bool IsInlineAsmIdentifier = false);
3122
3123  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3124                              TemplateArgumentListInfo &Buffer,
3125                              DeclarationNameInfo &NameInfo,
3126                              const TemplateArgumentListInfo *&TemplateArgs);
3127
3128  bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3129                           CorrectionCandidateCallback &CCC,
3130                           TemplateArgumentListInfo *ExplicitTemplateArgs = 0,
3131                           ArrayRef<Expr *> Args = None);
3132
3133  ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3134                                IdentifierInfo *II,
3135                                bool AllowBuiltinCreation=false);
3136
3137  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3138                                        SourceLocation TemplateKWLoc,
3139                                        const DeclarationNameInfo &NameInfo,
3140                                        bool isAddressOfOperand,
3141                                const TemplateArgumentListInfo *TemplateArgs);
3142
3143  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3144                              ExprValueKind VK,
3145                              SourceLocation Loc,
3146                              const CXXScopeSpec *SS = 0);
3147  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3148                              ExprValueKind VK,
3149                              const DeclarationNameInfo &NameInfo,
3150                              const CXXScopeSpec *SS = 0,
3151                              NamedDecl *FoundD = 0);
3152  ExprResult
3153  BuildAnonymousStructUnionMemberReference(
3154      const CXXScopeSpec &SS,
3155      SourceLocation nameLoc,
3156      IndirectFieldDecl *indirectField,
3157      DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_none),
3158      Expr *baseObjectExpr = 0,
3159      SourceLocation opLoc = SourceLocation());
3160
3161  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3162                                             SourceLocation TemplateKWLoc,
3163                                             LookupResult &R,
3164                                const TemplateArgumentListInfo *TemplateArgs);
3165  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3166                                     SourceLocation TemplateKWLoc,
3167                                     LookupResult &R,
3168                                const TemplateArgumentListInfo *TemplateArgs,
3169                                     bool IsDefiniteInstance);
3170  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3171                                  const LookupResult &R,
3172                                  bool HasTrailingLParen);
3173
3174  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3175                                         const DeclarationNameInfo &NameInfo,
3176                                               bool IsAddressOfOperand);
3177  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3178                                       SourceLocation TemplateKWLoc,
3179                                const DeclarationNameInfo &NameInfo,
3180                                const TemplateArgumentListInfo *TemplateArgs);
3181
3182  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3183                                      LookupResult &R,
3184                                      bool NeedsADL);
3185  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3186                                      const DeclarationNameInfo &NameInfo,
3187                                      NamedDecl *D, NamedDecl *FoundD = 0);
3188
3189  ExprResult BuildLiteralOperatorCall(LookupResult &R,
3190                                      DeclarationNameInfo &SuffixInfo,
3191                                      ArrayRef<Expr*> Args,
3192                                      SourceLocation LitEndLoc,
3193                            TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
3194
3195  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3196  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3197  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0);
3198  ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0);
3199  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3200  ExprResult ActOnParenListExpr(SourceLocation L,
3201                                SourceLocation R,
3202                                MultiExprArg Val);
3203
3204  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3205  /// fragments (e.g. "foo" "bar" L"baz").
3206  ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
3207                                Scope *UDLScope = 0);
3208
3209  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3210                                       SourceLocation DefaultLoc,
3211                                       SourceLocation RParenLoc,
3212                                       Expr *ControllingExpr,
3213                                       ArrayRef<ParsedType> ArgTypes,
3214                                       ArrayRef<Expr *> ArgExprs);
3215  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3216                                        SourceLocation DefaultLoc,
3217                                        SourceLocation RParenLoc,
3218                                        Expr *ControllingExpr,
3219                                        ArrayRef<TypeSourceInfo *> Types,
3220                                        ArrayRef<Expr *> Exprs);
3221
3222  // Binary/Unary Operators.  'Tok' is the token for the operator.
3223  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3224                                  Expr *InputExpr);
3225  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3226                          UnaryOperatorKind Opc, Expr *Input);
3227  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3228                          tok::TokenKind Op, Expr *Input);
3229
3230  QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3231
3232  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3233                                            SourceLocation OpLoc,
3234                                            UnaryExprOrTypeTrait ExprKind,
3235                                            SourceRange R);
3236  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3237                                            UnaryExprOrTypeTrait ExprKind);
3238  ExprResult
3239    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3240                                  UnaryExprOrTypeTrait ExprKind,
3241                                  bool IsType, void *TyOrEx,
3242                                  const SourceRange &ArgRange);
3243
3244  ExprResult CheckPlaceholderExpr(Expr *E);
3245  bool CheckVecStepExpr(Expr *E);
3246
3247  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3248  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3249                                        SourceRange ExprRange,
3250                                        UnaryExprOrTypeTrait ExprKind);
3251  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3252                                          SourceLocation OpLoc,
3253                                          IdentifierInfo &Name,
3254                                          SourceLocation NameLoc,
3255                                          SourceLocation RParenLoc);
3256  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3257                                 tok::TokenKind Kind, Expr *Input);
3258
3259  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3260                                     Expr *Idx, SourceLocation RLoc);
3261  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3262                                             Expr *Idx, SourceLocation RLoc);
3263
3264  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3265                                      SourceLocation OpLoc, bool IsArrow,
3266                                      CXXScopeSpec &SS,
3267                                      SourceLocation TemplateKWLoc,
3268                                      NamedDecl *FirstQualifierInScope,
3269                                const DeclarationNameInfo &NameInfo,
3270                                const TemplateArgumentListInfo *TemplateArgs);
3271
3272  // This struct is for use by ActOnMemberAccess to allow
3273  // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3274  // changing the access operator from a '.' to a '->' (to see if that is the
3275  // change needed to fix an error about an unknown member, e.g. when the class
3276  // defines a custom operator->).
3277  struct ActOnMemberAccessExtraArgs {
3278    Scope *S;
3279    UnqualifiedId &Id;
3280    Decl *ObjCImpDecl;
3281    bool HasTrailingLParen;
3282  };
3283
3284  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3285                                      SourceLocation OpLoc, bool IsArrow,
3286                                      const CXXScopeSpec &SS,
3287                                      SourceLocation TemplateKWLoc,
3288                                      NamedDecl *FirstQualifierInScope,
3289                                      LookupResult &R,
3290                                 const TemplateArgumentListInfo *TemplateArgs,
3291                                      bool SuppressQualifierCheck = false,
3292                                     ActOnMemberAccessExtraArgs *ExtraArgs = 0);
3293
3294  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3295  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
3296                              bool &IsArrow, SourceLocation OpLoc,
3297                              CXXScopeSpec &SS,
3298                              Decl *ObjCImpDecl,
3299                              bool HasTemplateArgs);
3300
3301  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3302                                     const CXXScopeSpec &SS,
3303                                     const LookupResult &R);
3304
3305  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3306                                      bool IsArrow, SourceLocation OpLoc,
3307                                      const CXXScopeSpec &SS,
3308                                      SourceLocation TemplateKWLoc,
3309                                      NamedDecl *FirstQualifierInScope,
3310                               const DeclarationNameInfo &NameInfo,
3311                               const TemplateArgumentListInfo *TemplateArgs);
3312
3313  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3314                                   SourceLocation OpLoc,
3315                                   tok::TokenKind OpKind,
3316                                   CXXScopeSpec &SS,
3317                                   SourceLocation TemplateKWLoc,
3318                                   UnqualifiedId &Member,
3319                                   Decl *ObjCImpDecl,
3320                                   bool HasTrailingLParen);
3321
3322  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3323  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3324                               FunctionDecl *FDecl,
3325                               const FunctionProtoType *Proto,
3326                               ArrayRef<Expr *> Args,
3327                               SourceLocation RParenLoc,
3328                               bool ExecConfig = false);
3329  void CheckStaticArrayArgument(SourceLocation CallLoc,
3330                                ParmVarDecl *Param,
3331                                const Expr *ArgExpr);
3332
3333  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3334  /// This provides the location of the left/right parens and a list of comma
3335  /// locations.
3336  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3337                           MultiExprArg ArgExprs, SourceLocation RParenLoc,
3338                           Expr *ExecConfig = 0, bool IsExecConfig = false);
3339  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3340                                   SourceLocation LParenLoc,
3341                                   ArrayRef<Expr *> Arg,
3342                                   SourceLocation RParenLoc,
3343                                   Expr *Config = 0,
3344                                   bool IsExecConfig = false);
3345
3346  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3347                                     MultiExprArg ExecConfig,
3348                                     SourceLocation GGGLoc);
3349
3350  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3351                           Declarator &D, ParsedType &Ty,
3352                           SourceLocation RParenLoc, Expr *CastExpr);
3353  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3354                                 TypeSourceInfo *Ty,
3355                                 SourceLocation RParenLoc,
3356                                 Expr *Op);
3357  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3358
3359  /// \brief Build an altivec or OpenCL literal.
3360  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3361                                SourceLocation RParenLoc, Expr *E,
3362                                TypeSourceInfo *TInfo);
3363
3364  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3365
3366  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3367                                  ParsedType Ty,
3368                                  SourceLocation RParenLoc,
3369                                  Expr *InitExpr);
3370
3371  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3372                                      TypeSourceInfo *TInfo,
3373                                      SourceLocation RParenLoc,
3374                                      Expr *LiteralExpr);
3375
3376  ExprResult ActOnInitList(SourceLocation LBraceLoc,
3377                           MultiExprArg InitArgList,
3378                           SourceLocation RBraceLoc);
3379
3380  ExprResult ActOnDesignatedInitializer(Designation &Desig,
3381                                        SourceLocation Loc,
3382                                        bool GNUSyntax,
3383                                        ExprResult Init);
3384
3385  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3386                        tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3387  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3388                        BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3389  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3390                                Expr *LHSExpr, Expr *RHSExpr);
3391
3392  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3393  /// in the case of a the GNU conditional expr extension.
3394  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3395                                SourceLocation ColonLoc,
3396                                Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3397
3398  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3399  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3400                            LabelDecl *TheDecl);
3401
3402  void ActOnStartStmtExpr();
3403  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3404                           SourceLocation RPLoc); // "({..})"
3405  void ActOnStmtExprError();
3406
3407  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3408  struct OffsetOfComponent {
3409    SourceLocation LocStart, LocEnd;
3410    bool isBrackets;  // true if [expr], false if .ident
3411    union {
3412      IdentifierInfo *IdentInfo;
3413      Expr *E;
3414    } U;
3415  };
3416
3417  /// __builtin_offsetof(type, a.b[123][456].c)
3418  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3419                                  TypeSourceInfo *TInfo,
3420                                  OffsetOfComponent *CompPtr,
3421                                  unsigned NumComponents,
3422                                  SourceLocation RParenLoc);
3423  ExprResult ActOnBuiltinOffsetOf(Scope *S,
3424                                  SourceLocation BuiltinLoc,
3425                                  SourceLocation TypeLoc,
3426                                  ParsedType ParsedArgTy,
3427                                  OffsetOfComponent *CompPtr,
3428                                  unsigned NumComponents,
3429                                  SourceLocation RParenLoc);
3430
3431  // __builtin_choose_expr(constExpr, expr1, expr2)
3432  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3433                             Expr *CondExpr, Expr *LHSExpr,
3434                             Expr *RHSExpr, SourceLocation RPLoc);
3435
3436  // __builtin_va_arg(expr, type)
3437  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3438                        SourceLocation RPLoc);
3439  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3440                            TypeSourceInfo *TInfo, SourceLocation RPLoc);
3441
3442  // __null
3443  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3444
3445  bool CheckCaseExpression(Expr *E);
3446
3447  /// \brief Describes the result of an "if-exists" condition check.
3448  enum IfExistsResult {
3449    /// \brief The symbol exists.
3450    IER_Exists,
3451
3452    /// \brief The symbol does not exist.
3453    IER_DoesNotExist,
3454
3455    /// \brief The name is a dependent name, so the results will differ
3456    /// from one instantiation to the next.
3457    IER_Dependent,
3458
3459    /// \brief An error occurred.
3460    IER_Error
3461  };
3462
3463  IfExistsResult
3464  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3465                               const DeclarationNameInfo &TargetNameInfo);
3466
3467  IfExistsResult
3468  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3469                               bool IsIfExists, CXXScopeSpec &SS,
3470                               UnqualifiedId &Name);
3471
3472  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3473                                        bool IsIfExists,
3474                                        NestedNameSpecifierLoc QualifierLoc,
3475                                        DeclarationNameInfo NameInfo,
3476                                        Stmt *Nested);
3477  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3478                                        bool IsIfExists,
3479                                        CXXScopeSpec &SS, UnqualifiedId &Name,
3480                                        Stmt *Nested);
3481
3482  //===------------------------- "Block" Extension ------------------------===//
3483
3484  /// ActOnBlockStart - This callback is invoked when a block literal is
3485  /// started.
3486  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3487
3488  /// ActOnBlockArguments - This callback allows processing of block arguments.
3489  /// If there are no arguments, this is still invoked.
3490  void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3491                           Scope *CurScope);
3492
3493  /// ActOnBlockError - If there is an error parsing a block, this callback
3494  /// is invoked to pop the information about the block from the action impl.
3495  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3496
3497  /// ActOnBlockStmtExpr - This is called when the body of a block statement
3498  /// literal was successfully completed.  ^(int x){...}
3499  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3500                                Scope *CurScope);
3501
3502  //===---------------------------- OpenCL Features -----------------------===//
3503
3504  /// __builtin_astype(...)
3505  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3506                             SourceLocation BuiltinLoc,
3507                             SourceLocation RParenLoc);
3508
3509  //===---------------------------- C++ Features --------------------------===//
3510
3511  // Act on C++ namespaces
3512  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3513                               SourceLocation NamespaceLoc,
3514                               SourceLocation IdentLoc,
3515                               IdentifierInfo *Ident,
3516                               SourceLocation LBrace,
3517                               AttributeList *AttrList);
3518  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3519
3520  NamespaceDecl *getStdNamespace() const;
3521  NamespaceDecl *getOrCreateStdNamespace();
3522
3523  CXXRecordDecl *getStdBadAlloc() const;
3524
3525  /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3526  /// it is and Element is not NULL, assigns the element type to Element.
3527  bool isStdInitializerList(QualType Ty, QualType *Element);
3528
3529  /// \brief Looks for the std::initializer_list template and instantiates it
3530  /// with Element, or emits an error if it's not found.
3531  ///
3532  /// \returns The instantiated template, or null on error.
3533  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3534
3535  /// \brief Determine whether Ctor is an initializer-list constructor, as
3536  /// defined in [dcl.init.list]p2.
3537  bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3538
3539  Decl *ActOnUsingDirective(Scope *CurScope,
3540                            SourceLocation UsingLoc,
3541                            SourceLocation NamespcLoc,
3542                            CXXScopeSpec &SS,
3543                            SourceLocation IdentLoc,
3544                            IdentifierInfo *NamespcName,
3545                            AttributeList *AttrList);
3546
3547  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3548
3549  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3550                               SourceLocation NamespaceLoc,
3551                               SourceLocation AliasLoc,
3552                               IdentifierInfo *Alias,
3553                               CXXScopeSpec &SS,
3554                               SourceLocation IdentLoc,
3555                               IdentifierInfo *Ident);
3556
3557  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3558  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3559                            const LookupResult &PreviousDecls);
3560  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3561                                        NamedDecl *Target);
3562
3563  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3564                                   bool isTypeName,
3565                                   const CXXScopeSpec &SS,
3566                                   SourceLocation NameLoc,
3567                                   const LookupResult &Previous);
3568  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3569                               const CXXScopeSpec &SS,
3570                               SourceLocation NameLoc);
3571
3572  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3573                                   SourceLocation UsingLoc,
3574                                   CXXScopeSpec &SS,
3575                                   const DeclarationNameInfo &NameInfo,
3576                                   AttributeList *AttrList,
3577                                   bool IsInstantiation,
3578                                   bool IsTypeName,
3579                                   SourceLocation TypenameLoc);
3580
3581  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3582
3583  Decl *ActOnUsingDeclaration(Scope *CurScope,
3584                              AccessSpecifier AS,
3585                              bool HasUsingKeyword,
3586                              SourceLocation UsingLoc,
3587                              CXXScopeSpec &SS,
3588                              UnqualifiedId &Name,
3589                              AttributeList *AttrList,
3590                              bool IsTypeName,
3591                              SourceLocation TypenameLoc);
3592  Decl *ActOnAliasDeclaration(Scope *CurScope,
3593                              AccessSpecifier AS,
3594                              MultiTemplateParamsArg TemplateParams,
3595                              SourceLocation UsingLoc,
3596                              UnqualifiedId &Name,
3597                              AttributeList *AttrList,
3598                              TypeResult Type);
3599
3600  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3601  /// including handling of its default argument expressions.
3602  ///
3603  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3604  ExprResult
3605  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3606                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3607                        bool HadMultipleCandidates, bool IsListInitialization,
3608                        bool RequiresZeroInit, unsigned ConstructKind,
3609                        SourceRange ParenRange);
3610
3611  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3612  // the constructor can be elidable?
3613  ExprResult
3614  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3615                        CXXConstructorDecl *Constructor, bool Elidable,
3616                        MultiExprArg Exprs, bool HadMultipleCandidates,
3617                        bool IsListInitialization, bool RequiresZeroInit,
3618                        unsigned ConstructKind, SourceRange ParenRange);
3619
3620  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3621  /// the default expr if needed.
3622  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3623                                    FunctionDecl *FD,
3624                                    ParmVarDecl *Param);
3625
3626  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3627  /// constructed variable.
3628  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3629
3630  /// \brief Helper class that collects exception specifications for
3631  /// implicitly-declared special member functions.
3632  class ImplicitExceptionSpecification {
3633    // Pointer to allow copying
3634    Sema *Self;
3635    // We order exception specifications thus:
3636    // noexcept is the most restrictive, but is only used in C++11.
3637    // throw() comes next.
3638    // Then a throw(collected exceptions)
3639    // Finally no specification, which is expressed as noexcept(false).
3640    // throw(...) is used instead if any called function uses it.
3641    ExceptionSpecificationType ComputedEST;
3642    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3643    SmallVector<QualType, 4> Exceptions;
3644
3645    void ClearExceptions() {
3646      ExceptionsSeen.clear();
3647      Exceptions.clear();
3648    }
3649
3650  public:
3651    explicit ImplicitExceptionSpecification(Sema &Self)
3652      : Self(&Self), ComputedEST(EST_BasicNoexcept) {
3653      if (!Self.getLangOpts().CPlusPlus11)
3654        ComputedEST = EST_DynamicNone;
3655    }
3656
3657    /// \brief Get the computed exception specification type.
3658    ExceptionSpecificationType getExceptionSpecType() const {
3659      assert(ComputedEST != EST_ComputedNoexcept &&
3660             "noexcept(expr) should not be a possible result");
3661      return ComputedEST;
3662    }
3663
3664    /// \brief The number of exceptions in the exception specification.
3665    unsigned size() const { return Exceptions.size(); }
3666
3667    /// \brief The set of exceptions in the exception specification.
3668    const QualType *data() const { return Exceptions.data(); }
3669
3670    /// \brief Integrate another called method into the collected data.
3671    void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
3672
3673    /// \brief Integrate an invoked expression into the collected data.
3674    void CalledExpr(Expr *E);
3675
3676    /// \brief Overwrite an EPI's exception specification with this
3677    /// computed exception specification.
3678    void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const {
3679      EPI.ExceptionSpecType = getExceptionSpecType();
3680      if (EPI.ExceptionSpecType == EST_Dynamic) {
3681        EPI.NumExceptions = size();
3682        EPI.Exceptions = data();
3683      } else if (EPI.ExceptionSpecType == EST_None) {
3684        /// C++11 [except.spec]p14:
3685        ///   The exception-specification is noexcept(false) if the set of
3686        ///   potential exceptions of the special member function contains "any"
3687        EPI.ExceptionSpecType = EST_ComputedNoexcept;
3688        EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
3689                                                     tok::kw_false).take();
3690      }
3691    }
3692    FunctionProtoType::ExtProtoInfo getEPI() const {
3693      FunctionProtoType::ExtProtoInfo EPI;
3694      getEPI(EPI);
3695      return EPI;
3696    }
3697  };
3698
3699  /// \brief Determine what sort of exception specification a defaulted
3700  /// copy constructor of a class will have.
3701  ImplicitExceptionSpecification
3702  ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
3703                                           CXXMethodDecl *MD);
3704
3705  /// \brief Determine what sort of exception specification a defaulted
3706  /// default constructor of a class will have, and whether the parameter
3707  /// will be const.
3708  ImplicitExceptionSpecification
3709  ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
3710
3711  /// \brief Determine what sort of exception specification a defautled
3712  /// copy assignment operator of a class will have, and whether the
3713  /// parameter will be const.
3714  ImplicitExceptionSpecification
3715  ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
3716
3717  /// \brief Determine what sort of exception specification a defaulted move
3718  /// constructor of a class will have.
3719  ImplicitExceptionSpecification
3720  ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
3721
3722  /// \brief Determine what sort of exception specification a defaulted move
3723  /// assignment operator of a class will have.
3724  ImplicitExceptionSpecification
3725  ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
3726
3727  /// \brief Determine what sort of exception specification a defaulted
3728  /// destructor of a class will have.
3729  ImplicitExceptionSpecification
3730  ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
3731
3732  /// \brief Determine what sort of exception specification an inheriting
3733  /// constructor of a class will have.
3734  ImplicitExceptionSpecification
3735  ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
3736
3737  /// \brief Evaluate the implicit exception specification for a defaulted
3738  /// special member function.
3739  void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
3740
3741  /// \brief Check the given exception-specification and update the
3742  /// extended prototype information with the results.
3743  void checkExceptionSpecification(ExceptionSpecificationType EST,
3744                                   ArrayRef<ParsedType> DynamicExceptions,
3745                                   ArrayRef<SourceRange> DynamicExceptionRanges,
3746                                   Expr *NoexceptExpr,
3747                                   SmallVectorImpl<QualType> &Exceptions,
3748                                   FunctionProtoType::ExtProtoInfo &EPI);
3749
3750  /// \brief Determine if a special member function should have a deleted
3751  /// definition when it is defaulted.
3752  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
3753                                 bool Diagnose = false);
3754
3755  /// \brief Declare the implicit default constructor for the given class.
3756  ///
3757  /// \param ClassDecl The class declaration into which the implicit
3758  /// default constructor will be added.
3759  ///
3760  /// \returns The implicitly-declared default constructor.
3761  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
3762                                                     CXXRecordDecl *ClassDecl);
3763
3764  /// DefineImplicitDefaultConstructor - Checks for feasibility of
3765  /// defining this constructor as the default constructor.
3766  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3767                                        CXXConstructorDecl *Constructor);
3768
3769  /// \brief Declare the implicit destructor for the given class.
3770  ///
3771  /// \param ClassDecl The class declaration into which the implicit
3772  /// destructor will be added.
3773  ///
3774  /// \returns The implicitly-declared destructor.
3775  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
3776
3777  /// DefineImplicitDestructor - Checks for feasibility of
3778  /// defining this destructor as the default destructor.
3779  void DefineImplicitDestructor(SourceLocation CurrentLocation,
3780                                CXXDestructorDecl *Destructor);
3781
3782  /// \brief Build an exception spec for destructors that don't have one.
3783  ///
3784  /// C++11 says that user-defined destructors with no exception spec get one
3785  /// that looks as if the destructor was implicitly declared.
3786  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
3787                                     CXXDestructorDecl *Destructor);
3788
3789  /// \brief Declare all inheriting constructors for the given class.
3790  ///
3791  /// \param ClassDecl The class declaration into which the inheriting
3792  /// constructors will be added.
3793  void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
3794
3795  /// \brief Define the specified inheriting constructor.
3796  void DefineInheritingConstructor(SourceLocation UseLoc,
3797                                   CXXConstructorDecl *Constructor);
3798
3799  /// \brief Declare the implicit copy constructor for the given class.
3800  ///
3801  /// \param ClassDecl The class declaration into which the implicit
3802  /// copy constructor will be added.
3803  ///
3804  /// \returns The implicitly-declared copy constructor.
3805  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
3806
3807  /// DefineImplicitCopyConstructor - Checks for feasibility of
3808  /// defining this constructor as the copy constructor.
3809  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3810                                     CXXConstructorDecl *Constructor);
3811
3812  /// \brief Declare the implicit move constructor for the given class.
3813  ///
3814  /// \param ClassDecl The Class declaration into which the implicit
3815  /// move constructor will be added.
3816  ///
3817  /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3818  /// declared.
3819  CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3820
3821  /// DefineImplicitMoveConstructor - Checks for feasibility of
3822  /// defining this constructor as the move constructor.
3823  void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3824                                     CXXConstructorDecl *Constructor);
3825
3826  /// \brief Declare the implicit copy assignment operator for the given class.
3827  ///
3828  /// \param ClassDecl The class declaration into which the implicit
3829  /// copy assignment operator will be added.
3830  ///
3831  /// \returns The implicitly-declared copy assignment operator.
3832  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3833
3834  /// \brief Defines an implicitly-declared copy assignment operator.
3835  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3836                                    CXXMethodDecl *MethodDecl);
3837
3838  /// \brief Declare the implicit move assignment operator for the given class.
3839  ///
3840  /// \param ClassDecl The Class declaration into which the implicit
3841  /// move assignment operator will be added.
3842  ///
3843  /// \returns The implicitly-declared move assignment operator, or NULL if it
3844  /// wasn't declared.
3845  CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3846
3847  /// \brief Defines an implicitly-declared move assignment operator.
3848  void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3849                                    CXXMethodDecl *MethodDecl);
3850
3851  /// \brief Force the declaration of any implicitly-declared members of this
3852  /// class.
3853  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3854
3855  /// \brief Determine whether the given function is an implicitly-deleted
3856  /// special member function.
3857  bool isImplicitlyDeleted(FunctionDecl *FD);
3858
3859  /// \brief Check whether 'this' shows up in the type of a static member
3860  /// function after the (naturally empty) cv-qualifier-seq would be.
3861  ///
3862  /// \returns true if an error occurred.
3863  bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
3864
3865  /// \brief Whether this' shows up in the exception specification of a static
3866  /// member function.
3867  bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
3868
3869  /// \brief Check whether 'this' shows up in the attributes of the given
3870  /// static member function.
3871  ///
3872  /// \returns true if an error occurred.
3873  bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
3874
3875  /// MaybeBindToTemporary - If the passed in expression has a record type with
3876  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3877  /// it simply returns the passed in expression.
3878  ExprResult MaybeBindToTemporary(Expr *E);
3879
3880  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3881                               MultiExprArg ArgsPtr,
3882                               SourceLocation Loc,
3883                               SmallVectorImpl<Expr*> &ConvertedArgs,
3884                               bool AllowExplicit = false,
3885                               bool IsListInitialization = false);
3886
3887  ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
3888                                          SourceLocation NameLoc,
3889                                          IdentifierInfo &Name);
3890
3891  ParsedType getDestructorName(SourceLocation TildeLoc,
3892                               IdentifierInfo &II, SourceLocation NameLoc,
3893                               Scope *S, CXXScopeSpec &SS,
3894                               ParsedType ObjectType,
3895                               bool EnteringContext);
3896
3897  ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
3898
3899  // Checks that reinterpret casts don't have undefined behavior.
3900  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
3901                                      bool IsDereference, SourceRange Range);
3902
3903  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
3904  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
3905                               tok::TokenKind Kind,
3906                               SourceLocation LAngleBracketLoc,
3907                               Declarator &D,
3908                               SourceLocation RAngleBracketLoc,
3909                               SourceLocation LParenLoc,
3910                               Expr *E,
3911                               SourceLocation RParenLoc);
3912
3913  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
3914                               tok::TokenKind Kind,
3915                               TypeSourceInfo *Ty,
3916                               Expr *E,
3917                               SourceRange AngleBrackets,
3918                               SourceRange Parens);
3919
3920  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3921                            SourceLocation TypeidLoc,
3922                            TypeSourceInfo *Operand,
3923                            SourceLocation RParenLoc);
3924  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3925                            SourceLocation TypeidLoc,
3926                            Expr *Operand,
3927                            SourceLocation RParenLoc);
3928
3929  /// ActOnCXXTypeid - Parse typeid( something ).
3930  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
3931                            SourceLocation LParenLoc, bool isType,
3932                            void *TyOrExpr,
3933                            SourceLocation RParenLoc);
3934
3935  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3936                            SourceLocation TypeidLoc,
3937                            TypeSourceInfo *Operand,
3938                            SourceLocation RParenLoc);
3939  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3940                            SourceLocation TypeidLoc,
3941                            Expr *Operand,
3942                            SourceLocation RParenLoc);
3943
3944  /// ActOnCXXUuidof - Parse __uuidof( something ).
3945  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
3946                            SourceLocation LParenLoc, bool isType,
3947                            void *TyOrExpr,
3948                            SourceLocation RParenLoc);
3949
3950
3951  //// ActOnCXXThis -  Parse 'this' pointer.
3952  ExprResult ActOnCXXThis(SourceLocation loc);
3953
3954  /// \brief Try to retrieve the type of the 'this' pointer.
3955  ///
3956  /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
3957  QualType getCurrentThisType();
3958
3959  /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
3960  /// current context not being a non-static member function. In such cases,
3961  /// this provides the type used for 'this'.
3962  QualType CXXThisTypeOverride;
3963
3964  /// \brief RAII object used to temporarily allow the C++ 'this' expression
3965  /// to be used, with the given qualifiers on the current class type.
3966  class CXXThisScopeRAII {
3967    Sema &S;
3968    QualType OldCXXThisTypeOverride;
3969    bool Enabled;
3970
3971  public:
3972    /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
3973    /// using the given declaration (which is either a class template or a
3974    /// class) along with the given qualifiers.
3975    /// along with the qualifiers placed on '*this'.
3976    CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
3977                     bool Enabled = true);
3978
3979    ~CXXThisScopeRAII();
3980  };
3981
3982  /// \brief Make sure the value of 'this' is actually available in the current
3983  /// context, if it is a potentially evaluated context.
3984  ///
3985  /// \param Loc The location at which the capture of 'this' occurs.
3986  ///
3987  /// \param Explicit Whether 'this' is explicitly captured in a lambda
3988  /// capture list.
3989  void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false);
3990
3991  /// \brief Determine whether the given type is the type of *this that is used
3992  /// outside of the body of a member function for a type that is currently
3993  /// being defined.
3994  bool isThisOutsideMemberFunctionBody(QualType BaseType);
3995
3996  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
3997  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3998
3999
4000  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4001  ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4002
4003  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4004  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4005
4006  //// ActOnCXXThrow -  Parse throw expressions.
4007  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4008  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4009                           bool IsThrownVarInScope);
4010  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
4011                                  bool IsThrownVarInScope);
4012
4013  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4014  /// Can be interpreted either as function-style casting ("int(x)")
4015  /// or class type construction ("ClassType(x,y,z)")
4016  /// or creation of a value-initialized type ("int()").
4017  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4018                                       SourceLocation LParenLoc,
4019                                       MultiExprArg Exprs,
4020                                       SourceLocation RParenLoc);
4021
4022  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4023                                       SourceLocation LParenLoc,
4024                                       MultiExprArg Exprs,
4025                                       SourceLocation RParenLoc);
4026
4027  /// ActOnCXXNew - Parsed a C++ 'new' expression.
4028  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4029                         SourceLocation PlacementLParen,
4030                         MultiExprArg PlacementArgs,
4031                         SourceLocation PlacementRParen,
4032                         SourceRange TypeIdParens, Declarator &D,
4033                         Expr *Initializer);
4034  ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4035                         SourceLocation PlacementLParen,
4036                         MultiExprArg PlacementArgs,
4037                         SourceLocation PlacementRParen,
4038                         SourceRange TypeIdParens,
4039                         QualType AllocType,
4040                         TypeSourceInfo *AllocTypeInfo,
4041                         Expr *ArraySize,
4042                         SourceRange DirectInitRange,
4043                         Expr *Initializer,
4044                         bool TypeMayContainAuto = true);
4045
4046  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4047                          SourceRange R);
4048  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4049                               bool UseGlobal, QualType AllocType, bool IsArray,
4050                               MultiExprArg PlaceArgs,
4051                               FunctionDecl *&OperatorNew,
4052                               FunctionDecl *&OperatorDelete);
4053  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4054                              DeclarationName Name, MultiExprArg Args,
4055                              DeclContext *Ctx,
4056                              bool AllowMissing, FunctionDecl *&Operator,
4057                              bool Diagnose = true);
4058  void DeclareGlobalNewDelete();
4059  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4060                                       QualType Argument,
4061                                       bool addMallocAttr = false);
4062
4063  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4064                                DeclarationName Name, FunctionDecl* &Operator,
4065                                bool Diagnose = true);
4066
4067  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4068  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4069                            bool UseGlobal, bool ArrayForm,
4070                            Expr *Operand);
4071
4072  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4073  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4074                                    SourceLocation StmtLoc,
4075                                    bool ConvertToBoolean);
4076
4077  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4078                               Expr *Operand, SourceLocation RParen);
4079  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4080                                  SourceLocation RParen);
4081
4082  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
4083  /// pseudo-functions.
4084  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
4085                                 SourceLocation KWLoc,
4086                                 ParsedType Ty,
4087                                 SourceLocation RParen);
4088
4089  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
4090                                 SourceLocation KWLoc,
4091                                 TypeSourceInfo *T,
4092                                 SourceLocation RParen);
4093
4094  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
4095  /// pseudo-functions.
4096  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
4097                                  SourceLocation KWLoc,
4098                                  ParsedType LhsTy,
4099                                  ParsedType RhsTy,
4100                                  SourceLocation RParen);
4101
4102  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
4103                                  SourceLocation KWLoc,
4104                                  TypeSourceInfo *LhsT,
4105                                  TypeSourceInfo *RhsT,
4106                                  SourceLocation RParen);
4107
4108  /// \brief Parsed one of the type trait support pseudo-functions.
4109  ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4110                            ArrayRef<ParsedType> Args,
4111                            SourceLocation RParenLoc);
4112  ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4113                            ArrayRef<TypeSourceInfo *> Args,
4114                            SourceLocation RParenLoc);
4115
4116  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4117  /// pseudo-functions.
4118  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4119                                 SourceLocation KWLoc,
4120                                 ParsedType LhsTy,
4121                                 Expr *DimExpr,
4122                                 SourceLocation RParen);
4123
4124  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4125                                 SourceLocation KWLoc,
4126                                 TypeSourceInfo *TSInfo,
4127                                 Expr *DimExpr,
4128                                 SourceLocation RParen);
4129
4130  /// ActOnExpressionTrait - Parsed one of the unary type trait support
4131  /// pseudo-functions.
4132  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4133                                  SourceLocation KWLoc,
4134                                  Expr *Queried,
4135                                  SourceLocation RParen);
4136
4137  ExprResult BuildExpressionTrait(ExpressionTrait OET,
4138                                  SourceLocation KWLoc,
4139                                  Expr *Queried,
4140                                  SourceLocation RParen);
4141
4142  ExprResult ActOnStartCXXMemberReference(Scope *S,
4143                                          Expr *Base,
4144                                          SourceLocation OpLoc,
4145                                          tok::TokenKind OpKind,
4146                                          ParsedType &ObjectType,
4147                                          bool &MayBePseudoDestructor);
4148
4149  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
4150
4151  ExprResult BuildPseudoDestructorExpr(Expr *Base,
4152                                       SourceLocation OpLoc,
4153                                       tok::TokenKind OpKind,
4154                                       const CXXScopeSpec &SS,
4155                                       TypeSourceInfo *ScopeType,
4156                                       SourceLocation CCLoc,
4157                                       SourceLocation TildeLoc,
4158                                     PseudoDestructorTypeStorage DestroyedType,
4159                                       bool HasTrailingLParen);
4160
4161  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4162                                       SourceLocation OpLoc,
4163                                       tok::TokenKind OpKind,
4164                                       CXXScopeSpec &SS,
4165                                       UnqualifiedId &FirstTypeName,
4166                                       SourceLocation CCLoc,
4167                                       SourceLocation TildeLoc,
4168                                       UnqualifiedId &SecondTypeName,
4169                                       bool HasTrailingLParen);
4170
4171  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4172                                       SourceLocation OpLoc,
4173                                       tok::TokenKind OpKind,
4174                                       SourceLocation TildeLoc,
4175                                       const DeclSpec& DS,
4176                                       bool HasTrailingLParen);
4177
4178  /// MaybeCreateExprWithCleanups - If the current full-expression
4179  /// requires any cleanups, surround it with a ExprWithCleanups node.
4180  /// Otherwise, just returns the passed-in expression.
4181  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4182  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4183  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4184
4185  ExprResult ActOnFinishFullExpr(Expr *Expr) {
4186    return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4187                                          : SourceLocation());
4188  }
4189  ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4190                                 bool DiscardedValue = false,
4191                                 bool IsConstexpr = false);
4192  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4193
4194  // Marks SS invalid if it represents an incomplete type.
4195  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4196
4197  DeclContext *computeDeclContext(QualType T);
4198  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4199                                  bool EnteringContext = false);
4200  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4201  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4202
4203  /// \brief The parser has parsed a global nested-name-specifier '::'.
4204  ///
4205  /// \param S The scope in which this nested-name-specifier occurs.
4206  ///
4207  /// \param CCLoc The location of the '::'.
4208  ///
4209  /// \param SS The nested-name-specifier, which will be updated in-place
4210  /// to reflect the parsed nested-name-specifier.
4211  ///
4212  /// \returns true if an error occurred, false otherwise.
4213  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
4214                                    CXXScopeSpec &SS);
4215
4216  bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
4217  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4218
4219  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4220                                    SourceLocation IdLoc,
4221                                    IdentifierInfo &II,
4222                                    ParsedType ObjectType);
4223
4224  bool BuildCXXNestedNameSpecifier(Scope *S,
4225                                   IdentifierInfo &Identifier,
4226                                   SourceLocation IdentifierLoc,
4227                                   SourceLocation CCLoc,
4228                                   QualType ObjectType,
4229                                   bool EnteringContext,
4230                                   CXXScopeSpec &SS,
4231                                   NamedDecl *ScopeLookupResult,
4232                                   bool ErrorRecoveryLookup);
4233
4234  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4235  ///
4236  /// \param S The scope in which this nested-name-specifier occurs.
4237  ///
4238  /// \param Identifier The identifier preceding the '::'.
4239  ///
4240  /// \param IdentifierLoc The location of the identifier.
4241  ///
4242  /// \param CCLoc The location of the '::'.
4243  ///
4244  /// \param ObjectType The type of the object, if we're parsing
4245  /// nested-name-specifier in a member access expression.
4246  ///
4247  /// \param EnteringContext Whether we're entering the context nominated by
4248  /// this nested-name-specifier.
4249  ///
4250  /// \param SS The nested-name-specifier, which is both an input
4251  /// parameter (the nested-name-specifier before this type) and an
4252  /// output parameter (containing the full nested-name-specifier,
4253  /// including this new type).
4254  ///
4255  /// \returns true if an error occurred, false otherwise.
4256  bool ActOnCXXNestedNameSpecifier(Scope *S,
4257                                   IdentifierInfo &Identifier,
4258                                   SourceLocation IdentifierLoc,
4259                                   SourceLocation CCLoc,
4260                                   ParsedType ObjectType,
4261                                   bool EnteringContext,
4262                                   CXXScopeSpec &SS);
4263
4264  ExprResult ActOnDecltypeExpression(Expr *E);
4265
4266  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4267                                           const DeclSpec &DS,
4268                                           SourceLocation ColonColonLoc);
4269
4270  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4271                                 IdentifierInfo &Identifier,
4272                                 SourceLocation IdentifierLoc,
4273                                 SourceLocation ColonLoc,
4274                                 ParsedType ObjectType,
4275                                 bool EnteringContext);
4276
4277  /// \brief The parser has parsed a nested-name-specifier
4278  /// 'template[opt] template-name < template-args >::'.
4279  ///
4280  /// \param S The scope in which this nested-name-specifier occurs.
4281  ///
4282  /// \param SS The nested-name-specifier, which is both an input
4283  /// parameter (the nested-name-specifier before this type) and an
4284  /// output parameter (containing the full nested-name-specifier,
4285  /// including this new type).
4286  ///
4287  /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4288  /// \param TemplateName the template name.
4289  /// \param TemplateNameLoc The location of the template name.
4290  /// \param LAngleLoc The location of the opening angle bracket  ('<').
4291  /// \param TemplateArgs The template arguments.
4292  /// \param RAngleLoc The location of the closing angle bracket  ('>').
4293  /// \param CCLoc The location of the '::'.
4294  ///
4295  /// \param EnteringContext Whether we're entering the context of the
4296  /// nested-name-specifier.
4297  ///
4298  ///
4299  /// \returns true if an error occurred, false otherwise.
4300  bool ActOnCXXNestedNameSpecifier(Scope *S,
4301                                   CXXScopeSpec &SS,
4302                                   SourceLocation TemplateKWLoc,
4303                                   TemplateTy TemplateName,
4304                                   SourceLocation TemplateNameLoc,
4305                                   SourceLocation LAngleLoc,
4306                                   ASTTemplateArgsPtr TemplateArgs,
4307                                   SourceLocation RAngleLoc,
4308                                   SourceLocation CCLoc,
4309                                   bool EnteringContext);
4310
4311  /// \brief Given a C++ nested-name-specifier, produce an annotation value
4312  /// that the parser can use later to reconstruct the given
4313  /// nested-name-specifier.
4314  ///
4315  /// \param SS A nested-name-specifier.
4316  ///
4317  /// \returns A pointer containing all of the information in the
4318  /// nested-name-specifier \p SS.
4319  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4320
4321  /// \brief Given an annotation pointer for a nested-name-specifier, restore
4322  /// the nested-name-specifier structure.
4323  ///
4324  /// \param Annotation The annotation pointer, produced by
4325  /// \c SaveNestedNameSpecifierAnnotation().
4326  ///
4327  /// \param AnnotationRange The source range corresponding to the annotation.
4328  ///
4329  /// \param SS The nested-name-specifier that will be updated with the contents
4330  /// of the annotation pointer.
4331  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4332                                            SourceRange AnnotationRange,
4333                                            CXXScopeSpec &SS);
4334
4335  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4336
4337  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4338  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4339  /// After this method is called, according to [C++ 3.4.3p3], names should be
4340  /// looked up in the declarator-id's scope, until the declarator is parsed and
4341  /// ActOnCXXExitDeclaratorScope is called.
4342  /// The 'SS' should be a non-empty valid CXXScopeSpec.
4343  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4344
4345  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4346  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4347  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4348  /// Used to indicate that names should revert to being looked up in the
4349  /// defining scope.
4350  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4351
4352  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4353  /// initializer for the declaration 'Dcl'.
4354  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4355  /// static data member of class X, names should be looked up in the scope of
4356  /// class X.
4357  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4358
4359  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4360  /// initializer for the declaration 'Dcl'.
4361  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4362
4363  /// \brief Create a new lambda closure type.
4364  CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4365                                         TypeSourceInfo *Info,
4366                                         bool KnownDependent);
4367
4368  /// \brief Start the definition of a lambda expression.
4369  CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4370                                       SourceRange IntroducerRange,
4371                                       TypeSourceInfo *MethodType,
4372                                       SourceLocation EndLoc,
4373                                       ArrayRef<ParmVarDecl *> Params);
4374
4375  /// \brief Introduce the scope for a lambda expression.
4376  sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator,
4377                                          SourceRange IntroducerRange,
4378                                          LambdaCaptureDefault CaptureDefault,
4379                                          bool ExplicitParams,
4380                                          bool ExplicitResultType,
4381                                          bool Mutable);
4382
4383  /// \brief Check and build an init-capture with the specified name and
4384  /// initializer.
4385  FieldDecl *checkInitCapture(SourceLocation Loc, bool ByRef,
4386                              IdentifierInfo *Id, Expr *Init);
4387
4388  /// \brief Note that we have finished the explicit captures for the
4389  /// given lambda.
4390  void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4391
4392  /// \brief Introduce the lambda parameters into scope.
4393  void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4394
4395  /// \brief Deduce a block or lambda's return type based on the return
4396  /// statements present in the body.
4397  void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4398
4399  /// ActOnStartOfLambdaDefinition - This is called just before we start
4400  /// parsing the body of a lambda; it analyzes the explicit captures and
4401  /// arguments, and sets up various data-structures for the body of the
4402  /// lambda.
4403  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4404                                    Declarator &ParamInfo, Scope *CurScope);
4405
4406  /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4407  /// is invoked to pop the information about the lambda.
4408  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4409                        bool IsInstantiation = false);
4410
4411  /// ActOnLambdaExpr - This is called when the body of a lambda expression
4412  /// was successfully completed.
4413  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4414                             Scope *CurScope,
4415                             bool IsInstantiation = false);
4416
4417  /// \brief Define the "body" of the conversion from a lambda object to a
4418  /// function pointer.
4419  ///
4420  /// This routine doesn't actually define a sensible body; rather, it fills
4421  /// in the initialization expression needed to copy the lambda object into
4422  /// the block, and IR generation actually generates the real body of the
4423  /// block pointer conversion.
4424  void DefineImplicitLambdaToFunctionPointerConversion(
4425         SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4426
4427  /// \brief Define the "body" of the conversion from a lambda object to a
4428  /// block pointer.
4429  ///
4430  /// This routine doesn't actually define a sensible body; rather, it fills
4431  /// in the initialization expression needed to copy the lambda object into
4432  /// the block, and IR generation actually generates the real body of the
4433  /// block pointer conversion.
4434  void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4435                                                    CXXConversionDecl *Conv);
4436
4437  ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4438                                           SourceLocation ConvLocation,
4439                                           CXXConversionDecl *Conv,
4440                                           Expr *Src);
4441
4442  // ParseObjCStringLiteral - Parse Objective-C string literals.
4443  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4444                                    Expr **Strings,
4445                                    unsigned NumStrings);
4446
4447  ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4448
4449  /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4450  /// numeric literal expression. Type of the expression will be "NSNumber *"
4451  /// or "id" if NSNumber is unavailable.
4452  ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4453  ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4454                                  bool Value);
4455  ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4456
4457  /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4458  /// '@' prefixed parenthesized expression. The type of the expression will
4459  /// either be "NSNumber *" or "NSString *" depending on the type of
4460  /// ValueType, which is allowed to be a built-in numeric type or
4461  /// "char *" or "const char *".
4462  ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4463
4464  ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4465                                          Expr *IndexExpr,
4466                                          ObjCMethodDecl *getterMethod,
4467                                          ObjCMethodDecl *setterMethod);
4468
4469  ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4470                                        ObjCDictionaryElement *Elements,
4471                                        unsigned NumElements);
4472
4473  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4474                                  TypeSourceInfo *EncodedTypeInfo,
4475                                  SourceLocation RParenLoc);
4476  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4477                                    CXXConversionDecl *Method,
4478                                    bool HadMultipleCandidates);
4479
4480  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4481                                       SourceLocation EncodeLoc,
4482                                       SourceLocation LParenLoc,
4483                                       ParsedType Ty,
4484                                       SourceLocation RParenLoc);
4485
4486  /// ParseObjCSelectorExpression - Build selector expression for \@selector
4487  ExprResult ParseObjCSelectorExpression(Selector Sel,
4488                                         SourceLocation AtLoc,
4489                                         SourceLocation SelLoc,
4490                                         SourceLocation LParenLoc,
4491                                         SourceLocation RParenLoc);
4492
4493  /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4494  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4495                                         SourceLocation AtLoc,
4496                                         SourceLocation ProtoLoc,
4497                                         SourceLocation LParenLoc,
4498                                         SourceLocation ProtoIdLoc,
4499                                         SourceLocation RParenLoc);
4500
4501  //===--------------------------------------------------------------------===//
4502  // C++ Declarations
4503  //
4504  Decl *ActOnStartLinkageSpecification(Scope *S,
4505                                       SourceLocation ExternLoc,
4506                                       SourceLocation LangLoc,
4507                                       StringRef Lang,
4508                                       SourceLocation LBraceLoc);
4509  Decl *ActOnFinishLinkageSpecification(Scope *S,
4510                                        Decl *LinkageSpec,
4511                                        SourceLocation RBraceLoc);
4512
4513
4514  //===--------------------------------------------------------------------===//
4515  // C++ Classes
4516  //
4517  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4518                          const CXXScopeSpec *SS = 0);
4519
4520  bool ActOnAccessSpecifier(AccessSpecifier Access,
4521                            SourceLocation ASLoc,
4522                            SourceLocation ColonLoc,
4523                            AttributeList *Attrs = 0);
4524
4525  NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4526                                 Declarator &D,
4527                                 MultiTemplateParamsArg TemplateParameterLists,
4528                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4529                                 InClassInitStyle InitStyle);
4530  void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
4531                                        Expr *Init);
4532
4533  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4534                                    Scope *S,
4535                                    CXXScopeSpec &SS,
4536                                    IdentifierInfo *MemberOrBase,
4537                                    ParsedType TemplateTypeTy,
4538                                    const DeclSpec &DS,
4539                                    SourceLocation IdLoc,
4540                                    SourceLocation LParenLoc,
4541                                    ArrayRef<Expr *> Args,
4542                                    SourceLocation RParenLoc,
4543                                    SourceLocation EllipsisLoc);
4544
4545  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4546                                    Scope *S,
4547                                    CXXScopeSpec &SS,
4548                                    IdentifierInfo *MemberOrBase,
4549                                    ParsedType TemplateTypeTy,
4550                                    const DeclSpec &DS,
4551                                    SourceLocation IdLoc,
4552                                    Expr *InitList,
4553                                    SourceLocation EllipsisLoc);
4554
4555  MemInitResult BuildMemInitializer(Decl *ConstructorD,
4556                                    Scope *S,
4557                                    CXXScopeSpec &SS,
4558                                    IdentifierInfo *MemberOrBase,
4559                                    ParsedType TemplateTypeTy,
4560                                    const DeclSpec &DS,
4561                                    SourceLocation IdLoc,
4562                                    Expr *Init,
4563                                    SourceLocation EllipsisLoc);
4564
4565  MemInitResult BuildMemberInitializer(ValueDecl *Member,
4566                                       Expr *Init,
4567                                       SourceLocation IdLoc);
4568
4569  MemInitResult BuildBaseInitializer(QualType BaseType,
4570                                     TypeSourceInfo *BaseTInfo,
4571                                     Expr *Init,
4572                                     CXXRecordDecl *ClassDecl,
4573                                     SourceLocation EllipsisLoc);
4574
4575  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
4576                                           Expr *Init,
4577                                           CXXRecordDecl *ClassDecl);
4578
4579  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4580                                CXXCtorInitializer *Initializer);
4581
4582  bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4583                           ArrayRef<CXXCtorInitializer *> Initializers = None);
4584
4585  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
4586
4587
4588  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4589  /// mark all the non-trivial destructors of its members and bases as
4590  /// referenced.
4591  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
4592                                              CXXRecordDecl *Record);
4593
4594  /// \brief The list of classes whose vtables have been used within
4595  /// this translation unit, and the source locations at which the
4596  /// first use occurred.
4597  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
4598
4599  /// \brief The list of vtables that are required but have not yet been
4600  /// materialized.
4601  SmallVector<VTableUse, 16> VTableUses;
4602
4603  /// \brief The set of classes whose vtables have been used within
4604  /// this translation unit, and a bit that will be true if the vtable is
4605  /// required to be emitted (otherwise, it should be emitted only if needed
4606  /// by code generation).
4607  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4608
4609  /// \brief Load any externally-stored vtable uses.
4610  void LoadExternalVTableUses();
4611
4612  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
4613                     &ExternalSemaSource::ReadDynamicClasses, 2, 2>
4614    DynamicClassesType;
4615
4616  /// \brief A list of all of the dynamic classes in this translation
4617  /// unit.
4618  DynamicClassesType DynamicClasses;
4619
4620  /// \brief Note that the vtable for the given class was used at the
4621  /// given location.
4622  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
4623                      bool DefinitionRequired = false);
4624
4625  /// \brief Mark the exception specifications of all virtual member functions
4626  /// in the given class as needed.
4627  void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
4628                                             const CXXRecordDecl *RD);
4629
4630  /// MarkVirtualMembersReferenced - Will mark all members of the given
4631  /// CXXRecordDecl referenced.
4632  void MarkVirtualMembersReferenced(SourceLocation Loc,
4633                                    const CXXRecordDecl *RD);
4634
4635  /// \brief Define all of the vtables that have been used in this
4636  /// translation unit and reference any virtual members used by those
4637  /// vtables.
4638  ///
4639  /// \returns true if any work was done, false otherwise.
4640  bool DefineUsedVTables();
4641
4642  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
4643
4644  void ActOnMemInitializers(Decl *ConstructorDecl,
4645                            SourceLocation ColonLoc,
4646                            ArrayRef<CXXCtorInitializer*> MemInits,
4647                            bool AnyErrors);
4648
4649  void CheckCompletedCXXClass(CXXRecordDecl *Record);
4650  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4651                                         Decl *TagDecl,
4652                                         SourceLocation LBrac,
4653                                         SourceLocation RBrac,
4654                                         AttributeList *AttrList);
4655  void ActOnFinishCXXMemberDecls();
4656
4657  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
4658  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
4659  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
4660  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4661  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4662  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
4663  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4664  void ActOnFinishDelayedMemberInitializers(Decl *Record);
4665  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
4666  bool IsInsideALocalClassWithinATemplateFunction();
4667
4668  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4669                                     Expr *AssertExpr,
4670                                     Expr *AssertMessageExpr,
4671                                     SourceLocation RParenLoc);
4672  Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4673                                     Expr *AssertExpr,
4674                                     StringLiteral *AssertMessageExpr,
4675                                     SourceLocation RParenLoc,
4676                                     bool Failed);
4677
4678  FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
4679                                  SourceLocation FriendLoc,
4680                                  TypeSourceInfo *TSInfo);
4681  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4682                            MultiTemplateParamsArg TemplateParams);
4683  NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
4684                                     MultiTemplateParamsArg TemplateParams);
4685
4686  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
4687                                      StorageClass& SC);
4688  void CheckConstructor(CXXConstructorDecl *Constructor);
4689  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
4690                                     StorageClass& SC);
4691  bool CheckDestructor(CXXDestructorDecl *Destructor);
4692  void CheckConversionDeclarator(Declarator &D, QualType &R,
4693                                 StorageClass& SC);
4694  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4695
4696  void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
4697  void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
4698                                                   const FunctionProtoType *T);
4699  void CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
4700
4701  //===--------------------------------------------------------------------===//
4702  // C++ Derived Classes
4703  //
4704
4705  /// ActOnBaseSpecifier - Parsed a base specifier
4706  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4707                                       SourceRange SpecifierRange,
4708                                       bool Virtual, AccessSpecifier Access,
4709                                       TypeSourceInfo *TInfo,
4710                                       SourceLocation EllipsisLoc);
4711
4712  BaseResult ActOnBaseSpecifier(Decl *classdecl,
4713                                SourceRange SpecifierRange,
4714                                ParsedAttributes &Attrs,
4715                                bool Virtual, AccessSpecifier Access,
4716                                ParsedType basetype,
4717                                SourceLocation BaseLoc,
4718                                SourceLocation EllipsisLoc);
4719
4720  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4721                            unsigned NumBases);
4722  void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4723                           unsigned NumBases);
4724
4725  bool IsDerivedFrom(QualType Derived, QualType Base);
4726  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4727
4728  // FIXME: I don't like this name.
4729  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
4730
4731  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
4732
4733  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4734                                    SourceLocation Loc, SourceRange Range,
4735                                    CXXCastPath *BasePath = 0,
4736                                    bool IgnoreAccess = false);
4737  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4738                                    unsigned InaccessibleBaseID,
4739                                    unsigned AmbigiousBaseConvID,
4740                                    SourceLocation Loc, SourceRange Range,
4741                                    DeclarationName Name,
4742                                    CXXCastPath *BasePath);
4743
4744  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
4745
4746  bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4747                                         const CXXMethodDecl *Old);
4748
4749  /// CheckOverridingFunctionReturnType - Checks whether the return types are
4750  /// covariant, according to C++ [class.virtual]p5.
4751  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4752                                         const CXXMethodDecl *Old);
4753
4754  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
4755  /// spec is a subset of base spec.
4756  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4757                                            const CXXMethodDecl *Old);
4758
4759  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
4760
4761  /// CheckOverrideControl - Check C++11 override control semantics.
4762  void CheckOverrideControl(Decl *D);
4763
4764  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
4765  /// overrides a virtual member function marked 'final', according to
4766  /// C++11 [class.virtual]p4.
4767  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
4768                                              const CXXMethodDecl *Old);
4769
4770
4771  //===--------------------------------------------------------------------===//
4772  // C++ Access Control
4773  //
4774
4775  enum AccessResult {
4776    AR_accessible,
4777    AR_inaccessible,
4778    AR_dependent,
4779    AR_delayed
4780  };
4781
4782  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
4783                                NamedDecl *PrevMemberDecl,
4784                                AccessSpecifier LexicalAS);
4785
4786  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
4787                                           DeclAccessPair FoundDecl);
4788  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
4789                                           DeclAccessPair FoundDecl);
4790  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
4791                                     SourceRange PlacementRange,
4792                                     CXXRecordDecl *NamingClass,
4793                                     DeclAccessPair FoundDecl,
4794                                     bool Diagnose = true);
4795  AccessResult CheckConstructorAccess(SourceLocation Loc,
4796                                      CXXConstructorDecl *D,
4797                                      const InitializedEntity &Entity,
4798                                      AccessSpecifier Access,
4799                                      bool IsCopyBindingRefToTemp = false);
4800  AccessResult CheckConstructorAccess(SourceLocation Loc,
4801                                      CXXConstructorDecl *D,
4802                                      const InitializedEntity &Entity,
4803                                      AccessSpecifier Access,
4804                                      const PartialDiagnostic &PDiag);
4805  AccessResult CheckDestructorAccess(SourceLocation Loc,
4806                                     CXXDestructorDecl *Dtor,
4807                                     const PartialDiagnostic &PDiag,
4808                                     QualType objectType = QualType());
4809  AccessResult CheckFriendAccess(NamedDecl *D);
4810  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
4811                                         Expr *ObjectExpr,
4812                                         Expr *ArgExpr,
4813                                         DeclAccessPair FoundDecl);
4814  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
4815                                          DeclAccessPair FoundDecl);
4816  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
4817                                    QualType Base, QualType Derived,
4818                                    const CXXBasePath &Path,
4819                                    unsigned DiagID,
4820                                    bool ForceCheck = false,
4821                                    bool ForceUnprivileged = false);
4822  void CheckLookupAccess(const LookupResult &R);
4823  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
4824  bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
4825                                            AccessSpecifier access,
4826                                            QualType objectType);
4827
4828  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
4829                         const MultiLevelTemplateArgumentList &TemplateArgs);
4830  void PerformDependentDiagnostics(const DeclContext *Pattern,
4831                        const MultiLevelTemplateArgumentList &TemplateArgs);
4832
4833  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4834
4835  /// \brief When true, access checking violations are treated as SFINAE
4836  /// failures rather than hard errors.
4837  bool AccessCheckingSFINAE;
4838
4839  enum AbstractDiagSelID {
4840    AbstractNone = -1,
4841    AbstractReturnType,
4842    AbstractParamType,
4843    AbstractVariableType,
4844    AbstractFieldType,
4845    AbstractIvarType,
4846    AbstractSynthesizedIvarType,
4847    AbstractArrayType
4848  };
4849
4850  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4851                              TypeDiagnoser &Diagnoser);
4852  template<typename T1>
4853  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4854                              unsigned DiagID,
4855                              const T1 &Arg1) {
4856    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
4857    return RequireNonAbstractType(Loc, T, Diagnoser);
4858  }
4859
4860  template<typename T1, typename T2>
4861  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4862                              unsigned DiagID,
4863                              const T1 &Arg1, const T2 &Arg2) {
4864    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
4865    return RequireNonAbstractType(Loc, T, Diagnoser);
4866  }
4867
4868  template<typename T1, typename T2, typename T3>
4869  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4870                              unsigned DiagID,
4871                              const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
4872    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
4873    return RequireNonAbstractType(Loc, T, Diagnoser);
4874  }
4875
4876  void DiagnoseAbstractType(const CXXRecordDecl *RD);
4877
4878  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
4879                              AbstractDiagSelID SelID = AbstractNone);
4880
4881  //===--------------------------------------------------------------------===//
4882  // C++ Overloaded Operators [C++ 13.5]
4883  //
4884
4885  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
4886
4887  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
4888
4889  //===--------------------------------------------------------------------===//
4890  // C++ Templates [C++ 14]
4891  //
4892  void FilterAcceptableTemplateNames(LookupResult &R,
4893                                     bool AllowFunctionTemplates = true);
4894  bool hasAnyAcceptableTemplateNames(LookupResult &R,
4895                                     bool AllowFunctionTemplates = true);
4896
4897  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
4898                          QualType ObjectType, bool EnteringContext,
4899                          bool &MemberOfUnknownSpecialization);
4900
4901  TemplateNameKind isTemplateName(Scope *S,
4902                                  CXXScopeSpec &SS,
4903                                  bool hasTemplateKeyword,
4904                                  UnqualifiedId &Name,
4905                                  ParsedType ObjectType,
4906                                  bool EnteringContext,
4907                                  TemplateTy &Template,
4908                                  bool &MemberOfUnknownSpecialization);
4909
4910  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
4911                                   SourceLocation IILoc,
4912                                   Scope *S,
4913                                   const CXXScopeSpec *SS,
4914                                   TemplateTy &SuggestedTemplate,
4915                                   TemplateNameKind &SuggestedKind);
4916
4917  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
4918  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
4919
4920  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
4921                           SourceLocation EllipsisLoc,
4922                           SourceLocation KeyLoc,
4923                           IdentifierInfo *ParamName,
4924                           SourceLocation ParamNameLoc,
4925                           unsigned Depth, unsigned Position,
4926                           SourceLocation EqualLoc,
4927                           ParsedType DefaultArg);
4928
4929  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
4930  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
4931                                      unsigned Depth,
4932                                      unsigned Position,
4933                                      SourceLocation EqualLoc,
4934                                      Expr *DefaultArg);
4935  Decl *ActOnTemplateTemplateParameter(Scope *S,
4936                                       SourceLocation TmpLoc,
4937                                       TemplateParameterList *Params,
4938                                       SourceLocation EllipsisLoc,
4939                                       IdentifierInfo *ParamName,
4940                                       SourceLocation ParamNameLoc,
4941                                       unsigned Depth,
4942                                       unsigned Position,
4943                                       SourceLocation EqualLoc,
4944                                       ParsedTemplateArgument DefaultArg);
4945
4946  TemplateParameterList *
4947  ActOnTemplateParameterList(unsigned Depth,
4948                             SourceLocation ExportLoc,
4949                             SourceLocation TemplateLoc,
4950                             SourceLocation LAngleLoc,
4951                             Decl **Params, unsigned NumParams,
4952                             SourceLocation RAngleLoc);
4953
4954  /// \brief The context in which we are checking a template parameter list.
4955  enum TemplateParamListContext {
4956    TPC_ClassTemplate,
4957    TPC_FunctionTemplate,
4958    TPC_ClassTemplateMember,
4959    TPC_FriendClassTemplate,
4960    TPC_FriendFunctionTemplate,
4961    TPC_FriendFunctionTemplateDefinition,
4962    TPC_TypeAliasTemplate
4963  };
4964
4965  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
4966                                  TemplateParameterList *OldParams,
4967                                  TemplateParamListContext TPC);
4968  TemplateParameterList *
4969  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
4970                                          SourceLocation DeclLoc,
4971                                          const CXXScopeSpec &SS,
4972                                          TemplateParameterList **ParamLists,
4973                                          unsigned NumParamLists,
4974                                          bool IsFriend,
4975                                          bool &IsExplicitSpecialization,
4976                                          bool &Invalid);
4977
4978  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
4979                                SourceLocation KWLoc, CXXScopeSpec &SS,
4980                                IdentifierInfo *Name, SourceLocation NameLoc,
4981                                AttributeList *Attr,
4982                                TemplateParameterList *TemplateParams,
4983                                AccessSpecifier AS,
4984                                SourceLocation ModulePrivateLoc,
4985                                unsigned NumOuterTemplateParamLists,
4986                            TemplateParameterList **OuterTemplateParamLists);
4987
4988  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
4989                                  TemplateArgumentListInfo &Out);
4990
4991  void NoteAllFoundTemplates(TemplateName Name);
4992
4993  QualType CheckTemplateIdType(TemplateName Template,
4994                               SourceLocation TemplateLoc,
4995                              TemplateArgumentListInfo &TemplateArgs);
4996
4997  TypeResult
4998  ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4999                      TemplateTy Template, SourceLocation TemplateLoc,
5000                      SourceLocation LAngleLoc,
5001                      ASTTemplateArgsPtr TemplateArgs,
5002                      SourceLocation RAngleLoc,
5003                      bool IsCtorOrDtorName = false);
5004
5005  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5006  /// such as \c class T::template apply<U>.
5007  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5008                                    TypeSpecifierType TagSpec,
5009                                    SourceLocation TagLoc,
5010                                    CXXScopeSpec &SS,
5011                                    SourceLocation TemplateKWLoc,
5012                                    TemplateTy TemplateD,
5013                                    SourceLocation TemplateLoc,
5014                                    SourceLocation LAngleLoc,
5015                                    ASTTemplateArgsPtr TemplateArgsIn,
5016                                    SourceLocation RAngleLoc);
5017
5018
5019  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5020                                 SourceLocation TemplateKWLoc,
5021                                 LookupResult &R,
5022                                 bool RequiresADL,
5023                               const TemplateArgumentListInfo *TemplateArgs);
5024
5025  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5026                                          SourceLocation TemplateKWLoc,
5027                               const DeclarationNameInfo &NameInfo,
5028                               const TemplateArgumentListInfo *TemplateArgs);
5029
5030  TemplateNameKind ActOnDependentTemplateName(Scope *S,
5031                                              CXXScopeSpec &SS,
5032                                              SourceLocation TemplateKWLoc,
5033                                              UnqualifiedId &Name,
5034                                              ParsedType ObjectType,
5035                                              bool EnteringContext,
5036                                              TemplateTy &Template);
5037
5038  DeclResult
5039  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5040                                   SourceLocation KWLoc,
5041                                   SourceLocation ModulePrivateLoc,
5042                                   CXXScopeSpec &SS,
5043                                   TemplateTy Template,
5044                                   SourceLocation TemplateNameLoc,
5045                                   SourceLocation LAngleLoc,
5046                                   ASTTemplateArgsPtr TemplateArgs,
5047                                   SourceLocation RAngleLoc,
5048                                   AttributeList *Attr,
5049                                 MultiTemplateParamsArg TemplateParameterLists);
5050
5051  Decl *ActOnTemplateDeclarator(Scope *S,
5052                                MultiTemplateParamsArg TemplateParameterLists,
5053                                Declarator &D);
5054
5055  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5056                                  MultiTemplateParamsArg TemplateParameterLists,
5057                                        Declarator &D);
5058
5059  bool
5060  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5061                                         TemplateSpecializationKind NewTSK,
5062                                         NamedDecl *PrevDecl,
5063                                         TemplateSpecializationKind PrevTSK,
5064                                         SourceLocation PrevPtOfInstantiation,
5065                                         bool &SuppressNew);
5066
5067  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5068                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
5069                                                    LookupResult &Previous);
5070
5071  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5072                         TemplateArgumentListInfo *ExplicitTemplateArgs,
5073                                           LookupResult &Previous);
5074  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5075
5076  DeclResult
5077  ActOnExplicitInstantiation(Scope *S,
5078                             SourceLocation ExternLoc,
5079                             SourceLocation TemplateLoc,
5080                             unsigned TagSpec,
5081                             SourceLocation KWLoc,
5082                             const CXXScopeSpec &SS,
5083                             TemplateTy Template,
5084                             SourceLocation TemplateNameLoc,
5085                             SourceLocation LAngleLoc,
5086                             ASTTemplateArgsPtr TemplateArgs,
5087                             SourceLocation RAngleLoc,
5088                             AttributeList *Attr);
5089
5090  DeclResult
5091  ActOnExplicitInstantiation(Scope *S,
5092                             SourceLocation ExternLoc,
5093                             SourceLocation TemplateLoc,
5094                             unsigned TagSpec,
5095                             SourceLocation KWLoc,
5096                             CXXScopeSpec &SS,
5097                             IdentifierInfo *Name,
5098                             SourceLocation NameLoc,
5099                             AttributeList *Attr);
5100
5101  DeclResult ActOnExplicitInstantiation(Scope *S,
5102                                        SourceLocation ExternLoc,
5103                                        SourceLocation TemplateLoc,
5104                                        Declarator &D);
5105
5106  TemplateArgumentLoc
5107  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5108                                          SourceLocation TemplateLoc,
5109                                          SourceLocation RAngleLoc,
5110                                          Decl *Param,
5111                                          SmallVectorImpl<TemplateArgument>
5112                                            &Converted,
5113                                          bool &HasDefaultArg);
5114
5115  /// \brief Specifies the context in which a particular template
5116  /// argument is being checked.
5117  enum CheckTemplateArgumentKind {
5118    /// \brief The template argument was specified in the code or was
5119    /// instantiated with some deduced template arguments.
5120    CTAK_Specified,
5121
5122    /// \brief The template argument was deduced via template argument
5123    /// deduction.
5124    CTAK_Deduced,
5125
5126    /// \brief The template argument was deduced from an array bound
5127    /// via template argument deduction.
5128    CTAK_DeducedFromArrayBound
5129  };
5130
5131  bool CheckTemplateArgument(NamedDecl *Param,
5132                             const TemplateArgumentLoc &Arg,
5133                             NamedDecl *Template,
5134                             SourceLocation TemplateLoc,
5135                             SourceLocation RAngleLoc,
5136                             unsigned ArgumentPackIndex,
5137                           SmallVectorImpl<TemplateArgument> &Converted,
5138                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
5139
5140  /// \brief Check that the given template arguments can be be provided to
5141  /// the given template, converting the arguments along the way.
5142  ///
5143  /// \param Template The template to which the template arguments are being
5144  /// provided.
5145  ///
5146  /// \param TemplateLoc The location of the template name in the source.
5147  ///
5148  /// \param TemplateArgs The list of template arguments. If the template is
5149  /// a template template parameter, this function may extend the set of
5150  /// template arguments to also include substituted, defaulted template
5151  /// arguments.
5152  ///
5153  /// \param PartialTemplateArgs True if the list of template arguments is
5154  /// intentionally partial, e.g., because we're checking just the initial
5155  /// set of template arguments.
5156  ///
5157  /// \param Converted Will receive the converted, canonicalized template
5158  /// arguments.
5159  ///
5160  ///
5161  /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate
5162  /// when the template arguments contain a pack expansion that is being
5163  /// expanded into a fixed parameter list.
5164  ///
5165  /// \returns True if an error occurred, false otherwise.
5166  bool CheckTemplateArgumentList(TemplateDecl *Template,
5167                                 SourceLocation TemplateLoc,
5168                                 TemplateArgumentListInfo &TemplateArgs,
5169                                 bool PartialTemplateArgs,
5170                           SmallVectorImpl<TemplateArgument> &Converted,
5171                                 bool *ExpansionIntoFixedList = 0);
5172
5173  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5174                                 const TemplateArgumentLoc &Arg,
5175                           SmallVectorImpl<TemplateArgument> &Converted);
5176
5177  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5178                             TypeSourceInfo *Arg);
5179  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5180                                   QualType InstantiatedParamType, Expr *Arg,
5181                                   TemplateArgument &Converted,
5182                               CheckTemplateArgumentKind CTAK = CTAK_Specified);
5183  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5184                             const TemplateArgumentLoc &Arg,
5185                             unsigned ArgumentPackIndex);
5186
5187  ExprResult
5188  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5189                                          QualType ParamType,
5190                                          SourceLocation Loc);
5191  ExprResult
5192  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5193                                              SourceLocation Loc);
5194
5195  /// \brief Enumeration describing how template parameter lists are compared
5196  /// for equality.
5197  enum TemplateParameterListEqualKind {
5198    /// \brief We are matching the template parameter lists of two templates
5199    /// that might be redeclarations.
5200    ///
5201    /// \code
5202    /// template<typename T> struct X;
5203    /// template<typename T> struct X;
5204    /// \endcode
5205    TPL_TemplateMatch,
5206
5207    /// \brief We are matching the template parameter lists of two template
5208    /// template parameters as part of matching the template parameter lists
5209    /// of two templates that might be redeclarations.
5210    ///
5211    /// \code
5212    /// template<template<int I> class TT> struct X;
5213    /// template<template<int Value> class Other> struct X;
5214    /// \endcode
5215    TPL_TemplateTemplateParmMatch,
5216
5217    /// \brief We are matching the template parameter lists of a template
5218    /// template argument against the template parameter lists of a template
5219    /// template parameter.
5220    ///
5221    /// \code
5222    /// template<template<int Value> class Metafun> struct X;
5223    /// template<int Value> struct integer_c;
5224    /// X<integer_c> xic;
5225    /// \endcode
5226    TPL_TemplateTemplateArgumentMatch
5227  };
5228
5229  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5230                                      TemplateParameterList *Old,
5231                                      bool Complain,
5232                                      TemplateParameterListEqualKind Kind,
5233                                      SourceLocation TemplateArgLoc
5234                                        = SourceLocation());
5235
5236  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5237
5238  /// \brief Called when the parser has parsed a C++ typename
5239  /// specifier, e.g., "typename T::type".
5240  ///
5241  /// \param S The scope in which this typename type occurs.
5242  /// \param TypenameLoc the location of the 'typename' keyword
5243  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5244  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5245  /// \param IdLoc the location of the identifier.
5246  TypeResult
5247  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5248                    const CXXScopeSpec &SS, const IdentifierInfo &II,
5249                    SourceLocation IdLoc);
5250
5251  /// \brief Called when the parser has parsed a C++ typename
5252  /// specifier that ends in a template-id, e.g.,
5253  /// "typename MetaFun::template apply<T1, T2>".
5254  ///
5255  /// \param S The scope in which this typename type occurs.
5256  /// \param TypenameLoc the location of the 'typename' keyword
5257  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5258  /// \param TemplateLoc the location of the 'template' keyword, if any.
5259  /// \param TemplateName The template name.
5260  /// \param TemplateNameLoc The location of the template name.
5261  /// \param LAngleLoc The location of the opening angle bracket  ('<').
5262  /// \param TemplateArgs The template arguments.
5263  /// \param RAngleLoc The location of the closing angle bracket  ('>').
5264  TypeResult
5265  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5266                    const CXXScopeSpec &SS,
5267                    SourceLocation TemplateLoc,
5268                    TemplateTy TemplateName,
5269                    SourceLocation TemplateNameLoc,
5270                    SourceLocation LAngleLoc,
5271                    ASTTemplateArgsPtr TemplateArgs,
5272                    SourceLocation RAngleLoc);
5273
5274  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5275                             SourceLocation KeywordLoc,
5276                             NestedNameSpecifierLoc QualifierLoc,
5277                             const IdentifierInfo &II,
5278                             SourceLocation IILoc);
5279
5280  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5281                                                    SourceLocation Loc,
5282                                                    DeclarationName Name);
5283  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5284
5285  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5286  bool RebuildTemplateParamsInCurrentInstantiation(
5287                                                TemplateParameterList *Params);
5288
5289  std::string
5290  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5291                                  const TemplateArgumentList &Args);
5292
5293  std::string
5294  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5295                                  const TemplateArgument *Args,
5296                                  unsigned NumArgs);
5297
5298  //===--------------------------------------------------------------------===//
5299  // C++ Variadic Templates (C++0x [temp.variadic])
5300  //===--------------------------------------------------------------------===//
5301
5302  /// \brief The context in which an unexpanded parameter pack is
5303  /// being diagnosed.
5304  ///
5305  /// Note that the values of this enumeration line up with the first
5306  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5307  enum UnexpandedParameterPackContext {
5308    /// \brief An arbitrary expression.
5309    UPPC_Expression = 0,
5310
5311    /// \brief The base type of a class type.
5312    UPPC_BaseType,
5313
5314    /// \brief The type of an arbitrary declaration.
5315    UPPC_DeclarationType,
5316
5317    /// \brief The type of a data member.
5318    UPPC_DataMemberType,
5319
5320    /// \brief The size of a bit-field.
5321    UPPC_BitFieldWidth,
5322
5323    /// \brief The expression in a static assertion.
5324    UPPC_StaticAssertExpression,
5325
5326    /// \brief The fixed underlying type of an enumeration.
5327    UPPC_FixedUnderlyingType,
5328
5329    /// \brief The enumerator value.
5330    UPPC_EnumeratorValue,
5331
5332    /// \brief A using declaration.
5333    UPPC_UsingDeclaration,
5334
5335    /// \brief A friend declaration.
5336    UPPC_FriendDeclaration,
5337
5338    /// \brief A declaration qualifier.
5339    UPPC_DeclarationQualifier,
5340
5341    /// \brief An initializer.
5342    UPPC_Initializer,
5343
5344    /// \brief A default argument.
5345    UPPC_DefaultArgument,
5346
5347    /// \brief The type of a non-type template parameter.
5348    UPPC_NonTypeTemplateParameterType,
5349
5350    /// \brief The type of an exception.
5351    UPPC_ExceptionType,
5352
5353    /// \brief Partial specialization.
5354    UPPC_PartialSpecialization,
5355
5356    /// \brief Microsoft __if_exists.
5357    UPPC_IfExists,
5358
5359    /// \brief Microsoft __if_not_exists.
5360    UPPC_IfNotExists,
5361
5362    /// \brief Lambda expression.
5363    UPPC_Lambda,
5364
5365    /// \brief Block expression,
5366    UPPC_Block
5367};
5368
5369  /// \brief Diagnose unexpanded parameter packs.
5370  ///
5371  /// \param Loc The location at which we should emit the diagnostic.
5372  ///
5373  /// \param UPPC The context in which we are diagnosing unexpanded
5374  /// parameter packs.
5375  ///
5376  /// \param Unexpanded the set of unexpanded parameter packs.
5377  ///
5378  /// \returns true if an error occurred, false otherwise.
5379  bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5380                                        UnexpandedParameterPackContext UPPC,
5381                                  ArrayRef<UnexpandedParameterPack> Unexpanded);
5382
5383  /// \brief If the given type contains an unexpanded parameter pack,
5384  /// diagnose the error.
5385  ///
5386  /// \param Loc The source location where a diagnostc should be emitted.
5387  ///
5388  /// \param T The type that is being checked for unexpanded parameter
5389  /// packs.
5390  ///
5391  /// \returns true if an error occurred, false otherwise.
5392  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5393                                       UnexpandedParameterPackContext UPPC);
5394
5395  /// \brief If the given expression contains an unexpanded parameter
5396  /// pack, diagnose the error.
5397  ///
5398  /// \param E The expression that is being checked for unexpanded
5399  /// parameter packs.
5400  ///
5401  /// \returns true if an error occurred, false otherwise.
5402  bool DiagnoseUnexpandedParameterPack(Expr *E,
5403                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
5404
5405  /// \brief If the given nested-name-specifier contains an unexpanded
5406  /// parameter pack, diagnose the error.
5407  ///
5408  /// \param SS The nested-name-specifier that is being checked for
5409  /// unexpanded parameter packs.
5410  ///
5411  /// \returns true if an error occurred, false otherwise.
5412  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5413                                       UnexpandedParameterPackContext UPPC);
5414
5415  /// \brief If the given name contains an unexpanded parameter pack,
5416  /// diagnose the error.
5417  ///
5418  /// \param NameInfo The name (with source location information) that
5419  /// is being checked for unexpanded parameter packs.
5420  ///
5421  /// \returns true if an error occurred, false otherwise.
5422  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5423                                       UnexpandedParameterPackContext UPPC);
5424
5425  /// \brief If the given template name contains an unexpanded parameter pack,
5426  /// diagnose the error.
5427  ///
5428  /// \param Loc The location of the template name.
5429  ///
5430  /// \param Template The template name that is being checked for unexpanded
5431  /// parameter packs.
5432  ///
5433  /// \returns true if an error occurred, false otherwise.
5434  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5435                                       TemplateName Template,
5436                                       UnexpandedParameterPackContext UPPC);
5437
5438  /// \brief If the given template argument contains an unexpanded parameter
5439  /// pack, diagnose the error.
5440  ///
5441  /// \param Arg The template argument that is being checked for unexpanded
5442  /// parameter packs.
5443  ///
5444  /// \returns true if an error occurred, false otherwise.
5445  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5446                                       UnexpandedParameterPackContext UPPC);
5447
5448  /// \brief Collect the set of unexpanded parameter packs within the given
5449  /// template argument.
5450  ///
5451  /// \param Arg The template argument that will be traversed to find
5452  /// unexpanded parameter packs.
5453  void collectUnexpandedParameterPacks(TemplateArgument Arg,
5454                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5455
5456  /// \brief Collect the set of unexpanded parameter packs within the given
5457  /// template argument.
5458  ///
5459  /// \param Arg The template argument that will be traversed to find
5460  /// unexpanded parameter packs.
5461  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5462                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5463
5464  /// \brief Collect the set of unexpanded parameter packs within the given
5465  /// type.
5466  ///
5467  /// \param T The type that will be traversed to find
5468  /// unexpanded parameter packs.
5469  void collectUnexpandedParameterPacks(QualType T,
5470                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5471
5472  /// \brief Collect the set of unexpanded parameter packs within the given
5473  /// type.
5474  ///
5475  /// \param TL The type that will be traversed to find
5476  /// unexpanded parameter packs.
5477  void collectUnexpandedParameterPacks(TypeLoc TL,
5478                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5479
5480  /// \brief Collect the set of unexpanded parameter packs within the given
5481  /// nested-name-specifier.
5482  ///
5483  /// \param SS The nested-name-specifier that will be traversed to find
5484  /// unexpanded parameter packs.
5485  void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5486                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5487
5488  /// \brief Collect the set of unexpanded parameter packs within the given
5489  /// name.
5490  ///
5491  /// \param NameInfo The name that will be traversed to find
5492  /// unexpanded parameter packs.
5493  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5494                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5495
5496  /// \brief Invoked when parsing a template argument followed by an
5497  /// ellipsis, which creates a pack expansion.
5498  ///
5499  /// \param Arg The template argument preceding the ellipsis, which
5500  /// may already be invalid.
5501  ///
5502  /// \param EllipsisLoc The location of the ellipsis.
5503  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5504                                            SourceLocation EllipsisLoc);
5505
5506  /// \brief Invoked when parsing a type followed by an ellipsis, which
5507  /// creates a pack expansion.
5508  ///
5509  /// \param Type The type preceding the ellipsis, which will become
5510  /// the pattern of the pack expansion.
5511  ///
5512  /// \param EllipsisLoc The location of the ellipsis.
5513  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5514
5515  /// \brief Construct a pack expansion type from the pattern of the pack
5516  /// expansion.
5517  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5518                                     SourceLocation EllipsisLoc,
5519                                     Optional<unsigned> NumExpansions);
5520
5521  /// \brief Construct a pack expansion type from the pattern of the pack
5522  /// expansion.
5523  QualType CheckPackExpansion(QualType Pattern,
5524                              SourceRange PatternRange,
5525                              SourceLocation EllipsisLoc,
5526                              Optional<unsigned> NumExpansions);
5527
5528  /// \brief Invoked when parsing an expression followed by an ellipsis, which
5529  /// creates a pack expansion.
5530  ///
5531  /// \param Pattern The expression preceding the ellipsis, which will become
5532  /// the pattern of the pack expansion.
5533  ///
5534  /// \param EllipsisLoc The location of the ellipsis.
5535  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5536
5537  /// \brief Invoked when parsing an expression followed by an ellipsis, which
5538  /// creates a pack expansion.
5539  ///
5540  /// \param Pattern The expression preceding the ellipsis, which will become
5541  /// the pattern of the pack expansion.
5542  ///
5543  /// \param EllipsisLoc The location of the ellipsis.
5544  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
5545                                Optional<unsigned> NumExpansions);
5546
5547  /// \brief Determine whether we could expand a pack expansion with the
5548  /// given set of parameter packs into separate arguments by repeatedly
5549  /// transforming the pattern.
5550  ///
5551  /// \param EllipsisLoc The location of the ellipsis that identifies the
5552  /// pack expansion.
5553  ///
5554  /// \param PatternRange The source range that covers the entire pattern of
5555  /// the pack expansion.
5556  ///
5557  /// \param Unexpanded The set of unexpanded parameter packs within the
5558  /// pattern.
5559  ///
5560  /// \param ShouldExpand Will be set to \c true if the transformer should
5561  /// expand the corresponding pack expansions into separate arguments. When
5562  /// set, \c NumExpansions must also be set.
5563  ///
5564  /// \param RetainExpansion Whether the caller should add an unexpanded
5565  /// pack expansion after all of the expanded arguments. This is used
5566  /// when extending explicitly-specified template argument packs per
5567  /// C++0x [temp.arg.explicit]p9.
5568  ///
5569  /// \param NumExpansions The number of separate arguments that will be in
5570  /// the expanded form of the corresponding pack expansion. This is both an
5571  /// input and an output parameter, which can be set by the caller if the
5572  /// number of expansions is known a priori (e.g., due to a prior substitution)
5573  /// and will be set by the callee when the number of expansions is known.
5574  /// The callee must set this value when \c ShouldExpand is \c true; it may
5575  /// set this value in other cases.
5576  ///
5577  /// \returns true if an error occurred (e.g., because the parameter packs
5578  /// are to be instantiated with arguments of different lengths), false
5579  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
5580  /// must be set.
5581  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
5582                                       SourceRange PatternRange,
5583                             ArrayRef<UnexpandedParameterPack> Unexpanded,
5584                             const MultiLevelTemplateArgumentList &TemplateArgs,
5585                                       bool &ShouldExpand,
5586                                       bool &RetainExpansion,
5587                                       Optional<unsigned> &NumExpansions);
5588
5589  /// \brief Determine the number of arguments in the given pack expansion
5590  /// type.
5591  ///
5592  /// This routine assumes that the number of arguments in the expansion is
5593  /// consistent across all of the unexpanded parameter packs in its pattern.
5594  ///
5595  /// Returns an empty Optional if the type can't be expanded.
5596  Optional<unsigned> getNumArgumentsInExpansion(QualType T,
5597      const MultiLevelTemplateArgumentList &TemplateArgs);
5598
5599  /// \brief Determine whether the given declarator contains any unexpanded
5600  /// parameter packs.
5601  ///
5602  /// This routine is used by the parser to disambiguate function declarators
5603  /// with an ellipsis prior to the ')', e.g.,
5604  ///
5605  /// \code
5606  ///   void f(T...);
5607  /// \endcode
5608  ///
5609  /// To determine whether we have an (unnamed) function parameter pack or
5610  /// a variadic function.
5611  ///
5612  /// \returns true if the declarator contains any unexpanded parameter packs,
5613  /// false otherwise.
5614  bool containsUnexpandedParameterPacks(Declarator &D);
5615
5616  /// \brief Returns the pattern of the pack expansion for a template argument.
5617  ///
5618  /// \param OrigLoc The template argument to expand.
5619  ///
5620  /// \param Ellipsis Will be set to the location of the ellipsis.
5621  ///
5622  /// \param NumExpansions Will be set to the number of expansions that will
5623  /// be generated from this pack expansion, if known a priori.
5624  TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
5625      TemplateArgumentLoc OrigLoc,
5626      SourceLocation &Ellipsis,
5627      Optional<unsigned> &NumExpansions) const;
5628
5629  //===--------------------------------------------------------------------===//
5630  // C++ Template Argument Deduction (C++ [temp.deduct])
5631  //===--------------------------------------------------------------------===//
5632
5633  /// \brief Describes the result of template argument deduction.
5634  ///
5635  /// The TemplateDeductionResult enumeration describes the result of
5636  /// template argument deduction, as returned from
5637  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
5638  /// structure provides additional information about the results of
5639  /// template argument deduction, e.g., the deduced template argument
5640  /// list (if successful) or the specific template parameters or
5641  /// deduced arguments that were involved in the failure.
5642  enum TemplateDeductionResult {
5643    /// \brief Template argument deduction was successful.
5644    TDK_Success = 0,
5645    /// \brief The declaration was invalid; do nothing.
5646    TDK_Invalid,
5647    /// \brief Template argument deduction exceeded the maximum template
5648    /// instantiation depth (which has already been diagnosed).
5649    TDK_InstantiationDepth,
5650    /// \brief Template argument deduction did not deduce a value
5651    /// for every template parameter.
5652    TDK_Incomplete,
5653    /// \brief Template argument deduction produced inconsistent
5654    /// deduced values for the given template parameter.
5655    TDK_Inconsistent,
5656    /// \brief Template argument deduction failed due to inconsistent
5657    /// cv-qualifiers on a template parameter type that would
5658    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
5659    /// but were given a non-const "X".
5660    TDK_Underqualified,
5661    /// \brief Substitution of the deduced template argument values
5662    /// resulted in an error.
5663    TDK_SubstitutionFailure,
5664    /// \brief A non-depnedent component of the parameter did not match the
5665    /// corresponding component of the argument.
5666    TDK_NonDeducedMismatch,
5667    /// \brief When performing template argument deduction for a function
5668    /// template, there were too many call arguments.
5669    TDK_TooManyArguments,
5670    /// \brief When performing template argument deduction for a function
5671    /// template, there were too few call arguments.
5672    TDK_TooFewArguments,
5673    /// \brief The explicitly-specified template arguments were not valid
5674    /// template arguments for the given template.
5675    TDK_InvalidExplicitArguments,
5676    /// \brief The arguments included an overloaded function name that could
5677    /// not be resolved to a suitable function.
5678    TDK_FailedOverloadResolution,
5679    /// \brief Deduction failed; that's all we know.
5680    TDK_MiscellaneousDeductionFailure
5681  };
5682
5683  TemplateDeductionResult
5684  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
5685                          const TemplateArgumentList &TemplateArgs,
5686                          sema::TemplateDeductionInfo &Info);
5687
5688  TemplateDeductionResult
5689  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5690                              TemplateArgumentListInfo &ExplicitTemplateArgs,
5691                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5692                                 SmallVectorImpl<QualType> &ParamTypes,
5693                                      QualType *FunctionType,
5694                                      sema::TemplateDeductionInfo &Info);
5695
5696  /// brief A function argument from which we performed template argument
5697  // deduction for a call.
5698  struct OriginalCallArg {
5699    OriginalCallArg(QualType OriginalParamType,
5700                    unsigned ArgIdx,
5701                    QualType OriginalArgType)
5702      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
5703        OriginalArgType(OriginalArgType) { }
5704
5705    QualType OriginalParamType;
5706    unsigned ArgIdx;
5707    QualType OriginalArgType;
5708  };
5709
5710  TemplateDeductionResult
5711  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
5712                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5713                                  unsigned NumExplicitlySpecified,
5714                                  FunctionDecl *&Specialization,
5715                                  sema::TemplateDeductionInfo &Info,
5716           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
5717
5718  TemplateDeductionResult
5719  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5720                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5721                          ArrayRef<Expr *> Args,
5722                          FunctionDecl *&Specialization,
5723                          sema::TemplateDeductionInfo &Info);
5724
5725  TemplateDeductionResult
5726  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5727                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5728                          QualType ArgFunctionType,
5729                          FunctionDecl *&Specialization,
5730                          sema::TemplateDeductionInfo &Info,
5731                          bool InOverloadResolution = false);
5732
5733  TemplateDeductionResult
5734  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5735                          QualType ToType,
5736                          CXXConversionDecl *&Specialization,
5737                          sema::TemplateDeductionInfo &Info);
5738
5739  TemplateDeductionResult
5740  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5741                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5742                          FunctionDecl *&Specialization,
5743                          sema::TemplateDeductionInfo &Info,
5744                          bool InOverloadResolution = false);
5745
5746  /// \brief Result type of DeduceAutoType.
5747  enum DeduceAutoResult {
5748    DAR_Succeeded,
5749    DAR_Failed,
5750    DAR_FailedAlreadyDiagnosed
5751  };
5752
5753  DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
5754                                  QualType &Result);
5755  DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
5756                                  QualType &Result);
5757  QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
5758  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
5759  bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
5760                        bool Diagnose = true);
5761
5762  bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
5763                                        SourceLocation ReturnLoc,
5764                                        Expr *&RetExpr, AutoType *AT);
5765
5766  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
5767                                                   FunctionTemplateDecl *FT2,
5768                                                   SourceLocation Loc,
5769                                           TemplatePartialOrderingContext TPOC,
5770                                                   unsigned NumCallArguments);
5771  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
5772                                           UnresolvedSetIterator SEnd,
5773                                           TemplatePartialOrderingContext TPOC,
5774                                           unsigned NumCallArguments,
5775                                           SourceLocation Loc,
5776                                           const PartialDiagnostic &NoneDiag,
5777                                           const PartialDiagnostic &AmbigDiag,
5778                                        const PartialDiagnostic &CandidateDiag,
5779                                        bool Complain = true,
5780                                        QualType TargetType = QualType());
5781
5782  ClassTemplatePartialSpecializationDecl *
5783  getMoreSpecializedPartialSpecialization(
5784                                  ClassTemplatePartialSpecializationDecl *PS1,
5785                                  ClassTemplatePartialSpecializationDecl *PS2,
5786                                  SourceLocation Loc);
5787
5788  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5789                                  bool OnlyDeduced,
5790                                  unsigned Depth,
5791                                  llvm::SmallBitVector &Used);
5792  void MarkDeducedTemplateParameters(
5793                                  const FunctionTemplateDecl *FunctionTemplate,
5794                                  llvm::SmallBitVector &Deduced) {
5795    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
5796  }
5797  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
5798                                  const FunctionTemplateDecl *FunctionTemplate,
5799                                  llvm::SmallBitVector &Deduced);
5800
5801  //===--------------------------------------------------------------------===//
5802  // C++ Template Instantiation
5803  //
5804
5805  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
5806                                     const TemplateArgumentList *Innermost = 0,
5807                                                bool RelativeToPrimary = false,
5808                                               const FunctionDecl *Pattern = 0);
5809
5810  /// \brief A template instantiation that is currently in progress.
5811  struct ActiveTemplateInstantiation {
5812    /// \brief The kind of template instantiation we are performing
5813    enum InstantiationKind {
5814      /// We are instantiating a template declaration. The entity is
5815      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
5816      TemplateInstantiation,
5817
5818      /// We are instantiating a default argument for a template
5819      /// parameter. The Entity is the template, and
5820      /// TemplateArgs/NumTemplateArguments provides the template
5821      /// arguments as specified.
5822      /// FIXME: Use a TemplateArgumentList
5823      DefaultTemplateArgumentInstantiation,
5824
5825      /// We are instantiating a default argument for a function.
5826      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
5827      /// provides the template arguments as specified.
5828      DefaultFunctionArgumentInstantiation,
5829
5830      /// We are substituting explicit template arguments provided for
5831      /// a function template. The entity is a FunctionTemplateDecl.
5832      ExplicitTemplateArgumentSubstitution,
5833
5834      /// We are substituting template argument determined as part of
5835      /// template argument deduction for either a class template
5836      /// partial specialization or a function template. The
5837      /// Entity is either a ClassTemplatePartialSpecializationDecl or
5838      /// a FunctionTemplateDecl.
5839      DeducedTemplateArgumentSubstitution,
5840
5841      /// We are substituting prior template arguments into a new
5842      /// template parameter. The template parameter itself is either a
5843      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
5844      PriorTemplateArgumentSubstitution,
5845
5846      /// We are checking the validity of a default template argument that
5847      /// has been used when naming a template-id.
5848      DefaultTemplateArgumentChecking,
5849
5850      /// We are instantiating the exception specification for a function
5851      /// template which was deferred until it was needed.
5852      ExceptionSpecInstantiation
5853    } Kind;
5854
5855    /// \brief The point of instantiation within the source code.
5856    SourceLocation PointOfInstantiation;
5857
5858    /// \brief The template (or partial specialization) in which we are
5859    /// performing the instantiation, for substitutions of prior template
5860    /// arguments.
5861    NamedDecl *Template;
5862
5863    /// \brief The entity that is being instantiated.
5864    Decl *Entity;
5865
5866    /// \brief The list of template arguments we are substituting, if they
5867    /// are not part of the entity.
5868    const TemplateArgument *TemplateArgs;
5869
5870    /// \brief The number of template arguments in TemplateArgs.
5871    unsigned NumTemplateArgs;
5872
5873    /// \brief The template deduction info object associated with the
5874    /// substitution or checking of explicit or deduced template arguments.
5875    sema::TemplateDeductionInfo *DeductionInfo;
5876
5877    /// \brief The source range that covers the construct that cause
5878    /// the instantiation, e.g., the template-id that causes a class
5879    /// template instantiation.
5880    SourceRange InstantiationRange;
5881
5882    ActiveTemplateInstantiation()
5883      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
5884        NumTemplateArgs(0), DeductionInfo(0) {}
5885
5886    /// \brief Determines whether this template is an actual instantiation
5887    /// that should be counted toward the maximum instantiation depth.
5888    bool isInstantiationRecord() const;
5889
5890    friend bool operator==(const ActiveTemplateInstantiation &X,
5891                           const ActiveTemplateInstantiation &Y) {
5892      if (X.Kind != Y.Kind)
5893        return false;
5894
5895      if (X.Entity != Y.Entity)
5896        return false;
5897
5898      switch (X.Kind) {
5899      case TemplateInstantiation:
5900      case ExceptionSpecInstantiation:
5901        return true;
5902
5903      case PriorTemplateArgumentSubstitution:
5904      case DefaultTemplateArgumentChecking:
5905        return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
5906
5907      case DefaultTemplateArgumentInstantiation:
5908      case ExplicitTemplateArgumentSubstitution:
5909      case DeducedTemplateArgumentSubstitution:
5910      case DefaultFunctionArgumentInstantiation:
5911        return X.TemplateArgs == Y.TemplateArgs;
5912
5913      }
5914
5915      llvm_unreachable("Invalid InstantiationKind!");
5916    }
5917
5918    friend bool operator!=(const ActiveTemplateInstantiation &X,
5919                           const ActiveTemplateInstantiation &Y) {
5920      return !(X == Y);
5921    }
5922  };
5923
5924  /// \brief List of active template instantiations.
5925  ///
5926  /// This vector is treated as a stack. As one template instantiation
5927  /// requires another template instantiation, additional
5928  /// instantiations are pushed onto the stack up to a
5929  /// user-configurable limit LangOptions::InstantiationDepth.
5930  SmallVector<ActiveTemplateInstantiation, 16>
5931    ActiveTemplateInstantiations;
5932
5933  /// \brief Whether we are in a SFINAE context that is not associated with
5934  /// template instantiation.
5935  ///
5936  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
5937  /// of a template instantiation or template argument deduction.
5938  bool InNonInstantiationSFINAEContext;
5939
5940  /// \brief The number of ActiveTemplateInstantiation entries in
5941  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
5942  /// therefore, should not be counted as part of the instantiation depth.
5943  unsigned NonInstantiationEntries;
5944
5945  /// \brief The last template from which a template instantiation
5946  /// error or warning was produced.
5947  ///
5948  /// This value is used to suppress printing of redundant template
5949  /// instantiation backtraces when there are multiple errors in the
5950  /// same instantiation. FIXME: Does this belong in Sema? It's tough
5951  /// to implement it anywhere else.
5952  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
5953
5954  /// \brief The current index into pack expansion arguments that will be
5955  /// used for substitution of parameter packs.
5956  ///
5957  /// The pack expansion index will be -1 to indicate that parameter packs
5958  /// should be instantiated as themselves. Otherwise, the index specifies
5959  /// which argument within the parameter pack will be used for substitution.
5960  int ArgumentPackSubstitutionIndex;
5961
5962  /// \brief RAII object used to change the argument pack substitution index
5963  /// within a \c Sema object.
5964  ///
5965  /// See \c ArgumentPackSubstitutionIndex for more information.
5966  class ArgumentPackSubstitutionIndexRAII {
5967    Sema &Self;
5968    int OldSubstitutionIndex;
5969
5970  public:
5971    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
5972      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
5973      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
5974    }
5975
5976    ~ArgumentPackSubstitutionIndexRAII() {
5977      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
5978    }
5979  };
5980
5981  friend class ArgumentPackSubstitutionRAII;
5982
5983  /// \brief The stack of calls expression undergoing template instantiation.
5984  ///
5985  /// The top of this stack is used by a fixit instantiating unresolved
5986  /// function calls to fix the AST to match the textual change it prints.
5987  SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
5988
5989  /// \brief For each declaration that involved template argument deduction, the
5990  /// set of diagnostics that were suppressed during that template argument
5991  /// deduction.
5992  ///
5993  /// FIXME: Serialize this structure to the AST file.
5994  typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
5995    SuppressedDiagnosticsMap;
5996  SuppressedDiagnosticsMap SuppressedDiagnostics;
5997
5998  /// \brief A stack object to be created when performing template
5999  /// instantiation.
6000  ///
6001  /// Construction of an object of type \c InstantiatingTemplate
6002  /// pushes the current instantiation onto the stack of active
6003  /// instantiations. If the size of this stack exceeds the maximum
6004  /// number of recursive template instantiations, construction
6005  /// produces an error and evaluates true.
6006  ///
6007  /// Destruction of this object will pop the named instantiation off
6008  /// the stack.
6009  struct InstantiatingTemplate {
6010    /// \brief Note that we are instantiating a class template,
6011    /// function template, or a member thereof.
6012    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6013                          Decl *Entity,
6014                          SourceRange InstantiationRange = SourceRange());
6015
6016    struct ExceptionSpecification {};
6017    /// \brief Note that we are instantiating an exception specification
6018    /// of a function template.
6019    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6020                          FunctionDecl *Entity, ExceptionSpecification,
6021                          SourceRange InstantiationRange = SourceRange());
6022
6023    /// \brief Note that we are instantiating a default argument in a
6024    /// template-id.
6025    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6026                          TemplateDecl *Template,
6027                          ArrayRef<TemplateArgument> TemplateArgs,
6028                          SourceRange InstantiationRange = SourceRange());
6029
6030    /// \brief Note that we are instantiating a default argument in a
6031    /// template-id.
6032    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6033                          FunctionTemplateDecl *FunctionTemplate,
6034                          ArrayRef<TemplateArgument> TemplateArgs,
6035                          ActiveTemplateInstantiation::InstantiationKind Kind,
6036                          sema::TemplateDeductionInfo &DeductionInfo,
6037                          SourceRange InstantiationRange = SourceRange());
6038
6039    /// \brief Note that we are instantiating as part of template
6040    /// argument deduction for a class template partial
6041    /// specialization.
6042    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6043                          ClassTemplatePartialSpecializationDecl *PartialSpec,
6044                          ArrayRef<TemplateArgument> TemplateArgs,
6045                          sema::TemplateDeductionInfo &DeductionInfo,
6046                          SourceRange InstantiationRange = SourceRange());
6047
6048    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6049                          ParmVarDecl *Param,
6050                          ArrayRef<TemplateArgument> TemplateArgs,
6051                          SourceRange InstantiationRange = SourceRange());
6052
6053    /// \brief Note that we are substituting prior template arguments into a
6054    /// non-type or template template parameter.
6055    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6056                          NamedDecl *Template,
6057                          NonTypeTemplateParmDecl *Param,
6058                          ArrayRef<TemplateArgument> TemplateArgs,
6059                          SourceRange InstantiationRange);
6060
6061    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6062                          NamedDecl *Template,
6063                          TemplateTemplateParmDecl *Param,
6064                          ArrayRef<TemplateArgument> TemplateArgs,
6065                          SourceRange InstantiationRange);
6066
6067    /// \brief Note that we are checking the default template argument
6068    /// against the template parameter for a given template-id.
6069    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6070                          TemplateDecl *Template,
6071                          NamedDecl *Param,
6072                          ArrayRef<TemplateArgument> TemplateArgs,
6073                          SourceRange InstantiationRange);
6074
6075
6076    /// \brief Note that we have finished instantiating this template.
6077    void Clear();
6078
6079    ~InstantiatingTemplate() { Clear(); }
6080
6081    /// \brief Determines whether we have exceeded the maximum
6082    /// recursive template instantiations.
6083    LLVM_EXPLICIT operator bool() const { return Invalid; }
6084
6085  private:
6086    Sema &SemaRef;
6087    bool Invalid;
6088    bool SavedInNonInstantiationSFINAEContext;
6089    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6090                                 SourceRange InstantiationRange);
6091
6092    InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6093
6094    InstantiatingTemplate&
6095    operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6096  };
6097
6098  void PrintInstantiationStack();
6099
6100  /// \brief Determines whether we are currently in a context where
6101  /// template argument substitution failures are not considered
6102  /// errors.
6103  ///
6104  /// \returns An empty \c Optional if we're not in a SFINAE context.
6105  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6106  /// template-deduction context object, which can be used to capture
6107  /// diagnostics that will be suppressed.
6108  Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6109
6110  /// \brief Determines whether we are currently in a context that
6111  /// is not evaluated as per C++ [expr] p5.
6112  bool isUnevaluatedContext() const {
6113    assert(!ExprEvalContexts.empty() &&
6114           "Must be in an expression evaluation context");
6115    return ExprEvalContexts.back().isUnevaluated();
6116  }
6117
6118  /// \brief RAII class used to determine whether SFINAE has
6119  /// trapped any errors that occur during template argument
6120  /// deduction.`
6121  class SFINAETrap {
6122    Sema &SemaRef;
6123    unsigned PrevSFINAEErrors;
6124    bool PrevInNonInstantiationSFINAEContext;
6125    bool PrevAccessCheckingSFINAE;
6126
6127  public:
6128    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6129      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6130        PrevInNonInstantiationSFINAEContext(
6131                                      SemaRef.InNonInstantiationSFINAEContext),
6132        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6133    {
6134      if (!SemaRef.isSFINAEContext())
6135        SemaRef.InNonInstantiationSFINAEContext = true;
6136      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6137    }
6138
6139    ~SFINAETrap() {
6140      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6141      SemaRef.InNonInstantiationSFINAEContext
6142        = PrevInNonInstantiationSFINAEContext;
6143      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6144    }
6145
6146    /// \brief Determine whether any SFINAE errors have been trapped.
6147    bool hasErrorOccurred() const {
6148      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6149    }
6150  };
6151
6152  /// \brief The current instantiation scope used to store local
6153  /// variables.
6154  LocalInstantiationScope *CurrentInstantiationScope;
6155
6156  /// \brief The number of typos corrected by CorrectTypo.
6157  unsigned TyposCorrected;
6158
6159  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
6160    UnqualifiedTyposCorrectedMap;
6161
6162  /// \brief A cache containing the results of typo correction for unqualified
6163  /// name lookup.
6164  ///
6165  /// The string is the string that we corrected to (which may be empty, if
6166  /// there was no correction), while the boolean will be true when the
6167  /// string represents a keyword.
6168  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
6169
6170  /// \brief Worker object for performing CFG-based warnings.
6171  sema::AnalysisBasedWarnings AnalysisWarnings;
6172
6173  /// \brief An entity for which implicit template instantiation is required.
6174  ///
6175  /// The source location associated with the declaration is the first place in
6176  /// the source code where the declaration was "used". It is not necessarily
6177  /// the point of instantiation (which will be either before or after the
6178  /// namespace-scope declaration that triggered this implicit instantiation),
6179  /// However, it is the location that diagnostics should generally refer to,
6180  /// because users will need to know what code triggered the instantiation.
6181  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6182
6183  /// \brief The queue of implicit template instantiations that are required
6184  /// but have not yet been performed.
6185  std::deque<PendingImplicitInstantiation> PendingInstantiations;
6186
6187  /// \brief The queue of implicit template instantiations that are required
6188  /// and must be performed within the current local scope.
6189  ///
6190  /// This queue is only used for member functions of local classes in
6191  /// templates, which must be instantiated in the same scope as their
6192  /// enclosing function, so that they can reference function-local
6193  /// types, static variables, enumerators, etc.
6194  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6195
6196  void PerformPendingInstantiations(bool LocalOnly = false);
6197
6198  TypeSourceInfo *SubstType(TypeSourceInfo *T,
6199                            const MultiLevelTemplateArgumentList &TemplateArgs,
6200                            SourceLocation Loc, DeclarationName Entity);
6201
6202  QualType SubstType(QualType T,
6203                     const MultiLevelTemplateArgumentList &TemplateArgs,
6204                     SourceLocation Loc, DeclarationName Entity);
6205
6206  TypeSourceInfo *SubstType(TypeLoc TL,
6207                            const MultiLevelTemplateArgumentList &TemplateArgs,
6208                            SourceLocation Loc, DeclarationName Entity);
6209
6210  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6211                            const MultiLevelTemplateArgumentList &TemplateArgs,
6212                                        SourceLocation Loc,
6213                                        DeclarationName Entity,
6214                                        CXXRecordDecl *ThisContext,
6215                                        unsigned ThisTypeQuals);
6216  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6217                            const MultiLevelTemplateArgumentList &TemplateArgs,
6218                                int indexAdjustment,
6219                                Optional<unsigned> NumExpansions,
6220                                bool ExpectParameterPack);
6221  bool SubstParmTypes(SourceLocation Loc,
6222                      ParmVarDecl **Params, unsigned NumParams,
6223                      const MultiLevelTemplateArgumentList &TemplateArgs,
6224                      SmallVectorImpl<QualType> &ParamTypes,
6225                      SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
6226  ExprResult SubstExpr(Expr *E,
6227                       const MultiLevelTemplateArgumentList &TemplateArgs);
6228
6229  /// \brief Substitute the given template arguments into a list of
6230  /// expressions, expanding pack expansions if required.
6231  ///
6232  /// \param Exprs The list of expressions to substitute into.
6233  ///
6234  /// \param NumExprs The number of expressions in \p Exprs.
6235  ///
6236  /// \param IsCall Whether this is some form of call, in which case
6237  /// default arguments will be dropped.
6238  ///
6239  /// \param TemplateArgs The set of template arguments to substitute.
6240  ///
6241  /// \param Outputs Will receive all of the substituted arguments.
6242  ///
6243  /// \returns true if an error occurred, false otherwise.
6244  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6245                  const MultiLevelTemplateArgumentList &TemplateArgs,
6246                  SmallVectorImpl<Expr *> &Outputs);
6247
6248  StmtResult SubstStmt(Stmt *S,
6249                       const MultiLevelTemplateArgumentList &TemplateArgs);
6250
6251  Decl *SubstDecl(Decl *D, DeclContext *Owner,
6252                  const MultiLevelTemplateArgumentList &TemplateArgs);
6253
6254  ExprResult SubstInitializer(Expr *E,
6255                       const MultiLevelTemplateArgumentList &TemplateArgs,
6256                       bool CXXDirectInit);
6257
6258  bool
6259  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6260                      CXXRecordDecl *Pattern,
6261                      const MultiLevelTemplateArgumentList &TemplateArgs);
6262
6263  bool
6264  InstantiateClass(SourceLocation PointOfInstantiation,
6265                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6266                   const MultiLevelTemplateArgumentList &TemplateArgs,
6267                   TemplateSpecializationKind TSK,
6268                   bool Complain = true);
6269
6270  bool InstantiateEnum(SourceLocation PointOfInstantiation,
6271                       EnumDecl *Instantiation, EnumDecl *Pattern,
6272                       const MultiLevelTemplateArgumentList &TemplateArgs,
6273                       TemplateSpecializationKind TSK);
6274
6275  struct LateInstantiatedAttribute {
6276    const Attr *TmplAttr;
6277    LocalInstantiationScope *Scope;
6278    Decl *NewDecl;
6279
6280    LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6281                              Decl *D)
6282      : TmplAttr(A), Scope(S), NewDecl(D)
6283    { }
6284  };
6285  typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6286
6287  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6288                        const Decl *Pattern, Decl *Inst,
6289                        LateInstantiatedAttrVec *LateAttrs = 0,
6290                        LocalInstantiationScope *OuterMostScope = 0);
6291
6292  bool
6293  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6294                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
6295                           TemplateSpecializationKind TSK,
6296                           bool Complain = true);
6297
6298  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6299                               CXXRecordDecl *Instantiation,
6300                            const MultiLevelTemplateArgumentList &TemplateArgs,
6301                               TemplateSpecializationKind TSK);
6302
6303  void InstantiateClassTemplateSpecializationMembers(
6304                                          SourceLocation PointOfInstantiation,
6305                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
6306                                                TemplateSpecializationKind TSK);
6307
6308  NestedNameSpecifierLoc
6309  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
6310                           const MultiLevelTemplateArgumentList &TemplateArgs);
6311
6312  DeclarationNameInfo
6313  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
6314                           const MultiLevelTemplateArgumentList &TemplateArgs);
6315  TemplateName
6316  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
6317                    SourceLocation Loc,
6318                    const MultiLevelTemplateArgumentList &TemplateArgs);
6319  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
6320             TemplateArgumentListInfo &Result,
6321             const MultiLevelTemplateArgumentList &TemplateArgs);
6322
6323  void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
6324                                FunctionDecl *Function);
6325  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
6326                                     FunctionDecl *Function,
6327                                     bool Recursive = false,
6328                                     bool DefinitionRequired = false);
6329  void InstantiateStaticDataMemberDefinition(
6330                                     SourceLocation PointOfInstantiation,
6331                                     VarDecl *Var,
6332                                     bool Recursive = false,
6333                                     bool DefinitionRequired = false);
6334
6335  void InstantiateMemInitializers(CXXConstructorDecl *New,
6336                                  const CXXConstructorDecl *Tmpl,
6337                            const MultiLevelTemplateArgumentList &TemplateArgs);
6338
6339  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6340                          const MultiLevelTemplateArgumentList &TemplateArgs);
6341  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
6342                          const MultiLevelTemplateArgumentList &TemplateArgs);
6343
6344  // Objective-C declarations.
6345  enum ObjCContainerKind {
6346    OCK_None = -1,
6347    OCK_Interface = 0,
6348    OCK_Protocol,
6349    OCK_Category,
6350    OCK_ClassExtension,
6351    OCK_Implementation,
6352    OCK_CategoryImplementation
6353  };
6354  ObjCContainerKind getObjCContainerKind() const;
6355
6356  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
6357                                 IdentifierInfo *ClassName,
6358                                 SourceLocation ClassLoc,
6359                                 IdentifierInfo *SuperName,
6360                                 SourceLocation SuperLoc,
6361                                 Decl * const *ProtoRefs,
6362                                 unsigned NumProtoRefs,
6363                                 const SourceLocation *ProtoLocs,
6364                                 SourceLocation EndProtoLoc,
6365                                 AttributeList *AttrList);
6366
6367  Decl *ActOnCompatibilityAlias(
6368                    SourceLocation AtCompatibilityAliasLoc,
6369                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
6370                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
6371
6372  bool CheckForwardProtocolDeclarationForCircularDependency(
6373    IdentifierInfo *PName,
6374    SourceLocation &PLoc, SourceLocation PrevLoc,
6375    const ObjCList<ObjCProtocolDecl> &PList);
6376
6377  Decl *ActOnStartProtocolInterface(
6378                    SourceLocation AtProtoInterfaceLoc,
6379                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6380                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6381                    const SourceLocation *ProtoLocs,
6382                    SourceLocation EndProtoLoc,
6383                    AttributeList *AttrList);
6384
6385  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6386                                    IdentifierInfo *ClassName,
6387                                    SourceLocation ClassLoc,
6388                                    IdentifierInfo *CategoryName,
6389                                    SourceLocation CategoryLoc,
6390                                    Decl * const *ProtoRefs,
6391                                    unsigned NumProtoRefs,
6392                                    const SourceLocation *ProtoLocs,
6393                                    SourceLocation EndProtoLoc);
6394
6395  Decl *ActOnStartClassImplementation(
6396                    SourceLocation AtClassImplLoc,
6397                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
6398                    IdentifierInfo *SuperClassname,
6399                    SourceLocation SuperClassLoc);
6400
6401  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
6402                                         IdentifierInfo *ClassName,
6403                                         SourceLocation ClassLoc,
6404                                         IdentifierInfo *CatName,
6405                                         SourceLocation CatLoc);
6406
6407  DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
6408                                               ArrayRef<Decl *> Decls);
6409
6410  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
6411                                     IdentifierInfo **IdentList,
6412                                     SourceLocation *IdentLocs,
6413                                     unsigned NumElts);
6414
6415  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
6416                                        const IdentifierLocPair *IdentList,
6417                                        unsigned NumElts,
6418                                        AttributeList *attrList);
6419
6420  void FindProtocolDeclaration(bool WarnOnDeclarations,
6421                               const IdentifierLocPair *ProtocolId,
6422                               unsigned NumProtocols,
6423                               SmallVectorImpl<Decl *> &Protocols);
6424
6425  /// Ensure attributes are consistent with type.
6426  /// \param [in, out] Attributes The attributes to check; they will
6427  /// be modified to be consistent with \p PropertyTy.
6428  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
6429                                   SourceLocation Loc,
6430                                   unsigned &Attributes,
6431                                   bool propertyInPrimaryClass);
6432
6433  /// Process the specified property declaration and create decls for the
6434  /// setters and getters as needed.
6435  /// \param property The property declaration being processed
6436  /// \param CD The semantic container for the property
6437  /// \param redeclaredProperty Declaration for property if redeclared
6438  ///        in class extension.
6439  /// \param lexicalDC Container for redeclaredProperty.
6440  void ProcessPropertyDecl(ObjCPropertyDecl *property,
6441                           ObjCContainerDecl *CD,
6442                           ObjCPropertyDecl *redeclaredProperty = 0,
6443                           ObjCContainerDecl *lexicalDC = 0);
6444
6445
6446  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
6447                                ObjCPropertyDecl *SuperProperty,
6448                                const IdentifierInfo *Name);
6449
6450  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
6451                                        ObjCInterfaceDecl *ID);
6452
6453  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
6454                   Decl **allMethods = 0, unsigned allNum = 0,
6455                   Decl **allProperties = 0, unsigned pNum = 0,
6456                   DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
6457
6458  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
6459                      SourceLocation LParenLoc,
6460                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
6461                      Selector GetterSel, Selector SetterSel,
6462                      bool *OverridingProperty,
6463                      tok::ObjCKeywordKind MethodImplKind,
6464                      DeclContext *lexicalDC = 0);
6465
6466  Decl *ActOnPropertyImplDecl(Scope *S,
6467                              SourceLocation AtLoc,
6468                              SourceLocation PropertyLoc,
6469                              bool ImplKind,
6470                              IdentifierInfo *PropertyId,
6471                              IdentifierInfo *PropertyIvar,
6472                              SourceLocation PropertyIvarLoc);
6473
6474  enum ObjCSpecialMethodKind {
6475    OSMK_None,
6476    OSMK_Alloc,
6477    OSMK_New,
6478    OSMK_Copy,
6479    OSMK_RetainingInit,
6480    OSMK_NonRetainingInit
6481  };
6482
6483  struct ObjCArgInfo {
6484    IdentifierInfo *Name;
6485    SourceLocation NameLoc;
6486    // The Type is null if no type was specified, and the DeclSpec is invalid
6487    // in this case.
6488    ParsedType Type;
6489    ObjCDeclSpec DeclSpec;
6490
6491    /// ArgAttrs - Attribute list for this argument.
6492    AttributeList *ArgAttrs;
6493  };
6494
6495  Decl *ActOnMethodDeclaration(
6496    Scope *S,
6497    SourceLocation BeginLoc, // location of the + or -.
6498    SourceLocation EndLoc,   // location of the ; or {.
6499    tok::TokenKind MethodType,
6500    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
6501    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
6502    // optional arguments. The number of types/arguments is obtained
6503    // from the Sel.getNumArgs().
6504    ObjCArgInfo *ArgInfo,
6505    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
6506    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
6507    bool isVariadic, bool MethodDefinition);
6508
6509  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
6510                                              const ObjCObjectPointerType *OPT,
6511                                              bool IsInstance);
6512  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
6513                                           bool IsInstance);
6514
6515  bool CheckARCMethodDecl(ObjCMethodDecl *method);
6516  bool inferObjCARCLifetime(ValueDecl *decl);
6517
6518  ExprResult
6519  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
6520                            Expr *BaseExpr,
6521                            SourceLocation OpLoc,
6522                            DeclarationName MemberName,
6523                            SourceLocation MemberLoc,
6524                            SourceLocation SuperLoc, QualType SuperType,
6525                            bool Super);
6526
6527  ExprResult
6528  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
6529                            IdentifierInfo &propertyName,
6530                            SourceLocation receiverNameLoc,
6531                            SourceLocation propertyNameLoc);
6532
6533  ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
6534
6535  /// \brief Describes the kind of message expression indicated by a message
6536  /// send that starts with an identifier.
6537  enum ObjCMessageKind {
6538    /// \brief The message is sent to 'super'.
6539    ObjCSuperMessage,
6540    /// \brief The message is an instance message.
6541    ObjCInstanceMessage,
6542    /// \brief The message is a class message, and the identifier is a type
6543    /// name.
6544    ObjCClassMessage
6545  };
6546
6547  ObjCMessageKind getObjCMessageKind(Scope *S,
6548                                     IdentifierInfo *Name,
6549                                     SourceLocation NameLoc,
6550                                     bool IsSuper,
6551                                     bool HasTrailingDot,
6552                                     ParsedType &ReceiverType);
6553
6554  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
6555                               Selector Sel,
6556                               SourceLocation LBracLoc,
6557                               ArrayRef<SourceLocation> SelectorLocs,
6558                               SourceLocation RBracLoc,
6559                               MultiExprArg Args);
6560
6561  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
6562                               QualType ReceiverType,
6563                               SourceLocation SuperLoc,
6564                               Selector Sel,
6565                               ObjCMethodDecl *Method,
6566                               SourceLocation LBracLoc,
6567                               ArrayRef<SourceLocation> SelectorLocs,
6568                               SourceLocation RBracLoc,
6569                               MultiExprArg Args,
6570                               bool isImplicit = false);
6571
6572  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
6573                                       bool isSuperReceiver,
6574                                       SourceLocation Loc,
6575                                       Selector Sel,
6576                                       ObjCMethodDecl *Method,
6577                                       MultiExprArg Args);
6578
6579  ExprResult ActOnClassMessage(Scope *S,
6580                               ParsedType Receiver,
6581                               Selector Sel,
6582                               SourceLocation LBracLoc,
6583                               ArrayRef<SourceLocation> SelectorLocs,
6584                               SourceLocation RBracLoc,
6585                               MultiExprArg Args);
6586
6587  ExprResult BuildInstanceMessage(Expr *Receiver,
6588                                  QualType ReceiverType,
6589                                  SourceLocation SuperLoc,
6590                                  Selector Sel,
6591                                  ObjCMethodDecl *Method,
6592                                  SourceLocation LBracLoc,
6593                                  ArrayRef<SourceLocation> SelectorLocs,
6594                                  SourceLocation RBracLoc,
6595                                  MultiExprArg Args,
6596                                  bool isImplicit = false);
6597
6598  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
6599                                          QualType ReceiverType,
6600                                          SourceLocation Loc,
6601                                          Selector Sel,
6602                                          ObjCMethodDecl *Method,
6603                                          MultiExprArg Args);
6604
6605  ExprResult ActOnInstanceMessage(Scope *S,
6606                                  Expr *Receiver,
6607                                  Selector Sel,
6608                                  SourceLocation LBracLoc,
6609                                  ArrayRef<SourceLocation> SelectorLocs,
6610                                  SourceLocation RBracLoc,
6611                                  MultiExprArg Args);
6612
6613  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
6614                                  ObjCBridgeCastKind Kind,
6615                                  SourceLocation BridgeKeywordLoc,
6616                                  TypeSourceInfo *TSInfo,
6617                                  Expr *SubExpr);
6618
6619  ExprResult ActOnObjCBridgedCast(Scope *S,
6620                                  SourceLocation LParenLoc,
6621                                  ObjCBridgeCastKind Kind,
6622                                  SourceLocation BridgeKeywordLoc,
6623                                  ParsedType Type,
6624                                  SourceLocation RParenLoc,
6625                                  Expr *SubExpr);
6626
6627  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
6628
6629  /// \brief Check whether the given new method is a valid override of the
6630  /// given overridden method, and set any properties that should be inherited.
6631  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
6632                               const ObjCMethodDecl *Overridden);
6633
6634  /// \brief Describes the compatibility of a result type with its method.
6635  enum ResultTypeCompatibilityKind {
6636    RTC_Compatible,
6637    RTC_Incompatible,
6638    RTC_Unknown
6639  };
6640
6641  void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
6642                                ObjCInterfaceDecl *CurrentClass,
6643                                ResultTypeCompatibilityKind RTC);
6644
6645  enum PragmaOptionsAlignKind {
6646    POAK_Native,  // #pragma options align=native
6647    POAK_Natural, // #pragma options align=natural
6648    POAK_Packed,  // #pragma options align=packed
6649    POAK_Power,   // #pragma options align=power
6650    POAK_Mac68k,  // #pragma options align=mac68k
6651    POAK_Reset    // #pragma options align=reset
6652  };
6653
6654  /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
6655  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
6656                               SourceLocation PragmaLoc);
6657
6658  enum PragmaPackKind {
6659    PPK_Default, // #pragma pack([n])
6660    PPK_Show,    // #pragma pack(show), only supported by MSVC.
6661    PPK_Push,    // #pragma pack(push, [identifier], [n])
6662    PPK_Pop      // #pragma pack(pop, [identifier], [n])
6663  };
6664
6665  enum PragmaMSStructKind {
6666    PMSST_OFF,  // #pragms ms_struct off
6667    PMSST_ON    // #pragms ms_struct on
6668  };
6669
6670  enum PragmaMSCommentKind {
6671    PCK_Unknown,
6672    PCK_Linker,   // #pragma comment(linker, ...)
6673    PCK_Lib,      // #pragma comment(lib, ...)
6674    PCK_Compiler, // #pragma comment(compiler, ...)
6675    PCK_ExeStr,   // #pragma comment(exestr, ...)
6676    PCK_User      // #pragma comment(user, ...)
6677  };
6678
6679  /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
6680  void ActOnPragmaPack(PragmaPackKind Kind,
6681                       IdentifierInfo *Name,
6682                       Expr *Alignment,
6683                       SourceLocation PragmaLoc,
6684                       SourceLocation LParenLoc,
6685                       SourceLocation RParenLoc);
6686
6687  /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
6688  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
6689
6690  /// ActOnPragmaMSStruct - Called on well formed \#pragma comment(kind, "arg").
6691  void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
6692
6693  /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
6694  void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
6695
6696  /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
6697  void ActOnPragmaUnused(const Token &Identifier,
6698                         Scope *curScope,
6699                         SourceLocation PragmaLoc);
6700
6701  /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
6702  void ActOnPragmaVisibility(const IdentifierInfo* VisType,
6703                             SourceLocation PragmaLoc);
6704
6705  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6706                                 SourceLocation Loc);
6707  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
6708
6709  /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
6710  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
6711                         SourceLocation PragmaLoc,
6712                         SourceLocation WeakNameLoc);
6713
6714  /// ActOnPragmaRedefineExtname - Called on well formed
6715  /// \#pragma redefine_extname oldname newname.
6716  void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
6717                                  IdentifierInfo* AliasName,
6718                                  SourceLocation PragmaLoc,
6719                                  SourceLocation WeakNameLoc,
6720                                  SourceLocation AliasNameLoc);
6721
6722  /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
6723  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
6724                            IdentifierInfo* AliasName,
6725                            SourceLocation PragmaLoc,
6726                            SourceLocation WeakNameLoc,
6727                            SourceLocation AliasNameLoc);
6728
6729  /// ActOnPragmaFPContract - Called on well formed
6730  /// \#pragma {STDC,OPENCL} FP_CONTRACT
6731  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
6732
6733  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
6734  /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
6735  void AddAlignmentAttributesForRecord(RecordDecl *RD);
6736
6737  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
6738  void AddMsStructLayoutForRecord(RecordDecl *RD);
6739
6740  /// FreePackedContext - Deallocate and null out PackContext.
6741  void FreePackedContext();
6742
6743  /// PushNamespaceVisibilityAttr - Note that we've entered a
6744  /// namespace with a visibility attribute.
6745  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
6746                                   SourceLocation Loc);
6747
6748  /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
6749  /// add an appropriate visibility attribute.
6750  void AddPushedVisibilityAttribute(Decl *RD);
6751
6752  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
6753  /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
6754  void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
6755
6756  /// FreeVisContext - Deallocate and null out VisContext.
6757  void FreeVisContext();
6758
6759  /// AddCFAuditedAttribute - Check whether we're currently within
6760  /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
6761  /// the appropriate attribute.
6762  void AddCFAuditedAttribute(Decl *D);
6763
6764  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
6765  void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
6766                      unsigned SpellingListIndex, bool IsPackExpansion);
6767  void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
6768                      unsigned SpellingListIndex, bool IsPackExpansion);
6769
6770  // OpenMP directives and clauses.
6771  /// \brief Called on correct id-expression from the '#pragma omp
6772  /// threadprivate'.
6773  ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
6774                                     CXXScopeSpec &ScopeSpec,
6775                                     const DeclarationNameInfo &Id);
6776  /// \brief Called on well-formed '#pragma omp threadprivate'.
6777  DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
6778                                     SourceLocation Loc,
6779                                     ArrayRef<Expr *> VarList);
6780  // \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
6781  OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
6782                                     SourceLocation Loc,
6783                                     ArrayRef<Expr *> VarList);
6784
6785  /// \brief The kind of conversion being performed.
6786  enum CheckedConversionKind {
6787    /// \brief An implicit conversion.
6788    CCK_ImplicitConversion,
6789    /// \brief A C-style cast.
6790    CCK_CStyleCast,
6791    /// \brief A functional-style cast.
6792    CCK_FunctionalCast,
6793    /// \brief A cast other than a C-style cast.
6794    CCK_OtherCast
6795  };
6796
6797  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
6798  /// cast.  If there is already an implicit cast, merge into the existing one.
6799  /// If isLvalue, the result of the cast is an lvalue.
6800  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
6801                               ExprValueKind VK = VK_RValue,
6802                               const CXXCastPath *BasePath = 0,
6803                               CheckedConversionKind CCK
6804                                  = CCK_ImplicitConversion);
6805
6806  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
6807  /// to the conversion from scalar type ScalarTy to the Boolean type.
6808  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
6809
6810  /// IgnoredValueConversions - Given that an expression's result is
6811  /// syntactically ignored, perform any conversions that are
6812  /// required.
6813  ExprResult IgnoredValueConversions(Expr *E);
6814
6815  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
6816  // functions and arrays to their respective pointers (C99 6.3.2.1).
6817  ExprResult UsualUnaryConversions(Expr *E);
6818
6819  // DefaultFunctionArrayConversion - converts functions and arrays
6820  // to their respective pointers (C99 6.3.2.1).
6821  ExprResult DefaultFunctionArrayConversion(Expr *E);
6822
6823  // DefaultFunctionArrayLvalueConversion - converts functions and
6824  // arrays to their respective pointers and performs the
6825  // lvalue-to-rvalue conversion.
6826  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
6827
6828  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
6829  // the operand.  This is DefaultFunctionArrayLvalueConversion,
6830  // except that it assumes the operand isn't of function or array
6831  // type.
6832  ExprResult DefaultLvalueConversion(Expr *E);
6833
6834  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
6835  // do not have a prototype. Integer promotions are performed on each
6836  // argument, and arguments that have type float are promoted to double.
6837  ExprResult DefaultArgumentPromotion(Expr *E);
6838
6839  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
6840  enum VariadicCallType {
6841    VariadicFunction,
6842    VariadicBlock,
6843    VariadicMethod,
6844    VariadicConstructor,
6845    VariadicDoesNotApply
6846  };
6847
6848  VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
6849                                       const FunctionProtoType *Proto,
6850                                       Expr *Fn);
6851
6852  // Used for determining in which context a type is allowed to be passed to a
6853  // vararg function.
6854  enum VarArgKind {
6855    VAK_Valid,
6856    VAK_ValidInCXX11,
6857    VAK_Invalid
6858  };
6859
6860  // Determines which VarArgKind fits an expression.
6861  VarArgKind isValidVarArgType(const QualType &Ty);
6862
6863  /// GatherArgumentsForCall - Collector argument expressions for various
6864  /// form of call prototypes.
6865  bool GatherArgumentsForCall(SourceLocation CallLoc,
6866                              FunctionDecl *FDecl,
6867                              const FunctionProtoType *Proto,
6868                              unsigned FirstProtoArg,
6869                              ArrayRef<Expr *> Args,
6870                              SmallVectorImpl<Expr *> &AllArgs,
6871                              VariadicCallType CallType = VariadicDoesNotApply,
6872                              bool AllowExplicit = false,
6873                              bool IsListInitialization = false);
6874
6875  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
6876  // will create a runtime trap if the resulting type is not a POD type.
6877  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
6878                                              FunctionDecl *FDecl);
6879
6880  /// Checks to see if the given expression is a valid argument to a variadic
6881  /// function, issuing a diagnostic and returning NULL if not.
6882  bool variadicArgumentPODCheck(const Expr *E, VariadicCallType CT);
6883
6884  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
6885  // operands and then handles various conversions that are common to binary
6886  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
6887  // routine returns the first non-arithmetic type found. The client is
6888  // responsible for emitting appropriate error diagnostics.
6889  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
6890                                      bool IsCompAssign = false);
6891
6892  /// AssignConvertType - All of the 'assignment' semantic checks return this
6893  /// enum to indicate whether the assignment was allowed.  These checks are
6894  /// done for simple assignments, as well as initialization, return from
6895  /// function, argument passing, etc.  The query is phrased in terms of a
6896  /// source and destination type.
6897  enum AssignConvertType {
6898    /// Compatible - the types are compatible according to the standard.
6899    Compatible,
6900
6901    /// PointerToInt - The assignment converts a pointer to an int, which we
6902    /// accept as an extension.
6903    PointerToInt,
6904
6905    /// IntToPointer - The assignment converts an int to a pointer, which we
6906    /// accept as an extension.
6907    IntToPointer,
6908
6909    /// FunctionVoidPointer - The assignment is between a function pointer and
6910    /// void*, which the standard doesn't allow, but we accept as an extension.
6911    FunctionVoidPointer,
6912
6913    /// IncompatiblePointer - The assignment is between two pointers types that
6914    /// are not compatible, but we accept them as an extension.
6915    IncompatiblePointer,
6916
6917    /// IncompatiblePointer - The assignment is between two pointers types which
6918    /// point to integers which have a different sign, but are otherwise
6919    /// identical. This is a subset of the above, but broken out because it's by
6920    /// far the most common case of incompatible pointers.
6921    IncompatiblePointerSign,
6922
6923    /// CompatiblePointerDiscardsQualifiers - The assignment discards
6924    /// c/v/r qualifiers, which we accept as an extension.
6925    CompatiblePointerDiscardsQualifiers,
6926
6927    /// IncompatiblePointerDiscardsQualifiers - The assignment
6928    /// discards qualifiers that we don't permit to be discarded,
6929    /// like address spaces.
6930    IncompatiblePointerDiscardsQualifiers,
6931
6932    /// IncompatibleNestedPointerQualifiers - The assignment is between two
6933    /// nested pointer types, and the qualifiers other than the first two
6934    /// levels differ e.g. char ** -> const char **, but we accept them as an
6935    /// extension.
6936    IncompatibleNestedPointerQualifiers,
6937
6938    /// IncompatibleVectors - The assignment is between two vector types that
6939    /// have the same size, which we accept as an extension.
6940    IncompatibleVectors,
6941
6942    /// IntToBlockPointer - The assignment converts an int to a block
6943    /// pointer. We disallow this.
6944    IntToBlockPointer,
6945
6946    /// IncompatibleBlockPointer - The assignment is between two block
6947    /// pointers types that are not compatible.
6948    IncompatibleBlockPointer,
6949
6950    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
6951    /// id type and something else (that is incompatible with it). For example,
6952    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
6953    IncompatibleObjCQualifiedId,
6954
6955    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
6956    /// object with __weak qualifier.
6957    IncompatibleObjCWeakRef,
6958
6959    /// Incompatible - We reject this conversion outright, it is invalid to
6960    /// represent it in the AST.
6961    Incompatible
6962  };
6963
6964  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
6965  /// assignment conversion type specified by ConvTy.  This returns true if the
6966  /// conversion was invalid or false if the conversion was accepted.
6967  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
6968                                SourceLocation Loc,
6969                                QualType DstType, QualType SrcType,
6970                                Expr *SrcExpr, AssignmentAction Action,
6971                                bool *Complained = 0);
6972
6973  /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
6974  /// integer not in the range of enum values.
6975  void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
6976                              Expr *SrcExpr);
6977
6978  /// CheckAssignmentConstraints - Perform type checking for assignment,
6979  /// argument passing, variable initialization, and function return values.
6980  /// C99 6.5.16.
6981  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
6982                                               QualType LHSType,
6983                                               QualType RHSType);
6984
6985  /// Check assignment constraints and prepare for a conversion of the
6986  /// RHS to the LHS type.
6987  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
6988                                               ExprResult &RHS,
6989                                               CastKind &Kind);
6990
6991  // CheckSingleAssignmentConstraints - Currently used by
6992  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
6993  // this routine performs the default function/array converions.
6994  AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
6995                                                     ExprResult &RHS,
6996                                                     bool Diagnose = true);
6997
6998  // \brief If the lhs type is a transparent union, check whether we
6999  // can initialize the transparent union with the given expression.
7000  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
7001                                                             ExprResult &RHS);
7002
7003  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
7004
7005  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
7006
7007  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7008                                       AssignmentAction Action,
7009                                       bool AllowExplicit = false);
7010  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7011                                       AssignmentAction Action,
7012                                       bool AllowExplicit,
7013                                       ImplicitConversionSequence& ICS);
7014  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7015                                       const ImplicitConversionSequence& ICS,
7016                                       AssignmentAction Action,
7017                                       CheckedConversionKind CCK
7018                                          = CCK_ImplicitConversion);
7019  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7020                                       const StandardConversionSequence& SCS,
7021                                       AssignmentAction Action,
7022                                       CheckedConversionKind CCK);
7023
7024  /// the following "Check" methods will return a valid/converted QualType
7025  /// or a null QualType (indicating an error diagnostic was issued).
7026
7027  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
7028  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7029                           ExprResult &RHS);
7030  QualType CheckPointerToMemberOperands( // C++ 5.5
7031    ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7032    SourceLocation OpLoc, bool isIndirect);
7033  QualType CheckMultiplyDivideOperands( // C99 6.5.5
7034    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
7035    bool IsDivide);
7036  QualType CheckRemainderOperands( // C99 6.5.5
7037    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7038    bool IsCompAssign = false);
7039  QualType CheckAdditionOperands( // C99 6.5.6
7040    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7041    QualType* CompLHSTy = 0);
7042  QualType CheckSubtractionOperands( // C99 6.5.6
7043    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7044    QualType* CompLHSTy = 0);
7045  QualType CheckShiftOperands( // C99 6.5.7
7046    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7047    bool IsCompAssign = false);
7048  QualType CheckCompareOperands( // C99 6.5.8/9
7049    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
7050                                bool isRelational);
7051  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
7052    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7053    bool IsCompAssign = false);
7054  QualType CheckLogicalOperands( // C99 6.5.[13,14]
7055    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
7056  // CheckAssignmentOperands is used for both simple and compound assignment.
7057  // For simple assignment, pass both expressions and a null converted type.
7058  // For compound assignment, pass both expressions and the converted type.
7059  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
7060    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
7061
7062  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
7063                                     UnaryOperatorKind Opcode, Expr *Op);
7064  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
7065                                         BinaryOperatorKind Opcode,
7066                                         Expr *LHS, Expr *RHS);
7067  ExprResult checkPseudoObjectRValue(Expr *E);
7068  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
7069
7070  QualType CheckConditionalOperands( // C99 6.5.15
7071    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
7072    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
7073  QualType CXXCheckConditionalOperands( // C++ 5.16
7074    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
7075    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
7076  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
7077                                    bool *NonStandardCompositeType = 0);
7078  QualType FindCompositePointerType(SourceLocation Loc,
7079                                    ExprResult &E1, ExprResult &E2,
7080                                    bool *NonStandardCompositeType = 0) {
7081    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
7082    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
7083                                                  NonStandardCompositeType);
7084    E1 = Owned(E1Tmp);
7085    E2 = Owned(E2Tmp);
7086    return Composite;
7087  }
7088
7089  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7090                                        SourceLocation QuestionLoc);
7091
7092  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7093                                  SourceLocation QuestionLoc);
7094
7095  /// type checking for vector binary operators.
7096  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7097                               SourceLocation Loc, bool IsCompAssign);
7098  QualType GetSignedVectorType(QualType V);
7099  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7100                                      SourceLocation Loc, bool isRelational);
7101  QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7102                                      SourceLocation Loc);
7103
7104  /// type checking declaration initializers (C99 6.7.8)
7105  bool CheckForConstantInitializer(Expr *e, QualType t);
7106
7107  // type checking C++ declaration initializers (C++ [dcl.init]).
7108
7109  /// ReferenceCompareResult - Expresses the result of comparing two
7110  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
7111  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
7112  enum ReferenceCompareResult {
7113    /// Ref_Incompatible - The two types are incompatible, so direct
7114    /// reference binding is not possible.
7115    Ref_Incompatible = 0,
7116    /// Ref_Related - The two types are reference-related, which means
7117    /// that their unqualified forms (T1 and T2) are either the same
7118    /// or T1 is a base class of T2.
7119    Ref_Related,
7120    /// Ref_Compatible_With_Added_Qualification - The two types are
7121    /// reference-compatible with added qualification, meaning that
7122    /// they are reference-compatible and the qualifiers on T1 (cv1)
7123    /// are greater than the qualifiers on T2 (cv2).
7124    Ref_Compatible_With_Added_Qualification,
7125    /// Ref_Compatible - The two types are reference-compatible and
7126    /// have equivalent qualifiers (cv1 == cv2).
7127    Ref_Compatible
7128  };
7129
7130  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
7131                                                      QualType T1, QualType T2,
7132                                                      bool &DerivedToBase,
7133                                                      bool &ObjCConversion,
7134                                                bool &ObjCLifetimeConversion);
7135
7136  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7137                                 Expr *CastExpr, CastKind &CastKind,
7138                                 ExprValueKind &VK, CXXCastPath &Path);
7139
7140  /// \brief Force an expression with unknown-type to an expression of the
7141  /// given type.
7142  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7143
7144  /// \brief Type-check an expression that's being passed to an
7145  /// __unknown_anytype parameter.
7146  ExprResult checkUnknownAnyArg(SourceLocation callLoc,
7147                                Expr *result, QualType &paramType);
7148
7149  // CheckVectorCast - check type constraints for vectors.
7150  // Since vectors are an extension, there are no C standard reference for this.
7151  // We allow casting between vectors and integer datatypes of the same size.
7152  // returns true if the cast is invalid
7153  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7154                       CastKind &Kind);
7155
7156  // CheckExtVectorCast - check type constraints for extended vectors.
7157  // Since vectors are an extension, there are no C standard reference for this.
7158  // We allow casting between vectors and integer datatypes of the same size,
7159  // or vectors and the element type of that vector.
7160  // returns the cast expr
7161  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
7162                                CastKind &Kind);
7163
7164  ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
7165                                        SourceLocation LParenLoc,
7166                                        Expr *CastExpr,
7167                                        SourceLocation RParenLoc);
7168
7169  enum ARCConversionResult { ACR_okay, ACR_unbridged };
7170
7171  /// \brief Checks for invalid conversions and casts between
7172  /// retainable pointers and other pointer kinds.
7173  ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
7174                                             QualType castType, Expr *&op,
7175                                             CheckedConversionKind CCK);
7176
7177  Expr *stripARCUnbridgedCast(Expr *e);
7178  void diagnoseARCUnbridgedCast(Expr *e);
7179
7180  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
7181                                             QualType ExprType);
7182
7183  /// checkRetainCycles - Check whether an Objective-C message send
7184  /// might create an obvious retain cycle.
7185  void checkRetainCycles(ObjCMessageExpr *msg);
7186  void checkRetainCycles(Expr *receiver, Expr *argument);
7187  void checkRetainCycles(VarDecl *Var, Expr *Init);
7188
7189  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
7190  /// to weak/__unsafe_unretained type.
7191  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
7192
7193  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
7194  /// to weak/__unsafe_unretained expression.
7195  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
7196
7197  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
7198  /// \param Method - May be null.
7199  /// \param [out] ReturnType - The return type of the send.
7200  /// \return true iff there were any incompatible types.
7201  bool CheckMessageArgumentTypes(QualType ReceiverType,
7202                                 MultiExprArg Args, Selector Sel,
7203                                 ArrayRef<SourceLocation> SelectorLocs,
7204                                 ObjCMethodDecl *Method, bool isClassMessage,
7205                                 bool isSuperMessage,
7206                                 SourceLocation lbrac, SourceLocation rbrac,
7207                                 QualType &ReturnType, ExprValueKind &VK);
7208
7209  /// \brief Determine the result of a message send expression based on
7210  /// the type of the receiver, the method expected to receive the message,
7211  /// and the form of the message send.
7212  QualType getMessageSendResultType(QualType ReceiverType,
7213                                    ObjCMethodDecl *Method,
7214                                    bool isClassMessage, bool isSuperMessage);
7215
7216  /// \brief If the given expression involves a message send to a method
7217  /// with a related result type, emit a note describing what happened.
7218  void EmitRelatedResultTypeNote(const Expr *E);
7219
7220  /// \brief Given that we had incompatible pointer types in a return
7221  /// statement, check whether we're in a method with a related result
7222  /// type, and if so, emit a note describing what happened.
7223  void EmitRelatedResultTypeNoteForReturn(QualType destType);
7224
7225  /// CheckBooleanCondition - Diagnose problems involving the use of
7226  /// the given expression as a boolean condition (e.g. in an if
7227  /// statement).  Also performs the standard function and array
7228  /// decays, possibly changing the input variable.
7229  ///
7230  /// \param Loc - A location associated with the condition, e.g. the
7231  /// 'if' keyword.
7232  /// \return true iff there were any errors
7233  ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
7234
7235  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7236                                   Expr *SubExpr);
7237
7238  /// DiagnoseAssignmentAsCondition - Given that an expression is
7239  /// being used as a boolean condition, warn if it's an assignment.
7240  void DiagnoseAssignmentAsCondition(Expr *E);
7241
7242  /// \brief Redundant parentheses over an equality comparison can indicate
7243  /// that the user intended an assignment used as condition.
7244  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7245
7246  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
7247  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
7248
7249  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
7250  /// the specified width and sign.  If an overflow occurs, detect it and emit
7251  /// the specified diagnostic.
7252  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
7253                                          unsigned NewWidth, bool NewSign,
7254                                          SourceLocation Loc, unsigned DiagID);
7255
7256  /// Checks that the Objective-C declaration is declared in the global scope.
7257  /// Emits an error and marks the declaration as invalid if it's not declared
7258  /// in the global scope.
7259  bool CheckObjCDeclScope(Decl *D);
7260
7261  /// \brief Abstract base class used for diagnosing integer constant
7262  /// expression violations.
7263  class VerifyICEDiagnoser {
7264  public:
7265    bool Suppress;
7266
7267    VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
7268
7269    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
7270    virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
7271    virtual ~VerifyICEDiagnoser() { }
7272  };
7273
7274  /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7275  /// and reports the appropriate diagnostics. Returns false on success.
7276  /// Can optionally return the value of the expression.
7277  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7278                                             VerifyICEDiagnoser &Diagnoser,
7279                                             bool AllowFold = true);
7280  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7281                                             unsigned DiagID,
7282                                             bool AllowFold = true);
7283  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0);
7284
7285  /// VerifyBitField - verifies that a bit field expression is an ICE and has
7286  /// the correct width, and that the field type is valid.
7287  /// Returns false on success.
7288  /// Can optionally return whether the bit-field is of width 0
7289  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
7290                            QualType FieldTy, Expr *BitWidth,
7291                            bool *ZeroWidth = 0);
7292
7293  enum CUDAFunctionTarget {
7294    CFT_Device,
7295    CFT_Global,
7296    CFT_Host,
7297    CFT_HostDevice
7298  };
7299
7300  CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
7301
7302  bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
7303                       CUDAFunctionTarget CalleeTarget);
7304
7305  bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
7306    return CheckCUDATarget(IdentifyCUDATarget(Caller),
7307                           IdentifyCUDATarget(Callee));
7308  }
7309
7310  /// \name Code completion
7311  //@{
7312  /// \brief Describes the context in which code completion occurs.
7313  enum ParserCompletionContext {
7314    /// \brief Code completion occurs at top-level or namespace context.
7315    PCC_Namespace,
7316    /// \brief Code completion occurs within a class, struct, or union.
7317    PCC_Class,
7318    /// \brief Code completion occurs within an Objective-C interface, protocol,
7319    /// or category.
7320    PCC_ObjCInterface,
7321    /// \brief Code completion occurs within an Objective-C implementation or
7322    /// category implementation
7323    PCC_ObjCImplementation,
7324    /// \brief Code completion occurs within the list of instance variables
7325    /// in an Objective-C interface, protocol, category, or implementation.
7326    PCC_ObjCInstanceVariableList,
7327    /// \brief Code completion occurs following one or more template
7328    /// headers.
7329    PCC_Template,
7330    /// \brief Code completion occurs following one or more template
7331    /// headers within a class.
7332    PCC_MemberTemplate,
7333    /// \brief Code completion occurs within an expression.
7334    PCC_Expression,
7335    /// \brief Code completion occurs within a statement, which may
7336    /// also be an expression or a declaration.
7337    PCC_Statement,
7338    /// \brief Code completion occurs at the beginning of the
7339    /// initialization statement (or expression) in a for loop.
7340    PCC_ForInit,
7341    /// \brief Code completion occurs within the condition of an if,
7342    /// while, switch, or for statement.
7343    PCC_Condition,
7344    /// \brief Code completion occurs within the body of a function on a
7345    /// recovery path, where we do not have a specific handle on our position
7346    /// in the grammar.
7347    PCC_RecoveryInFunction,
7348    /// \brief Code completion occurs where only a type is permitted.
7349    PCC_Type,
7350    /// \brief Code completion occurs in a parenthesized expression, which
7351    /// might also be a type cast.
7352    PCC_ParenthesizedExpression,
7353    /// \brief Code completion occurs within a sequence of declaration
7354    /// specifiers within a function, method, or block.
7355    PCC_LocalDeclarationSpecifiers
7356  };
7357
7358  void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
7359  void CodeCompleteOrdinaryName(Scope *S,
7360                                ParserCompletionContext CompletionContext);
7361  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
7362                            bool AllowNonIdentifiers,
7363                            bool AllowNestedNameSpecifiers);
7364
7365  struct CodeCompleteExpressionData;
7366  void CodeCompleteExpression(Scope *S,
7367                              const CodeCompleteExpressionData &Data);
7368  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
7369                                       SourceLocation OpLoc,
7370                                       bool IsArrow);
7371  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
7372  void CodeCompleteTag(Scope *S, unsigned TagSpec);
7373  void CodeCompleteTypeQualifiers(DeclSpec &DS);
7374  void CodeCompleteCase(Scope *S);
7375  void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
7376  void CodeCompleteInitializer(Scope *S, Decl *D);
7377  void CodeCompleteReturn(Scope *S);
7378  void CodeCompleteAfterIf(Scope *S);
7379  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
7380
7381  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
7382                               bool EnteringContext);
7383  void CodeCompleteUsing(Scope *S);
7384  void CodeCompleteUsingDirective(Scope *S);
7385  void CodeCompleteNamespaceDecl(Scope *S);
7386  void CodeCompleteNamespaceAliasDecl(Scope *S);
7387  void CodeCompleteOperatorName(Scope *S);
7388  void CodeCompleteConstructorInitializer(
7389                                Decl *Constructor,
7390                                ArrayRef<CXXCtorInitializer *> Initializers);
7391
7392  void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7393                                    bool AfterAmpersand);
7394
7395  void CodeCompleteObjCAtDirective(Scope *S);
7396  void CodeCompleteObjCAtVisibility(Scope *S);
7397  void CodeCompleteObjCAtStatement(Scope *S);
7398  void CodeCompleteObjCAtExpression(Scope *S);
7399  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
7400  void CodeCompleteObjCPropertyGetter(Scope *S);
7401  void CodeCompleteObjCPropertySetter(Scope *S);
7402  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7403                                   bool IsParameter);
7404  void CodeCompleteObjCMessageReceiver(Scope *S);
7405  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
7406                                    ArrayRef<IdentifierInfo *> SelIdents,
7407                                    bool AtArgumentExpression);
7408  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
7409                                    ArrayRef<IdentifierInfo *> SelIdents,
7410                                    bool AtArgumentExpression,
7411                                    bool IsSuper = false);
7412  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
7413                                       ArrayRef<IdentifierInfo *> SelIdents,
7414                                       bool AtArgumentExpression,
7415                                       ObjCInterfaceDecl *Super = 0);
7416  void CodeCompleteObjCForCollection(Scope *S,
7417                                     DeclGroupPtrTy IterationVar);
7418  void CodeCompleteObjCSelector(Scope *S,
7419                                ArrayRef<IdentifierInfo *> SelIdents);
7420  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
7421                                          unsigned NumProtocols);
7422  void CodeCompleteObjCProtocolDecl(Scope *S);
7423  void CodeCompleteObjCInterfaceDecl(Scope *S);
7424  void CodeCompleteObjCSuperclass(Scope *S,
7425                                  IdentifierInfo *ClassName,
7426                                  SourceLocation ClassNameLoc);
7427  void CodeCompleteObjCImplementationDecl(Scope *S);
7428  void CodeCompleteObjCInterfaceCategory(Scope *S,
7429                                         IdentifierInfo *ClassName,
7430                                         SourceLocation ClassNameLoc);
7431  void CodeCompleteObjCImplementationCategory(Scope *S,
7432                                              IdentifierInfo *ClassName,
7433                                              SourceLocation ClassNameLoc);
7434  void CodeCompleteObjCPropertyDefinition(Scope *S);
7435  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
7436                                              IdentifierInfo *PropertyName);
7437  void CodeCompleteObjCMethodDecl(Scope *S,
7438                                  bool IsInstanceMethod,
7439                                  ParsedType ReturnType);
7440  void CodeCompleteObjCMethodDeclSelector(Scope *S,
7441                                          bool IsInstanceMethod,
7442                                          bool AtParameterName,
7443                                          ParsedType ReturnType,
7444                                          ArrayRef<IdentifierInfo *> SelIdents);
7445  void CodeCompletePreprocessorDirective(bool InConditional);
7446  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
7447  void CodeCompletePreprocessorMacroName(bool IsDefinition);
7448  void CodeCompletePreprocessorExpression();
7449  void CodeCompletePreprocessorMacroArgument(Scope *S,
7450                                             IdentifierInfo *Macro,
7451                                             MacroInfo *MacroInfo,
7452                                             unsigned Argument);
7453  void CodeCompleteNaturalLanguage();
7454  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7455                                   CodeCompletionTUInfo &CCTUInfo,
7456                  SmallVectorImpl<CodeCompletionResult> &Results);
7457  //@}
7458
7459  //===--------------------------------------------------------------------===//
7460  // Extra semantic analysis beyond the C type system
7461
7462public:
7463  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
7464                                                unsigned ByteNo) const;
7465
7466private:
7467  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7468                        const ArraySubscriptExpr *ASE=0,
7469                        bool AllowOnePastEnd=true, bool IndexNegated=false);
7470  void CheckArrayAccess(const Expr *E);
7471  // Used to grab the relevant information from a FormatAttr and a
7472  // FunctionDeclaration.
7473  struct FormatStringInfo {
7474    unsigned FormatIdx;
7475    unsigned FirstDataArg;
7476    bool HasVAListArg;
7477  };
7478
7479  bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7480                           FormatStringInfo *FSI);
7481  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
7482                         const FunctionProtoType *Proto);
7483  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
7484                           ArrayRef<const Expr *> Args);
7485  bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
7486                        const FunctionProtoType *Proto);
7487  bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
7488  void CheckConstructorCall(FunctionDecl *FDecl,
7489                            ArrayRef<const Expr *> Args,
7490                            const FunctionProtoType *Proto,
7491                            SourceLocation Loc);
7492
7493  void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
7494                 unsigned NumProtoArgs, bool IsMemberFunction,
7495                 SourceLocation Loc, SourceRange Range,
7496                 VariadicCallType CallType);
7497
7498
7499  bool CheckObjCString(Expr *Arg);
7500
7501  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7502
7503  bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall);
7504  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7505
7506  bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7507
7508  bool SemaBuiltinVAStart(CallExpr *TheCall);
7509  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
7510  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
7511
7512public:
7513  // Used by C++ template instantiation.
7514  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
7515
7516private:
7517  bool SemaBuiltinPrefetch(CallExpr *TheCall);
7518  bool SemaBuiltinObjectSize(CallExpr *TheCall);
7519  bool SemaBuiltinLongjmp(CallExpr *TheCall);
7520  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
7521  ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
7522                                     AtomicExpr::AtomicOp Op);
7523  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7524                              llvm::APSInt &Result);
7525
7526  enum FormatStringType {
7527    FST_Scanf,
7528    FST_Printf,
7529    FST_NSString,
7530    FST_Strftime,
7531    FST_Strfmon,
7532    FST_Kprintf,
7533    FST_Unknown
7534  };
7535  static FormatStringType GetFormatStringType(const FormatAttr *Format);
7536
7537  enum StringLiteralCheckType {
7538    SLCT_NotALiteral,
7539    SLCT_UncheckedLiteral,
7540    SLCT_CheckedLiteral
7541  };
7542
7543  StringLiteralCheckType checkFormatStringExpr(const Expr *E,
7544                                               ArrayRef<const Expr *> Args,
7545                                               bool HasVAListArg,
7546                                               unsigned format_idx,
7547                                               unsigned firstDataArg,
7548                                               FormatStringType Type,
7549                                               VariadicCallType CallType,
7550                                               bool inFunctionCall = true);
7551
7552  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
7553                         ArrayRef<const Expr *> Args, bool HasVAListArg,
7554                         unsigned format_idx, unsigned firstDataArg,
7555                         FormatStringType Type, bool inFunctionCall,
7556                         VariadicCallType CallType);
7557
7558  bool CheckFormatArguments(const FormatAttr *Format,
7559                            ArrayRef<const Expr *> Args,
7560                            bool IsCXXMember,
7561                            VariadicCallType CallType,
7562                            SourceLocation Loc, SourceRange Range);
7563  bool CheckFormatArguments(ArrayRef<const Expr *> Args,
7564                            bool HasVAListArg, unsigned format_idx,
7565                            unsigned firstDataArg, FormatStringType Type,
7566                            VariadicCallType CallType,
7567                            SourceLocation Loc, SourceRange range);
7568
7569  void CheckNonNullArguments(const NonNullAttr *NonNull,
7570                             const Expr * const *ExprArgs,
7571                             SourceLocation CallSiteLoc);
7572
7573  void CheckMemaccessArguments(const CallExpr *Call,
7574                               unsigned BId,
7575                               IdentifierInfo *FnName);
7576
7577  void CheckStrlcpycatArguments(const CallExpr *Call,
7578                                IdentifierInfo *FnName);
7579
7580  void CheckStrncatArguments(const CallExpr *Call,
7581                             IdentifierInfo *FnName);
7582
7583  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
7584                            SourceLocation ReturnLoc);
7585  void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
7586  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
7587  void CheckForIntOverflow(Expr *E);
7588  void CheckUnsequencedOperations(Expr *E);
7589
7590  /// \brief Perform semantic checks on a completed expression. This will either
7591  /// be a full-expression or a default argument expression.
7592  void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
7593                          bool IsConstexpr = false);
7594
7595  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
7596                                   Expr *Init);
7597
7598public:
7599  /// \brief Register a magic integral constant to be used as a type tag.
7600  void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7601                                  uint64_t MagicValue, QualType Type,
7602                                  bool LayoutCompatible, bool MustBeNull);
7603
7604  struct TypeTagData {
7605    TypeTagData() {}
7606
7607    TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
7608        Type(Type), LayoutCompatible(LayoutCompatible),
7609        MustBeNull(MustBeNull)
7610    {}
7611
7612    QualType Type;
7613
7614    /// If true, \c Type should be compared with other expression's types for
7615    /// layout-compatibility.
7616    unsigned LayoutCompatible : 1;
7617    unsigned MustBeNull : 1;
7618  };
7619
7620  /// A pair of ArgumentKind identifier and magic value.  This uniquely
7621  /// identifies the magic value.
7622  typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
7623
7624private:
7625  /// \brief A map from magic value to type information.
7626  OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> >
7627      TypeTagForDatatypeMagicValues;
7628
7629  /// \brief Peform checks on a call of a function with argument_with_type_tag
7630  /// or pointer_with_type_tag attributes.
7631  void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7632                                const Expr * const *ExprArgs);
7633
7634  /// \brief The parser's current scope.
7635  ///
7636  /// The parser maintains this state here.
7637  Scope *CurScope;
7638
7639  mutable IdentifierInfo *Ident_super;
7640  mutable IdentifierInfo *Ident___float128;
7641
7642protected:
7643  friend class Parser;
7644  friend class InitializationSequence;
7645  friend class ASTReader;
7646  friend class ASTWriter;
7647
7648public:
7649  /// \brief Retrieve the parser's current scope.
7650  ///
7651  /// This routine must only be used when it is certain that semantic analysis
7652  /// and the parser are in precisely the same context, which is not the case
7653  /// when, e.g., we are performing any kind of template instantiation.
7654  /// Therefore, the only safe places to use this scope are in the parser
7655  /// itself and in routines directly invoked from the parser and *never* from
7656  /// template substitution or instantiation.
7657  Scope *getCurScope() const { return CurScope; }
7658
7659  IdentifierInfo *getSuperIdentifier() const;
7660  IdentifierInfo *getFloat128Identifier() const;
7661
7662  Decl *getObjCDeclContext() const;
7663
7664  DeclContext *getCurLexicalContext() const {
7665    return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
7666  }
7667
7668  AvailabilityResult getCurContextAvailability() const;
7669
7670  const DeclContext *getCurObjCLexicalContext() const {
7671    const DeclContext *DC = getCurLexicalContext();
7672    // A category implicitly has the attribute of the interface.
7673    if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
7674      DC = CatD->getClassInterface();
7675    return DC;
7676  }
7677};
7678
7679/// \brief RAII object that enters a new expression evaluation context.
7680class EnterExpressionEvaluationContext {
7681  Sema &Actions;
7682
7683public:
7684  EnterExpressionEvaluationContext(Sema &Actions,
7685                                   Sema::ExpressionEvaluationContext NewContext,
7686                                   Decl *LambdaContextDecl = 0,
7687                                   bool IsDecltype = false)
7688    : Actions(Actions) {
7689    Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
7690                                            IsDecltype);
7691  }
7692  EnterExpressionEvaluationContext(Sema &Actions,
7693                                   Sema::ExpressionEvaluationContext NewContext,
7694                                   Sema::ReuseLambdaContextDecl_t,
7695                                   bool IsDecltype = false)
7696    : Actions(Actions) {
7697    Actions.PushExpressionEvaluationContext(NewContext,
7698                                            Sema::ReuseLambdaContextDecl,
7699                                            IsDecltype);
7700  }
7701
7702  ~EnterExpressionEvaluationContext() {
7703    Actions.PopExpressionEvaluationContext();
7704  }
7705};
7706
7707}  // end namespace clang
7708
7709#endif
7710