Home | History | Annotate | Download | only in Sema
      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/LocInfoType.h"
     24 #include "clang/AST/MangleNumberingContext.h"
     25 #include "clang/AST/NSAPI.h"
     26 #include "clang/AST/PrettyPrinter.h"
     27 #include "clang/AST/TypeLoc.h"
     28 #include "clang/Basic/ExpressionTraits.h"
     29 #include "clang/Basic/LangOptions.h"
     30 #include "clang/Basic/Module.h"
     31 #include "clang/Basic/OpenMPKinds.h"
     32 #include "clang/Basic/PragmaKinds.h"
     33 #include "clang/Basic/Specifiers.h"
     34 #include "clang/Basic/TemplateKinds.h"
     35 #include "clang/Basic/TypeTraits.h"
     36 #include "clang/Sema/AnalysisBasedWarnings.h"
     37 #include "clang/Sema/CleanupInfo.h"
     38 #include "clang/Sema/DeclSpec.h"
     39 #include "clang/Sema/ExternalSemaSource.h"
     40 #include "clang/Sema/IdentifierResolver.h"
     41 #include "clang/Sema/ObjCMethodList.h"
     42 #include "clang/Sema/Ownership.h"
     43 #include "clang/Sema/Scope.h"
     44 #include "clang/Sema/ScopeInfo.h"
     45 #include "clang/Sema/TypoCorrection.h"
     46 #include "clang/Sema/Weak.h"
     47 #include "llvm/ADT/ArrayRef.h"
     48 #include "llvm/ADT/Optional.h"
     49 #include "llvm/ADT/SetVector.h"
     50 #include "llvm/ADT/SmallPtrSet.h"
     51 #include "llvm/ADT/SmallVector.h"
     52 #include "llvm/ADT/TinyPtrVector.h"
     53 #include <deque>
     54 #include <memory>
     55 #include <string>
     56 #include <vector>
     57 
     58 namespace llvm {
     59   class APSInt;
     60   template <typename ValueT> struct DenseMapInfo;
     61   template <typename ValueT, typename ValueInfoT> class DenseSet;
     62   class SmallBitVector;
     63   class InlineAsmIdentifierInfo;
     64 }
     65 
     66 namespace clang {
     67   class ADLResult;
     68   class ASTConsumer;
     69   class ASTContext;
     70   class ASTMutationListener;
     71   class ASTReader;
     72   class ASTWriter;
     73   class ArrayType;
     74   class AttributeList;
     75   class BlockDecl;
     76   class CapturedDecl;
     77   class CXXBasePath;
     78   class CXXBasePaths;
     79   class CXXBindTemporaryExpr;
     80   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
     81   class CXXConstructorDecl;
     82   class CXXConversionDecl;
     83   class CXXDeleteExpr;
     84   class CXXDestructorDecl;
     85   class CXXFieldCollector;
     86   class CXXMemberCallExpr;
     87   class CXXMethodDecl;
     88   class CXXScopeSpec;
     89   class CXXTemporary;
     90   class CXXTryStmt;
     91   class CallExpr;
     92   class ClassTemplateDecl;
     93   class ClassTemplatePartialSpecializationDecl;
     94   class ClassTemplateSpecializationDecl;
     95   class VarTemplatePartialSpecializationDecl;
     96   class CodeCompleteConsumer;
     97   class CodeCompletionAllocator;
     98   class CodeCompletionTUInfo;
     99   class CodeCompletionResult;
    100   class Decl;
    101   class DeclAccessPair;
    102   class DeclContext;
    103   class DeclRefExpr;
    104   class DeclaratorDecl;
    105   class DeducedTemplateArgument;
    106   class DependentDiagnostic;
    107   class DesignatedInitExpr;
    108   class Designation;
    109   class EnableIfAttr;
    110   class EnumConstantDecl;
    111   class Expr;
    112   class ExtVectorType;
    113   class FormatAttr;
    114   class FriendDecl;
    115   class FunctionDecl;
    116   class FunctionProtoType;
    117   class FunctionTemplateDecl;
    118   class ImplicitConversionSequence;
    119   class InitListExpr;
    120   class InitializationKind;
    121   class InitializationSequence;
    122   class InitializedEntity;
    123   class IntegerLiteral;
    124   class LabelStmt;
    125   class LambdaExpr;
    126   class LangOptions;
    127   class LocalInstantiationScope;
    128   class LookupResult;
    129   class MacroInfo;
    130   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
    131   class ModuleLoader;
    132   class MultiLevelTemplateArgumentList;
    133   class NamedDecl;
    134   class ObjCCategoryDecl;
    135   class ObjCCategoryImplDecl;
    136   class ObjCCompatibleAliasDecl;
    137   class ObjCContainerDecl;
    138   class ObjCImplDecl;
    139   class ObjCImplementationDecl;
    140   class ObjCInterfaceDecl;
    141   class ObjCIvarDecl;
    142   template <class T> class ObjCList;
    143   class ObjCMessageExpr;
    144   class ObjCMethodDecl;
    145   class ObjCPropertyDecl;
    146   class ObjCProtocolDecl;
    147   class OMPThreadPrivateDecl;
    148   class OMPDeclareReductionDecl;
    149   class OMPDeclareSimdDecl;
    150   class OMPClause;
    151   struct OverloadCandidate;
    152   class OverloadCandidateSet;
    153   class OverloadExpr;
    154   class ParenListExpr;
    155   class ParmVarDecl;
    156   class Preprocessor;
    157   class PseudoDestructorTypeStorage;
    158   class PseudoObjectExpr;
    159   class QualType;
    160   class StandardConversionSequence;
    161   class Stmt;
    162   class StringLiteral;
    163   class SwitchStmt;
    164   class TemplateArgument;
    165   class TemplateArgumentList;
    166   class TemplateArgumentLoc;
    167   class TemplateDecl;
    168   class TemplateParameterList;
    169   class TemplatePartialOrderingContext;
    170   class TemplateTemplateParmDecl;
    171   class Token;
    172   class TypeAliasDecl;
    173   class TypedefDecl;
    174   class TypedefNameDecl;
    175   class TypeLoc;
    176   class TypoCorrectionConsumer;
    177   class UnqualifiedId;
    178   class UnresolvedLookupExpr;
    179   class UnresolvedMemberExpr;
    180   class UnresolvedSetImpl;
    181   class UnresolvedSetIterator;
    182   class UsingDecl;
    183   class UsingShadowDecl;
    184   class ValueDecl;
    185   class VarDecl;
    186   class VarTemplateSpecializationDecl;
    187   class VisibilityAttr;
    188   class VisibleDeclConsumer;
    189   class IndirectFieldDecl;
    190   struct DeductionFailureInfo;
    191   class TemplateSpecCandidateSet;
    192 
    193 namespace sema {
    194   class AccessedEntity;
    195   class BlockScopeInfo;
    196   class CapturedRegionScopeInfo;
    197   class CapturingScopeInfo;
    198   class CompoundScopeInfo;
    199   class DelayedDiagnostic;
    200   class DelayedDiagnosticPool;
    201   class FunctionScopeInfo;
    202   class LambdaScopeInfo;
    203   class PossiblyUnreachableDiag;
    204   class TemplateDeductionInfo;
    205 }
    206 
    207 namespace threadSafety {
    208   class BeforeSet;
    209   void threadSafetyCleanup(BeforeSet* Cache);
    210 }
    211 
    212 // FIXME: No way to easily map from TemplateTypeParmTypes to
    213 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
    214 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
    215                   SourceLocation> UnexpandedParameterPack;
    216 
    217 /// Describes whether we've seen any nullability information for the given
    218 /// file.
    219 struct FileNullability {
    220   /// The first pointer declarator (of any pointer kind) in the file that does
    221   /// not have a corresponding nullability annotation.
    222   SourceLocation PointerLoc;
    223 
    224   /// Which kind of pointer declarator we saw.
    225   uint8_t PointerKind;
    226 
    227   /// Whether we saw any type nullability annotations in the given file.
    228   bool SawTypeNullability = false;
    229 };
    230 
    231 /// A mapping from file IDs to a record of whether we've seen nullability
    232 /// information in that file.
    233 class FileNullabilityMap {
    234   /// A mapping from file IDs to the nullability information for each file ID.
    235   llvm::DenseMap<FileID, FileNullability> Map;
    236 
    237   /// A single-element cache based on the file ID.
    238   struct {
    239     FileID File;
    240     FileNullability Nullability;
    241   } Cache;
    242 
    243 public:
    244   FileNullability &operator[](FileID file) {
    245     // Check the single-element cache.
    246     if (file == Cache.File)
    247       return Cache.Nullability;
    248 
    249     // It's not in the single-element cache; flush the cache if we have one.
    250     if (!Cache.File.isInvalid()) {
    251       Map[Cache.File] = Cache.Nullability;
    252     }
    253 
    254     // Pull this entry into the cache.
    255     Cache.File = file;
    256     Cache.Nullability = Map[file];
    257     return Cache.Nullability;
    258   }
    259 };
    260 
    261 /// Sema - This implements semantic analysis and AST building for C.
    262 class Sema {
    263   Sema(const Sema &) = delete;
    264   void operator=(const Sema &) = delete;
    265 
    266   ///\brief Source of additional semantic information.
    267   ExternalSemaSource *ExternalSource;
    268 
    269   ///\brief Whether Sema has generated a multiplexer and has to delete it.
    270   bool isMultiplexExternalSource;
    271 
    272   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
    273 
    274   bool isVisibleSlow(const NamedDecl *D);
    275 
    276   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
    277                                     const NamedDecl *New) {
    278     // We are about to link these. It is now safe to compute the linkage of
    279     // the new decl. If the new decl has external linkage, we will
    280     // link it with the hidden decl (which also has external linkage) and
    281     // it will keep having external linkage. If it has internal linkage, we
    282     // will not link it. Since it has no previous decls, it will remain
    283     // with internal linkage.
    284     return isVisible(Old) || New->isExternallyVisible();
    285   }
    286   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
    287 
    288 public:
    289   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
    290   typedef OpaquePtr<TemplateName> TemplateTy;
    291   typedef OpaquePtr<QualType> TypeTy;
    292 
    293   OpenCLOptions OpenCLFeatures;
    294   FPOptions FPFeatures;
    295 
    296   const LangOptions &LangOpts;
    297   Preprocessor &PP;
    298   ASTContext &Context;
    299   ASTConsumer &Consumer;
    300   DiagnosticsEngine &Diags;
    301   SourceManager &SourceMgr;
    302 
    303   /// \brief Flag indicating whether or not to collect detailed statistics.
    304   bool CollectStats;
    305 
    306   /// \brief Code-completion consumer.
    307   CodeCompleteConsumer *CodeCompleter;
    308 
    309   /// CurContext - This is the current declaration context of parsing.
    310   DeclContext *CurContext;
    311 
    312   /// \brief Generally null except when we temporarily switch decl contexts,
    313   /// like in \see ActOnObjCTemporaryExitContainerContext.
    314   DeclContext *OriginalLexicalContext;
    315 
    316   /// VAListTagName - The declaration name corresponding to __va_list_tag.
    317   /// This is used as part of a hack to omit that class from ADL results.
    318   DeclarationName VAListTagName;
    319 
    320   bool MSStructPragmaOn; // True when \#pragma ms_struct on
    321 
    322   /// \brief Controls member pointer representation format under the MS ABI.
    323   LangOptions::PragmaMSPointersToMembersKind
    324       MSPointerToMemberRepresentationMethod;
    325 
    326   /// Stack of active SEH __finally scopes.  Can be empty.
    327   SmallVector<Scope*, 2> CurrentSEHFinally;
    328 
    329   /// \brief Source location for newly created implicit MSInheritanceAttrs
    330   SourceLocation ImplicitMSInheritanceAttrLoc;
    331 
    332   enum PragmaMsStackAction {
    333     PSK_Reset     = 0x0,                // #pragma ()
    334     PSK_Set       = 0x1,                // #pragma (value)
    335     PSK_Push      = 0x2,                // #pragma (push[, id])
    336     PSK_Pop       = 0x4,                // #pragma (pop[, id])
    337     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
    338     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
    339     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
    340   };
    341 
    342   template<typename ValueType>
    343   struct PragmaStack {
    344     struct Slot {
    345       llvm::StringRef StackSlotLabel;
    346       ValueType Value;
    347       SourceLocation PragmaLocation;
    348       Slot(llvm::StringRef StackSlotLabel,
    349            ValueType Value,
    350            SourceLocation PragmaLocation)
    351         : StackSlotLabel(StackSlotLabel), Value(Value),
    352           PragmaLocation(PragmaLocation) {}
    353     };
    354     void Act(SourceLocation PragmaLocation,
    355              PragmaMsStackAction Action,
    356              llvm::StringRef StackSlotLabel,
    357              ValueType Value);
    358 
    359     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
    360     // method body to restore the stacks on exit, so it works like this:
    361     //
    362     //   struct S {
    363     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
    364     //     void Method {}
    365     //     #pragma <name>(pop, InternalPragmaSlot)
    366     //   };
    367     //
    368     // It works even with #pragma vtordisp, although MSVC doesn't support
    369     //   #pragma vtordisp(push [, id], n)
    370     // syntax.
    371     //
    372     // Push / pop a named sentinel slot.
    373     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
    374       assert((Action == PSK_Push || Action == PSK_Pop) &&
    375              "Can only push / pop #pragma stack sentinels!");
    376       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
    377     }
    378 
    379     // Constructors.
    380     explicit PragmaStack(const ValueType &Default)
    381         : DefaultValue(Default), CurrentValue(Default) {}
    382 
    383     SmallVector<Slot, 2> Stack;
    384     ValueType DefaultValue; // Value used for PSK_Reset action.
    385     ValueType CurrentValue;
    386     SourceLocation CurrentPragmaLocation;
    387   };
    388   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
    389   // we shouldn't do so if they're in a module).
    390 
    391   /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
    392   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
    393   ///
    394   /// 0: Suppress all vtordisps
    395   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
    396   ///    structors
    397   /// 2: Always insert vtordisps to support RTTI on partially constructed
    398   ///    objects
    399   PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
    400   // #pragma pack.
    401   // Sentinel to represent when the stack is set to mac68k alignment.
    402   static const unsigned kMac68kAlignmentSentinel = ~0U;
    403   PragmaStack<unsigned> PackStack;
    404   // Segment #pragmas.
    405   PragmaStack<StringLiteral *> DataSegStack;
    406   PragmaStack<StringLiteral *> BSSSegStack;
    407   PragmaStack<StringLiteral *> ConstSegStack;
    408   PragmaStack<StringLiteral *> CodeSegStack;
    409 
    410   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
    411   // Actions should be performed only if we enter / exit a C++ method body.
    412   class PragmaStackSentinelRAII {
    413   public:
    414     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
    415     ~PragmaStackSentinelRAII();
    416 
    417   private:
    418     Sema &S;
    419     StringRef SlotLabel;
    420     bool ShouldAct;
    421   };
    422 
    423   /// A mapping that describes the nullability we've seen in each header file.
    424   FileNullabilityMap NullabilityMap;
    425 
    426   /// Last section used with #pragma init_seg.
    427   StringLiteral *CurInitSeg;
    428   SourceLocation CurInitSegLoc;
    429 
    430   /// VisContext - Manages the stack for \#pragma GCC visibility.
    431   void *VisContext; // Really a "PragmaVisStack*"
    432 
    433   /// \brief This represents the last location of a "#pragma clang optimize off"
    434   /// directive if such a directive has not been closed by an "on" yet. If
    435   /// optimizations are currently "on", this is set to an invalid location.
    436   SourceLocation OptimizeOffPragmaLocation;
    437 
    438   /// \brief Flag indicating if Sema is building a recovery call expression.
    439   ///
    440   /// This flag is used to avoid building recovery call expressions
    441   /// if Sema is already doing so, which would cause infinite recursions.
    442   bool IsBuildingRecoveryCallExpr;
    443 
    444   /// Used to control the generation of ExprWithCleanups.
    445   CleanupInfo Cleanup;
    446 
    447   /// ExprCleanupObjects - This is the stack of objects requiring
    448   /// cleanup that are created by the current full expression.  The
    449   /// element type here is ExprWithCleanups::Object.
    450   SmallVector<BlockDecl*, 8> ExprCleanupObjects;
    451 
    452   /// \brief Store a list of either DeclRefExprs or MemberExprs
    453   ///  that contain a reference to a variable (constant) that may or may not
    454   ///  be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
    455   ///  and discarded value conversions have been applied to all subexpressions
    456   ///  of the enclosing full expression.  This is cleared at the end of each
    457   ///  full expression.
    458   llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
    459 
    460   /// \brief Stack containing information about each of the nested
    461   /// function, block, and method scopes that are currently active.
    462   ///
    463   /// This array is never empty.  Clients should ignore the first
    464   /// element, which is used to cache a single FunctionScopeInfo
    465   /// that's used to parse every top-level function.
    466   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
    467 
    468   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
    469                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
    470     ExtVectorDeclsType;
    471 
    472   /// ExtVectorDecls - This is a list all the extended vector types. This allows
    473   /// us to associate a raw vector type with one of the ext_vector type names.
    474   /// This is only necessary for issuing pretty diagnostics.
    475   ExtVectorDeclsType ExtVectorDecls;
    476 
    477   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
    478   std::unique_ptr<CXXFieldCollector> FieldCollector;
    479 
    480   typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
    481 
    482   /// \brief Set containing all declared private fields that are not used.
    483   NamedDeclSetType UnusedPrivateFields;
    484 
    485   /// \brief Set containing all typedefs that are likely unused.
    486   llvm::SmallSetVector<const TypedefNameDecl *, 4>
    487       UnusedLocalTypedefNameCandidates;
    488 
    489   /// \brief Delete-expressions to be analyzed at the end of translation unit
    490   ///
    491   /// This list contains class members, and locations of delete-expressions
    492   /// that could not be proven as to whether they mismatch with new-expression
    493   /// used in initializer of the field.
    494   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
    495   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
    496   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
    497 
    498   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
    499 
    500   /// PureVirtualClassDiagSet - a set of class declarations which we have
    501   /// emitted a list of pure virtual functions. Used to prevent emitting the
    502   /// same list more than once.
    503   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
    504 
    505   /// ParsingInitForAutoVars - a set of declarations with auto types for which
    506   /// we are currently parsing the initializer.
    507   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
    508 
    509   /// \brief Look for a locally scoped extern "C" declaration by the given name.
    510   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
    511 
    512   typedef LazyVector<VarDecl *, ExternalSemaSource,
    513                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
    514     TentativeDefinitionsType;
    515 
    516   /// \brief All the tentative definitions encountered in the TU.
    517   TentativeDefinitionsType TentativeDefinitions;
    518 
    519   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
    520                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
    521     UnusedFileScopedDeclsType;
    522 
    523   /// \brief The set of file scoped decls seen so far that have not been used
    524   /// and must warn if not used. Only contains the first declaration.
    525   UnusedFileScopedDeclsType UnusedFileScopedDecls;
    526 
    527   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
    528                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
    529     DelegatingCtorDeclsType;
    530 
    531   /// \brief All the delegating constructors seen so far in the file, used for
    532   /// cycle detection at the end of the TU.
    533   DelegatingCtorDeclsType DelegatingCtorDecls;
    534 
    535   /// \brief All the overriding functions seen during a class definition
    536   /// that had their exception spec checks delayed, plus the overridden
    537   /// function.
    538   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
    539     DelayedExceptionSpecChecks;
    540 
    541   /// \brief All the members seen during a class definition which were both
    542   /// explicitly defaulted and had explicitly-specified exception
    543   /// specifications, along with the function type containing their
    544   /// user-specified exception specification. Those exception specifications
    545   /// were overridden with the default specifications, but we still need to
    546   /// check whether they are compatible with the default specification, and
    547   /// we can't do that until the nesting set of class definitions is complete.
    548   SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
    549     DelayedDefaultedMemberExceptionSpecs;
    550 
    551   typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *>
    552       LateParsedTemplateMapT;
    553   LateParsedTemplateMapT LateParsedTemplateMap;
    554 
    555   /// \brief Callback to the parser to parse templated functions when needed.
    556   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
    557   typedef void LateTemplateParserCleanupCB(void *P);
    558   LateTemplateParserCB *LateTemplateParser;
    559   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
    560   void *OpaqueParser;
    561 
    562   void SetLateTemplateParser(LateTemplateParserCB *LTP,
    563                              LateTemplateParserCleanupCB *LTPCleanup,
    564                              void *P) {
    565     LateTemplateParser = LTP;
    566     LateTemplateParserCleanup = LTPCleanup;
    567     OpaqueParser = P;
    568   }
    569 
    570   class DelayedDiagnostics;
    571 
    572   class DelayedDiagnosticsState {
    573     sema::DelayedDiagnosticPool *SavedPool;
    574     friend class Sema::DelayedDiagnostics;
    575   };
    576   typedef DelayedDiagnosticsState ParsingDeclState;
    577   typedef DelayedDiagnosticsState ProcessingContextState;
    578 
    579   /// A class which encapsulates the logic for delaying diagnostics
    580   /// during parsing and other processing.
    581   class DelayedDiagnostics {
    582     /// \brief The current pool of diagnostics into which delayed
    583     /// diagnostics should go.
    584     sema::DelayedDiagnosticPool *CurPool;
    585 
    586   public:
    587     DelayedDiagnostics() : CurPool(nullptr) {}
    588 
    589     /// Adds a delayed diagnostic.
    590     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
    591 
    592     /// Determines whether diagnostics should be delayed.
    593     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
    594 
    595     /// Returns the current delayed-diagnostics pool.
    596     sema::DelayedDiagnosticPool *getCurrentPool() const {
    597       return CurPool;
    598     }
    599 
    600     /// Enter a new scope.  Access and deprecation diagnostics will be
    601     /// collected in this pool.
    602     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
    603       DelayedDiagnosticsState state;
    604       state.SavedPool = CurPool;
    605       CurPool = &pool;
    606       return state;
    607     }
    608 
    609     /// Leave a delayed-diagnostic state that was previously pushed.
    610     /// Do not emit any of the diagnostics.  This is performed as part
    611     /// of the bookkeeping of popping a pool "properly".
    612     void popWithoutEmitting(DelayedDiagnosticsState state) {
    613       CurPool = state.SavedPool;
    614     }
    615 
    616     /// Enter a new scope where access and deprecation diagnostics are
    617     /// not delayed.
    618     DelayedDiagnosticsState pushUndelayed() {
    619       DelayedDiagnosticsState state;
    620       state.SavedPool = CurPool;
    621       CurPool = nullptr;
    622       return state;
    623     }
    624 
    625     /// Undo a previous pushUndelayed().
    626     void popUndelayed(DelayedDiagnosticsState state) {
    627       assert(CurPool == nullptr);
    628       CurPool = state.SavedPool;
    629     }
    630   } DelayedDiagnostics;
    631 
    632   /// A RAII object to temporarily push a declaration context.
    633   class ContextRAII {
    634   private:
    635     Sema &S;
    636     DeclContext *SavedContext;
    637     ProcessingContextState SavedContextState;
    638     QualType SavedCXXThisTypeOverride;
    639 
    640   public:
    641     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
    642       : S(S), SavedContext(S.CurContext),
    643         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
    644         SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
    645     {
    646       assert(ContextToPush && "pushing null context");
    647       S.CurContext = ContextToPush;
    648       if (NewThisContext)
    649         S.CXXThisTypeOverride = QualType();
    650     }
    651 
    652     void pop() {
    653       if (!SavedContext) return;
    654       S.CurContext = SavedContext;
    655       S.DelayedDiagnostics.popUndelayed(SavedContextState);
    656       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
    657       SavedContext = nullptr;
    658     }
    659 
    660     ~ContextRAII() {
    661       pop();
    662     }
    663   };
    664 
    665   /// \brief RAII object to handle the state changes required to synthesize
    666   /// a function body.
    667   class SynthesizedFunctionScope {
    668     Sema &S;
    669     Sema::ContextRAII SavedContext;
    670 
    671   public:
    672     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
    673       : S(S), SavedContext(S, DC)
    674     {
    675       S.PushFunctionScope();
    676       S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
    677     }
    678 
    679     ~SynthesizedFunctionScope() {
    680       S.PopExpressionEvaluationContext();
    681       S.PopFunctionScopeInfo();
    682     }
    683   };
    684 
    685   /// WeakUndeclaredIdentifiers - Identifiers contained in
    686   /// \#pragma weak before declared. rare. may alias another
    687   /// identifier, declared or undeclared
    688   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
    689 
    690   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
    691   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
    692   /// to define functions that occur in multiple standards to call the version
    693   /// in the currently selected standard.
    694   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
    695 
    696 
    697   /// \brief Load weak undeclared identifiers from the external source.
    698   void LoadExternalWeakUndeclaredIdentifiers();
    699 
    700   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
    701   /// \#pragma weak during processing of other Decls.
    702   /// I couldn't figure out a clean way to generate these in-line, so
    703   /// we store them here and handle separately -- which is a hack.
    704   /// It would be best to refactor this.
    705   SmallVector<Decl*,2> WeakTopLevelDecl;
    706 
    707   IdentifierResolver IdResolver;
    708 
    709   /// Translation Unit Scope - useful to Objective-C actions that need
    710   /// to lookup file scope declarations in the "ordinary" C decl namespace.
    711   /// For example, user-defined classes, built-in "id" type, etc.
    712   Scope *TUScope;
    713 
    714   /// \brief The C++ "std" namespace, where the standard library resides.
    715   LazyDeclPtr StdNamespace;
    716 
    717   /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
    718   /// standard library.
    719   LazyDeclPtr StdBadAlloc;
    720 
    721   /// \brief The C++ "std::initializer_list" template, which is defined in
    722   /// \<initializer_list>.
    723   ClassTemplateDecl *StdInitializerList;
    724 
    725   /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
    726   RecordDecl *CXXTypeInfoDecl;
    727 
    728   /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
    729   RecordDecl *MSVCGuidDecl;
    730 
    731   /// \brief Caches identifiers/selectors for NSFoundation APIs.
    732   std::unique_ptr<NSAPI> NSAPIObj;
    733 
    734   /// \brief The declaration of the Objective-C NSNumber class.
    735   ObjCInterfaceDecl *NSNumberDecl;
    736 
    737   /// \brief The declaration of the Objective-C NSValue class.
    738   ObjCInterfaceDecl *NSValueDecl;
    739 
    740   /// \brief Pointer to NSNumber type (NSNumber *).
    741   QualType NSNumberPointer;
    742 
    743   /// \brief Pointer to NSValue type (NSValue *).
    744   QualType NSValuePointer;
    745 
    746   /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
    747   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
    748 
    749   /// \brief The declaration of the Objective-C NSString class.
    750   ObjCInterfaceDecl *NSStringDecl;
    751 
    752   /// \brief Pointer to NSString type (NSString *).
    753   QualType NSStringPointer;
    754 
    755   /// \brief The declaration of the stringWithUTF8String: method.
    756   ObjCMethodDecl *StringWithUTF8StringMethod;
    757 
    758   /// \brief The declaration of the valueWithBytes:objCType: method.
    759   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
    760 
    761   /// \brief The declaration of the Objective-C NSArray class.
    762   ObjCInterfaceDecl *NSArrayDecl;
    763 
    764   /// \brief The declaration of the arrayWithObjects:count: method.
    765   ObjCMethodDecl *ArrayWithObjectsMethod;
    766 
    767   /// \brief The declaration of the Objective-C NSDictionary class.
    768   ObjCInterfaceDecl *NSDictionaryDecl;
    769 
    770   /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
    771   ObjCMethodDecl *DictionaryWithObjectsMethod;
    772 
    773   /// \brief id<NSCopying> type.
    774   QualType QIDNSCopying;
    775 
    776   /// \brief will hold 'respondsToSelector:'
    777   Selector RespondsToSelectorSel;
    778 
    779   /// \brief counter for internal MS Asm label names.
    780   unsigned MSAsmLabelNameCounter;
    781 
    782   /// A flag to remember whether the implicit forms of operator new and delete
    783   /// have been declared.
    784   bool GlobalNewDeleteDeclared;
    785 
    786   /// A flag to indicate that we're in a context that permits abstract
    787   /// references to fields.  This is really a
    788   bool AllowAbstractFieldReference;
    789 
    790   /// \brief Describes how the expressions currently being parsed are
    791   /// evaluated at run-time, if at all.
    792   enum ExpressionEvaluationContext {
    793     /// \brief The current expression and its subexpressions occur within an
    794     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
    795     /// \c sizeof, where the type of the expression may be significant but
    796     /// no code will be generated to evaluate the value of the expression at
    797     /// run time.
    798     Unevaluated,
    799 
    800     /// \brief The current expression occurs within a discarded statement.
    801     /// This behaves largely similarly to an unevaluated operand in preventing
    802     /// definitions from being required, but not in other ways.
    803     DiscardedStatement,
    804 
    805     /// \brief The current expression occurs within an unevaluated
    806     /// operand that unconditionally permits abstract references to
    807     /// fields, such as a SIZE operator in MS-style inline assembly.
    808     UnevaluatedAbstract,
    809 
    810     /// \brief The current context is "potentially evaluated" in C++11 terms,
    811     /// but the expression is evaluated at compile-time (like the values of
    812     /// cases in a switch statement).
    813     ConstantEvaluated,
    814 
    815     /// \brief The current expression is potentially evaluated at run time,
    816     /// which means that code may be generated to evaluate the value of the
    817     /// expression at run time.
    818     PotentiallyEvaluated,
    819 
    820     /// \brief The current expression is potentially evaluated, but any
    821     /// declarations referenced inside that expression are only used if
    822     /// in fact the current expression is used.
    823     ///
    824     /// This value is used when parsing default function arguments, for which
    825     /// we would like to provide diagnostics (e.g., passing non-POD arguments
    826     /// through varargs) but do not want to mark declarations as "referenced"
    827     /// until the default argument is used.
    828     PotentiallyEvaluatedIfUsed
    829   };
    830 
    831   /// \brief Data structure used to record current or nested
    832   /// expression evaluation contexts.
    833   struct ExpressionEvaluationContextRecord {
    834     /// \brief The expression evaluation context.
    835     ExpressionEvaluationContext Context;
    836 
    837     /// \brief Whether the enclosing context needed a cleanup.
    838     CleanupInfo ParentCleanup;
    839 
    840     /// \brief Whether we are in a decltype expression.
    841     bool IsDecltype;
    842 
    843     /// \brief The number of active cleanup objects when we entered
    844     /// this expression evaluation context.
    845     unsigned NumCleanupObjects;
    846 
    847     /// \brief The number of typos encountered during this expression evaluation
    848     /// context (i.e. the number of TypoExprs created).
    849     unsigned NumTypos;
    850 
    851     llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
    852 
    853     /// \brief The lambdas that are present within this context, if it
    854     /// is indeed an unevaluated context.
    855     SmallVector<LambdaExpr *, 2> Lambdas;
    856 
    857     /// \brief The declaration that provides context for lambda expressions
    858     /// and block literals if the normal declaration context does not
    859     /// suffice, e.g., in a default function argument.
    860     Decl *ManglingContextDecl;
    861 
    862     /// \brief The context information used to mangle lambda expressions
    863     /// and block literals within this context.
    864     ///
    865     /// This mangling information is allocated lazily, since most contexts
    866     /// do not have lambda expressions or block literals.
    867     IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
    868 
    869     /// \brief If we are processing a decltype type, a set of call expressions
    870     /// for which we have deferred checking the completeness of the return type.
    871     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
    872 
    873     /// \brief If we are processing a decltype type, a set of temporary binding
    874     /// expressions for which we have deferred checking the destructor.
    875     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
    876 
    877     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
    878                                       unsigned NumCleanupObjects,
    879                                       CleanupInfo ParentCleanup,
    880                                       Decl *ManglingContextDecl,
    881                                       bool IsDecltype)
    882       : Context(Context), ParentCleanup(ParentCleanup),
    883         IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
    884         NumTypos(0),
    885         ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
    886 
    887     /// \brief Retrieve the mangling numbering context, used to consistently
    888     /// number constructs like lambdas for mangling.
    889     MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
    890 
    891     bool isUnevaluated() const {
    892       return Context == Unevaluated || Context == UnevaluatedAbstract;
    893     }
    894   };
    895 
    896   /// A stack of expression evaluation contexts.
    897   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
    898 
    899   /// \brief Compute the mangling number context for a lambda expression or
    900   /// block literal.
    901   ///
    902   /// \param DC - The DeclContext containing the lambda expression or
    903   /// block literal.
    904   /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
    905   /// associated with the context, if relevant.
    906   MangleNumberingContext *getCurrentMangleNumberContext(
    907     const DeclContext *DC,
    908     Decl *&ManglingContextDecl);
    909 
    910 
    911   /// SpecialMemberOverloadResult - The overloading result for a special member
    912   /// function.
    913   ///
    914   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
    915   /// integer are used to determine whether overload resolution succeeded.
    916   class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
    917   public:
    918     enum Kind {
    919       NoMemberOrDeleted,
    920       Ambiguous,
    921       Success
    922     };
    923 
    924   private:
    925     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
    926 
    927   public:
    928     SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
    929       : FastFoldingSetNode(ID)
    930     {}
    931 
    932     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
    933     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
    934 
    935     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
    936     void setKind(Kind K) { Pair.setInt(K); }
    937   };
    938 
    939   /// \brief A cache of special member function overload resolution results
    940   /// for C++ records.
    941   llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
    942 
    943   /// \brief A cache of the flags available in enumerations with the flag_bits
    944   /// attribute.
    945   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
    946 
    947   /// \brief The kind of translation unit we are processing.
    948   ///
    949   /// When we're processing a complete translation unit, Sema will perform
    950   /// end-of-translation-unit semantic tasks (such as creating
    951   /// initializers for tentative definitions in C) once parsing has
    952   /// completed. Modules and precompiled headers perform different kinds of
    953   /// checks.
    954   TranslationUnitKind TUKind;
    955 
    956   llvm::BumpPtrAllocator BumpAlloc;
    957 
    958   /// \brief The number of SFINAE diagnostics that have been trapped.
    959   unsigned NumSFINAEErrors;
    960 
    961   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
    962     UnparsedDefaultArgInstantiationsMap;
    963 
    964   /// \brief A mapping from parameters with unparsed default arguments to the
    965   /// set of instantiations of each parameter.
    966   ///
    967   /// This mapping is a temporary data structure used when parsing
    968   /// nested class templates or nested classes of class templates,
    969   /// where we might end up instantiating an inner class before the
    970   /// default arguments of its methods have been parsed.
    971   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
    972 
    973   // Contains the locations of the beginning of unparsed default
    974   // argument locations.
    975   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
    976 
    977   /// UndefinedInternals - all the used, undefined objects which require a
    978   /// definition in this translation unit.
    979   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
    980 
    981   /// Obtain a sorted list of functions that are undefined but ODR-used.
    982   void getUndefinedButUsed(
    983       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
    984 
    985   /// Retrieves list of suspicious delete-expressions that will be checked at
    986   /// the end of translation unit.
    987   const llvm::MapVector<FieldDecl *, DeleteLocs> &
    988   getMismatchingDeleteExpressions() const;
    989 
    990   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
    991   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
    992 
    993   /// Method Pool - allows efficient lookup when typechecking messages to "id".
    994   /// We need to maintain a list, since selectors can have differing signatures
    995   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
    996   /// of selectors are "overloaded").
    997   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
    998   /// methods inside categories with a particular selector.
    999   GlobalMethodPool MethodPool;
   1000 
   1001   /// Method selectors used in a \@selector expression. Used for implementation
   1002   /// of -Wselector.
   1003   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
   1004 
   1005   /// Kinds of C++ special members.
   1006   enum CXXSpecialMember {
   1007     CXXDefaultConstructor,
   1008     CXXCopyConstructor,
   1009     CXXMoveConstructor,
   1010     CXXCopyAssignment,
   1011     CXXMoveAssignment,
   1012     CXXDestructor,
   1013     CXXInvalid
   1014   };
   1015 
   1016   typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
   1017 
   1018   /// The C++ special members which we are currently in the process of
   1019   /// declaring. If this process recursively triggers the declaration of the
   1020   /// same special member, we should act as if it is not yet declared.
   1021   llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
   1022 
   1023   void ReadMethodPool(Selector Sel);
   1024   void updateOutOfDateSelector(Selector Sel);
   1025 
   1026   /// Private Helper predicate to check for 'self'.
   1027   bool isSelfExpr(Expr *RExpr);
   1028   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
   1029 
   1030   /// \brief Cause the active diagnostic on the DiagosticsEngine to be
   1031   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
   1032   /// should not be used elsewhere.
   1033   void EmitCurrentDiagnostic(unsigned DiagID);
   1034 
   1035   /// Records and restores the FP_CONTRACT state on entry/exit of compound
   1036   /// statements.
   1037   class FPContractStateRAII {
   1038   public:
   1039     FPContractStateRAII(Sema& S)
   1040       : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
   1041     ~FPContractStateRAII() {
   1042       S.FPFeatures.fp_contract = OldFPContractState;
   1043     }
   1044   private:
   1045     Sema& S;
   1046     bool OldFPContractState : 1;
   1047   };
   1048 
   1049   void addImplicitTypedef(StringRef Name, QualType T);
   1050 
   1051 public:
   1052   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
   1053        TranslationUnitKind TUKind = TU_Complete,
   1054        CodeCompleteConsumer *CompletionConsumer = nullptr);
   1055   ~Sema();
   1056 
   1057   /// \brief Perform initialization that occurs after the parser has been
   1058   /// initialized but before it parses anything.
   1059   void Initialize();
   1060 
   1061   const LangOptions &getLangOpts() const { return LangOpts; }
   1062   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
   1063   FPOptions     &getFPOptions() { return FPFeatures; }
   1064 
   1065   DiagnosticsEngine &getDiagnostics() const { return Diags; }
   1066   SourceManager &getSourceManager() const { return SourceMgr; }
   1067   Preprocessor &getPreprocessor() const { return PP; }
   1068   ASTContext &getASTContext() const { return Context; }
   1069   ASTConsumer &getASTConsumer() const { return Consumer; }
   1070   ASTMutationListener *getASTMutationListener() const;
   1071   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
   1072 
   1073   ///\brief Registers an external source. If an external source already exists,
   1074   /// creates a multiplex external source and appends to it.
   1075   ///
   1076   ///\param[in] E - A non-null external sema source.
   1077   ///
   1078   void addExternalSource(ExternalSemaSource *E);
   1079 
   1080   void PrintStats() const;
   1081 
   1082   /// \brief Helper class that creates diagnostics with optional
   1083   /// template instantiation stacks.
   1084   ///
   1085   /// This class provides a wrapper around the basic DiagnosticBuilder
   1086   /// class that emits diagnostics. SemaDiagnosticBuilder is
   1087   /// responsible for emitting the diagnostic (as DiagnosticBuilder
   1088   /// does) and, if the diagnostic comes from inside a template
   1089   /// instantiation, printing the template instantiation stack as
   1090   /// well.
   1091   class SemaDiagnosticBuilder : public DiagnosticBuilder {
   1092     Sema &SemaRef;
   1093     unsigned DiagID;
   1094 
   1095   public:
   1096     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
   1097       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
   1098 
   1099     // This is a cunning lie. DiagnosticBuilder actually performs move
   1100     // construction in its copy constructor (but due to varied uses, it's not
   1101     // possible to conveniently express this as actual move construction). So
   1102     // the default copy ctor here is fine, because the base class disables the
   1103     // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
   1104     // in that case anwyay.
   1105     SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
   1106 
   1107     ~SemaDiagnosticBuilder() {
   1108       // If we aren't active, there is nothing to do.
   1109       if (!isActive()) return;
   1110 
   1111       // Otherwise, we need to emit the diagnostic. First flush the underlying
   1112       // DiagnosticBuilder data, and clear the diagnostic builder itself so it
   1113       // won't emit the diagnostic in its own destructor.
   1114       //
   1115       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
   1116       // do its own needless checks to see if the diagnostic needs to be
   1117       // emitted. However, because we take care to ensure that the builder
   1118       // objects never escape, a sufficiently smart compiler will be able to
   1119       // eliminate that code.
   1120       FlushCounts();
   1121       Clear();
   1122 
   1123       // Dispatch to Sema to emit the diagnostic.
   1124       SemaRef.EmitCurrentDiagnostic(DiagID);
   1125     }
   1126 
   1127     /// Teach operator<< to produce an object of the correct type.
   1128     template<typename T>
   1129     friend const SemaDiagnosticBuilder &operator<<(
   1130         const SemaDiagnosticBuilder &Diag, const T &Value) {
   1131       const DiagnosticBuilder &BaseDiag = Diag;
   1132       BaseDiag << Value;
   1133       return Diag;
   1134     }
   1135   };
   1136 
   1137   /// \brief Emit a diagnostic.
   1138   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
   1139     DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
   1140     return SemaDiagnosticBuilder(DB, *this, DiagID);
   1141   }
   1142 
   1143   /// \brief Emit a partial diagnostic.
   1144   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
   1145 
   1146   /// \brief Build a partial diagnostic.
   1147   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
   1148 
   1149   bool findMacroSpelling(SourceLocation &loc, StringRef name);
   1150 
   1151   /// \brief Get a string to suggest for zero-initialization of a type.
   1152   std::string
   1153   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
   1154   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
   1155 
   1156   /// \brief Calls \c Lexer::getLocForEndOfToken()
   1157   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
   1158 
   1159   /// \brief Retrieve the module loader associated with the preprocessor.
   1160   ModuleLoader &getModuleLoader() const;
   1161 
   1162   void emitAndClearUnusedLocalTypedefWarnings();
   1163 
   1164   void ActOnEndOfTranslationUnit();
   1165 
   1166   void CheckDelegatingCtorCycles();
   1167 
   1168   Scope *getScopeForContext(DeclContext *Ctx);
   1169 
   1170   void PushFunctionScope();
   1171   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
   1172   sema::LambdaScopeInfo *PushLambdaScope();
   1173 
   1174   /// \brief This is used to inform Sema what the current TemplateParameterDepth
   1175   /// is during Parsing.  Currently it is used to pass on the depth
   1176   /// when parsing generic lambda 'auto' parameters.
   1177   void RecordParsingTemplateParameterDepth(unsigned Depth);
   1178 
   1179   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
   1180                                RecordDecl *RD,
   1181                                CapturedRegionKind K);
   1182   void
   1183   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
   1184                        const Decl *D = nullptr,
   1185                        const BlockExpr *blkExpr = nullptr);
   1186 
   1187   sema::FunctionScopeInfo *getCurFunction() const {
   1188     return FunctionScopes.back();
   1189   }
   1190 
   1191   sema::FunctionScopeInfo *getEnclosingFunction() const {
   1192     if (FunctionScopes.empty())
   1193       return nullptr;
   1194 
   1195     for (int e = FunctionScopes.size()-1; e >= 0; --e) {
   1196       if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
   1197         continue;
   1198       return FunctionScopes[e];
   1199     }
   1200     return nullptr;
   1201   }
   1202 
   1203   template <typename ExprT>
   1204   void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
   1205     if (!isUnevaluatedContext())
   1206       getCurFunction()->recordUseOfWeak(E, IsRead);
   1207   }
   1208 
   1209   void PushCompoundScope();
   1210   void PopCompoundScope();
   1211 
   1212   sema::CompoundScopeInfo &getCurCompoundScope() const;
   1213 
   1214   bool hasAnyUnrecoverableErrorsInThisFunction() const;
   1215 
   1216   /// \brief Retrieve the current block, if any.
   1217   sema::BlockScopeInfo *getCurBlock();
   1218 
   1219   /// \brief Retrieve the current lambda scope info, if any.
   1220   sema::LambdaScopeInfo *getCurLambda();
   1221 
   1222   /// \brief Retrieve the current generic lambda info, if any.
   1223   sema::LambdaScopeInfo *getCurGenericLambda();
   1224 
   1225   /// \brief Retrieve the current captured region, if any.
   1226   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
   1227 
   1228   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
   1229   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
   1230 
   1231   void ActOnComment(SourceRange Comment);
   1232 
   1233   //===--------------------------------------------------------------------===//
   1234   // Type Analysis / Processing: SemaType.cpp.
   1235   //
   1236 
   1237   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
   1238                               const DeclSpec *DS = nullptr);
   1239   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
   1240                               const DeclSpec *DS = nullptr);
   1241   QualType BuildPointerType(QualType T,
   1242                             SourceLocation Loc, DeclarationName Entity);
   1243   QualType BuildReferenceType(QualType T, bool LValueRef,
   1244                               SourceLocation Loc, DeclarationName Entity);
   1245   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
   1246                           Expr *ArraySize, unsigned Quals,
   1247                           SourceRange Brackets, DeclarationName Entity);
   1248   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
   1249                               SourceLocation AttrLoc);
   1250 
   1251   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
   1252 
   1253   /// \brief Build a function type.
   1254   ///
   1255   /// This routine checks the function type according to C++ rules and
   1256   /// under the assumption that the result type and parameter types have
   1257   /// just been instantiated from a template. It therefore duplicates
   1258   /// some of the behavior of GetTypeForDeclarator, but in a much
   1259   /// simpler form that is only suitable for this narrow use case.
   1260   ///
   1261   /// \param T The return type of the function.
   1262   ///
   1263   /// \param ParamTypes The parameter types of the function. This array
   1264   /// will be modified to account for adjustments to the types of the
   1265   /// function parameters.
   1266   ///
   1267   /// \param Loc The location of the entity whose type involves this
   1268   /// function type or, if there is no such entity, the location of the
   1269   /// type that will have function type.
   1270   ///
   1271   /// \param Entity The name of the entity that involves the function
   1272   /// type, if known.
   1273   ///
   1274   /// \param EPI Extra information about the function type. Usually this will
   1275   /// be taken from an existing function with the same prototype.
   1276   ///
   1277   /// \returns A suitable function type, if there are no errors. The
   1278   /// unqualified type will always be a FunctionProtoType.
   1279   /// Otherwise, returns a NULL type.
   1280   QualType BuildFunctionType(QualType T,
   1281                              MutableArrayRef<QualType> ParamTypes,
   1282                              SourceLocation Loc, DeclarationName Entity,
   1283                              const FunctionProtoType::ExtProtoInfo &EPI);
   1284 
   1285   QualType BuildMemberPointerType(QualType T, QualType Class,
   1286                                   SourceLocation Loc,
   1287                                   DeclarationName Entity);
   1288   QualType BuildBlockPointerType(QualType T,
   1289                                  SourceLocation Loc, DeclarationName Entity);
   1290   QualType BuildParenType(QualType T);
   1291   QualType BuildAtomicType(QualType T, SourceLocation Loc);
   1292   QualType BuildPipeType(QualType T,
   1293                          SourceLocation Loc);
   1294 
   1295   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
   1296   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
   1297   TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
   1298                                                TypeSourceInfo *ReturnTypeInfo);
   1299 
   1300   /// \brief Package the given type and TSI into a ParsedType.
   1301   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
   1302   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
   1303   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
   1304   static QualType GetTypeFromParser(ParsedType Ty,
   1305                                     TypeSourceInfo **TInfo = nullptr);
   1306   CanThrowResult canThrow(const Expr *E);
   1307   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
   1308                                                 const FunctionProtoType *FPT);
   1309   void UpdateExceptionSpec(FunctionDecl *FD,
   1310                            const FunctionProtoType::ExceptionSpecInfo &ESI);
   1311   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
   1312   bool CheckDistantExceptionSpec(QualType T);
   1313   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
   1314   bool CheckEquivalentExceptionSpec(
   1315       const FunctionProtoType *Old, SourceLocation OldLoc,
   1316       const FunctionProtoType *New, SourceLocation NewLoc);
   1317   bool CheckEquivalentExceptionSpec(
   1318       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
   1319       const FunctionProtoType *Old, SourceLocation OldLoc,
   1320       const FunctionProtoType *New, SourceLocation NewLoc,
   1321       bool *MissingExceptionSpecification = nullptr,
   1322       bool *MissingEmptyExceptionSpecification = nullptr,
   1323       bool AllowNoexceptAllMatchWithNoSpec = false,
   1324       bool IsOperatorNew = false);
   1325   bool CheckExceptionSpecSubset(
   1326       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
   1327       const FunctionProtoType *Superset, SourceLocation SuperLoc,
   1328       const FunctionProtoType *Subset, SourceLocation SubLoc);
   1329   bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
   1330       const FunctionProtoType *Target, SourceLocation TargetLoc,
   1331       const FunctionProtoType *Source, SourceLocation SourceLoc);
   1332 
   1333   TypeResult ActOnTypeName(Scope *S, Declarator &D);
   1334 
   1335   /// \brief The parser has parsed the context-sensitive type 'instancetype'
   1336   /// in an Objective-C message declaration. Return the appropriate type.
   1337   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
   1338 
   1339   /// \brief Abstract class used to diagnose incomplete types.
   1340   struct TypeDiagnoser {
   1341     TypeDiagnoser() {}
   1342 
   1343     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
   1344     virtual ~TypeDiagnoser() {}
   1345   };
   1346 
   1347   static int getPrintable(int I) { return I; }
   1348   static unsigned getPrintable(unsigned I) { return I; }
   1349   static bool getPrintable(bool B) { return B; }
   1350   static const char * getPrintable(const char *S) { return S; }
   1351   static StringRef getPrintable(StringRef S) { return S; }
   1352   static const std::string &getPrintable(const std::string &S) { return S; }
   1353   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
   1354     return II;
   1355   }
   1356   static DeclarationName getPrintable(DeclarationName N) { return N; }
   1357   static QualType getPrintable(QualType T) { return T; }
   1358   static SourceRange getPrintable(SourceRange R) { return R; }
   1359   static SourceRange getPrintable(SourceLocation L) { return L; }
   1360   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
   1361   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
   1362 
   1363   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
   1364     unsigned DiagID;
   1365     std::tuple<const Ts &...> Args;
   1366 
   1367     template <std::size_t... Is>
   1368     void emit(const SemaDiagnosticBuilder &DB,
   1369               llvm::index_sequence<Is...>) const {
   1370       // Apply all tuple elements to the builder in order.
   1371       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
   1372       (void)Dummy;
   1373     }
   1374 
   1375   public:
   1376     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
   1377         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
   1378       assert(DiagID != 0 && "no diagnostic for type diagnoser");
   1379     }
   1380 
   1381     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
   1382       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
   1383       emit(DB, llvm::index_sequence_for<Ts...>());
   1384       DB << T;
   1385     }
   1386   };
   1387 
   1388 private:
   1389   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
   1390                                TypeDiagnoser *Diagnoser);
   1391 
   1392   VisibleModuleSet VisibleModules;
   1393   llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
   1394 
   1395   Module *CachedFakeTopLevelModule;
   1396 
   1397 public:
   1398   /// \brief Get the module owning an entity.
   1399   Module *getOwningModule(Decl *Entity);
   1400 
   1401   /// \brief Make a merged definition of an existing hidden definition \p ND
   1402   /// visible at the specified location.
   1403   void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
   1404 
   1405   bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
   1406 
   1407   /// Determine whether a declaration is visible to name lookup.
   1408   bool isVisible(const NamedDecl *D) {
   1409     return !D->isHidden() || isVisibleSlow(D);
   1410   }
   1411 
   1412   /// Determine whether any declaration of an entity is visible.
   1413   bool
   1414   hasVisibleDeclaration(const NamedDecl *D,
   1415                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
   1416     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
   1417   }
   1418   bool hasVisibleDeclarationSlow(const NamedDecl *D,
   1419                                  llvm::SmallVectorImpl<Module *> *Modules);
   1420 
   1421   bool hasVisibleMergedDefinition(NamedDecl *Def);
   1422 
   1423   /// Determine if \p D has a visible definition. If not, suggest a declaration
   1424   /// that should be made visible to expose the definition.
   1425   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
   1426                             bool OnlyNeedComplete = false);
   1427   bool hasVisibleDefinition(const NamedDecl *D) {
   1428     NamedDecl *Hidden;
   1429     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
   1430   }
   1431 
   1432   /// Determine if the template parameter \p D has a visible default argument.
   1433   bool
   1434   hasVisibleDefaultArgument(const NamedDecl *D,
   1435                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
   1436 
   1437   /// Determine if there is a visible declaration of \p D that is a member
   1438   /// specialization declaration (as opposed to an instantiated declaration).
   1439   bool hasVisibleMemberSpecialization(
   1440       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
   1441 
   1442   /// Determine if \p A and \p B are equivalent internal linkage declarations
   1443   /// from different modules, and thus an ambiguity error can be downgraded to
   1444   /// an extension warning.
   1445   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
   1446                                               const NamedDecl *B);
   1447   void diagnoseEquivalentInternalLinkageDeclarations(
   1448       SourceLocation Loc, const NamedDecl *D,
   1449       ArrayRef<const NamedDecl *> Equiv);
   1450 
   1451   bool isCompleteType(SourceLocation Loc, QualType T) {
   1452     return !RequireCompleteTypeImpl(Loc, T, nullptr);
   1453   }
   1454   bool RequireCompleteType(SourceLocation Loc, QualType T,
   1455                            TypeDiagnoser &Diagnoser);
   1456   bool RequireCompleteType(SourceLocation Loc, QualType T,
   1457                            unsigned DiagID);
   1458 
   1459   template <typename... Ts>
   1460   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
   1461                            const Ts &...Args) {
   1462     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
   1463     return RequireCompleteType(Loc, T, Diagnoser);
   1464   }
   1465 
   1466   void completeExprArrayBound(Expr *E);
   1467   bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
   1468   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
   1469 
   1470   template <typename... Ts>
   1471   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
   1472     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
   1473     return RequireCompleteExprType(E, Diagnoser);
   1474   }
   1475 
   1476   bool RequireLiteralType(SourceLocation Loc, QualType T,
   1477                           TypeDiagnoser &Diagnoser);
   1478   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
   1479 
   1480   template <typename... Ts>
   1481   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
   1482                           const Ts &...Args) {
   1483     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
   1484     return RequireLiteralType(Loc, T, Diagnoser);
   1485   }
   1486 
   1487   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
   1488                              const CXXScopeSpec &SS, QualType T);
   1489 
   1490   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
   1491   /// If AsUnevaluated is false, E is treated as though it were an evaluated
   1492   /// context, such as when building a type for decltype(auto).
   1493   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
   1494                              bool AsUnevaluated = true);
   1495   QualType BuildUnaryTransformType(QualType BaseType,
   1496                                    UnaryTransformType::UTTKind UKind,
   1497                                    SourceLocation Loc);
   1498 
   1499   //===--------------------------------------------------------------------===//
   1500   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
   1501   //
   1502 
   1503   struct SkipBodyInfo {
   1504     SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
   1505     bool ShouldSkip;
   1506     NamedDecl *Previous;
   1507   };
   1508 
   1509   /// List of decls defined in a function prototype. This contains EnumConstants
   1510   /// that incorrectly end up in translation unit scope because there is no
   1511   /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
   1512   /// them into the FunctionDecl.
   1513   std::vector<NamedDecl*> DeclsInPrototypeScope;
   1514 
   1515   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
   1516 
   1517   void DiagnoseUseOfUnimplementedSelectors();
   1518 
   1519   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
   1520 
   1521   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
   1522                          Scope *S, CXXScopeSpec *SS = nullptr,
   1523                          bool isClassName = false, bool HasTrailingDot = false,
   1524                          ParsedType ObjectType = nullptr,
   1525                          bool IsCtorOrDtorName = false,
   1526                          bool WantNontrivialTypeSourceInfo = false,
   1527                          IdentifierInfo **CorrectedII = nullptr);
   1528   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
   1529   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
   1530   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
   1531                                SourceLocation IILoc,
   1532                                Scope *S,
   1533                                CXXScopeSpec *SS,
   1534                                ParsedType &SuggestedType,
   1535                                bool AllowClassTemplates = false);
   1536 
   1537   /// Attempt to behave like MSVC in situations where lookup of an unqualified
   1538   /// type name has failed in a dependent context. In these situations, we
   1539   /// automatically form a DependentTypeName that will retry lookup in a related
   1540   /// scope during instantiation.
   1541   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
   1542                                       SourceLocation NameLoc,
   1543                                       bool IsTemplateTypeArg);
   1544 
   1545   /// \brief Describes the result of the name lookup and resolution performed
   1546   /// by \c ClassifyName().
   1547   enum NameClassificationKind {
   1548     NC_Unknown,
   1549     NC_Error,
   1550     NC_Keyword,
   1551     NC_Type,
   1552     NC_Expression,
   1553     NC_NestedNameSpecifier,
   1554     NC_TypeTemplate,
   1555     NC_VarTemplate,
   1556     NC_FunctionTemplate
   1557   };
   1558 
   1559   class NameClassification {
   1560     NameClassificationKind Kind;
   1561     ExprResult Expr;
   1562     TemplateName Template;
   1563     ParsedType Type;
   1564     const IdentifierInfo *Keyword;
   1565 
   1566     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
   1567 
   1568   public:
   1569     NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
   1570 
   1571     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
   1572 
   1573     NameClassification(const IdentifierInfo *Keyword)
   1574       : Kind(NC_Keyword), Keyword(Keyword) { }
   1575 
   1576     static NameClassification Error() {
   1577       return NameClassification(NC_Error);
   1578     }
   1579 
   1580     static NameClassification Unknown() {
   1581       return NameClassification(NC_Unknown);
   1582     }
   1583 
   1584     static NameClassification NestedNameSpecifier() {
   1585       return NameClassification(NC_NestedNameSpecifier);
   1586     }
   1587 
   1588     static NameClassification TypeTemplate(TemplateName Name) {
   1589       NameClassification Result(NC_TypeTemplate);
   1590       Result.Template = Name;
   1591       return Result;
   1592     }
   1593 
   1594     static NameClassification VarTemplate(TemplateName Name) {
   1595       NameClassification Result(NC_VarTemplate);
   1596       Result.Template = Name;
   1597       return Result;
   1598     }
   1599 
   1600     static NameClassification FunctionTemplate(TemplateName Name) {
   1601       NameClassification Result(NC_FunctionTemplate);
   1602       Result.Template = Name;
   1603       return Result;
   1604     }
   1605 
   1606     NameClassificationKind getKind() const { return Kind; }
   1607 
   1608     ParsedType getType() const {
   1609       assert(Kind == NC_Type);
   1610       return Type;
   1611     }
   1612 
   1613     ExprResult getExpression() const {
   1614       assert(Kind == NC_Expression);
   1615       return Expr;
   1616     }
   1617 
   1618     TemplateName getTemplateName() const {
   1619       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
   1620              Kind == NC_VarTemplate);
   1621       return Template;
   1622     }
   1623 
   1624     TemplateNameKind getTemplateNameKind() const {
   1625       switch (Kind) {
   1626       case NC_TypeTemplate:
   1627         return TNK_Type_template;
   1628       case NC_FunctionTemplate:
   1629         return TNK_Function_template;
   1630       case NC_VarTemplate:
   1631         return TNK_Var_template;
   1632       default:
   1633         llvm_unreachable("unsupported name classification.");
   1634       }
   1635     }
   1636   };
   1637 
   1638   /// \brief Perform name lookup on the given name, classifying it based on
   1639   /// the results of name lookup and the following token.
   1640   ///
   1641   /// This routine is used by the parser to resolve identifiers and help direct
   1642   /// parsing. When the identifier cannot be found, this routine will attempt
   1643   /// to correct the typo and classify based on the resulting name.
   1644   ///
   1645   /// \param S The scope in which we're performing name lookup.
   1646   ///
   1647   /// \param SS The nested-name-specifier that precedes the name.
   1648   ///
   1649   /// \param Name The identifier. If typo correction finds an alternative name,
   1650   /// this pointer parameter will be updated accordingly.
   1651   ///
   1652   /// \param NameLoc The location of the identifier.
   1653   ///
   1654   /// \param NextToken The token following the identifier. Used to help
   1655   /// disambiguate the name.
   1656   ///
   1657   /// \param IsAddressOfOperand True if this name is the operand of a unary
   1658   ///        address of ('&') expression, assuming it is classified as an
   1659   ///        expression.
   1660   ///
   1661   /// \param CCC The correction callback, if typo correction is desired.
   1662   NameClassification
   1663   ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
   1664                SourceLocation NameLoc, const Token &NextToken,
   1665                bool IsAddressOfOperand,
   1666                std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
   1667 
   1668   Decl *ActOnDeclarator(Scope *S, Declarator &D);
   1669 
   1670   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
   1671                               MultiTemplateParamsArg TemplateParameterLists);
   1672   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
   1673   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
   1674   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
   1675                                     DeclarationName Name,
   1676                                     SourceLocation Loc);
   1677   void
   1678   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
   1679                             SourceLocation FallbackLoc,
   1680                             SourceLocation ConstQualLoc = SourceLocation(),
   1681                             SourceLocation VolatileQualLoc = SourceLocation(),
   1682                             SourceLocation RestrictQualLoc = SourceLocation(),
   1683                             SourceLocation AtomicQualLoc = SourceLocation(),
   1684                             SourceLocation UnalignedQualLoc = SourceLocation());
   1685 
   1686   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
   1687   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
   1688   void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
   1689   void CheckShadow(Scope *S, VarDecl *D);
   1690 
   1691   /// Warn if 'E', which is an expression that is about to be modified, refers
   1692   /// to a shadowing declaration.
   1693   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
   1694 
   1695 private:
   1696   /// Map of current shadowing declarations to shadowed declarations. Warn if
   1697   /// it looks like the user is trying to modify the shadowing declaration.
   1698   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
   1699 
   1700 public:
   1701   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
   1702   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
   1703   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
   1704                                     TypedefNameDecl *NewTD);
   1705   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
   1706   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
   1707                                     TypeSourceInfo *TInfo,
   1708                                     LookupResult &Previous);
   1709   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
   1710                                   LookupResult &Previous, bool &Redeclaration);
   1711   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
   1712                                      TypeSourceInfo *TInfo,
   1713                                      LookupResult &Previous,
   1714                                      MultiTemplateParamsArg TemplateParamLists,
   1715                                      bool &AddToScope);
   1716   // Returns true if the variable declaration is a redeclaration
   1717   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
   1718   void CheckVariableDeclarationType(VarDecl *NewVD);
   1719   void CheckCompleteVariableDeclaration(VarDecl *var);
   1720   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
   1721 
   1722   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
   1723                                      TypeSourceInfo *TInfo,
   1724                                      LookupResult &Previous,
   1725                                      MultiTemplateParamsArg TemplateParamLists,
   1726                                      bool &AddToScope);
   1727   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
   1728 
   1729   bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
   1730   bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
   1731 
   1732   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
   1733   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
   1734                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
   1735   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
   1736                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
   1737   // Returns true if the function declaration is a redeclaration
   1738   bool CheckFunctionDeclaration(Scope *S,
   1739                                 FunctionDecl *NewFD, LookupResult &Previous,
   1740                                 bool IsExplicitSpecialization);
   1741   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
   1742   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
   1743   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
   1744   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
   1745                                           SourceLocation Loc,
   1746                                           QualType T);
   1747   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
   1748                               SourceLocation NameLoc, IdentifierInfo *Name,
   1749                               QualType T, TypeSourceInfo *TSInfo,
   1750                               StorageClass SC);
   1751   void ActOnParamDefaultArgument(Decl *param,
   1752                                  SourceLocation EqualLoc,
   1753                                  Expr *defarg);
   1754   void ActOnParamUnparsedDefaultArgument(Decl *param,
   1755                                          SourceLocation EqualLoc,
   1756                                          SourceLocation ArgLoc);
   1757   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
   1758   bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
   1759                                SourceLocation EqualLoc);
   1760 
   1761   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
   1762                             bool TypeMayContainAuto);
   1763   void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
   1764   void ActOnInitializerError(Decl *Dcl);
   1765   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
   1766   void ActOnCXXForRangeDecl(Decl *D);
   1767   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
   1768                                         IdentifierInfo *Ident,
   1769                                         ParsedAttributes &Attrs,
   1770                                         SourceLocation AttrEnd);
   1771   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
   1772   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
   1773   void FinalizeDeclaration(Decl *D);
   1774   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
   1775                                          ArrayRef<Decl *> Group);
   1776   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
   1777                                       bool TypeMayContainAuto = true);
   1778 
   1779   /// Should be called on all declarations that might have attached
   1780   /// documentation comments.
   1781   void ActOnDocumentableDecl(Decl *D);
   1782   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
   1783 
   1784   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
   1785                                        SourceLocation LocAfterDecls);
   1786   void CheckForFunctionRedefinition(
   1787       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
   1788       SkipBodyInfo *SkipBody = nullptr);
   1789   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
   1790                                 MultiTemplateParamsArg TemplateParamLists,
   1791                                 SkipBodyInfo *SkipBody = nullptr);
   1792   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
   1793                                 SkipBodyInfo *SkipBody = nullptr);
   1794   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
   1795   bool isObjCMethodDecl(Decl *D) {
   1796     return D && isa<ObjCMethodDecl>(D);
   1797   }
   1798 
   1799   /// \brief Determine whether we can delay parsing the body of a function or
   1800   /// function template until it is used, assuming we don't care about emitting
   1801   /// code for that function.
   1802   ///
   1803   /// This will be \c false if we may need the body of the function in the
   1804   /// middle of parsing an expression (where it's impractical to switch to
   1805   /// parsing a different function), for instance, if it's constexpr in C++11
   1806   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
   1807   bool canDelayFunctionBody(const Declarator &D);
   1808 
   1809   /// \brief Determine whether we can skip parsing the body of a function
   1810   /// definition, assuming we don't care about analyzing its body or emitting
   1811   /// code for that function.
   1812   ///
   1813   /// This will be \c false only if we may need the body of the function in
   1814   /// order to parse the rest of the program (for instance, if it is
   1815   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
   1816   bool canSkipFunctionBody(Decl *D);
   1817 
   1818   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
   1819   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
   1820   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
   1821   Decl *ActOnSkippedFunctionBody(Decl *Decl);
   1822   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
   1823 
   1824   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
   1825   /// attribute for which parsing is delayed.
   1826   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
   1827 
   1828   /// \brief Diagnose any unused parameters in the given sequence of
   1829   /// ParmVarDecl pointers.
   1830   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
   1831 
   1832   /// \brief Diagnose whether the size of parameters or return value of a
   1833   /// function or obj-c method definition is pass-by-value and larger than a
   1834   /// specified threshold.
   1835   void
   1836   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
   1837                                          QualType ReturnTy, NamedDecl *D);
   1838 
   1839   void DiagnoseInvalidJumps(Stmt *Body);
   1840   Decl *ActOnFileScopeAsmDecl(Expr *expr,
   1841                               SourceLocation AsmLoc,
   1842                               SourceLocation RParenLoc);
   1843 
   1844   /// \brief Handle a C++11 empty-declaration and attribute-declaration.
   1845   Decl *ActOnEmptyDeclaration(Scope *S,
   1846                               AttributeList *AttrList,
   1847                               SourceLocation SemiLoc);
   1848 
   1849   /// \brief The parser has processed a module import declaration.
   1850   ///
   1851   /// \param AtLoc The location of the '@' symbol, if any.
   1852   ///
   1853   /// \param ImportLoc The location of the 'import' keyword.
   1854   ///
   1855   /// \param Path The module access path.
   1856   DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
   1857                                ModuleIdPath Path);
   1858 
   1859   /// \brief The parser has processed a module import translated from a
   1860   /// #include or similar preprocessing directive.
   1861   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
   1862 
   1863   /// \brief The parsed has entered a submodule.
   1864   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
   1865   /// \brief The parser has left a submodule.
   1866   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
   1867 
   1868   /// \brief Check if module import may be found in the current context,
   1869   /// emit error if not.
   1870   void diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc);
   1871 
   1872   /// \brief Create an implicit import of the given module at the given
   1873   /// source location, for error recovery, if possible.
   1874   ///
   1875   /// This routine is typically used when an entity found by name lookup
   1876   /// is actually hidden within a module that we know about but the user
   1877   /// has forgotten to import.
   1878   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
   1879                                                   Module *Mod);
   1880 
   1881   /// Kinds of missing import. Note, the values of these enumerators correspond
   1882   /// to %select values in diagnostics.
   1883   enum class MissingImportKind {
   1884     Declaration,
   1885     Definition,
   1886     DefaultArgument,
   1887     ExplicitSpecialization,
   1888     PartialSpecialization
   1889   };
   1890 
   1891   /// \brief Diagnose that the specified declaration needs to be visible but
   1892   /// isn't, and suggest a module import that would resolve the problem.
   1893   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
   1894                              MissingImportKind MIK, bool Recover = true);
   1895   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
   1896                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
   1897                              MissingImportKind MIK, bool Recover);
   1898 
   1899   /// \brief We've found a use of a templated declaration that would trigger an
   1900   /// implicit instantiation. Check that any relevant explicit specializations
   1901   /// and partial specializations are visible, and diagnose if not.
   1902   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
   1903 
   1904   /// \brief We've found a use of a template specialization that would select a
   1905   /// partial specialization. Check that the partial specialization is visible,
   1906   /// and diagnose if not.
   1907   void checkPartialSpecializationVisibility(SourceLocation Loc,
   1908                                             NamedDecl *Spec);
   1909 
   1910   /// \brief Retrieve a suitable printing policy.
   1911   PrintingPolicy getPrintingPolicy() const {
   1912     return getPrintingPolicy(Context, PP);
   1913   }
   1914 
   1915   /// \brief Retrieve a suitable printing policy.
   1916   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
   1917                                           const Preprocessor &PP);
   1918 
   1919   /// Scope actions.
   1920   void ActOnPopScope(SourceLocation Loc, Scope *S);
   1921   void ActOnTranslationUnitScope(Scope *S);
   1922 
   1923   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
   1924                                    RecordDecl *&AnonRecord);
   1925   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
   1926                                    MultiTemplateParamsArg TemplateParams,
   1927                                    bool IsExplicitInstantiation,
   1928                                    RecordDecl *&AnonRecord);
   1929 
   1930   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
   1931                                     AccessSpecifier AS,
   1932                                     RecordDecl *Record,
   1933                                     const PrintingPolicy &Policy);
   1934 
   1935   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
   1936                                        RecordDecl *Record);
   1937 
   1938   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
   1939                                     TagTypeKind NewTag, bool isDefinition,
   1940                                     SourceLocation NewTagLoc,
   1941                                     const IdentifierInfo *Name);
   1942 
   1943   enum TagUseKind {
   1944     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
   1945     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
   1946     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
   1947     TUK_Friend       // Friend declaration:  'friend struct foo;'
   1948   };
   1949 
   1950   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
   1951                  SourceLocation KWLoc, CXXScopeSpec &SS,
   1952                  IdentifierInfo *Name, SourceLocation NameLoc,
   1953                  AttributeList *Attr, AccessSpecifier AS,
   1954                  SourceLocation ModulePrivateLoc,
   1955                  MultiTemplateParamsArg TemplateParameterLists,
   1956                  bool &OwnedDecl, bool &IsDependent,
   1957                  SourceLocation ScopedEnumKWLoc,
   1958                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
   1959                  bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
   1960 
   1961   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
   1962                                 unsigned TagSpec, SourceLocation TagLoc,
   1963                                 CXXScopeSpec &SS,
   1964                                 IdentifierInfo *Name, SourceLocation NameLoc,
   1965                                 AttributeList *Attr,
   1966                                 MultiTemplateParamsArg TempParamLists);
   1967 
   1968   TypeResult ActOnDependentTag(Scope *S,
   1969                                unsigned TagSpec,
   1970                                TagUseKind TUK,
   1971                                const CXXScopeSpec &SS,
   1972                                IdentifierInfo *Name,
   1973                                SourceLocation TagLoc,
   1974                                SourceLocation NameLoc);
   1975 
   1976   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
   1977                  IdentifierInfo *ClassName,
   1978                  SmallVectorImpl<Decl *> &Decls);
   1979   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
   1980                    Declarator &D, Expr *BitfieldWidth);
   1981 
   1982   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
   1983                          Declarator &D, Expr *BitfieldWidth,
   1984                          InClassInitStyle InitStyle,
   1985                          AccessSpecifier AS);
   1986   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
   1987                                    SourceLocation DeclStart,
   1988                                    Declarator &D, Expr *BitfieldWidth,
   1989                                    InClassInitStyle InitStyle,
   1990                                    AccessSpecifier AS,
   1991                                    AttributeList *MSPropertyAttr);
   1992 
   1993   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
   1994                             TypeSourceInfo *TInfo,
   1995                             RecordDecl *Record, SourceLocation Loc,
   1996                             bool Mutable, Expr *BitfieldWidth,
   1997                             InClassInitStyle InitStyle,
   1998                             SourceLocation TSSL,
   1999                             AccessSpecifier AS, NamedDecl *PrevDecl,
   2000                             Declarator *D = nullptr);
   2001 
   2002   bool CheckNontrivialField(FieldDecl *FD);
   2003   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
   2004   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
   2005                               bool Diagnose = false);
   2006   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
   2007   void ActOnLastBitfield(SourceLocation DeclStart,
   2008                          SmallVectorImpl<Decl *> &AllIvarDecls);
   2009   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
   2010                   Declarator &D, Expr *BitfieldWidth,
   2011                   tok::ObjCKeywordKind visibility);
   2012 
   2013   // This is used for both record definitions and ObjC interface declarations.
   2014   void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
   2015                    ArrayRef<Decl *> Fields,
   2016                    SourceLocation LBrac, SourceLocation RBrac,
   2017                    AttributeList *AttrList);
   2018 
   2019   /// ActOnTagStartDefinition - Invoked when we have entered the
   2020   /// scope of a tag's definition (e.g., for an enumeration, class,
   2021   /// struct, or union).
   2022   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
   2023 
   2024   typedef void *SkippedDefinitionContext;
   2025 
   2026   /// \brief Invoked when we enter a tag definition that we're skipping.
   2027   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
   2028 
   2029   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
   2030 
   2031   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
   2032   /// C++ record definition's base-specifiers clause and are starting its
   2033   /// member declarations.
   2034   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
   2035                                        SourceLocation FinalLoc,
   2036                                        bool IsFinalSpelledSealed,
   2037                                        SourceLocation LBraceLoc);
   2038 
   2039   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
   2040   /// the definition of a tag (enumeration, class, struct, or union).
   2041   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
   2042                                 SourceLocation RBraceLoc);
   2043 
   2044   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
   2045 
   2046   void ActOnObjCContainerFinishDefinition();
   2047 
   2048   /// \brief Invoked when we must temporarily exit the objective-c container
   2049   /// scope for parsing/looking-up C constructs.
   2050   ///
   2051   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
   2052   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
   2053   void ActOnObjCReenterContainerContext(DeclContext *DC);
   2054 
   2055   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
   2056   /// error parsing the definition of a tag.
   2057   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
   2058 
   2059   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
   2060                                       EnumConstantDecl *LastEnumConst,
   2061                                       SourceLocation IdLoc,
   2062                                       IdentifierInfo *Id,
   2063                                       Expr *val);
   2064   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
   2065   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
   2066                               QualType EnumUnderlyingTy,
   2067                               bool EnumUnderlyingIsImplicit,
   2068                               const EnumDecl *Prev);
   2069 
   2070   /// Determine whether the body of an anonymous enumeration should be skipped.
   2071   /// \param II The name of the first enumerator.
   2072   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
   2073                                       SourceLocation IILoc);
   2074 
   2075   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
   2076                           SourceLocation IdLoc, IdentifierInfo *Id,
   2077                           AttributeList *Attrs,
   2078                           SourceLocation EqualLoc, Expr *Val);
   2079   void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
   2080                      SourceLocation RBraceLoc, Decl *EnumDecl,
   2081                      ArrayRef<Decl *> Elements,
   2082                      Scope *S, AttributeList *Attr);
   2083 
   2084   DeclContext *getContainingDC(DeclContext *DC);
   2085 
   2086   /// Set the current declaration context until it gets popped.
   2087   void PushDeclContext(Scope *S, DeclContext *DC);
   2088   void PopDeclContext();
   2089 
   2090   /// EnterDeclaratorContext - Used when we must lookup names in the context
   2091   /// of a declarator's nested name specifier.
   2092   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
   2093   void ExitDeclaratorContext(Scope *S);
   2094 
   2095   /// Push the parameters of D, which must be a function, into scope.
   2096   void ActOnReenterFunctionContext(Scope* S, Decl* D);
   2097   void ActOnExitFunctionContext();
   2098 
   2099   DeclContext *getFunctionLevelDeclContext();
   2100 
   2101   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
   2102   /// to the function decl for the function being parsed.  If we're currently
   2103   /// in a 'block', this returns the containing context.
   2104   FunctionDecl *getCurFunctionDecl();
   2105 
   2106   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
   2107   /// the method decl for the method being parsed.  If we're currently
   2108   /// in a 'block', this returns the containing context.
   2109   ObjCMethodDecl *getCurMethodDecl();
   2110 
   2111   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
   2112   /// or C function we're in, otherwise return null.  If we're currently
   2113   /// in a 'block', this returns the containing context.
   2114   NamedDecl *getCurFunctionOrMethodDecl();
   2115 
   2116   /// Add this decl to the scope shadowed decl chains.
   2117   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
   2118 
   2119   /// \brief Make the given externally-produced declaration visible at the
   2120   /// top level scope.
   2121   ///
   2122   /// \param D The externally-produced declaration to push.
   2123   ///
   2124   /// \param Name The name of the externally-produced declaration.
   2125   void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
   2126 
   2127   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
   2128   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
   2129   /// true if 'D' belongs to the given declaration context.
   2130   ///
   2131   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
   2132   ///        enclosing namespace set of the context, rather than contained
   2133   ///        directly within it.
   2134   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
   2135                      bool AllowInlineNamespace = false);
   2136 
   2137   /// Finds the scope corresponding to the given decl context, if it
   2138   /// happens to be an enclosing scope.  Otherwise return NULL.
   2139   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
   2140 
   2141   /// Subroutines of ActOnDeclarator().
   2142   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
   2143                                 TypeSourceInfo *TInfo);
   2144   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
   2145 
   2146   /// \brief Describes the kind of merge to perform for availability
   2147   /// attributes (including "deprecated", "unavailable", and "availability").
   2148   enum AvailabilityMergeKind {
   2149     /// \brief Don't merge availability attributes at all.
   2150     AMK_None,
   2151     /// \brief Merge availability attributes for a redeclaration, which requires
   2152     /// an exact match.
   2153     AMK_Redeclaration,
   2154     /// \brief Merge availability attributes for an override, which requires
   2155     /// an exact match or a weakening of constraints.
   2156     AMK_Override,
   2157     /// \brief Merge availability attributes for an implementation of
   2158     /// a protocol requirement.
   2159     AMK_ProtocolImplementation,
   2160   };
   2161 
   2162   /// Attribute merging methods. Return true if a new attribute was added.
   2163   AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
   2164                                           IdentifierInfo *Platform,
   2165                                           bool Implicit,
   2166                                           VersionTuple Introduced,
   2167                                           VersionTuple Deprecated,
   2168                                           VersionTuple Obsoleted,
   2169                                           bool IsUnavailable,
   2170                                           StringRef Message,
   2171                                           bool IsStrict, StringRef Replacement,
   2172                                           AvailabilityMergeKind AMK,
   2173                                           unsigned AttrSpellingListIndex);
   2174   TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
   2175                                        TypeVisibilityAttr::VisibilityType Vis,
   2176                                               unsigned AttrSpellingListIndex);
   2177   VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
   2178                                       VisibilityAttr::VisibilityType Vis,
   2179                                       unsigned AttrSpellingListIndex);
   2180   DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
   2181                                     unsigned AttrSpellingListIndex);
   2182   DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
   2183                                     unsigned AttrSpellingListIndex);
   2184   MSInheritanceAttr *
   2185   mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
   2186                          unsigned AttrSpellingListIndex,
   2187                          MSInheritanceAttr::Spelling SemanticSpelling);
   2188   FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
   2189                               IdentifierInfo *Format, int FormatIdx,
   2190                               int FirstArg, unsigned AttrSpellingListIndex);
   2191   SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
   2192                                 unsigned AttrSpellingListIndex);
   2193   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
   2194                                           IdentifierInfo *Ident,
   2195                                           unsigned AttrSpellingListIndex);
   2196   MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
   2197                                 unsigned AttrSpellingListIndex);
   2198   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
   2199                                           unsigned AttrSpellingListIndex);
   2200   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
   2201                                                 IdentifierInfo *Ident,
   2202                                                 unsigned AttrSpellingListIndex);
   2203   CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
   2204                               unsigned AttrSpellingListIndex);
   2205 
   2206   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
   2207                            AvailabilityMergeKind AMK = AMK_Redeclaration);
   2208   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
   2209                             LookupResult &OldDecls);
   2210   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
   2211                          bool MergeTypeWithOld);
   2212   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
   2213                                     Scope *S, bool MergeTypeWithOld);
   2214   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
   2215   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
   2216   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
   2217   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
   2218   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
   2219 
   2220   // AssignmentAction - This is used by all the assignment diagnostic functions
   2221   // to represent what is actually causing the operation
   2222   enum AssignmentAction {
   2223     AA_Assigning,
   2224     AA_Passing,
   2225     AA_Returning,
   2226     AA_Converting,
   2227     AA_Initializing,
   2228     AA_Sending,
   2229     AA_Casting,
   2230     AA_Passing_CFAudited
   2231   };
   2232 
   2233   /// C++ Overloading.
   2234   enum OverloadKind {
   2235     /// This is a legitimate overload: the existing declarations are
   2236     /// functions or function templates with different signatures.
   2237     Ovl_Overload,
   2238 
   2239     /// This is not an overload because the signature exactly matches
   2240     /// an existing declaration.
   2241     Ovl_Match,
   2242 
   2243     /// This is not an overload because the lookup results contain a
   2244     /// non-function.
   2245     Ovl_NonFunction
   2246   };
   2247   OverloadKind CheckOverload(Scope *S,
   2248                              FunctionDecl *New,
   2249                              const LookupResult &OldDecls,
   2250                              NamedDecl *&OldDecl,
   2251                              bool IsForUsingDecl);
   2252   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
   2253                   bool ConsiderCudaAttrs = true);
   2254 
   2255   /// \brief Checks availability of the function depending on the current
   2256   /// function context.Inside an unavailable function,unavailability is ignored.
   2257   ///
   2258   /// \returns true if \p FD is unavailable and current context is inside
   2259   /// an available function, false otherwise.
   2260   bool isFunctionConsideredUnavailable(FunctionDecl *FD);
   2261 
   2262   ImplicitConversionSequence
   2263   TryImplicitConversion(Expr *From, QualType ToType,
   2264                         bool SuppressUserConversions,
   2265                         bool AllowExplicit,
   2266                         bool InOverloadResolution,
   2267                         bool CStyle,
   2268                         bool AllowObjCWritebackConversion);
   2269 
   2270   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
   2271   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
   2272   bool IsComplexPromotion(QualType FromType, QualType ToType);
   2273   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
   2274                            bool InOverloadResolution,
   2275                            QualType& ConvertedType, bool &IncompatibleObjC);
   2276   bool isObjCPointerConversion(QualType FromType, QualType ToType,
   2277                                QualType& ConvertedType, bool &IncompatibleObjC);
   2278   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
   2279                                  QualType &ConvertedType);
   2280   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
   2281                                 QualType& ConvertedType);
   2282   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
   2283                                   const FunctionProtoType *NewType,
   2284                                   unsigned *ArgPos = nullptr);
   2285   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
   2286                                   QualType FromType, QualType ToType);
   2287 
   2288   void maybeExtendBlockObject(ExprResult &E);
   2289   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
   2290   bool CheckPointerConversion(Expr *From, QualType ToType,
   2291                               CastKind &Kind,
   2292                               CXXCastPath& BasePath,
   2293                               bool IgnoreBaseAccess,
   2294                               bool Diagnose = true);
   2295   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
   2296                                  bool InOverloadResolution,
   2297                                  QualType &ConvertedType);
   2298   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
   2299                                     CastKind &Kind,
   2300                                     CXXCastPath &BasePath,
   2301                                     bool IgnoreBaseAccess);
   2302   bool IsQualificationConversion(QualType FromType, QualType ToType,
   2303                                  bool CStyle, bool &ObjCLifetimeConversion);
   2304   bool IsNoReturnConversion(QualType FromType, QualType ToType,
   2305                             QualType &ResultTy);
   2306   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
   2307   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
   2308 
   2309   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
   2310                                              const VarDecl *NRVOCandidate,
   2311                                              QualType ResultType,
   2312                                              Expr *Value,
   2313                                              bool AllowNRVO = true);
   2314 
   2315   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
   2316                                     ExprResult Init);
   2317   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
   2318                                        SourceLocation EqualLoc,
   2319                                        ExprResult Init,
   2320                                        bool TopLevelOfInitList = false,
   2321                                        bool AllowExplicit = false);
   2322   ExprResult PerformObjectArgumentInitialization(Expr *From,
   2323                                                  NestedNameSpecifier *Qualifier,
   2324                                                  NamedDecl *FoundDecl,
   2325                                                  CXXMethodDecl *Method);
   2326 
   2327   ExprResult PerformContextuallyConvertToBool(Expr *From);
   2328   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
   2329 
   2330   /// Contexts in which a converted constant expression is required.
   2331   enum CCEKind {
   2332     CCEK_CaseValue,   ///< Expression in a case label.
   2333     CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
   2334     CCEK_TemplateArg, ///< Value of a non-type template parameter.
   2335     CCEK_NewExpr,     ///< Constant expression in a noptr-new-declarator.
   2336     CCEK_ConstexprIf  ///< Condition in a constexpr if statement.
   2337   };
   2338   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
   2339                                               llvm::APSInt &Value, CCEKind CCE);
   2340   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
   2341                                               APValue &Value, CCEKind CCE);
   2342 
   2343   /// \brief Abstract base class used to perform a contextual implicit
   2344   /// conversion from an expression to any type passing a filter.
   2345   class ContextualImplicitConverter {
   2346   public:
   2347     bool Suppress;
   2348     bool SuppressConversion;
   2349 
   2350     ContextualImplicitConverter(bool Suppress = false,
   2351                                 bool SuppressConversion = false)
   2352         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
   2353 
   2354     /// \brief Determine whether the specified type is a valid destination type
   2355     /// for this conversion.
   2356     virtual bool match(QualType T) = 0;
   2357 
   2358     /// \brief Emits a diagnostic complaining that the expression does not have
   2359     /// integral or enumeration type.
   2360     virtual SemaDiagnosticBuilder
   2361     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
   2362 
   2363     /// \brief Emits a diagnostic when the expression has incomplete class type.
   2364     virtual SemaDiagnosticBuilder
   2365     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
   2366 
   2367     /// \brief Emits a diagnostic when the only matching conversion function
   2368     /// is explicit.
   2369     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
   2370         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
   2371 
   2372     /// \brief Emits a note for the explicit conversion function.
   2373     virtual SemaDiagnosticBuilder
   2374     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
   2375 
   2376     /// \brief Emits a diagnostic when there are multiple possible conversion
   2377     /// functions.
   2378     virtual SemaDiagnosticBuilder
   2379     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
   2380 
   2381     /// \brief Emits a note for one of the candidate conversions.
   2382     virtual SemaDiagnosticBuilder
   2383     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
   2384 
   2385     /// \brief Emits a diagnostic when we picked a conversion function
   2386     /// (for cases when we are not allowed to pick a conversion function).
   2387     virtual SemaDiagnosticBuilder diagnoseConversion(
   2388         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
   2389 
   2390     virtual ~ContextualImplicitConverter() {}
   2391   };
   2392 
   2393   class ICEConvertDiagnoser : public ContextualImplicitConverter {
   2394     bool AllowScopedEnumerations;
   2395 
   2396   public:
   2397     ICEConvertDiagnoser(bool AllowScopedEnumerations,
   2398                         bool Suppress, bool SuppressConversion)
   2399         : ContextualImplicitConverter(Suppress, SuppressConversion),
   2400           AllowScopedEnumerations(AllowScopedEnumerations) {}
   2401 
   2402     /// Match an integral or (possibly scoped) enumeration type.
   2403     bool match(QualType T) override;
   2404 
   2405     SemaDiagnosticBuilder
   2406     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
   2407       return diagnoseNotInt(S, Loc, T);
   2408     }
   2409 
   2410     /// \brief Emits a diagnostic complaining that the expression does not have
   2411     /// integral or enumeration type.
   2412     virtual SemaDiagnosticBuilder
   2413     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
   2414   };
   2415 
   2416   /// Perform a contextual implicit conversion.
   2417   ExprResult PerformContextualImplicitConversion(
   2418       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
   2419 
   2420 
   2421   enum ObjCSubscriptKind {
   2422     OS_Array,
   2423     OS_Dictionary,
   2424     OS_Error
   2425   };
   2426   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
   2427 
   2428   // Note that LK_String is intentionally after the other literals, as
   2429   // this is used for diagnostics logic.
   2430   enum ObjCLiteralKind {
   2431     LK_Array,
   2432     LK_Dictionary,
   2433     LK_Numeric,
   2434     LK_Boxed,
   2435     LK_String,
   2436     LK_Block,
   2437     LK_None
   2438   };
   2439   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
   2440 
   2441   ExprResult PerformObjectMemberConversion(Expr *From,
   2442                                            NestedNameSpecifier *Qualifier,
   2443                                            NamedDecl *FoundDecl,
   2444                                            NamedDecl *Member);
   2445 
   2446   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
   2447   // TODO: make this is a typesafe union.
   2448   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
   2449   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
   2450 
   2451   void AddOverloadCandidate(FunctionDecl *Function,
   2452                             DeclAccessPair FoundDecl,
   2453                             ArrayRef<Expr *> Args,
   2454                             OverloadCandidateSet& CandidateSet,
   2455                             bool SuppressUserConversions = false,
   2456                             bool PartialOverloading = false,
   2457                             bool AllowExplicit = false);
   2458   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
   2459                       ArrayRef<Expr *> Args,
   2460                       OverloadCandidateSet &CandidateSet,
   2461                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
   2462                       bool SuppressUserConversions = false,
   2463                       bool PartialOverloading = false);
   2464   void AddMethodCandidate(DeclAccessPair FoundDecl,
   2465                           QualType ObjectType,
   2466                           Expr::Classification ObjectClassification,
   2467                           ArrayRef<Expr *> Args,
   2468                           OverloadCandidateSet& CandidateSet,
   2469                           bool SuppressUserConversion = false);
   2470   void AddMethodCandidate(CXXMethodDecl *Method,
   2471                           DeclAccessPair FoundDecl,
   2472                           CXXRecordDecl *ActingContext, QualType ObjectType,
   2473                           Expr::Classification ObjectClassification,
   2474                           ArrayRef<Expr *> Args,
   2475                           OverloadCandidateSet& CandidateSet,
   2476                           bool SuppressUserConversions = false,
   2477                           bool PartialOverloading = false);
   2478   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
   2479                                   DeclAccessPair FoundDecl,
   2480                                   CXXRecordDecl *ActingContext,
   2481                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
   2482                                   QualType ObjectType,
   2483                                   Expr::Classification ObjectClassification,
   2484                                   ArrayRef<Expr *> Args,
   2485                                   OverloadCandidateSet& CandidateSet,
   2486                                   bool SuppressUserConversions = false,
   2487                                   bool PartialOverloading = false);
   2488   void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
   2489                                     DeclAccessPair FoundDecl,
   2490                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
   2491                                     ArrayRef<Expr *> Args,
   2492                                     OverloadCandidateSet& CandidateSet,
   2493                                     bool SuppressUserConversions = false,
   2494                                     bool PartialOverloading = false);
   2495   void AddConversionCandidate(CXXConversionDecl *Conversion,
   2496                               DeclAccessPair FoundDecl,
   2497                               CXXRecordDecl *ActingContext,
   2498                               Expr *From, QualType ToType,
   2499                               OverloadCandidateSet& CandidateSet,
   2500                               bool AllowObjCConversionOnExplicit);
   2501   void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
   2502                                       DeclAccessPair FoundDecl,
   2503                                       CXXRecordDecl *ActingContext,
   2504                                       Expr *From, QualType ToType,
   2505                                       OverloadCandidateSet &CandidateSet,
   2506                                       bool AllowObjCConversionOnExplicit);
   2507   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
   2508                              DeclAccessPair FoundDecl,
   2509                              CXXRecordDecl *ActingContext,
   2510                              const FunctionProtoType *Proto,
   2511                              Expr *Object, ArrayRef<Expr *> Args,
   2512                              OverloadCandidateSet& CandidateSet);
   2513   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
   2514                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
   2515                                    OverloadCandidateSet& CandidateSet,
   2516                                    SourceRange OpRange = SourceRange());
   2517   void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
   2518                            ArrayRef<Expr *> Args,
   2519                            OverloadCandidateSet& CandidateSet,
   2520                            bool IsAssignmentOperator = false,
   2521                            unsigned NumContextualBoolArguments = 0);
   2522   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
   2523                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
   2524                                     OverloadCandidateSet& CandidateSet);
   2525   void AddArgumentDependentLookupCandidates(DeclarationName Name,
   2526                                             SourceLocation Loc,
   2527                                             ArrayRef<Expr *> Args,
   2528                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
   2529                                             OverloadCandidateSet& CandidateSet,
   2530                                             bool PartialOverloading = false);
   2531 
   2532   // Emit as a 'note' the specific overload candidate
   2533   void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
   2534                              QualType DestType = QualType(),
   2535                              bool TakingAddress = false);
   2536 
   2537   // Emit as a series of 'note's all template and non-templates identified by
   2538   // the expression Expr
   2539   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
   2540                                  bool TakingAddress = false);
   2541 
   2542   /// Check the enable_if expressions on the given function. Returns the first
   2543   /// failing attribute, or NULL if they were all successful.
   2544   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
   2545                               bool MissingImplicitThis = false);
   2546 
   2547   /// Returns whether the given function's address can be taken or not,
   2548   /// optionally emitting a diagnostic if the address can't be taken.
   2549   ///
   2550   /// Returns false if taking the address of the function is illegal.
   2551   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
   2552                                          bool Complain = false,
   2553                                          SourceLocation Loc = SourceLocation());
   2554 
   2555   // [PossiblyAFunctionType]  -->   [Return]
   2556   // NonFunctionType --> NonFunctionType
   2557   // R (A) --> R(A)
   2558   // R (*)(A) --> R (A)
   2559   // R (&)(A) --> R (A)
   2560   // R (S::*)(A) --> R (A)
   2561   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
   2562 
   2563   FunctionDecl *
   2564   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
   2565                                      QualType TargetType,
   2566                                      bool Complain,
   2567                                      DeclAccessPair &Found,
   2568                                      bool *pHadMultipleCandidates = nullptr);
   2569 
   2570   FunctionDecl *
   2571   resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
   2572                                               DeclAccessPair &FoundResult);
   2573 
   2574   bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
   2575 
   2576   FunctionDecl *
   2577   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
   2578                                               bool Complain = false,
   2579                                               DeclAccessPair *Found = nullptr);
   2580 
   2581   bool ResolveAndFixSingleFunctionTemplateSpecialization(
   2582                       ExprResult &SrcExpr,
   2583                       bool DoFunctionPointerConverion = false,
   2584                       bool Complain = false,
   2585                       SourceRange OpRangeForComplaining = SourceRange(),
   2586                       QualType DestTypeForComplaining = QualType(),
   2587                       unsigned DiagIDForComplaining = 0);
   2588 
   2589 
   2590   Expr *FixOverloadedFunctionReference(Expr *E,
   2591                                        DeclAccessPair FoundDecl,
   2592                                        FunctionDecl *Fn);
   2593   ExprResult FixOverloadedFunctionReference(ExprResult,
   2594                                             DeclAccessPair FoundDecl,
   2595                                             FunctionDecl *Fn);
   2596 
   2597   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
   2598                                    ArrayRef<Expr *> Args,
   2599                                    OverloadCandidateSet &CandidateSet,
   2600                                    bool PartialOverloading = false);
   2601 
   2602   // An enum used to represent the different possible results of building a
   2603   // range-based for loop.
   2604   enum ForRangeStatus {
   2605     FRS_Success,
   2606     FRS_NoViableFunction,
   2607     FRS_DiagnosticIssued
   2608   };
   2609 
   2610   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
   2611                                            SourceLocation RangeLoc,
   2612                                            const DeclarationNameInfo &NameInfo,
   2613                                            LookupResult &MemberLookup,
   2614                                            OverloadCandidateSet *CandidateSet,
   2615                                            Expr *Range, ExprResult *CallExpr);
   2616 
   2617   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
   2618                                      UnresolvedLookupExpr *ULE,
   2619                                      SourceLocation LParenLoc,
   2620                                      MultiExprArg Args,
   2621                                      SourceLocation RParenLoc,
   2622                                      Expr *ExecConfig,
   2623                                      bool AllowTypoCorrection=true,
   2624                                      bool CalleesAddressIsTaken=false);
   2625 
   2626   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
   2627                               MultiExprArg Args, SourceLocation RParenLoc,
   2628                               OverloadCandidateSet *CandidateSet,
   2629                               ExprResult *Result);
   2630 
   2631   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
   2632                                      UnaryOperatorKind Opc,
   2633                                      const UnresolvedSetImpl &Fns,
   2634                                      Expr *input);
   2635 
   2636   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
   2637                                    BinaryOperatorKind Opc,
   2638                                    const UnresolvedSetImpl &Fns,
   2639                                    Expr *LHS, Expr *RHS);
   2640 
   2641   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
   2642                                                 SourceLocation RLoc,
   2643                                                 Expr *Base,Expr *Idx);
   2644 
   2645   ExprResult
   2646   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
   2647                             SourceLocation LParenLoc,
   2648                             MultiExprArg Args,
   2649                             SourceLocation RParenLoc);
   2650   ExprResult
   2651   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
   2652                                MultiExprArg Args,
   2653                                SourceLocation RParenLoc);
   2654 
   2655   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
   2656                                       SourceLocation OpLoc,
   2657                                       bool *NoArrowOperatorFound = nullptr);
   2658 
   2659   /// CheckCallReturnType - Checks that a call expression's return type is
   2660   /// complete. Returns true on failure. The location passed in is the location
   2661   /// that best represents the call.
   2662   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
   2663                            CallExpr *CE, FunctionDecl *FD);
   2664 
   2665   /// Helpers for dealing with blocks and functions.
   2666   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
   2667                                 bool CheckParameterNames);
   2668   void CheckCXXDefaultArguments(FunctionDecl *FD);
   2669   void CheckExtraCXXDefaultArguments(Declarator &D);
   2670   Scope *getNonFieldDeclScope(Scope *S);
   2671 
   2672   /// \name Name lookup
   2673   ///
   2674   /// These routines provide name lookup that is used during semantic
   2675   /// analysis to resolve the various kinds of names (identifiers,
   2676   /// overloaded operator names, constructor names, etc.) into zero or
   2677   /// more declarations within a particular scope. The major entry
   2678   /// points are LookupName, which performs unqualified name lookup,
   2679   /// and LookupQualifiedName, which performs qualified name lookup.
   2680   ///
   2681   /// All name lookup is performed based on some specific criteria,
   2682   /// which specify what names will be visible to name lookup and how
   2683   /// far name lookup should work. These criteria are important both
   2684   /// for capturing language semantics (certain lookups will ignore
   2685   /// certain names, for example) and for performance, since name
   2686   /// lookup is often a bottleneck in the compilation of C++. Name
   2687   /// lookup criteria is specified via the LookupCriteria enumeration.
   2688   ///
   2689   /// The results of name lookup can vary based on the kind of name
   2690   /// lookup performed, the current language, and the translation
   2691   /// unit. In C, for example, name lookup will either return nothing
   2692   /// (no entity found) or a single declaration. In C++, name lookup
   2693   /// can additionally refer to a set of overloaded functions or
   2694   /// result in an ambiguity. All of the possible results of name
   2695   /// lookup are captured by the LookupResult class, which provides
   2696   /// the ability to distinguish among them.
   2697   //@{
   2698 
   2699   /// @brief Describes the kind of name lookup to perform.
   2700   enum LookupNameKind {
   2701     /// Ordinary name lookup, which finds ordinary names (functions,
   2702     /// variables, typedefs, etc.) in C and most kinds of names
   2703     /// (functions, variables, members, types, etc.) in C++.
   2704     LookupOrdinaryName = 0,
   2705     /// Tag name lookup, which finds the names of enums, classes,
   2706     /// structs, and unions.
   2707     LookupTagName,
   2708     /// Label name lookup.
   2709     LookupLabel,
   2710     /// Member name lookup, which finds the names of
   2711     /// class/struct/union members.
   2712     LookupMemberName,
   2713     /// Look up of an operator name (e.g., operator+) for use with
   2714     /// operator overloading. This lookup is similar to ordinary name
   2715     /// lookup, but will ignore any declarations that are class members.
   2716     LookupOperatorName,
   2717     /// Look up of a name that precedes the '::' scope resolution
   2718     /// operator in C++. This lookup completely ignores operator, object,
   2719     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
   2720     LookupNestedNameSpecifierName,
   2721     /// Look up a namespace name within a C++ using directive or
   2722     /// namespace alias definition, ignoring non-namespace names (C++
   2723     /// [basic.lookup.udir]p1).
   2724     LookupNamespaceName,
   2725     /// Look up all declarations in a scope with the given name,
   2726     /// including resolved using declarations.  This is appropriate
   2727     /// for checking redeclarations for a using declaration.
   2728     LookupUsingDeclName,
   2729     /// Look up an ordinary name that is going to be redeclared as a
   2730     /// name with linkage. This lookup ignores any declarations that
   2731     /// are outside of the current scope unless they have linkage. See
   2732     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
   2733     LookupRedeclarationWithLinkage,
   2734     /// Look up a friend of a local class. This lookup does not look
   2735     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
   2736     LookupLocalFriendName,
   2737     /// Look up the name of an Objective-C protocol.
   2738     LookupObjCProtocolName,
   2739     /// Look up implicit 'self' parameter of an objective-c method.
   2740     LookupObjCImplicitSelfParam,
   2741     /// \brief Look up the name of an OpenMP user-defined reduction operation.
   2742     LookupOMPReductionName,
   2743     /// \brief Look up any declaration with any name.
   2744     LookupAnyName
   2745   };
   2746 
   2747   /// \brief Specifies whether (or how) name lookup is being performed for a
   2748   /// redeclaration (vs. a reference).
   2749   enum RedeclarationKind {
   2750     /// \brief The lookup is a reference to this name that is not for the
   2751     /// purpose of redeclaring the name.
   2752     NotForRedeclaration = 0,
   2753     /// \brief The lookup results will be used for redeclaration of a name,
   2754     /// if an entity by that name already exists.
   2755     ForRedeclaration
   2756   };
   2757 
   2758   /// \brief The possible outcomes of name lookup for a literal operator.
   2759   enum LiteralOperatorLookupResult {
   2760     /// \brief The lookup resulted in an error.
   2761     LOLR_Error,
   2762     /// \brief The lookup found a single 'cooked' literal operator, which
   2763     /// expects a normal literal to be built and passed to it.
   2764     LOLR_Cooked,
   2765     /// \brief The lookup found a single 'raw' literal operator, which expects
   2766     /// a string literal containing the spelling of the literal token.
   2767     LOLR_Raw,
   2768     /// \brief The lookup found an overload set of literal operator templates,
   2769     /// which expect the characters of the spelling of the literal token to be
   2770     /// passed as a non-type template argument pack.
   2771     LOLR_Template,
   2772     /// \brief The lookup found an overload set of literal operator templates,
   2773     /// which expect the character type and characters of the spelling of the
   2774     /// string literal token to be passed as template arguments.
   2775     LOLR_StringTemplate
   2776   };
   2777 
   2778   SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
   2779                                                    CXXSpecialMember SM,
   2780                                                    bool ConstArg,
   2781                                                    bool VolatileArg,
   2782                                                    bool RValueThis,
   2783                                                    bool ConstThis,
   2784                                                    bool VolatileThis);
   2785 
   2786   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
   2787   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
   2788       TypoRecoveryCallback;
   2789 
   2790 private:
   2791   bool CppLookupName(LookupResult &R, Scope *S);
   2792 
   2793   struct TypoExprState {
   2794     std::unique_ptr<TypoCorrectionConsumer> Consumer;
   2795     TypoDiagnosticGenerator DiagHandler;
   2796     TypoRecoveryCallback RecoveryHandler;
   2797     TypoExprState();
   2798     TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
   2799     TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
   2800   };
   2801 
   2802   /// \brief The set of unhandled TypoExprs and their associated state.
   2803   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
   2804 
   2805   /// \brief Creates a new TypoExpr AST node.
   2806   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
   2807                               TypoDiagnosticGenerator TDG,
   2808                               TypoRecoveryCallback TRC);
   2809 
   2810   // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
   2811   //
   2812   // The boolean value will be true to indicate that the namespace was loaded
   2813   // from an AST/PCH file, or false otherwise.
   2814   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
   2815 
   2816   /// \brief Whether we have already loaded known namespaces from an extenal
   2817   /// source.
   2818   bool LoadedExternalKnownNamespaces;
   2819 
   2820   /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
   2821   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
   2822   /// should be skipped entirely.
   2823   std::unique_ptr<TypoCorrectionConsumer>
   2824   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
   2825                              Sema::LookupNameKind LookupKind, Scope *S,
   2826                              CXXScopeSpec *SS,
   2827                              std::unique_ptr<CorrectionCandidateCallback> CCC,
   2828                              DeclContext *MemberContext, bool EnteringContext,
   2829                              const ObjCObjectPointerType *OPT,
   2830                              bool ErrorRecovery);
   2831 
   2832 public:
   2833   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
   2834 
   2835   /// \brief Clears the state of the given TypoExpr.
   2836   void clearDelayedTypo(TypoExpr *TE);
   2837 
   2838   /// \brief Look up a name, looking for a single declaration.  Return
   2839   /// null if the results were absent, ambiguous, or overloaded.
   2840   ///
   2841   /// It is preferable to use the elaborated form and explicitly handle
   2842   /// ambiguity and overloaded.
   2843   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
   2844                               SourceLocation Loc,
   2845                               LookupNameKind NameKind,
   2846                               RedeclarationKind Redecl
   2847                                 = NotForRedeclaration);
   2848   bool LookupName(LookupResult &R, Scope *S,
   2849                   bool AllowBuiltinCreation = false);
   2850   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
   2851                            bool InUnqualifiedLookup = false);
   2852   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
   2853                            CXXScopeSpec &SS);
   2854   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
   2855                         bool AllowBuiltinCreation = false,
   2856                         bool EnteringContext = false);
   2857   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
   2858                                    RedeclarationKind Redecl
   2859                                      = NotForRedeclaration);
   2860   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
   2861 
   2862   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
   2863                                     QualType T1, QualType T2,
   2864                                     UnresolvedSetImpl &Functions);
   2865   void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
   2866                                             DeclAccessPair Operator,
   2867                                             QualType T1, QualType T2);
   2868 
   2869   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
   2870                                  SourceLocation GnuLabelLoc = SourceLocation());
   2871 
   2872   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
   2873   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
   2874   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
   2875                                                unsigned Quals);
   2876   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
   2877                                          bool RValueThis, unsigned ThisQuals);
   2878   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
   2879                                               unsigned Quals);
   2880   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
   2881                                         bool RValueThis, unsigned ThisQuals);
   2882   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
   2883 
   2884   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
   2885   LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
   2886                                                     ArrayRef<QualType> ArgTys,
   2887                                                     bool AllowRaw,
   2888                                                     bool AllowTemplate,
   2889                                                     bool AllowStringTemplate);
   2890   bool isKnownName(StringRef name);
   2891 
   2892   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
   2893                                ArrayRef<Expr *> Args, ADLResult &Functions);
   2894 
   2895   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
   2896                           VisibleDeclConsumer &Consumer,
   2897                           bool IncludeGlobalScope = true);
   2898   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
   2899                           VisibleDeclConsumer &Consumer,
   2900                           bool IncludeGlobalScope = true);
   2901 
   2902   enum CorrectTypoKind {
   2903     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
   2904     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
   2905   };
   2906 
   2907   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
   2908                              Sema::LookupNameKind LookupKind,
   2909                              Scope *S, CXXScopeSpec *SS,
   2910                              std::unique_ptr<CorrectionCandidateCallback> CCC,
   2911                              CorrectTypoKind Mode,
   2912                              DeclContext *MemberContext = nullptr,
   2913                              bool EnteringContext = false,
   2914                              const ObjCObjectPointerType *OPT = nullptr,
   2915                              bool RecordFailure = true);
   2916 
   2917   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
   2918                                Sema::LookupNameKind LookupKind, Scope *S,
   2919                                CXXScopeSpec *SS,
   2920                                std::unique_ptr<CorrectionCandidateCallback> CCC,
   2921                                TypoDiagnosticGenerator TDG,
   2922                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
   2923                                DeclContext *MemberContext = nullptr,
   2924                                bool EnteringContext = false,
   2925                                const ObjCObjectPointerType *OPT = nullptr);
   2926 
   2927   /// \brief Process any TypoExprs in the given Expr and its children,
   2928   /// generating diagnostics as appropriate and returning a new Expr if there
   2929   /// were typos that were all successfully corrected and ExprError if one or
   2930   /// more typos could not be corrected.
   2931   ///
   2932   /// \param E The Expr to check for TypoExprs.
   2933   ///
   2934   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
   2935   /// initializer.
   2936   ///
   2937   /// \param Filter A function applied to a newly rebuilt Expr to determine if
   2938   /// it is an acceptable/usable result from a single combination of typo
   2939   /// corrections. As long as the filter returns ExprError, different
   2940   /// combinations of corrections will be tried until all are exhausted.
   2941   ExprResult
   2942   CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
   2943                             llvm::function_ref<ExprResult(Expr *)> Filter =
   2944                                 [](Expr *E) -> ExprResult { return E; });
   2945 
   2946   ExprResult
   2947   CorrectDelayedTyposInExpr(Expr *E,
   2948                             llvm::function_ref<ExprResult(Expr *)> Filter) {
   2949     return CorrectDelayedTyposInExpr(E, nullptr, Filter);
   2950   }
   2951 
   2952   ExprResult
   2953   CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
   2954                             llvm::function_ref<ExprResult(Expr *)> Filter =
   2955                                 [](Expr *E) -> ExprResult { return E; }) {
   2956     return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
   2957   }
   2958 
   2959   ExprResult
   2960   CorrectDelayedTyposInExpr(ExprResult ER,
   2961                             llvm::function_ref<ExprResult(Expr *)> Filter) {
   2962     return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
   2963   }
   2964 
   2965   void diagnoseTypo(const TypoCorrection &Correction,
   2966                     const PartialDiagnostic &TypoDiag,
   2967                     bool ErrorRecovery = true);
   2968 
   2969   void diagnoseTypo(const TypoCorrection &Correction,
   2970                     const PartialDiagnostic &TypoDiag,
   2971                     const PartialDiagnostic &PrevNote,
   2972                     bool ErrorRecovery = true);
   2973 
   2974   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
   2975                                           ArrayRef<Expr *> Args,
   2976                                    AssociatedNamespaceSet &AssociatedNamespaces,
   2977                                    AssociatedClassSet &AssociatedClasses);
   2978 
   2979   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
   2980                             bool ConsiderLinkage, bool AllowInlineNamespace);
   2981 
   2982   void DiagnoseAmbiguousLookup(LookupResult &Result);
   2983   //@}
   2984 
   2985   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
   2986                                           SourceLocation IdLoc,
   2987                                           bool TypoCorrection = false);
   2988   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
   2989                                  Scope *S, bool ForRedeclaration,
   2990                                  SourceLocation Loc);
   2991   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
   2992                                       Scope *S);
   2993   void AddKnownFunctionAttributes(FunctionDecl *FD);
   2994 
   2995   // More parsing and symbol table subroutines.
   2996 
   2997   void ProcessPragmaWeak(Scope *S, Decl *D);
   2998   // Decl attributes - this routine is the top level dispatcher.
   2999   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
   3000   void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
   3001                                 bool IncludeCXX11Attributes = true);
   3002   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
   3003                                       const AttributeList *AttrList);
   3004 
   3005   void checkUnusedDeclAttributes(Declarator &D);
   3006 
   3007   /// Determine if type T is a valid subject for a nonnull and similar
   3008   /// attributes. By default, we look through references (the behavior used by
   3009   /// nonnull), but if the second parameter is true, then we treat a reference
   3010   /// type as valid.
   3011   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
   3012 
   3013   bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
   3014   bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
   3015                             const FunctionDecl *FD = nullptr);
   3016   bool CheckNoReturnAttr(const AttributeList &attr);
   3017   bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
   3018                                       unsigned ArgNum, StringRef &Str,
   3019                                       SourceLocation *ArgLocation = nullptr);
   3020   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
   3021   void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
   3022   bool checkMSInheritanceAttrOnDefinition(
   3023       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
   3024       MSInheritanceAttr::Spelling SemanticSpelling);
   3025 
   3026   void CheckAlignasUnderalignment(Decl *D);
   3027 
   3028   /// Adjust the calling convention of a method to be the ABI default if it
   3029   /// wasn't specified explicitly.  This handles method types formed from
   3030   /// function type typedefs and typename template arguments.
   3031   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
   3032                               SourceLocation Loc);
   3033 
   3034   // Check if there is an explicit attribute, but only look through parens.
   3035   // The intent is to look for an attribute on the current declarator, but not
   3036   // one that came from a typedef.
   3037   bool hasExplicitCallingConv(QualType &T);
   3038 
   3039   /// Get the outermost AttributedType node that sets a calling convention.
   3040   /// Valid types should not have multiple attributes with different CCs.
   3041   const AttributedType *getCallingConvAttributedType(QualType T) const;
   3042 
   3043   /// Check whether a nullability type specifier can be added to the given
   3044   /// type.
   3045   ///
   3046   /// \param type The type to which the nullability specifier will be
   3047   /// added. On success, this type will be updated appropriately.
   3048   ///
   3049   /// \param nullability The nullability specifier to add.
   3050   ///
   3051   /// \param nullabilityLoc The location of the nullability specifier.
   3052   ///
   3053   /// \param isContextSensitive Whether this nullability specifier was
   3054   /// written as a context-sensitive keyword (in an Objective-C
   3055   /// method) or an Objective-C property attribute, rather than as an
   3056   /// underscored type specifier.
   3057   ///
   3058   /// \returns true if nullability cannot be applied, false otherwise.
   3059   bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
   3060                                      SourceLocation nullabilityLoc,
   3061                                      bool isContextSensitive);
   3062 
   3063   /// \brief Stmt attributes - this routine is the top level dispatcher.
   3064   StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
   3065                                    SourceRange Range);
   3066 
   3067   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
   3068                                    ObjCMethodDecl *MethodDecl,
   3069                                    bool IsProtocolMethodDecl);
   3070 
   3071   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
   3072                                    ObjCMethodDecl *Overridden,
   3073                                    bool IsProtocolMethodDecl);
   3074 
   3075   /// WarnExactTypedMethods - This routine issues a warning if method
   3076   /// implementation declaration matches exactly that of its declaration.
   3077   void WarnExactTypedMethods(ObjCMethodDecl *Method,
   3078                              ObjCMethodDecl *MethodDecl,
   3079                              bool IsProtocolMethodDecl);
   3080 
   3081   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
   3082   typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
   3083 
   3084   /// CheckImplementationIvars - This routine checks if the instance variables
   3085   /// listed in the implelementation match those listed in the interface.
   3086   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
   3087                                 ObjCIvarDecl **Fields, unsigned nIvars,
   3088                                 SourceLocation Loc);
   3089 
   3090   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
   3091   /// remains unimplemented in the class or category \@implementation.
   3092   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
   3093                                  ObjCContainerDecl* IDecl,
   3094                                  bool IncompleteImpl = false);
   3095 
   3096   /// DiagnoseUnimplementedProperties - This routine warns on those properties
   3097   /// which must be implemented by this implementation.
   3098   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
   3099                                        ObjCContainerDecl *CDecl,
   3100                                        bool SynthesizeProperties);
   3101 
   3102   /// Diagnose any null-resettable synthesized setters.
   3103   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
   3104 
   3105   /// DefaultSynthesizeProperties - This routine default synthesizes all
   3106   /// properties which must be synthesized in the class's \@implementation.
   3107   void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
   3108                                     ObjCInterfaceDecl *IDecl);
   3109   void DefaultSynthesizeProperties(Scope *S, Decl *D);
   3110 
   3111   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
   3112   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
   3113   /// declared in class 'IFace'.
   3114   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
   3115                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
   3116 
   3117   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
   3118   /// backs the property is not used in the property's accessor.
   3119   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
   3120                                            const ObjCImplementationDecl *ImplD);
   3121 
   3122   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
   3123   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
   3124   /// It also returns ivar's property on success.
   3125   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
   3126                                                const ObjCPropertyDecl *&PDecl) const;
   3127 
   3128   /// Called by ActOnProperty to handle \@property declarations in
   3129   /// class extensions.
   3130   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
   3131                       SourceLocation AtLoc,
   3132                       SourceLocation LParenLoc,
   3133                       FieldDeclarator &FD,
   3134                       Selector GetterSel,
   3135                       Selector SetterSel,
   3136                       const bool isReadWrite,
   3137                       unsigned &Attributes,
   3138                       const unsigned AttributesAsWritten,
   3139                       QualType T,
   3140                       TypeSourceInfo *TSI,
   3141                       tok::ObjCKeywordKind MethodImplKind);
   3142 
   3143   /// Called by ActOnProperty and HandlePropertyInClassExtension to
   3144   /// handle creating the ObjcPropertyDecl for a category or \@interface.
   3145   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
   3146                                        ObjCContainerDecl *CDecl,
   3147                                        SourceLocation AtLoc,
   3148                                        SourceLocation LParenLoc,
   3149                                        FieldDeclarator &FD,
   3150                                        Selector GetterSel,
   3151                                        Selector SetterSel,
   3152                                        const bool isReadWrite,
   3153                                        const unsigned Attributes,
   3154                                        const unsigned AttributesAsWritten,
   3155                                        QualType T,
   3156                                        TypeSourceInfo *TSI,
   3157                                        tok::ObjCKeywordKind MethodImplKind,
   3158                                        DeclContext *lexicalDC = nullptr);
   3159 
   3160   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
   3161   /// warning) when atomic property has one but not the other user-declared
   3162   /// setter or getter.
   3163   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
   3164                                        ObjCInterfaceDecl* IDecl);
   3165 
   3166   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
   3167 
   3168   void DiagnoseMissingDesignatedInitOverrides(
   3169                                           const ObjCImplementationDecl *ImplD,
   3170                                           const ObjCInterfaceDecl *IFD);
   3171 
   3172   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
   3173 
   3174   enum MethodMatchStrategy {
   3175     MMS_loose,
   3176     MMS_strict
   3177   };
   3178 
   3179   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
   3180   /// true, or false, accordingly.
   3181   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
   3182                                   const ObjCMethodDecl *PrevMethod,
   3183                                   MethodMatchStrategy strategy = MMS_strict);
   3184 
   3185   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
   3186   /// or protocol against those declared in their implementations.
   3187   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
   3188                                   const SelectorSet &ClsMap,
   3189                                   SelectorSet &InsMapSeen,
   3190                                   SelectorSet &ClsMapSeen,
   3191                                   ObjCImplDecl* IMPDecl,
   3192                                   ObjCContainerDecl* IDecl,
   3193                                   bool &IncompleteImpl,
   3194                                   bool ImmediateClass,
   3195                                   bool WarnCategoryMethodImpl=false);
   3196 
   3197   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
   3198   /// category matches with those implemented in its primary class and
   3199   /// warns each time an exact match is found.
   3200   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
   3201 
   3202   /// \brief Add the given method to the list of globally-known methods.
   3203   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
   3204 
   3205 private:
   3206   /// AddMethodToGlobalPool - Add an instance or factory method to the global
   3207   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
   3208   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
   3209 
   3210   /// LookupMethodInGlobalPool - Returns the instance or factory method and
   3211   /// optionally warns if there are multiple signatures.
   3212   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
   3213                                            bool receiverIdOrClass,
   3214                                            bool instance);
   3215 
   3216 public:
   3217   /// \brief - Returns instance or factory methods in global method pool for
   3218   /// given selector. It checks the desired kind first, if none is found, and
   3219   /// parameter checkTheOther is set, it then checks the other kind. If no such
   3220   /// method or only one method is found, function returns false; otherwise, it
   3221   /// returns true.
   3222   bool
   3223   CollectMultipleMethodsInGlobalPool(Selector Sel,
   3224                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
   3225                                      bool InstanceFirst, bool CheckTheOther,
   3226                                      const ObjCObjectType *TypeBound = nullptr);
   3227 
   3228   bool
   3229   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
   3230                                  SourceRange R, bool receiverIdOrClass,
   3231                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
   3232 
   3233   void
   3234   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
   3235                                      Selector Sel, SourceRange R,
   3236                                      bool receiverIdOrClass);
   3237 
   3238 private:
   3239   /// \brief - Returns a selector which best matches given argument list or
   3240   /// nullptr if none could be found
   3241   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
   3242                                    bool IsInstance,
   3243                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
   3244 
   3245 
   3246   /// \brief Record the typo correction failure and return an empty correction.
   3247   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
   3248                                   bool RecordFailure = true) {
   3249     if (RecordFailure)
   3250       TypoCorrectionFailures[Typo].insert(TypoLoc);
   3251     return TypoCorrection();
   3252   }
   3253 
   3254 public:
   3255   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
   3256   /// unit are added to a global pool. This allows us to efficiently associate
   3257   /// a selector with a method declaraation for purposes of typechecking
   3258   /// messages sent to "id" (where the class of the object is unknown).
   3259   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
   3260     AddMethodToGlobalPool(Method, impl, /*instance*/true);
   3261   }
   3262 
   3263   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
   3264   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
   3265     AddMethodToGlobalPool(Method, impl, /*instance*/false);
   3266   }
   3267 
   3268   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
   3269   /// pool.
   3270   void AddAnyMethodToGlobalPool(Decl *D);
   3271 
   3272   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
   3273   /// there are multiple signatures.
   3274   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
   3275                                                    bool receiverIdOrClass=false) {
   3276     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
   3277                                     /*instance*/true);
   3278   }
   3279 
   3280   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
   3281   /// there are multiple signatures.
   3282   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
   3283                                                   bool receiverIdOrClass=false) {
   3284     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
   3285                                     /*instance*/false);
   3286   }
   3287 
   3288   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
   3289                               QualType ObjectType=QualType());
   3290   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
   3291   /// implementation.
   3292   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
   3293 
   3294   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
   3295   /// initialization.
   3296   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
   3297                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
   3298 
   3299   //===--------------------------------------------------------------------===//
   3300   // Statement Parsing Callbacks: SemaStmt.cpp.
   3301 public:
   3302   class FullExprArg {
   3303   public:
   3304     FullExprArg() : E(nullptr) { }
   3305     FullExprArg(Sema &actions) : E(nullptr) { }
   3306 
   3307     ExprResult release() {
   3308       return E;
   3309     }
   3310 
   3311     Expr *get() const { return E; }
   3312 
   3313     Expr *operator->() {
   3314       return E;
   3315     }
   3316 
   3317   private:
   3318     // FIXME: No need to make the entire Sema class a friend when it's just
   3319     // Sema::MakeFullExpr that needs access to the constructor below.
   3320     friend class Sema;
   3321 
   3322     explicit FullExprArg(Expr *expr) : E(expr) {}
   3323 
   3324     Expr *E;
   3325   };
   3326 
   3327   FullExprArg MakeFullExpr(Expr *Arg) {
   3328     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
   3329   }
   3330   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
   3331     return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
   3332   }
   3333   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
   3334     ExprResult FE =
   3335       ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
   3336                           /*DiscardedValue*/ true);
   3337     return FullExprArg(FE.get());
   3338   }
   3339 
   3340   StmtResult ActOnExprStmt(ExprResult Arg);
   3341   StmtResult ActOnExprStmtError();
   3342 
   3343   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
   3344                            bool HasLeadingEmptyMacro = false);
   3345 
   3346   void ActOnStartOfCompoundStmt();
   3347   void ActOnFinishOfCompoundStmt();
   3348   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
   3349                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
   3350 
   3351   /// \brief A RAII object to enter scope of a compound statement.
   3352   class CompoundScopeRAII {
   3353   public:
   3354     CompoundScopeRAII(Sema &S): S(S) {
   3355       S.ActOnStartOfCompoundStmt();
   3356     }
   3357 
   3358     ~CompoundScopeRAII() {
   3359       S.ActOnFinishOfCompoundStmt();
   3360     }
   3361 
   3362   private:
   3363     Sema &S;
   3364   };
   3365 
   3366   /// An RAII helper that pops function a function scope on exit.
   3367   struct FunctionScopeRAII {
   3368     Sema &S;
   3369     bool Active;
   3370     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
   3371     ~FunctionScopeRAII() {
   3372       if (Active)
   3373         S.PopFunctionScopeInfo();
   3374     }
   3375     void disable() { Active = false; }
   3376   };
   3377 
   3378   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
   3379                                    SourceLocation StartLoc,
   3380                                    SourceLocation EndLoc);
   3381   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
   3382   StmtResult ActOnForEachLValueExpr(Expr *E);
   3383   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
   3384                                    SourceLocation DotDotDotLoc, Expr *RHSVal,
   3385                                    SourceLocation ColonLoc);
   3386   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
   3387 
   3388   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
   3389                                       SourceLocation ColonLoc,
   3390                                       Stmt *SubStmt, Scope *CurScope);
   3391   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
   3392                             SourceLocation ColonLoc, Stmt *SubStmt);
   3393 
   3394   StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
   3395                                  ArrayRef<const Attr*> Attrs,
   3396                                  Stmt *SubStmt);
   3397 
   3398   class ConditionResult;
   3399   StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
   3400                          Stmt *InitStmt,
   3401                          ConditionResult Cond, Stmt *ThenVal,
   3402                          SourceLocation ElseLoc, Stmt *ElseVal);
   3403   StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
   3404                          Stmt *InitStmt,
   3405                          ConditionResult Cond, Stmt *ThenVal,
   3406                          SourceLocation ElseLoc, Stmt *ElseVal);
   3407   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
   3408                                     Stmt *InitStmt,
   3409                                     ConditionResult Cond);
   3410   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
   3411                                            Stmt *Switch, Stmt *Body);
   3412   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
   3413                             Stmt *Body);
   3414   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
   3415                          SourceLocation WhileLoc, SourceLocation CondLParen,
   3416                          Expr *Cond, SourceLocation CondRParen);
   3417 
   3418   StmtResult ActOnForStmt(SourceLocation ForLoc,
   3419                           SourceLocation LParenLoc,
   3420                           Stmt *First,
   3421                           ConditionResult Second,
   3422                           FullExprArg Third,
   3423                           SourceLocation RParenLoc,
   3424                           Stmt *Body);
   3425   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
   3426                                            Expr *collection);
   3427   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
   3428                                         Stmt *First, Expr *collection,
   3429                                         SourceLocation RParenLoc);
   3430   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
   3431 
   3432   enum BuildForRangeKind {
   3433     /// Initial building of a for-range statement.
   3434     BFRK_Build,
   3435     /// Instantiation or recovery rebuild of a for-range statement. Don't
   3436     /// attempt any typo-correction.
   3437     BFRK_Rebuild,
   3438     /// Determining whether a for-range statement could be built. Avoid any
   3439     /// unnecessary or irreversible actions.
   3440     BFRK_Check
   3441   };
   3442 
   3443   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
   3444                                   SourceLocation CoawaitLoc,
   3445                                   Stmt *LoopVar,
   3446                                   SourceLocation ColonLoc, Expr *Collection,
   3447                                   SourceLocation RParenLoc,
   3448                                   BuildForRangeKind Kind);
   3449   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
   3450                                   SourceLocation CoawaitLoc,
   3451                                   SourceLocation ColonLoc,
   3452                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
   3453                                   Expr *Cond, Expr *Inc,
   3454                                   Stmt *LoopVarDecl,
   3455                                   SourceLocation RParenLoc,
   3456                                   BuildForRangeKind Kind);
   3457   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
   3458 
   3459   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
   3460                            SourceLocation LabelLoc,
   3461                            LabelDecl *TheDecl);
   3462   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
   3463                                    SourceLocation StarLoc,
   3464                                    Expr *DestExp);
   3465   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
   3466   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
   3467 
   3468   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
   3469                                 CapturedRegionKind Kind, unsigned NumParams);
   3470   typedef std::pair<StringRef, QualType> CapturedParamNameType;
   3471   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
   3472                                 CapturedRegionKind Kind,
   3473                                 ArrayRef<CapturedParamNameType> Params);
   3474   StmtResult ActOnCapturedRegionEnd(Stmt *S);
   3475   void ActOnCapturedRegionError();
   3476   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
   3477                                            SourceLocation Loc,
   3478                                            unsigned NumParams);
   3479   VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
   3480                                    bool AllowParamOrMoveConstructible);
   3481   bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
   3482                               bool AllowParamOrMoveConstructible);
   3483 
   3484   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
   3485                              Scope *CurScope);
   3486   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
   3487   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
   3488 
   3489   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
   3490                              bool IsVolatile, unsigned NumOutputs,
   3491                              unsigned NumInputs, IdentifierInfo **Names,
   3492                              MultiExprArg Constraints, MultiExprArg Exprs,
   3493                              Expr *AsmString, MultiExprArg Clobbers,
   3494                              SourceLocation RParenLoc);
   3495 
   3496   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
   3497                                        SourceLocation TemplateKWLoc,
   3498                                        UnqualifiedId &Id,
   3499                                        llvm::InlineAsmIdentifierInfo &Info,
   3500                                        bool IsUnevaluatedContext);
   3501   bool LookupInlineAsmField(StringRef Base, StringRef Member,
   3502                             unsigned &Offset, SourceLocation AsmLoc);
   3503   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
   3504                                          llvm::InlineAsmIdentifierInfo &Info,
   3505                                          SourceLocation AsmLoc);
   3506   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
   3507                             ArrayRef<Token> AsmToks,
   3508                             StringRef AsmString,
   3509                             unsigned NumOutputs, unsigned NumInputs,
   3510                             ArrayRef<StringRef> Constraints,
   3511                             ArrayRef<StringRef> Clobbers,
   3512                             ArrayRef<Expr*> Exprs,
   3513                             SourceLocation EndLoc);
   3514   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
   3515                                    SourceLocation Location,
   3516                                    bool AlwaysCreate);
   3517 
   3518   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
   3519                                   SourceLocation StartLoc,
   3520                                   SourceLocation IdLoc, IdentifierInfo *Id,
   3521                                   bool Invalid = false);
   3522 
   3523   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
   3524 
   3525   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
   3526                                   Decl *Parm, Stmt *Body);
   3527 
   3528   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
   3529 
   3530   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
   3531                                 MultiStmtArg Catch, Stmt *Finally);
   3532 
   3533   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
   3534   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
   3535                                   Scope *CurScope);
   3536   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
   3537                                             Expr *operand);
   3538   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
   3539                                          Expr *SynchExpr,
   3540                                          Stmt *SynchBody);
   3541 
   3542   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
   3543 
   3544   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
   3545                                      SourceLocation StartLoc,
   3546                                      SourceLocation IdLoc,
   3547                                      IdentifierInfo *Id);
   3548 
   3549   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
   3550 
   3551   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
   3552                                 Decl *ExDecl, Stmt *HandlerBlock);
   3553   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
   3554                               ArrayRef<Stmt *> Handlers);
   3555 
   3556   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
   3557                               SourceLocation TryLoc, Stmt *TryBlock,
   3558                               Stmt *Handler);
   3559   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
   3560                                  Expr *FilterExpr,
   3561                                  Stmt *Block);
   3562   void ActOnStartSEHFinallyBlock();
   3563   void ActOnAbortSEHFinallyBlock();
   3564   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
   3565   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
   3566 
   3567   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
   3568 
   3569   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
   3570 
   3571   /// \brief If it's a file scoped decl that must warn if not used, keep track
   3572   /// of it.
   3573   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
   3574 
   3575   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
   3576   /// whose result is unused, warn.
   3577   void DiagnoseUnusedExprResult(const Stmt *S);
   3578   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
   3579   void DiagnoseUnusedDecl(const NamedDecl *ND);
   3580 
   3581   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
   3582   /// statement as a \p Body, and it is located on the same line.
   3583   ///
   3584   /// This helps prevent bugs due to typos, such as:
   3585   ///     if (condition);
   3586   ///       do_stuff();
   3587   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
   3588                              const Stmt *Body,
   3589                              unsigned DiagID);
   3590 
   3591   /// Warn if a for/while loop statement \p S, which is followed by
   3592   /// \p PossibleBody, has a suspicious null statement as a body.
   3593   void DiagnoseEmptyLoopBody(const Stmt *S,
   3594                              const Stmt *PossibleBody);
   3595 
   3596   /// Warn if a value is moved to itself.
   3597   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
   3598                         SourceLocation OpLoc);
   3599 
   3600   /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
   3601   /// _Nonnull one.
   3602   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
   3603                                            SourceLocation Loc);
   3604 
   3605   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
   3606     return DelayedDiagnostics.push(pool);
   3607   }
   3608   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
   3609 
   3610   typedef ProcessingContextState ParsingClassState;
   3611   ParsingClassState PushParsingClass() {
   3612     return DelayedDiagnostics.pushUndelayed();
   3613   }
   3614   void PopParsingClass(ParsingClassState state) {
   3615     DelayedDiagnostics.popUndelayed(state);
   3616   }
   3617 
   3618   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
   3619 
   3620   enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
   3621 
   3622   void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
   3623                                NamedDecl *D, StringRef Message,
   3624                                SourceLocation Loc,
   3625                                const ObjCInterfaceDecl *UnknownObjCClass,
   3626                                const ObjCPropertyDecl  *ObjCProperty,
   3627                                bool ObjCPropertyAccess);
   3628 
   3629   bool makeUnavailableInSystemHeader(SourceLocation loc,
   3630                                      UnavailableAttr::ImplicitReason reason);
   3631 
   3632   //===--------------------------------------------------------------------===//
   3633   // Expression Parsing Callbacks: SemaExpr.cpp.
   3634 
   3635   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
   3636   bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
   3637                          const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
   3638                          bool ObjCPropertyAccess=false);
   3639   void NoteDeletedFunction(FunctionDecl *FD);
   3640   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
   3641   std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
   3642   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
   3643                                         ObjCMethodDecl *Getter,
   3644                                         SourceLocation Loc);
   3645   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
   3646                              ArrayRef<Expr *> Args);
   3647 
   3648   void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
   3649                                        Decl *LambdaContextDecl = nullptr,
   3650                                        bool IsDecltype = false);
   3651   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
   3652   void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
   3653                                        ReuseLambdaContextDecl_t,
   3654                                        bool IsDecltype = false);
   3655   void PopExpressionEvaluationContext();
   3656 
   3657   void DiscardCleanupsInEvaluationContext();
   3658 
   3659   ExprResult TransformToPotentiallyEvaluated(Expr *E);
   3660   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
   3661 
   3662   ExprResult ActOnConstantExpression(ExprResult Res);
   3663 
   3664   // Functions for marking a declaration referenced.  These functions also
   3665   // contain the relevant logic for marking if a reference to a function or
   3666   // variable is an odr-use (in the C++11 sense).  There are separate variants
   3667   // for expressions referring to a decl; these exist because odr-use marking
   3668   // needs to be delayed for some constant variables when we build one of the
   3669   // named expressions.
   3670   //
   3671   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
   3672   // should usually be true. This only needs to be set to false if the lack of
   3673   // odr-use cannot be determined from the current context (for instance,
   3674   // because the name denotes a virtual function and was written without an
   3675   // explicit nested-name-specifier).
   3676   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
   3677   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
   3678                               bool MightBeOdrUse = true);
   3679   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
   3680   void MarkDeclRefReferenced(DeclRefExpr *E);
   3681   void MarkMemberReferenced(MemberExpr *E);
   3682 
   3683   void UpdateMarkingForLValueToRValue(Expr *E);
   3684   void CleanupVarDeclMarking();
   3685 
   3686   enum TryCaptureKind {
   3687     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
   3688   };
   3689 
   3690   /// \brief Try to capture the given variable.
   3691   ///
   3692   /// \param Var The variable to capture.
   3693   ///
   3694   /// \param Loc The location at which the capture occurs.
   3695   ///
   3696   /// \param Kind The kind of capture, which may be implicit (for either a
   3697   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
   3698   ///
   3699   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
   3700   /// an explicit lambda capture.
   3701   ///
   3702   /// \param BuildAndDiagnose Whether we are actually supposed to add the
   3703   /// captures or diagnose errors. If false, this routine merely check whether
   3704   /// the capture can occur without performing the capture itself or complaining
   3705   /// if the variable cannot be captured.
   3706   ///
   3707   /// \param CaptureType Will be set to the type of the field used to capture
   3708   /// this variable in the innermost block or lambda. Only valid when the
   3709   /// variable can be captured.
   3710   ///
   3711   /// \param DeclRefType Will be set to the type of a reference to the capture
   3712   /// from within the current scope. Only valid when the variable can be
   3713   /// captured.
   3714   ///
   3715   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
   3716   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
   3717   /// This is useful when enclosing lambdas must speculatively capture
   3718   /// variables that may or may not be used in certain specializations of
   3719   /// a nested generic lambda.
   3720   ///
   3721   /// \returns true if an error occurred (i.e., the variable cannot be
   3722   /// captured) and false if the capture succeeded.
   3723   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
   3724                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
   3725                           QualType &CaptureType,
   3726                           QualType &DeclRefType,
   3727                           const unsigned *const FunctionScopeIndexToStopAt);
   3728 
   3729   /// \brief Try to capture the given variable.
   3730   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
   3731                           TryCaptureKind Kind = TryCapture_Implicit,
   3732                           SourceLocation EllipsisLoc = SourceLocation());
   3733 
   3734   /// \brief Checks if the variable must be captured.
   3735   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
   3736 
   3737   /// \brief Given a variable, determine the type that a reference to that
   3738   /// variable will have in the given scope.
   3739   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
   3740 
   3741   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
   3742   void MarkDeclarationsReferencedInExpr(Expr *E,
   3743                                         bool SkipLocalVariables = false);
   3744 
   3745   /// \brief Try to recover by turning the given expression into a
   3746   /// call.  Returns true if recovery was attempted or an error was
   3747   /// emitted; this may also leave the ExprResult invalid.
   3748   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
   3749                             bool ForceComplain = false,
   3750                             bool (*IsPlausibleResult)(QualType) = nullptr);
   3751 
   3752   /// \brief Figure out if an expression could be turned into a call.
   3753   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
   3754                      UnresolvedSetImpl &NonTemplateOverloads);
   3755 
   3756   /// \brief Conditionally issue a diagnostic based on the current
   3757   /// evaluation context.
   3758   ///
   3759   /// \param Statement If Statement is non-null, delay reporting the
   3760   /// diagnostic until the function body is parsed, and then do a basic
   3761   /// reachability analysis to determine if the statement is reachable.
   3762   /// If it is unreachable, the diagnostic will not be emitted.
   3763   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
   3764                            const PartialDiagnostic &PD);
   3765 
   3766   // Primary Expressions.
   3767   SourceRange getExprRange(Expr *E) const;
   3768 
   3769   ExprResult ActOnIdExpression(
   3770       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
   3771       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
   3772       std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
   3773       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
   3774 
   3775   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
   3776                               TemplateArgumentListInfo &Buffer,
   3777                               DeclarationNameInfo &NameInfo,
   3778                               const TemplateArgumentListInfo *&TemplateArgs);
   3779 
   3780   bool
   3781   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
   3782                       std::unique_ptr<CorrectionCandidateCallback> CCC,
   3783                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
   3784                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
   3785 
   3786   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
   3787                                 IdentifierInfo *II,
   3788                                 bool AllowBuiltinCreation=false);
   3789 
   3790   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
   3791                                         SourceLocation TemplateKWLoc,
   3792                                         const DeclarationNameInfo &NameInfo,
   3793                                         bool isAddressOfOperand,
   3794                                 const TemplateArgumentListInfo *TemplateArgs);
   3795 
   3796   ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
   3797                               ExprValueKind VK,
   3798                               SourceLocation Loc,
   3799                               const CXXScopeSpec *SS = nullptr);
   3800   ExprResult
   3801   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
   3802                    const DeclarationNameInfo &NameInfo,
   3803                    const CXXScopeSpec *SS = nullptr,
   3804                    NamedDecl *FoundD = nullptr,
   3805                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
   3806   ExprResult
   3807   BuildAnonymousStructUnionMemberReference(
   3808       const CXXScopeSpec &SS,
   3809       SourceLocation nameLoc,
   3810       IndirectFieldDecl *indirectField,
   3811       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
   3812       Expr *baseObjectExpr = nullptr,
   3813       SourceLocation opLoc = SourceLocation());
   3814 
   3815   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
   3816                                              SourceLocation TemplateKWLoc,
   3817                                              LookupResult &R,
   3818                                 const TemplateArgumentListInfo *TemplateArgs,
   3819                                              const Scope *S);
   3820   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
   3821                                      SourceLocation TemplateKWLoc,
   3822                                      LookupResult &R,
   3823                                 const TemplateArgumentListInfo *TemplateArgs,
   3824                                      bool IsDefiniteInstance,
   3825                                      const Scope *S);
   3826   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
   3827                                   const LookupResult &R,
   3828                                   bool HasTrailingLParen);
   3829 
   3830   ExprResult
   3831   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
   3832                                     const DeclarationNameInfo &NameInfo,
   3833                                     bool IsAddressOfOperand, const Scope *S,
   3834                                     TypeSourceInfo **RecoveryTSI = nullptr);
   3835 
   3836   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
   3837                                        SourceLocation TemplateKWLoc,
   3838                                 const DeclarationNameInfo &NameInfo,
   3839                                 const TemplateArgumentListInfo *TemplateArgs);
   3840 
   3841   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
   3842                                       LookupResult &R,
   3843                                       bool NeedsADL,
   3844                                       bool AcceptInvalidDecl = false);
   3845   ExprResult BuildDeclarationNameExpr(
   3846       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
   3847       NamedDecl *FoundD = nullptr,
   3848       const TemplateArgumentListInfo *TemplateArgs = nullptr,
   3849       bool AcceptInvalidDecl = false);
   3850 
   3851   ExprResult BuildLiteralOperatorCall(LookupResult &R,
   3852                       DeclarationNameInfo &SuffixInfo,
   3853                       ArrayRef<Expr *> Args,
   3854                       SourceLocation LitEndLoc,
   3855                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
   3856 
   3857   ExprResult BuildPredefinedExpr(SourceLocation Loc,
   3858                                  PredefinedExpr::IdentType IT);
   3859   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
   3860   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
   3861 
   3862   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
   3863 
   3864   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
   3865   ExprResult ActOnCharacterConstant(const Token &Tok,
   3866                                     Scope *UDLScope = nullptr);
   3867   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
   3868   ExprResult ActOnParenListExpr(SourceLocation L,
   3869                                 SourceLocation R,
   3870                                 MultiExprArg Val);
   3871 
   3872   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
   3873   /// fragments (e.g. "foo" "bar" L"baz").
   3874   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
   3875                                 Scope *UDLScope = nullptr);
   3876 
   3877   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
   3878                                        SourceLocation DefaultLoc,
   3879                                        SourceLocation RParenLoc,
   3880                                        Expr *ControllingExpr,
   3881                                        ArrayRef<ParsedType> ArgTypes,
   3882                                        ArrayRef<Expr *> ArgExprs);
   3883   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
   3884                                         SourceLocation DefaultLoc,
   3885                                         SourceLocation RParenLoc,
   3886                                         Expr *ControllingExpr,
   3887                                         ArrayRef<TypeSourceInfo *> Types,
   3888                                         ArrayRef<Expr *> Exprs);
   3889 
   3890   // Binary/Unary Operators.  'Tok' is the token for the operator.
   3891   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
   3892                                   Expr *InputExpr);
   3893   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
   3894                           UnaryOperatorKind Opc, Expr *Input);
   3895   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
   3896                           tok::TokenKind Op, Expr *Input);
   3897 
   3898   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
   3899 
   3900   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
   3901                                             SourceLocation OpLoc,
   3902                                             UnaryExprOrTypeTrait ExprKind,
   3903                                             SourceRange R);
   3904   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
   3905                                             UnaryExprOrTypeTrait ExprKind);
   3906   ExprResult
   3907     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
   3908                                   UnaryExprOrTypeTrait ExprKind,
   3909                                   bool IsType, void *TyOrEx,
   3910                                   SourceRange ArgRange);
   3911 
   3912   ExprResult CheckPlaceholderExpr(Expr *E);
   3913   bool CheckVecStepExpr(Expr *E);
   3914 
   3915   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
   3916   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
   3917                                         SourceRange ExprRange,
   3918                                         UnaryExprOrTypeTrait ExprKind);
   3919   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
   3920                                           SourceLocation OpLoc,
   3921                                           IdentifierInfo &Name,
   3922                                           SourceLocation NameLoc,
   3923                                           SourceLocation RParenLoc);
   3924   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
   3925                                  tok::TokenKind Kind, Expr *Input);
   3926 
   3927   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
   3928                                      Expr *Idx, SourceLocation RLoc);
   3929   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
   3930                                              Expr *Idx, SourceLocation RLoc);
   3931   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
   3932                                       Expr *LowerBound, SourceLocation ColonLoc,
   3933                                       Expr *Length, SourceLocation RBLoc);
   3934 
   3935   // This struct is for use by ActOnMemberAccess to allow
   3936   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
   3937   // changing the access operator from a '.' to a '->' (to see if that is the
   3938   // change needed to fix an error about an unknown member, e.g. when the class
   3939   // defines a custom operator->).
   3940   struct ActOnMemberAccessExtraArgs {
   3941     Scope *S;
   3942     UnqualifiedId &Id;
   3943     Decl *ObjCImpDecl;
   3944   };
   3945 
   3946   ExprResult BuildMemberReferenceExpr(
   3947       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
   3948       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
   3949       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
   3950       const TemplateArgumentListInfo *TemplateArgs,
   3951       const Scope *S,
   3952       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
   3953 
   3954   ExprResult
   3955   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
   3956                            bool IsArrow, const CXXScopeSpec &SS,
   3957                            SourceLocation TemplateKWLoc,
   3958                            NamedDecl *FirstQualifierInScope, LookupResult &R,
   3959                            const TemplateArgumentListInfo *TemplateArgs,
   3960                            const Scope *S,
   3961                            bool SuppressQualifierCheck = false,
   3962                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
   3963 
   3964   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
   3965 
   3966   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
   3967                                      const CXXScopeSpec &SS,
   3968                                      const LookupResult &R);
   3969 
   3970   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
   3971                                       bool IsArrow, SourceLocation OpLoc,
   3972                                       const CXXScopeSpec &SS,
   3973                                       SourceLocation TemplateKWLoc,
   3974                                       NamedDecl *FirstQualifierInScope,
   3975                                const DeclarationNameInfo &NameInfo,
   3976                                const TemplateArgumentListInfo *TemplateArgs);
   3977 
   3978   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
   3979                                    SourceLocation OpLoc,
   3980                                    tok::TokenKind OpKind,
   3981                                    CXXScopeSpec &SS,
   3982                                    SourceLocation TemplateKWLoc,
   3983                                    UnqualifiedId &Member,
   3984                                    Decl *ObjCImpDecl);
   3985 
   3986   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
   3987   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
   3988                                FunctionDecl *FDecl,
   3989                                const FunctionProtoType *Proto,
   3990                                ArrayRef<Expr *> Args,
   3991                                SourceLocation RParenLoc,
   3992                                bool ExecConfig = false);
   3993   void CheckStaticArrayArgument(SourceLocation CallLoc,
   3994                                 ParmVarDecl *Param,
   3995                                 const Expr *ArgExpr);
   3996 
   3997   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
   3998   /// This provides the location of the left/right parens and a list of comma
   3999   /// locations.
   4000   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
   4001                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
   4002                            Expr *ExecConfig = nullptr,
   4003                            bool IsExecConfig = false);
   4004   ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
   4005                                    SourceLocation LParenLoc,
   4006                                    ArrayRef<Expr *> Arg,
   4007                                    SourceLocation RParenLoc,
   4008                                    Expr *Config = nullptr,
   4009                                    bool IsExecConfig = false);
   4010 
   4011   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
   4012                                      MultiExprArg ExecConfig,
   4013                                      SourceLocation GGGLoc);
   4014 
   4015   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
   4016                            Declarator &D, ParsedType &Ty,
   4017                            SourceLocation RParenLoc, Expr *CastExpr);
   4018   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
   4019                                  TypeSourceInfo *Ty,
   4020                                  SourceLocation RParenLoc,
   4021                                  Expr *Op);
   4022   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
   4023 
   4024   /// \brief Build an altivec or OpenCL literal.
   4025   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
   4026                                 SourceLocation RParenLoc, Expr *E,
   4027                                 TypeSourceInfo *TInfo);
   4028 
   4029   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
   4030 
   4031   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
   4032                                   ParsedType Ty,
   4033                                   SourceLocation RParenLoc,
   4034                                   Expr *InitExpr);
   4035 
   4036   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
   4037                                       TypeSourceInfo *TInfo,
   4038                                       SourceLocation RParenLoc,
   4039                                       Expr *LiteralExpr);
   4040 
   4041   ExprResult ActOnInitList(SourceLocation LBraceLoc,
   4042                            MultiExprArg InitArgList,
   4043                            SourceLocation RBraceLoc);
   4044 
   4045   ExprResult ActOnDesignatedInitializer(Designation &Desig,
   4046                                         SourceLocation Loc,
   4047                                         bool GNUSyntax,
   4048                                         ExprResult Init);
   4049 
   4050 private:
   4051   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
   4052 
   4053 public:
   4054   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
   4055                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
   4056   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
   4057                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
   4058   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
   4059                                 Expr *LHSExpr, Expr *RHSExpr);
   4060 
   4061   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
   4062 
   4063   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
   4064   /// in the case of a the GNU conditional expr extension.
   4065   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
   4066                                 SourceLocation ColonLoc,
   4067                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
   4068 
   4069   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
   4070   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
   4071                             LabelDecl *TheDecl);
   4072 
   4073   void ActOnStartStmtExpr();
   4074   ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
   4075                            SourceLocation RPLoc); // "({..})"
   4076   void ActOnStmtExprError();
   4077 
   4078   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
   4079   struct OffsetOfComponent {
   4080     SourceLocation LocStart, LocEnd;
   4081     bool isBrackets;  // true if [expr], false if .ident
   4082     union {
   4083       IdentifierInfo *IdentInfo;
   4084       Expr *E;
   4085     } U;
   4086   };
   4087 
   4088   /// __builtin_offsetof(type, a.b[123][456].c)
   4089   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
   4090                                   TypeSourceInfo *TInfo,
   4091                                   ArrayRef<OffsetOfComponent> Components,
   4092                                   SourceLocation RParenLoc);
   4093   ExprResult ActOnBuiltinOffsetOf(Scope *S,
   4094                                   SourceLocation BuiltinLoc,
   4095                                   SourceLocation TypeLoc,
   4096                                   ParsedType ParsedArgTy,
   4097                                   ArrayRef<OffsetOfComponent> Components,
   4098                                   SourceLocation RParenLoc);
   4099 
   4100   // __builtin_choose_expr(constExpr, expr1, expr2)
   4101   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
   4102                              Expr *CondExpr, Expr *LHSExpr,
   4103                              Expr *RHSExpr, SourceLocation RPLoc);
   4104 
   4105   // __builtin_va_arg(expr, type)
   4106   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
   4107                         SourceLocation RPLoc);
   4108   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
   4109                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
   4110 
   4111   // __null
   4112   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
   4113 
   4114   bool CheckCaseExpression(Expr *E);
   4115 
   4116   /// \brief Describes the result of an "if-exists" condition check.
   4117   enum IfExistsResult {
   4118     /// \brief The symbol exists.
   4119     IER_Exists,
   4120 
   4121     /// \brief The symbol does not exist.
   4122     IER_DoesNotExist,
   4123 
   4124     /// \brief The name is a dependent name, so the results will differ
   4125     /// from one instantiation to the next.
   4126     IER_Dependent,
   4127 
   4128     /// \brief An error occurred.
   4129     IER_Error
   4130   };
   4131 
   4132   IfExistsResult
   4133   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
   4134                                const DeclarationNameInfo &TargetNameInfo);
   4135 
   4136   IfExistsResult
   4137   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
   4138                                bool IsIfExists, CXXScopeSpec &SS,
   4139                                UnqualifiedId &Name);
   4140 
   4141   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
   4142                                         bool IsIfExists,
   4143                                         NestedNameSpecifierLoc QualifierLoc,
   4144                                         DeclarationNameInfo NameInfo,
   4145                                         Stmt *Nested);
   4146   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
   4147                                         bool IsIfExists,
   4148                                         CXXScopeSpec &SS, UnqualifiedId &Name,
   4149                                         Stmt *Nested);
   4150 
   4151   //===------------------------- "Block" Extension ------------------------===//
   4152 
   4153   /// ActOnBlockStart - This callback is invoked when a block literal is
   4154   /// started.
   4155   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
   4156 
   4157   /// ActOnBlockArguments - This callback allows processing of block arguments.
   4158   /// If there are no arguments, this is still invoked.
   4159   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
   4160                            Scope *CurScope);
   4161 
   4162   /// ActOnBlockError - If there is an error parsing a block, this callback
   4163   /// is invoked to pop the information about the block from the action impl.
   4164   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
   4165 
   4166   /// ActOnBlockStmtExpr - This is called when the body of a block statement
   4167   /// literal was successfully completed.  ^(int x){...}
   4168   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
   4169                                 Scope *CurScope);
   4170 
   4171   //===---------------------------- Clang Extensions ----------------------===//
   4172 
   4173   /// __builtin_convertvector(...)
   4174   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
   4175                                     SourceLocation BuiltinLoc,
   4176                                     SourceLocation RParenLoc);
   4177 
   4178   //===---------------------------- OpenCL Features -----------------------===//
   4179 
   4180   /// __builtin_astype(...)
   4181   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
   4182                              SourceLocation BuiltinLoc,
   4183                              SourceLocation RParenLoc);
   4184 
   4185   //===---------------------------- C++ Features --------------------------===//
   4186 
   4187   // Act on C++ namespaces
   4188   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
   4189                                SourceLocation NamespaceLoc,
   4190                                SourceLocation IdentLoc,
   4191                                IdentifierInfo *Ident,
   4192                                SourceLocation LBrace,
   4193                                AttributeList *AttrList,
   4194                                UsingDirectiveDecl * &UsingDecl);
   4195   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
   4196 
   4197   NamespaceDecl *getStdNamespace() const;
   4198   NamespaceDecl *getOrCreateStdNamespace();
   4199 
   4200   CXXRecordDecl *getStdBadAlloc() const;
   4201 
   4202   /// \brief Tests whether Ty is an instance of std::initializer_list and, if
   4203   /// it is and Element is not NULL, assigns the element type to Element.
   4204   bool isStdInitializerList(QualType Ty, QualType *Element);
   4205 
   4206   /// \brief Looks for the std::initializer_list template and instantiates it
   4207   /// with Element, or emits an error if it's not found.
   4208   ///
   4209   /// \returns The instantiated template, or null on error.
   4210   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
   4211 
   4212   /// \brief Determine whether Ctor is an initializer-list constructor, as
   4213   /// defined in [dcl.init.list]p2.
   4214   bool isInitListConstructor(const CXXConstructorDecl *Ctor);
   4215 
   4216   Decl *ActOnUsingDirective(Scope *CurScope,
   4217                             SourceLocation UsingLoc,
   4218                             SourceLocation NamespcLoc,
   4219                             CXXScopeSpec &SS,
   4220                             SourceLocation IdentLoc,
   4221                             IdentifierInfo *NamespcName,
   4222                             AttributeList *AttrList);
   4223 
   4224   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
   4225 
   4226   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
   4227                                SourceLocation NamespaceLoc,
   4228                                SourceLocation AliasLoc,
   4229                                IdentifierInfo *Alias,
   4230                                CXXScopeSpec &SS,
   4231                                SourceLocation IdentLoc,
   4232                                IdentifierInfo *Ident);
   4233 
   4234   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
   4235   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
   4236                             const LookupResult &PreviousDecls,
   4237                             UsingShadowDecl *&PrevShadow);
   4238   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
   4239                                         NamedDecl *Target,
   4240                                         UsingShadowDecl *PrevDecl);
   4241 
   4242   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
   4243                                    bool HasTypenameKeyword,
   4244                                    const CXXScopeSpec &SS,
   4245                                    SourceLocation NameLoc,
   4246                                    const LookupResult &Previous);
   4247   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
   4248                                const CXXScopeSpec &SS,
   4249                                const DeclarationNameInfo &NameInfo,
   4250                                SourceLocation NameLoc);
   4251 
   4252   NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
   4253                                    SourceLocation UsingLoc,
   4254                                    CXXScopeSpec &SS,
   4255                                    DeclarationNameInfo NameInfo,
   4256                                    AttributeList *AttrList,
   4257                                    bool IsInstantiation,
   4258                                    bool HasTypenameKeyword,
   4259                                    SourceLocation TypenameLoc);
   4260 
   4261   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
   4262 
   4263   /// Given a derived-class using shadow declaration for a constructor and the
   4264   /// correspnding base class constructor, find or create the implicit
   4265   /// synthesized derived class constructor to use for this initialization.
   4266   CXXConstructorDecl *
   4267   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
   4268                             ConstructorUsingShadowDecl *DerivedShadow);
   4269 
   4270   Decl *ActOnUsingDeclaration(Scope *CurScope,
   4271                               AccessSpecifier AS,
   4272                               bool HasUsingKeyword,
   4273                               SourceLocation UsingLoc,
   4274                               CXXScopeSpec &SS,
   4275                               UnqualifiedId &Name,
   4276                               AttributeList *AttrList,
   4277                               bool HasTypenameKeyword,
   4278                               SourceLocation TypenameLoc);
   4279   Decl *ActOnAliasDeclaration(Scope *CurScope,
   4280                               AccessSpecifier AS,
   4281                               MultiTemplateParamsArg TemplateParams,
   4282                               SourceLocation UsingLoc,
   4283                               UnqualifiedId &Name,
   4284                               AttributeList *AttrList,
   4285                               TypeResult Type,
   4286                               Decl *DeclFromDeclSpec);
   4287 
   4288   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
   4289   /// including handling of its default argument expressions.
   4290   ///
   4291   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
   4292   ExprResult
   4293   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   4294                         NamedDecl *FoundDecl,
   4295                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
   4296                         bool HadMultipleCandidates, bool IsListInitialization,
   4297                         bool IsStdInitListInitialization,
   4298                         bool RequiresZeroInit, unsigned ConstructKind,
   4299                         SourceRange ParenRange);
   4300 
   4301   /// Build a CXXConstructExpr whose constructor has already been resolved if
   4302   /// it denotes an inherited constructor.
   4303   ExprResult
   4304   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   4305                         CXXConstructorDecl *Constructor, bool Elidable,
   4306                         MultiExprArg Exprs,
   4307                         bool HadMultipleCandidates, bool IsListInitialization,
   4308                         bool IsStdInitListInitialization,
   4309                         bool RequiresZeroInit, unsigned ConstructKind,
   4310                         SourceRange ParenRange);
   4311 
   4312   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
   4313   // the constructor can be elidable?
   4314   ExprResult
   4315   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   4316                         NamedDecl *FoundDecl,
   4317                         CXXConstructorDecl *Constructor, bool Elidable,
   4318                         MultiExprArg Exprs, bool HadMultipleCandidates,
   4319                         bool IsListInitialization,
   4320                         bool IsStdInitListInitialization, bool RequiresZeroInit,
   4321                         unsigned ConstructKind, SourceRange ParenRange);
   4322 
   4323   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
   4324 
   4325   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
   4326   /// the default expr if needed.
   4327   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
   4328                                     FunctionDecl *FD,
   4329                                     ParmVarDecl *Param);
   4330 
   4331   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
   4332   /// constructed variable.
   4333   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
   4334 
   4335   /// \brief Helper class that collects exception specifications for
   4336   /// implicitly-declared special member functions.
   4337   class ImplicitExceptionSpecification {
   4338     // Pointer to allow copying
   4339     Sema *Self;
   4340     // We order exception specifications thus:
   4341     // noexcept is the most restrictive, but is only used in C++11.
   4342     // throw() comes next.
   4343     // Then a throw(collected exceptions)
   4344     // Finally no specification, which is expressed as noexcept(false).
   4345     // throw(...) is used instead if any called function uses it.
   4346     ExceptionSpecificationType ComputedEST;
   4347     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
   4348     SmallVector<QualType, 4> Exceptions;
   4349 
   4350     void ClearExceptions() {
   4351       ExceptionsSeen.clear();
   4352       Exceptions.clear();
   4353     }
   4354 
   4355   public:
   4356     explicit ImplicitExceptionSpecification(Sema &Self)
   4357       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
   4358       if (!Self.getLangOpts().CPlusPlus11)
   4359         ComputedEST = EST_DynamicNone;
   4360     }
   4361 
   4362     /// \brief Get the computed exception specification type.
   4363     ExceptionSpecificationType getExceptionSpecType() const {
   4364       assert(ComputedEST != EST_ComputedNoexcept &&
   4365              "noexcept(expr) should not be a possible result");
   4366       return ComputedEST;
   4367     }
   4368 
   4369     /// \brief The number of exceptions in the exception specification.
   4370     unsigned size() const { return Exceptions.size(); }
   4371 
   4372     /// \brief The set of exceptions in the exception specification.
   4373     const QualType *data() const { return Exceptions.data(); }
   4374 
   4375     /// \brief Integrate another called method into the collected data.
   4376     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
   4377 
   4378     /// \brief Integrate an invoked expression into the collected data.
   4379     void CalledExpr(Expr *E);
   4380 
   4381     /// \brief Overwrite an EPI's exception specification with this
   4382     /// computed exception specification.
   4383     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
   4384       FunctionProtoType::ExceptionSpecInfo ESI;
   4385       ESI.Type = getExceptionSpecType();
   4386       if (ESI.Type == EST_Dynamic) {
   4387         ESI.Exceptions = Exceptions;
   4388       } else if (ESI.Type == EST_None) {
   4389         /// C++11 [except.spec]p14:
   4390         ///   The exception-specification is noexcept(false) if the set of
   4391         ///   potential exceptions of the special member function contains "any"
   4392         ESI.Type = EST_ComputedNoexcept;
   4393         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
   4394                                                      tok::kw_false).get();
   4395       }
   4396       return ESI;
   4397     }
   4398   };
   4399 
   4400   /// \brief Determine what sort of exception specification a defaulted
   4401   /// copy constructor of a class will have.
   4402   ImplicitExceptionSpecification
   4403   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
   4404                                            CXXMethodDecl *MD);
   4405 
   4406   /// \brief Determine what sort of exception specification a defaulted
   4407   /// default constructor of a class will have, and whether the parameter
   4408   /// will be const.
   4409   ImplicitExceptionSpecification
   4410   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
   4411 
   4412   /// \brief Determine what sort of exception specification a defautled
   4413   /// copy assignment operator of a class will have, and whether the
   4414   /// parameter will be const.
   4415   ImplicitExceptionSpecification
   4416   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
   4417 
   4418   /// \brief Determine what sort of exception specification a defaulted move
   4419   /// constructor of a class will have.
   4420   ImplicitExceptionSpecification
   4421   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
   4422 
   4423   /// \brief Determine what sort of exception specification a defaulted move
   4424   /// assignment operator of a class will have.
   4425   ImplicitExceptionSpecification
   4426   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
   4427 
   4428   /// \brief Determine what sort of exception specification a defaulted
   4429   /// destructor of a class will have.
   4430   ImplicitExceptionSpecification
   4431   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
   4432 
   4433   /// \brief Determine what sort of exception specification an inheriting
   4434   /// constructor of a class will have.
   4435   ImplicitExceptionSpecification
   4436   ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
   4437                                      CXXConstructorDecl *CD);
   4438 
   4439   /// \brief Evaluate the implicit exception specification for a defaulted
   4440   /// special member function.
   4441   void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
   4442 
   4443   /// \brief Check the given exception-specification and update the
   4444   /// exception specification information with the results.
   4445   void checkExceptionSpecification(bool IsTopLevel,
   4446                                    ExceptionSpecificationType EST,
   4447                                    ArrayRef<ParsedType> DynamicExceptions,
   4448                                    ArrayRef<SourceRange> DynamicExceptionRanges,
   4449                                    Expr *NoexceptExpr,
   4450                                    SmallVectorImpl<QualType> &Exceptions,
   4451                                    FunctionProtoType::ExceptionSpecInfo &ESI);
   4452 
   4453   /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
   4454   /// parse an exception specification to work around a libstdc++ bug.
   4455   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
   4456 
   4457   /// \brief Add an exception-specification to the given member function
   4458   /// (or member function template). The exception-specification was parsed
   4459   /// after the method itself was declared.
   4460   void actOnDelayedExceptionSpecification(Decl *Method,
   4461          ExceptionSpecificationType EST,
   4462          SourceRange SpecificationRange,
   4463          ArrayRef<ParsedType> DynamicExceptions,
   4464          ArrayRef<SourceRange> DynamicExceptionRanges,
   4465          Expr *NoexceptExpr);
   4466 
   4467   class InheritedConstructorInfo;
   4468 
   4469   /// \brief Determine if a special member function should have a deleted
   4470   /// definition when it is defaulted.
   4471   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
   4472                                  InheritedConstructorInfo *ICI = nullptr,
   4473                                  bool Diagnose = false);
   4474 
   4475   /// \brief Declare the implicit default constructor for the given class.
   4476   ///
   4477   /// \param ClassDecl The class declaration into which the implicit
   4478   /// default constructor will be added.
   4479   ///
   4480   /// \returns The implicitly-declared default constructor.
   4481   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
   4482                                                      CXXRecordDecl *ClassDecl);
   4483 
   4484   /// DefineImplicitDefaultConstructor - Checks for feasibility of
   4485   /// defining this constructor as the default constructor.
   4486   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
   4487                                         CXXConstructorDecl *Constructor);
   4488 
   4489   /// \brief Declare the implicit destructor for the given class.
   4490   ///
   4491   /// \param ClassDecl The class declaration into which the implicit
   4492   /// destructor will be added.
   4493   ///
   4494   /// \returns The implicitly-declared destructor.
   4495   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
   4496 
   4497   /// DefineImplicitDestructor - Checks for feasibility of
   4498   /// defining this destructor as the default destructor.
   4499   void DefineImplicitDestructor(SourceLocation CurrentLocation,
   4500                                 CXXDestructorDecl *Destructor);
   4501 
   4502   /// \brief Build an exception spec for destructors that don't have one.
   4503   ///
   4504   /// C++11 says that user-defined destructors with no exception spec get one
   4505   /// that looks as if the destructor was implicitly declared.
   4506   void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
   4507                                      CXXDestructorDecl *Destructor);
   4508 
   4509   /// \brief Define the specified inheriting constructor.
   4510   void DefineInheritingConstructor(SourceLocation UseLoc,
   4511                                    CXXConstructorDecl *Constructor);
   4512 
   4513   /// \brief Declare the implicit copy constructor for the given class.
   4514   ///
   4515   /// \param ClassDecl The class declaration into which the implicit
   4516   /// copy constructor will be added.
   4517   ///
   4518   /// \returns The implicitly-declared copy constructor.
   4519   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
   4520 
   4521   /// DefineImplicitCopyConstructor - Checks for feasibility of
   4522   /// defining this constructor as the copy constructor.
   4523   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
   4524                                      CXXConstructorDecl *Constructor);
   4525 
   4526   /// \brief Declare the implicit move constructor for the given class.
   4527   ///
   4528   /// \param ClassDecl The Class declaration into which the implicit
   4529   /// move constructor will be added.
   4530   ///
   4531   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
   4532   /// declared.
   4533   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
   4534 
   4535   /// DefineImplicitMoveConstructor - Checks for feasibility of
   4536   /// defining this constructor as the move constructor.
   4537   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
   4538                                      CXXConstructorDecl *Constructor);
   4539 
   4540   /// \brief Declare the implicit copy assignment operator for the given class.
   4541   ///
   4542   /// \param ClassDecl The class declaration into which the implicit
   4543   /// copy assignment operator will be added.
   4544   ///
   4545   /// \returns The implicitly-declared copy assignment operator.
   4546   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
   4547 
   4548   /// \brief Defines an implicitly-declared copy assignment operator.
   4549   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
   4550                                     CXXMethodDecl *MethodDecl);
   4551 
   4552   /// \brief Declare the implicit move assignment operator for the given class.
   4553   ///
   4554   /// \param ClassDecl The Class declaration into which the implicit
   4555   /// move assignment operator will be added.
   4556   ///
   4557   /// \returns The implicitly-declared move assignment operator, or NULL if it
   4558   /// wasn't declared.
   4559   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
   4560 
   4561   /// \brief Defines an implicitly-declared move assignment operator.
   4562   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
   4563                                     CXXMethodDecl *MethodDecl);
   4564 
   4565   /// \brief Force the declaration of any implicitly-declared members of this
   4566   /// class.
   4567   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
   4568 
   4569   /// \brief Check a completed declaration of an implicit special member.
   4570   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
   4571 
   4572   /// \brief Determine whether the given function is an implicitly-deleted
   4573   /// special member function.
   4574   bool isImplicitlyDeleted(FunctionDecl *FD);
   4575 
   4576   /// \brief Check whether 'this' shows up in the type of a static member
   4577   /// function after the (naturally empty) cv-qualifier-seq would be.
   4578   ///
   4579   /// \returns true if an error occurred.
   4580   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
   4581 
   4582   /// \brief Whether this' shows up in the exception specification of a static
   4583   /// member function.
   4584   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
   4585 
   4586   /// \brief Check whether 'this' shows up in the attributes of the given
   4587   /// static member function.
   4588   ///
   4589   /// \returns true if an error occurred.
   4590   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
   4591 
   4592   /// MaybeBindToTemporary - If the passed in expression has a record type with
   4593   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
   4594   /// it simply returns the passed in expression.
   4595   ExprResult MaybeBindToTemporary(Expr *E);
   4596 
   4597   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
   4598                                MultiExprArg ArgsPtr,
   4599                                SourceLocation Loc,
   4600                                SmallVectorImpl<Expr*> &ConvertedArgs,
   4601                                bool AllowExplicit = false,
   4602                                bool IsListInitialization = false);
   4603 
   4604   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
   4605                                           SourceLocation NameLoc,
   4606                                           IdentifierInfo &Name);
   4607 
   4608   ParsedType getDestructorName(SourceLocation TildeLoc,
   4609                                IdentifierInfo &II, SourceLocation NameLoc,
   4610                                Scope *S, CXXScopeSpec &SS,
   4611                                ParsedType ObjectType,
   4612                                bool EnteringContext);
   4613 
   4614   ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
   4615 
   4616   // Checks that reinterpret casts don't have undefined behavior.
   4617   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
   4618                                       bool IsDereference, SourceRange Range);
   4619 
   4620   /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
   4621   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
   4622                                tok::TokenKind Kind,
   4623                                SourceLocation LAngleBracketLoc,
   4624                                Declarator &D,
   4625                                SourceLocation RAngleBracketLoc,
   4626                                SourceLocation LParenLoc,
   4627                                Expr *E,
   4628                                SourceLocation RParenLoc);
   4629 
   4630   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
   4631                                tok::TokenKind Kind,
   4632                                TypeSourceInfo *Ty,
   4633                                Expr *E,
   4634                                SourceRange AngleBrackets,
   4635                                SourceRange Parens);
   4636 
   4637   ExprResult BuildCXXTypeId(QualType TypeInfoType,
   4638                             SourceLocation TypeidLoc,
   4639                             TypeSourceInfo *Operand,
   4640                             SourceLocation RParenLoc);
   4641   ExprResult BuildCXXTypeId(QualType TypeInfoType,
   4642                             SourceLocation TypeidLoc,
   4643                             Expr *Operand,
   4644                             SourceLocation RParenLoc);
   4645 
   4646   /// ActOnCXXTypeid - Parse typeid( something ).
   4647   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
   4648                             SourceLocation LParenLoc, bool isType,
   4649                             void *TyOrExpr,
   4650                             SourceLocation RParenLoc);
   4651 
   4652   ExprResult BuildCXXUuidof(QualType TypeInfoType,
   4653                             SourceLocation TypeidLoc,
   4654                             TypeSourceInfo *Operand,
   4655                             SourceLocation RParenLoc);
   4656   ExprResult BuildCXXUuidof(QualType TypeInfoType,
   4657                             SourceLocation TypeidLoc,
   4658                             Expr *Operand,
   4659                             SourceLocation RParenLoc);
   4660 
   4661   /// ActOnCXXUuidof - Parse __uuidof( something ).
   4662   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
   4663                             SourceLocation LParenLoc, bool isType,
   4664                             void *TyOrExpr,
   4665                             SourceLocation RParenLoc);
   4666 
   4667   /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
   4668   ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
   4669                               tok::TokenKind Operator,
   4670                               SourceLocation EllipsisLoc, Expr *RHS,
   4671                               SourceLocation RParenLoc);
   4672   ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
   4673                               BinaryOperatorKind Operator,
   4674                               SourceLocation EllipsisLoc, Expr *RHS,
   4675                               SourceLocation RParenLoc);
   4676   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
   4677                                    BinaryOperatorKind Operator);
   4678 
   4679   //// ActOnCXXThis -  Parse 'this' pointer.
   4680   ExprResult ActOnCXXThis(SourceLocation loc);
   4681 
   4682   /// \brief Try to retrieve the type of the 'this' pointer.
   4683   ///
   4684   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
   4685   QualType getCurrentThisType();
   4686 
   4687   /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
   4688   /// current context not being a non-static member function. In such cases,
   4689   /// this provides the type used for 'this'.
   4690   QualType CXXThisTypeOverride;
   4691 
   4692   /// \brief RAII object used to temporarily allow the C++ 'this' expression
   4693   /// to be used, with the given qualifiers on the current class type.
   4694   class CXXThisScopeRAII {
   4695     Sema &S;
   4696     QualType OldCXXThisTypeOverride;
   4697     bool Enabled;
   4698 
   4699   public:
   4700     /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
   4701     /// using the given declaration (which is either a class template or a
   4702     /// class) along with the given qualifiers.
   4703     /// along with the qualifiers placed on '*this'.
   4704     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
   4705                      bool Enabled = true);
   4706 
   4707     ~CXXThisScopeRAII();
   4708   };
   4709 
   4710   /// \brief Make sure the value of 'this' is actually available in the current
   4711   /// context, if it is a potentially evaluated context.
   4712   ///
   4713   /// \param Loc The location at which the capture of 'this' occurs.
   4714   ///
   4715   /// \param Explicit Whether 'this' is explicitly captured in a lambda
   4716   /// capture list.
   4717   ///
   4718   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
   4719   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
   4720   /// This is useful when enclosing lambdas must speculatively capture
   4721   /// 'this' that may or may not be used in certain specializations of
   4722   /// a nested generic lambda (depending on whether the name resolves to
   4723   /// a non-static member function or a static function).
   4724   /// \return returns 'true' if failed, 'false' if success.
   4725   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
   4726       bool BuildAndDiagnose = true,
   4727       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
   4728       bool ByCopy = false);
   4729 
   4730   /// \brief Determine whether the given type is the type of *this that is used
   4731   /// outside of the body of a member function for a type that is currently
   4732   /// being defined.
   4733   bool isThisOutsideMemberFunctionBody(QualType BaseType);
   4734 
   4735   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
   4736   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
   4737 
   4738 
   4739   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
   4740   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
   4741 
   4742   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
   4743   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
   4744 
   4745   //// ActOnCXXThrow -  Parse throw expressions.
   4746   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
   4747   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
   4748                            bool IsThrownVarInScope);
   4749   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
   4750 
   4751   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
   4752   /// Can be interpreted either as function-style casting ("int(x)")
   4753   /// or class type construction ("ClassType(x,y,z)")
   4754   /// or creation of a value-initialized type ("int()").
   4755   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
   4756                                        SourceLocation LParenLoc,
   4757                                        MultiExprArg Exprs,
   4758                                        SourceLocation RParenLoc);
   4759 
   4760   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
   4761                                        SourceLocation LParenLoc,
   4762                                        MultiExprArg Exprs,
   4763                                        SourceLocation RParenLoc);
   4764 
   4765   /// ActOnCXXNew - Parsed a C++ 'new' expression.
   4766   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
   4767                          SourceLocation PlacementLParen,
   4768                          MultiExprArg PlacementArgs,
   4769                          SourceLocation PlacementRParen,
   4770                          SourceRange TypeIdParens, Declarator &D,
   4771                          Expr *Initializer);
   4772   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
   4773                          SourceLocation PlacementLParen,
   4774                          MultiExprArg PlacementArgs,
   4775                          SourceLocation PlacementRParen,
   4776                          SourceRange TypeIdParens,
   4777                          QualType AllocType,
   4778                          TypeSourceInfo *AllocTypeInfo,
   4779                          Expr *ArraySize,
   4780                          SourceRange DirectInitRange,
   4781                          Expr *Initializer,
   4782                          bool TypeMayContainAuto = true);
   4783 
   4784   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
   4785                           SourceRange R);
   4786   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
   4787                                bool UseGlobal, QualType AllocType, bool IsArray,
   4788                                MultiExprArg PlaceArgs,
   4789                                FunctionDecl *&OperatorNew,
   4790                                FunctionDecl *&OperatorDelete);
   4791   bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
   4792                               DeclarationName Name, MultiExprArg Args,
   4793                               DeclContext *Ctx,
   4794                               bool AllowMissing, FunctionDecl *&Operator,
   4795                               bool Diagnose = true);
   4796   void DeclareGlobalNewDelete();
   4797   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
   4798                                        QualType Param1,
   4799                                        QualType Param2 = QualType());
   4800 
   4801   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
   4802                                 DeclarationName Name, FunctionDecl* &Operator,
   4803                                 bool Diagnose = true);
   4804   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
   4805                                               bool CanProvideSize,
   4806                                               DeclarationName Name);
   4807 
   4808   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
   4809   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
   4810                             bool UseGlobal, bool ArrayForm,
   4811                             Expr *Operand);
   4812   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
   4813                             bool IsDelete, bool CallCanBeVirtual,
   4814                             bool WarnOnNonAbstractTypes,
   4815                             SourceLocation DtorLoc);
   4816 
   4817   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
   4818                                Expr *Operand, SourceLocation RParen);
   4819   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
   4820                                   SourceLocation RParen);
   4821 
   4822   /// \brief Parsed one of the type trait support pseudo-functions.
   4823   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
   4824                             ArrayRef<ParsedType> Args,
   4825                             SourceLocation RParenLoc);
   4826   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
   4827                             ArrayRef<TypeSourceInfo *> Args,
   4828                             SourceLocation RParenLoc);
   4829 
   4830   /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
   4831   /// pseudo-functions.
   4832   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
   4833                                  SourceLocation KWLoc,
   4834                                  ParsedType LhsTy,
   4835                                  Expr *DimExpr,
   4836                                  SourceLocation RParen);
   4837 
   4838   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
   4839                                  SourceLocation KWLoc,
   4840                                  TypeSourceInfo *TSInfo,
   4841                                  Expr *DimExpr,
   4842                                  SourceLocation RParen);
   4843 
   4844   /// ActOnExpressionTrait - Parsed one of the unary type trait support
   4845   /// pseudo-functions.
   4846   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
   4847                                   SourceLocation KWLoc,
   4848                                   Expr *Queried,
   4849                                   SourceLocation RParen);
   4850 
   4851   ExprResult BuildExpressionTrait(ExpressionTrait OET,
   4852                                   SourceLocation KWLoc,
   4853                                   Expr *Queried,
   4854                                   SourceLocation RParen);
   4855 
   4856   ExprResult ActOnStartCXXMemberReference(Scope *S,
   4857                                           Expr *Base,
   4858                                           SourceLocation OpLoc,
   4859                                           tok::TokenKind OpKind,
   4860                                           ParsedType &ObjectType,
   4861                                           bool &MayBePseudoDestructor);
   4862 
   4863   ExprResult BuildPseudoDestructorExpr(Expr *Base,
   4864                                        SourceLocation OpLoc,
   4865                                        tok::TokenKind OpKind,
   4866                                        const CXXScopeSpec &SS,
   4867                                        TypeSourceInfo *ScopeType,
   4868                                        SourceLocation CCLoc,
   4869                                        SourceLocation TildeLoc,
   4870                                      PseudoDestructorTypeStorage DestroyedType);
   4871 
   4872   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
   4873                                        SourceLocation OpLoc,
   4874                                        tok::TokenKind OpKind,
   4875                                        CXXScopeSpec &SS,
   4876                                        UnqualifiedId &FirstTypeName,
   4877                                        SourceLocation CCLoc,
   4878                                        SourceLocation TildeLoc,
   4879                                        UnqualifiedId &SecondTypeName);
   4880 
   4881   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
   4882                                        SourceLocation OpLoc,
   4883                                        tok::TokenKind OpKind,
   4884                                        SourceLocation TildeLoc,
   4885                                        const DeclSpec& DS);
   4886 
   4887   /// MaybeCreateExprWithCleanups - If the current full-expression
   4888   /// requires any cleanups, surround it with a ExprWithCleanups node.
   4889   /// Otherwise, just returns the passed-in expression.
   4890   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
   4891   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
   4892   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
   4893 
   4894   MaterializeTemporaryExpr *
   4895   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
   4896                                  bool BoundToLvalueReference);
   4897 
   4898   ExprResult ActOnFinishFullExpr(Expr *Expr) {
   4899     return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
   4900                                           : SourceLocation());
   4901   }
   4902   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
   4903                                  bool DiscardedValue = false,
   4904                                  bool IsConstexpr = false,
   4905                                  bool IsLambdaInitCaptureInitializer = false);
   4906   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
   4907 
   4908   // Marks SS invalid if it represents an incomplete type.
   4909   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
   4910 
   4911   DeclContext *computeDeclContext(QualType T);
   4912   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
   4913                                   bool EnteringContext = false);
   4914   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
   4915   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
   4916 
   4917   /// \brief The parser has parsed a global nested-name-specifier '::'.
   4918   ///
   4919   /// \param CCLoc The location of the '::'.
   4920   ///
   4921   /// \param SS The nested-name-specifier, which will be updated in-place
   4922   /// to reflect the parsed nested-name-specifier.
   4923   ///
   4924   /// \returns true if an error occurred, false otherwise.
   4925   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
   4926 
   4927   /// \brief The parser has parsed a '__super' nested-name-specifier.
   4928   ///
   4929   /// \param SuperLoc The location of the '__super' keyword.
   4930   ///
   4931   /// \param ColonColonLoc The location of the '::'.
   4932   ///
   4933   /// \param SS The nested-name-specifier, which will be updated in-place
   4934   /// to reflect the parsed nested-name-specifier.
   4935   ///
   4936   /// \returns true if an error occurred, false otherwise.
   4937   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
   4938                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
   4939 
   4940   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
   4941                                        bool *CanCorrect = nullptr);
   4942   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
   4943 
   4944   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
   4945                                     SourceLocation IdLoc,
   4946                                     IdentifierInfo &II,
   4947                                     ParsedType ObjectType);
   4948 
   4949   bool BuildCXXNestedNameSpecifier(Scope *S,
   4950                                    IdentifierInfo &Identifier,
   4951                                    SourceLocation IdentifierLoc,
   4952                                    SourceLocation CCLoc,
   4953                                    QualType ObjectType,
   4954                                    bool EnteringContext,
   4955                                    CXXScopeSpec &SS,
   4956                                    NamedDecl *ScopeLookupResult,
   4957                                    bool ErrorRecoveryLookup,
   4958                                    bool *IsCorrectedToColon = nullptr);
   4959 
   4960   /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
   4961   ///
   4962   /// \param S The scope in which this nested-name-specifier occurs.
   4963   ///
   4964   /// \param Identifier The identifier preceding the '::'.
   4965   ///
   4966   /// \param IdentifierLoc The location of the identifier.
   4967   ///
   4968   /// \param CCLoc The location of the '::'.
   4969   ///
   4970   /// \param ObjectType The type of the object, if we're parsing
   4971   /// nested-name-specifier in a member access expression.
   4972   ///
   4973   /// \param EnteringContext Whether we're entering the context nominated by
   4974   /// this nested-name-specifier.
   4975   ///
   4976   /// \param SS The nested-name-specifier, which is both an input
   4977   /// parameter (the nested-name-specifier before this type) and an
   4978   /// output parameter (containing the full nested-name-specifier,
   4979   /// including this new type).
   4980   ///
   4981   /// \param ErrorRecoveryLookup If true, then this method is called to improve
   4982   /// error recovery. In this case do not emit error message.
   4983   ///
   4984   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
   4985   /// are allowed.  The bool value pointed by this parameter is set to 'true'
   4986   /// if the identifier is treated as if it was followed by ':', not '::'.
   4987   ///
   4988   /// \returns true if an error occurred, false otherwise.
   4989   bool ActOnCXXNestedNameSpecifier(Scope *S,
   4990                                    IdentifierInfo &Identifier,
   4991                                    SourceLocation IdentifierLoc,
   4992                                    SourceLocation CCLoc,
   4993                                    ParsedType ObjectType,
   4994                                    bool EnteringContext,
   4995                                    CXXScopeSpec &SS,
   4996                                    bool ErrorRecoveryLookup = false,
   4997                                    bool *IsCorrectedToColon = nullptr);
   4998 
   4999   ExprResult ActOnDecltypeExpression(Expr *E);
   5000 
   5001   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
   5002                                            const DeclSpec &DS,
   5003                                            SourceLocation ColonColonLoc);
   5004 
   5005   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
   5006                                  IdentifierInfo &Identifier,
   5007                                  SourceLocation IdentifierLoc,
   5008                                  SourceLocation ColonLoc,
   5009                                  ParsedType ObjectType,
   5010                                  bool EnteringContext);
   5011 
   5012   /// \brief The parser has parsed a nested-name-specifier
   5013   /// 'template[opt] template-name < template-args >::'.
   5014   ///
   5015   /// \param S The scope in which this nested-name-specifier occurs.
   5016   ///
   5017   /// \param SS The nested-name-specifier, which is both an input
   5018   /// parameter (the nested-name-specifier before this type) and an
   5019   /// output parameter (containing the full nested-name-specifier,
   5020   /// including this new type).
   5021   ///
   5022   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
   5023   /// \param TemplateName the template name.
   5024   /// \param TemplateNameLoc The location of the template name.
   5025   /// \param LAngleLoc The location of the opening angle bracket  ('<').
   5026   /// \param TemplateArgs The template arguments.
   5027   /// \param RAngleLoc The location of the closing angle bracket  ('>').
   5028   /// \param CCLoc The location of the '::'.
   5029   ///
   5030   /// \param EnteringContext Whether we're entering the context of the
   5031   /// nested-name-specifier.
   5032   ///
   5033   ///
   5034   /// \returns true if an error occurred, false otherwise.
   5035   bool ActOnCXXNestedNameSpecifier(Scope *S,
   5036                                    CXXScopeSpec &SS,
   5037                                    SourceLocation TemplateKWLoc,
   5038                                    TemplateTy TemplateName,
   5039                                    SourceLocation TemplateNameLoc,
   5040                                    SourceLocation LAngleLoc,
   5041                                    ASTTemplateArgsPtr TemplateArgs,
   5042                                    SourceLocation RAngleLoc,
   5043                                    SourceLocation CCLoc,
   5044                                    bool EnteringContext);
   5045 
   5046   /// \brief Given a C++ nested-name-specifier, produce an annotation value
   5047   /// that the parser can use later to reconstruct the given
   5048   /// nested-name-specifier.
   5049   ///
   5050   /// \param SS A nested-name-specifier.
   5051   ///
   5052   /// \returns A pointer containing all of the information in the
   5053   /// nested-name-specifier \p SS.
   5054   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
   5055 
   5056   /// \brief Given an annotation pointer for a nested-name-specifier, restore
   5057   /// the nested-name-specifier structure.
   5058   ///
   5059   /// \param Annotation The annotation pointer, produced by
   5060   /// \c SaveNestedNameSpecifierAnnotation().
   5061   ///
   5062   /// \param AnnotationRange The source range corresponding to the annotation.
   5063   ///
   5064   /// \param SS The nested-name-specifier that will be updated with the contents
   5065   /// of the annotation pointer.
   5066   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
   5067                                             SourceRange AnnotationRange,
   5068                                             CXXScopeSpec &SS);
   5069 
   5070   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
   5071 
   5072   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
   5073   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
   5074   /// After this method is called, according to [C++ 3.4.3p3], names should be
   5075   /// looked up in the declarator-id's scope, until the declarator is parsed and
   5076   /// ActOnCXXExitDeclaratorScope is called.
   5077   /// The 'SS' should be a non-empty valid CXXScopeSpec.
   5078   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
   5079 
   5080   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
   5081   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
   5082   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
   5083   /// Used to indicate that names should revert to being looked up in the
   5084   /// defining scope.
   5085   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
   5086 
   5087   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
   5088   /// initializer for the declaration 'Dcl'.
   5089   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
   5090   /// static data member of class X, names should be looked up in the scope of
   5091   /// class X.
   5092   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
   5093 
   5094   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
   5095   /// initializer for the declaration 'Dcl'.
   5096   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
   5097 
   5098   /// \brief Create a new lambda closure type.
   5099   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
   5100                                          TypeSourceInfo *Info,
   5101                                          bool KnownDependent,
   5102                                          LambdaCaptureDefault CaptureDefault);
   5103 
   5104   /// \brief Start the definition of a lambda expression.
   5105   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
   5106                                        SourceRange IntroducerRange,
   5107                                        TypeSourceInfo *MethodType,
   5108                                        SourceLocation EndLoc,
   5109                                        ArrayRef<ParmVarDecl *> Params,
   5110                                        bool IsConstexprSpecified);
   5111 
   5112   /// \brief Endow the lambda scope info with the relevant properties.
   5113   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
   5114                         CXXMethodDecl *CallOperator,
   5115                         SourceRange IntroducerRange,
   5116                         LambdaCaptureDefault CaptureDefault,
   5117                         SourceLocation CaptureDefaultLoc,
   5118                         bool ExplicitParams,
   5119                         bool ExplicitResultType,
   5120                         bool Mutable);
   5121 
   5122   /// \brief Perform initialization analysis of the init-capture and perform
   5123   /// any implicit conversions such as an lvalue-to-rvalue conversion if
   5124   /// not being used to initialize a reference.
   5125   ParsedType actOnLambdaInitCaptureInitialization(
   5126       SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
   5127       LambdaCaptureInitKind InitKind, Expr *&Init) {
   5128     return ParsedType::make(buildLambdaInitCaptureInitialization(
   5129         Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
   5130   }
   5131   QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
   5132                                                 IdentifierInfo *Id,
   5133                                                 bool DirectInit, Expr *&Init);
   5134 
   5135   /// \brief Create a dummy variable within the declcontext of the lambda's
   5136   ///  call operator, for name lookup purposes for a lambda init capture.
   5137   ///
   5138   ///  CodeGen handles emission of lambda captures, ignoring these dummy
   5139   ///  variables appropriately.
   5140   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
   5141                                           QualType InitCaptureType,
   5142                                           IdentifierInfo *Id,
   5143                                           unsigned InitStyle, Expr *Init);
   5144 
   5145   /// \brief Build the implicit field for an init-capture.
   5146   FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
   5147 
   5148   /// \brief Note that we have finished the explicit captures for the
   5149   /// given lambda.
   5150   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
   5151 
   5152   /// \brief Introduce the lambda parameters into scope.
   5153   void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
   5154 
   5155   /// \brief Deduce a block or lambda's return type based on the return
   5156   /// statements present in the body.
   5157   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
   5158 
   5159   /// ActOnStartOfLambdaDefinition - This is called just before we start
   5160   /// parsing the body of a lambda; it analyzes the explicit captures and
   5161   /// arguments, and sets up various data-structures for the body of the
   5162   /// lambda.
   5163   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
   5164                                     Declarator &ParamInfo, Scope *CurScope);
   5165 
   5166   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
   5167   /// is invoked to pop the information about the lambda.
   5168   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
   5169                         bool IsInstantiation = false);
   5170 
   5171   /// ActOnLambdaExpr - This is called when the body of a lambda expression
   5172   /// was successfully completed.
   5173   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
   5174                              Scope *CurScope);
   5175 
   5176   /// \brief Complete a lambda-expression having processed and attached the
   5177   /// lambda body.
   5178   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
   5179                              sema::LambdaScopeInfo *LSI);
   5180 
   5181   /// \brief Define the "body" of the conversion from a lambda object to a
   5182   /// function pointer.
   5183   ///
   5184   /// This routine doesn't actually define a sensible body; rather, it fills
   5185   /// in the initialization expression needed to copy the lambda object into
   5186   /// the block, and IR generation actually generates the real body of the
   5187   /// block pointer conversion.
   5188   void DefineImplicitLambdaToFunctionPointerConversion(
   5189          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
   5190 
   5191   /// \brief Define the "body" of the conversion from a lambda object to a
   5192   /// block pointer.
   5193   ///
   5194   /// This routine doesn't actually define a sensible body; rather, it fills
   5195   /// in the initialization expression needed to copy the lambda object into
   5196   /// the block, and IR generation actually generates the real body of the
   5197   /// block pointer conversion.
   5198   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
   5199                                                     CXXConversionDecl *Conv);
   5200 
   5201   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
   5202                                            SourceLocation ConvLocation,
   5203                                            CXXConversionDecl *Conv,
   5204                                            Expr *Src);
   5205 
   5206   // ParseObjCStringLiteral - Parse Objective-C string literals.
   5207   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
   5208                                     ArrayRef<Expr *> Strings);
   5209 
   5210   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
   5211 
   5212   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
   5213   /// numeric literal expression. Type of the expression will be "NSNumber *"
   5214   /// or "id" if NSNumber is unavailable.
   5215   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
   5216   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
   5217                                   bool Value);
   5218   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
   5219 
   5220   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
   5221   /// '@' prefixed parenthesized expression. The type of the expression will
   5222   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
   5223   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
   5224   /// "const char *" or C structure with attribute 'objc_boxable'.
   5225   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
   5226 
   5227   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
   5228                                           Expr *IndexExpr,
   5229                                           ObjCMethodDecl *getterMethod,
   5230                                           ObjCMethodDecl *setterMethod);
   5231 
   5232   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
   5233                                MutableArrayRef<ObjCDictionaryElement> Elements);
   5234 
   5235   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
   5236                                   TypeSourceInfo *EncodedTypeInfo,
   5237                                   SourceLocation RParenLoc);
   5238   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
   5239                                     CXXConversionDecl *Method,
   5240                                     bool HadMultipleCandidates);
   5241 
   5242   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
   5243                                        SourceLocation EncodeLoc,
   5244                                        SourceLocation LParenLoc,
   5245                                        ParsedType Ty,
   5246                                        SourceLocation RParenLoc);
   5247 
   5248   /// ParseObjCSelectorExpression - Build selector expression for \@selector
   5249   ExprResult ParseObjCSelectorExpression(Selector Sel,
   5250                                          SourceLocation AtLoc,
   5251                                          SourceLocation SelLoc,
   5252                                          SourceLocation LParenLoc,
   5253                                          SourceLocation RParenLoc,
   5254                                          bool WarnMultipleSelectors);
   5255 
   5256   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
   5257   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
   5258                                          SourceLocation AtLoc,
   5259                                          SourceLocation ProtoLoc,
   5260                                          SourceLocation LParenLoc,
   5261                                          SourceLocation ProtoIdLoc,
   5262                                          SourceLocation RParenLoc);
   5263 
   5264   //===--------------------------------------------------------------------===//
   5265   // C++ Declarations
   5266   //
   5267   Decl *ActOnStartLinkageSpecification(Scope *S,
   5268                                        SourceLocation ExternLoc,
   5269                                        Expr *LangStr,
   5270                                        SourceLocation LBraceLoc);
   5271   Decl *ActOnFinishLinkageSpecification(Scope *S,
   5272                                         Decl *LinkageSpec,
   5273                                         SourceLocation RBraceLoc);
   5274 
   5275 
   5276   //===--------------------------------------------------------------------===//
   5277   // C++ Classes
   5278   //
   5279   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
   5280                           const CXXScopeSpec *SS = nullptr);
   5281   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
   5282 
   5283   bool ActOnAccessSpecifier(AccessSpecifier Access,
   5284                             SourceLocation ASLoc,
   5285                             SourceLocation ColonLoc,
   5286                             AttributeList *Attrs = nullptr);
   5287 
   5288   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
   5289                                  Declarator &D,
   5290                                  MultiTemplateParamsArg TemplateParameterLists,
   5291                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
   5292                                  InClassInitStyle InitStyle);
   5293 
   5294   void ActOnStartCXXInClassMemberInitializer();
   5295   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
   5296                                               SourceLocation EqualLoc,
   5297                                               Expr *Init);
   5298 
   5299   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
   5300                                     Scope *S,
   5301                                     CXXScopeSpec &SS,
   5302                                     IdentifierInfo *MemberOrBase,
   5303                                     ParsedType TemplateTypeTy,
   5304                                     const DeclSpec &DS,
   5305                                     SourceLocation IdLoc,
   5306                                     SourceLocation LParenLoc,
   5307                                     ArrayRef<Expr *> Args,
   5308                                     SourceLocation RParenLoc,
   5309                                     SourceLocation EllipsisLoc);
   5310 
   5311   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
   5312                                     Scope *S,
   5313                                     CXXScopeSpec &SS,
   5314                                     IdentifierInfo *MemberOrBase,
   5315                                     ParsedType TemplateTypeTy,
   5316                                     const DeclSpec &DS,
   5317                                     SourceLocation IdLoc,
   5318                                     Expr *InitList,
   5319                                     SourceLocation EllipsisLoc);
   5320 
   5321   MemInitResult BuildMemInitializer(Decl *ConstructorD,
   5322                                     Scope *S,
   5323                                     CXXScopeSpec &SS,
   5324                                     IdentifierInfo *MemberOrBase,
   5325                                     ParsedType TemplateTypeTy,
   5326                                     const DeclSpec &DS,
   5327                                     SourceLocation IdLoc,
   5328                                     Expr *Init,
   5329                                     SourceLocation EllipsisLoc);
   5330 
   5331   MemInitResult BuildMemberInitializer(ValueDecl *Member,
   5332                                        Expr *Init,
   5333                                        SourceLocation IdLoc);
   5334 
   5335   MemInitResult BuildBaseInitializer(QualType BaseType,
   5336                                      TypeSourceInfo *BaseTInfo,
   5337                                      Expr *Init,
   5338                                      CXXRecordDecl *ClassDecl,
   5339                                      SourceLocation EllipsisLoc);
   5340 
   5341   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
   5342                                            Expr *Init,
   5343                                            CXXRecordDecl *ClassDecl);
   5344 
   5345   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
   5346                                 CXXCtorInitializer *Initializer);
   5347 
   5348   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
   5349                            ArrayRef<CXXCtorInitializer *> Initializers = None);
   5350 
   5351   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
   5352 
   5353 
   5354   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
   5355   /// mark all the non-trivial destructors of its members and bases as
   5356   /// referenced.
   5357   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
   5358                                               CXXRecordDecl *Record);
   5359 
   5360   /// \brief The list of classes whose vtables have been used within
   5361   /// this translation unit, and the source locations at which the
   5362   /// first use occurred.
   5363   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
   5364 
   5365   /// \brief The list of vtables that are required but have not yet been
   5366   /// materialized.
   5367   SmallVector<VTableUse, 16> VTableUses;
   5368 
   5369   /// \brief The set of classes whose vtables have been used within
   5370   /// this translation unit, and a bit that will be true if the vtable is
   5371   /// required to be emitted (otherwise, it should be emitted only if needed
   5372   /// by code generation).
   5373   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
   5374 
   5375   /// \brief Load any externally-stored vtable uses.
   5376   void LoadExternalVTableUses();
   5377 
   5378   /// \brief Note that the vtable for the given class was used at the
   5379   /// given location.
   5380   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
   5381                       bool DefinitionRequired = false);
   5382 
   5383   /// \brief Mark the exception specifications of all virtual member functions
   5384   /// in the given class as needed.
   5385   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
   5386                                              const CXXRecordDecl *RD);
   5387 
   5388   /// MarkVirtualMembersReferenced - Will mark all members of the given
   5389   /// CXXRecordDecl referenced.
   5390   void MarkVirtualMembersReferenced(SourceLocation Loc,
   5391                                     const CXXRecordDecl *RD);
   5392 
   5393   /// \brief Define all of the vtables that have been used in this
   5394   /// translation unit and reference any virtual members used by those
   5395   /// vtables.
   5396   ///
   5397   /// \returns true if any work was done, false otherwise.
   5398   bool DefineUsedVTables();
   5399 
   5400   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
   5401 
   5402   void ActOnMemInitializers(Decl *ConstructorDecl,
   5403                             SourceLocation ColonLoc,
   5404                             ArrayRef<CXXCtorInitializer*> MemInits,
   5405                             bool AnyErrors);
   5406 
   5407   /// \brief Check class-level dllimport/dllexport attribute. The caller must
   5408   /// ensure that referenceDLLExportedClassMethods is called some point later
   5409   /// when all outer classes of Class are complete.
   5410   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
   5411 
   5412   void referenceDLLExportedClassMethods();
   5413 
   5414   void propagateDLLAttrToBaseClassTemplate(
   5415       CXXRecordDecl *Class, Attr *ClassAttr,
   5416       ClassTemplateSpecializationDecl *BaseTemplateSpec,
   5417       SourceLocation BaseLoc);
   5418 
   5419   void CheckCompletedCXXClass(CXXRecordDecl *Record);
   5420   void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
   5421                                          Decl *TagDecl,
   5422                                          SourceLocation LBrac,
   5423                                          SourceLocation RBrac,
   5424                                          AttributeList *AttrList);
   5425   void ActOnFinishCXXMemberDecls();
   5426   void ActOnFinishCXXNonNestedClass(Decl *D);
   5427 
   5428   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
   5429   unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
   5430   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
   5431   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
   5432   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
   5433   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
   5434   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
   5435   void ActOnFinishDelayedMemberInitializers(Decl *Record);
   5436   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
   5437                                 CachedTokens &Toks);
   5438   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
   5439   bool IsInsideALocalClassWithinATemplateFunction();
   5440 
   5441   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
   5442                                      Expr *AssertExpr,
   5443                                      Expr *AssertMessageExpr,
   5444                                      SourceLocation RParenLoc);
   5445   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
   5446                                      Expr *AssertExpr,
   5447                                      StringLiteral *AssertMessageExpr,
   5448                                      SourceLocation RParenLoc,
   5449                                      bool Failed);
   5450 
   5451   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
   5452                                   SourceLocation FriendLoc,
   5453                                   TypeSourceInfo *TSInfo);
   5454   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
   5455                             MultiTemplateParamsArg TemplateParams);
   5456   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
   5457                                      MultiTemplateParamsArg TemplateParams);
   5458 
   5459   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
   5460                                       StorageClass& SC);
   5461   void CheckConstructor(CXXConstructorDecl *Constructor);
   5462   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
   5463                                      StorageClass& SC);
   5464   bool CheckDestructor(CXXDestructorDecl *Destructor);
   5465   void CheckConversionDeclarator(Declarator &D, QualType &R,
   5466                                  StorageClass& SC);
   5467   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
   5468 
   5469   void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
   5470   void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
   5471                                                    const FunctionProtoType *T);
   5472   void CheckDelayedMemberExceptionSpecs();
   5473 
   5474   //===--------------------------------------------------------------------===//
   5475   // C++ Derived Classes
   5476   //
   5477 
   5478   /// ActOnBaseSpecifier - Parsed a base specifier
   5479   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
   5480                                        SourceRange SpecifierRange,
   5481                                        bool Virtual, AccessSpecifier Access,
   5482                                        TypeSourceInfo *TInfo,
   5483                                        SourceLocation EllipsisLoc);
   5484 
   5485   BaseResult ActOnBaseSpecifier(Decl *classdecl,
   5486                                 SourceRange SpecifierRange,
   5487                                 ParsedAttributes &Attrs,
   5488                                 bool Virtual, AccessSpecifier Access,
   5489                                 ParsedType basetype,
   5490                                 SourceLocation BaseLoc,
   5491                                 SourceLocation EllipsisLoc);
   5492 
   5493   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
   5494                             MutableArrayRef<CXXBaseSpecifier *> Bases);
   5495   void ActOnBaseSpecifiers(Decl *ClassDecl,
   5496                            MutableArrayRef<CXXBaseSpecifier *> Bases);
   5497 
   5498   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
   5499   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
   5500                      CXXBasePaths &Paths);
   5501 
   5502   // FIXME: I don't like this name.
   5503   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
   5504 
   5505   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
   5506                                     SourceLocation Loc, SourceRange Range,
   5507                                     CXXCastPath *BasePath = nullptr,
   5508                                     bool IgnoreAccess = false);
   5509   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
   5510                                     unsigned InaccessibleBaseID,
   5511                                     unsigned AmbigiousBaseConvID,
   5512                                     SourceLocation Loc, SourceRange Range,
   5513                                     DeclarationName Name,
   5514                                     CXXCastPath *BasePath,
   5515                                     bool IgnoreAccess = false);
   5516 
   5517   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
   5518 
   5519   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
   5520                                          const CXXMethodDecl *Old);
   5521 
   5522   /// CheckOverridingFunctionReturnType - Checks whether the return types are
   5523   /// covariant, according to C++ [class.virtual]p5.
   5524   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
   5525                                          const CXXMethodDecl *Old);
   5526 
   5527   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
   5528   /// spec is a subset of base spec.
   5529   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
   5530                                             const CXXMethodDecl *Old);
   5531 
   5532   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
   5533 
   5534   /// CheckOverrideControl - Check C++11 override control semantics.
   5535   void CheckOverrideControl(NamedDecl *D);
   5536 
   5537   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
   5538   /// not used in the declaration of an overriding method.
   5539   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
   5540 
   5541   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
   5542   /// overrides a virtual member function marked 'final', according to
   5543   /// C++11 [class.virtual]p4.
   5544   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
   5545                                               const CXXMethodDecl *Old);
   5546 
   5547 
   5548   //===--------------------------------------------------------------------===//
   5549   // C++ Access Control
   5550   //
   5551 
   5552   enum AccessResult {
   5553     AR_accessible,
   5554     AR_inaccessible,
   5555     AR_dependent,
   5556     AR_delayed
   5557   };
   5558 
   5559   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
   5560                                 NamedDecl *PrevMemberDecl,
   5561                                 AccessSpecifier LexicalAS);
   5562 
   5563   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
   5564                                            DeclAccessPair FoundDecl);
   5565   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
   5566                                            DeclAccessPair FoundDecl);
   5567   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
   5568                                      SourceRange PlacementRange,
   5569                                      CXXRecordDecl *NamingClass,
   5570                                      DeclAccessPair FoundDecl,
   5571                                      bool Diagnose = true);
   5572   AccessResult CheckConstructorAccess(SourceLocation Loc,
   5573                                       CXXConstructorDecl *D,
   5574                                       DeclAccessPair FoundDecl,
   5575                                       const InitializedEntity &Entity,
   5576                                       bool IsCopyBindingRefToTemp = false);
   5577   AccessResult CheckConstructorAccess(SourceLocation Loc,
   5578                                       CXXConstructorDecl *D,
   5579                                       DeclAccessPair FoundDecl,
   5580                                       const InitializedEntity &Entity,
   5581                                       const PartialDiagnostic &PDiag);
   5582   AccessResult CheckDestructorAccess(SourceLocation Loc,
   5583                                      CXXDestructorDecl *Dtor,
   5584                                      const PartialDiagnostic &PDiag,
   5585                                      QualType objectType = QualType());
   5586   AccessResult CheckFriendAccess(NamedDecl *D);
   5587   AccessResult CheckMemberAccess(SourceLocation UseLoc,
   5588                                  CXXRecordDecl *NamingClass,
   5589                                  DeclAccessPair Found);
   5590   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
   5591                                          Expr *ObjectExpr,
   5592                                          Expr *ArgExpr,
   5593                                          DeclAccessPair FoundDecl);
   5594   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
   5595                                           DeclAccessPair FoundDecl);
   5596   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
   5597                                     QualType Base, QualType Derived,
   5598                                     const CXXBasePath &Path,
   5599                                     unsigned DiagID,
   5600                                     bool ForceCheck = false,
   5601                                     bool ForceUnprivileged = false);
   5602   void CheckLookupAccess(const LookupResult &R);
   5603   bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
   5604   bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
   5605                                             AccessSpecifier access,
   5606                                             QualType objectType);
   5607 
   5608   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
   5609                          const MultiLevelTemplateArgumentList &TemplateArgs);
   5610   void PerformDependentDiagnostics(const DeclContext *Pattern,
   5611                         const MultiLevelTemplateArgumentList &TemplateArgs);
   5612 
   5613   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
   5614 
   5615   /// \brief When true, access checking violations are treated as SFINAE
   5616   /// failures rather than hard errors.
   5617   bool AccessCheckingSFINAE;
   5618 
   5619   enum AbstractDiagSelID {
   5620     AbstractNone = -1,
   5621     AbstractReturnType,
   5622     AbstractParamType,
   5623     AbstractVariableType,
   5624     AbstractFieldType,
   5625     AbstractIvarType,
   5626     AbstractSynthesizedIvarType,
   5627     AbstractArrayType
   5628   };
   5629 
   5630   bool isAbstractType(SourceLocation Loc, QualType T);
   5631   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
   5632                               TypeDiagnoser &Diagnoser);
   5633   template <typename... Ts>
   5634   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
   5635                               const Ts &...Args) {
   5636     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
   5637     return RequireNonAbstractType(Loc, T, Diagnoser);
   5638   }
   5639 
   5640   void DiagnoseAbstractType(const CXXRecordDecl *RD);
   5641 
   5642   //===--------------------------------------------------------------------===//
   5643   // C++ Overloaded Operators [C++ 13.5]
   5644   //
   5645 
   5646   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
   5647 
   5648   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
   5649 
   5650   //===--------------------------------------------------------------------===//
   5651   // C++ Templates [C++ 14]
   5652   //
   5653   void FilterAcceptableTemplateNames(LookupResult &R,
   5654                                      bool AllowFunctionTemplates = true);
   5655   bool hasAnyAcceptableTemplateNames(LookupResult &R,
   5656                                      bool AllowFunctionTemplates = true);
   5657 
   5658   void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
   5659                           QualType ObjectType, bool EnteringContext,
   5660                           bool &MemberOfUnknownSpecialization);
   5661 
   5662   TemplateNameKind isTemplateName(Scope *S,
   5663                                   CXXScopeSpec &SS,
   5664                                   bool hasTemplateKeyword,
   5665                                   UnqualifiedId &Name,
   5666                                   ParsedType ObjectType,
   5667                                   bool EnteringContext,
   5668                                   TemplateTy &Template,
   5669                                   bool &MemberOfUnknownSpecialization);
   5670 
   5671   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
   5672                                    SourceLocation IILoc,
   5673                                    Scope *S,
   5674                                    const CXXScopeSpec *SS,
   5675                                    TemplateTy &SuggestedTemplate,
   5676                                    TemplateNameKind &SuggestedKind);
   5677 
   5678   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
   5679   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
   5680 
   5681   Decl *ActOnTypeParameter(Scope *S, bool Typename,
   5682                            SourceLocation EllipsisLoc,
   5683                            SourceLocation KeyLoc,
   5684                            IdentifierInfo *ParamName,
   5685                            SourceLocation ParamNameLoc,
   5686                            unsigned Depth, unsigned Position,
   5687                            SourceLocation EqualLoc,
   5688                            ParsedType DefaultArg);
   5689 
   5690   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
   5691   Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
   5692                                       unsigned Depth,
   5693                                       unsigned Position,
   5694                                       SourceLocation EqualLoc,
   5695                                       Expr *DefaultArg);
   5696   Decl *ActOnTemplateTemplateParameter(Scope *S,
   5697                                        SourceLocation TmpLoc,
   5698                                        TemplateParameterList *Params,
   5699                                        SourceLocation