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
58namespace 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
66namespace 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
193namespace 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
207namespace 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.
214typedef 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.
219struct 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.
233class 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
243public:
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.
262class 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
288public:
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
1051public:
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
1388private:
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
1397public:
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
1695private:
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
1700public:
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
2790private:
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
2832public:
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
3205private:
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
3216public:
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
3238private:
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
3254public:
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.
3301public:
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
4050private:
4051  static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4052
4053public:
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 EllipsisLoc,
5700                                       IdentifierInfo *ParamName,
5701                                       SourceLocation ParamNameLoc,
5702                                       unsigned Depth,
5703                                       unsigned Position,
5704                                       SourceLocation EqualLoc,
5705                                       ParsedTemplateArgument DefaultArg);
5706
5707  TemplateParameterList *
5708  ActOnTemplateParameterList(unsigned Depth,
5709                             SourceLocation ExportLoc,
5710                             SourceLocation TemplateLoc,
5711                             SourceLocation LAngleLoc,
5712                             ArrayRef<Decl *> Params,
5713                             SourceLocation RAngleLoc,
5714                             Expr *RequiresClause);
5715
5716  /// \brief The context in which we are checking a template parameter list.
5717  enum TemplateParamListContext {
5718    TPC_ClassTemplate,
5719    TPC_VarTemplate,
5720    TPC_FunctionTemplate,
5721    TPC_ClassTemplateMember,
5722    TPC_FriendClassTemplate,
5723    TPC_FriendFunctionTemplate,
5724    TPC_FriendFunctionTemplateDefinition,
5725    TPC_TypeAliasTemplate
5726  };
5727
5728  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5729                                  TemplateParameterList *OldParams,
5730                                  TemplateParamListContext TPC);
5731  TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5732      SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5733      const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5734      ArrayRef<TemplateParameterList *> ParamLists,
5735      bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5736
5737  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5738                                SourceLocation KWLoc, CXXScopeSpec &SS,
5739                                IdentifierInfo *Name, SourceLocation NameLoc,
5740                                AttributeList *Attr,
5741                                TemplateParameterList *TemplateParams,
5742                                AccessSpecifier AS,
5743                                SourceLocation ModulePrivateLoc,
5744                                SourceLocation FriendLoc,
5745                                unsigned NumOuterTemplateParamLists,
5746                            TemplateParameterList **OuterTemplateParamLists,
5747                                SkipBodyInfo *SkipBody = nullptr);
5748
5749  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5750                                  TemplateArgumentListInfo &Out);
5751
5752  void NoteAllFoundTemplates(TemplateName Name);
5753
5754  QualType CheckTemplateIdType(TemplateName Template,
5755                               SourceLocation TemplateLoc,
5756                              TemplateArgumentListInfo &TemplateArgs);
5757
5758  TypeResult
5759  ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5760                      TemplateTy Template, SourceLocation TemplateLoc,
5761                      SourceLocation LAngleLoc,
5762                      ASTTemplateArgsPtr TemplateArgs,
5763                      SourceLocation RAngleLoc,
5764                      bool IsCtorOrDtorName = false);
5765
5766  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5767  /// such as \c class T::template apply<U>.
5768  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5769                                    TypeSpecifierType TagSpec,
5770                                    SourceLocation TagLoc,
5771                                    CXXScopeSpec &SS,
5772                                    SourceLocation TemplateKWLoc,
5773                                    TemplateTy TemplateD,
5774                                    SourceLocation TemplateLoc,
5775                                    SourceLocation LAngleLoc,
5776                                    ASTTemplateArgsPtr TemplateArgsIn,
5777                                    SourceLocation RAngleLoc);
5778
5779  DeclResult ActOnVarTemplateSpecialization(
5780      Scope *S, Declarator &D, TypeSourceInfo *DI,
5781      SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5782      StorageClass SC, bool IsPartialSpecialization);
5783
5784  DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5785                                SourceLocation TemplateLoc,
5786                                SourceLocation TemplateNameLoc,
5787                                const TemplateArgumentListInfo &TemplateArgs);
5788
5789  ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5790                                const DeclarationNameInfo &NameInfo,
5791                                VarTemplateDecl *Template,
5792                                SourceLocation TemplateLoc,
5793                                const TemplateArgumentListInfo *TemplateArgs);
5794
5795  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5796                                 SourceLocation TemplateKWLoc,
5797                                 LookupResult &R,
5798                                 bool RequiresADL,
5799                               const TemplateArgumentListInfo *TemplateArgs);
5800
5801  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5802                                          SourceLocation TemplateKWLoc,
5803                               const DeclarationNameInfo &NameInfo,
5804                               const TemplateArgumentListInfo *TemplateArgs);
5805
5806  TemplateNameKind ActOnDependentTemplateName(Scope *S,
5807                                              CXXScopeSpec &SS,
5808                                              SourceLocation TemplateKWLoc,
5809                                              UnqualifiedId &Name,
5810                                              ParsedType ObjectType,
5811                                              bool EnteringContext,
5812                                              TemplateTy &Template);
5813
5814  DeclResult
5815  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5816                                   SourceLocation KWLoc,
5817                                   SourceLocation ModulePrivateLoc,
5818                                   TemplateIdAnnotation &TemplateId,
5819                                   AttributeList *Attr,
5820                                 MultiTemplateParamsArg TemplateParameterLists,
5821                                   SkipBodyInfo *SkipBody = nullptr);
5822
5823  Decl *ActOnTemplateDeclarator(Scope *S,
5824                                MultiTemplateParamsArg TemplateParameterLists,
5825                                Declarator &D);
5826
5827  bool
5828  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5829                                         TemplateSpecializationKind NewTSK,
5830                                         NamedDecl *PrevDecl,
5831                                         TemplateSpecializationKind PrevTSK,
5832                                         SourceLocation PrevPtOfInstantiation,
5833                                         bool &SuppressNew);
5834
5835  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5836                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
5837                                                    LookupResult &Previous);
5838
5839  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5840                         TemplateArgumentListInfo *ExplicitTemplateArgs,
5841                                           LookupResult &Previous);
5842  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5843
5844  DeclResult
5845  ActOnExplicitInstantiation(Scope *S,
5846                             SourceLocation ExternLoc,
5847                             SourceLocation TemplateLoc,
5848                             unsigned TagSpec,
5849                             SourceLocation KWLoc,
5850                             const CXXScopeSpec &SS,
5851                             TemplateTy Template,
5852                             SourceLocation TemplateNameLoc,
5853                             SourceLocation LAngleLoc,
5854                             ASTTemplateArgsPtr TemplateArgs,
5855                             SourceLocation RAngleLoc,
5856                             AttributeList *Attr);
5857
5858  DeclResult
5859  ActOnExplicitInstantiation(Scope *S,
5860                             SourceLocation ExternLoc,
5861                             SourceLocation TemplateLoc,
5862                             unsigned TagSpec,
5863                             SourceLocation KWLoc,
5864                             CXXScopeSpec &SS,
5865                             IdentifierInfo *Name,
5866                             SourceLocation NameLoc,
5867                             AttributeList *Attr);
5868
5869  DeclResult ActOnExplicitInstantiation(Scope *S,
5870                                        SourceLocation ExternLoc,
5871                                        SourceLocation TemplateLoc,
5872                                        Declarator &D);
5873
5874  TemplateArgumentLoc
5875  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5876                                          SourceLocation TemplateLoc,
5877                                          SourceLocation RAngleLoc,
5878                                          Decl *Param,
5879                                          SmallVectorImpl<TemplateArgument>
5880                                            &Converted,
5881                                          bool &HasDefaultArg);
5882
5883  /// \brief Specifies the context in which a particular template
5884  /// argument is being checked.
5885  enum CheckTemplateArgumentKind {
5886    /// \brief The template argument was specified in the code or was
5887    /// instantiated with some deduced template arguments.
5888    CTAK_Specified,
5889
5890    /// \brief The template argument was deduced via template argument
5891    /// deduction.
5892    CTAK_Deduced,
5893
5894    /// \brief The template argument was deduced from an array bound
5895    /// via template argument deduction.
5896    CTAK_DeducedFromArrayBound
5897  };
5898
5899  bool CheckTemplateArgument(NamedDecl *Param,
5900                             TemplateArgumentLoc &Arg,
5901                             NamedDecl *Template,
5902                             SourceLocation TemplateLoc,
5903                             SourceLocation RAngleLoc,
5904                             unsigned ArgumentPackIndex,
5905                           SmallVectorImpl<TemplateArgument> &Converted,
5906                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
5907
5908  /// \brief Check that the given template arguments can be be provided to
5909  /// the given template, converting the arguments along the way.
5910  ///
5911  /// \param Template The template to which the template arguments are being
5912  /// provided.
5913  ///
5914  /// \param TemplateLoc The location of the template name in the source.
5915  ///
5916  /// \param TemplateArgs The list of template arguments. If the template is
5917  /// a template template parameter, this function may extend the set of
5918  /// template arguments to also include substituted, defaulted template
5919  /// arguments.
5920  ///
5921  /// \param PartialTemplateArgs True if the list of template arguments is
5922  /// intentionally partial, e.g., because we're checking just the initial
5923  /// set of template arguments.
5924  ///
5925  /// \param Converted Will receive the converted, canonicalized template
5926  /// arguments.
5927  ///
5928  /// \returns true if an error occurred, false otherwise.
5929  bool CheckTemplateArgumentList(TemplateDecl *Template,
5930                                 SourceLocation TemplateLoc,
5931                                 TemplateArgumentListInfo &TemplateArgs,
5932                                 bool PartialTemplateArgs,
5933                           SmallVectorImpl<TemplateArgument> &Converted);
5934
5935  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5936                                 TemplateArgumentLoc &Arg,
5937                           SmallVectorImpl<TemplateArgument> &Converted);
5938
5939  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5940                             TypeSourceInfo *Arg);
5941  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5942                                   QualType InstantiatedParamType, Expr *Arg,
5943                                   TemplateArgument &Converted,
5944                               CheckTemplateArgumentKind CTAK = CTAK_Specified);
5945  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5946                             TemplateArgumentLoc &Arg,
5947                             unsigned ArgumentPackIndex);
5948
5949  ExprResult
5950  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5951                                          QualType ParamType,
5952                                          SourceLocation Loc);
5953  ExprResult
5954  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5955                                              SourceLocation Loc);
5956
5957  /// \brief Enumeration describing how template parameter lists are compared
5958  /// for equality.
5959  enum TemplateParameterListEqualKind {
5960    /// \brief We are matching the template parameter lists of two templates
5961    /// that might be redeclarations.
5962    ///
5963    /// \code
5964    /// template<typename T> struct X;
5965    /// template<typename T> struct X;
5966    /// \endcode
5967    TPL_TemplateMatch,
5968
5969    /// \brief We are matching the template parameter lists of two template
5970    /// template parameters as part of matching the template parameter lists
5971    /// of two templates that might be redeclarations.
5972    ///
5973    /// \code
5974    /// template<template<int I> class TT> struct X;
5975    /// template<template<int Value> class Other> struct X;
5976    /// \endcode
5977    TPL_TemplateTemplateParmMatch,
5978
5979    /// \brief We are matching the template parameter lists of a template
5980    /// template argument against the template parameter lists of a template
5981    /// template parameter.
5982    ///
5983    /// \code
5984    /// template<template<int Value> class Metafun> struct X;
5985    /// template<int Value> struct integer_c;
5986    /// X<integer_c> xic;
5987    /// \endcode
5988    TPL_TemplateTemplateArgumentMatch
5989  };
5990
5991  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5992                                      TemplateParameterList *Old,
5993                                      bool Complain,
5994                                      TemplateParameterListEqualKind Kind,
5995                                      SourceLocation TemplateArgLoc
5996                                        = SourceLocation());
5997
5998  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5999
6000  /// \brief Called when the parser has parsed a C++ typename
6001  /// specifier, e.g., "typename T::type".
6002  ///
6003  /// \param S The scope in which this typename type occurs.
6004  /// \param TypenameLoc the location of the 'typename' keyword
6005  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6006  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6007  /// \param IdLoc the location of the identifier.
6008  TypeResult
6009  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6010                    const CXXScopeSpec &SS, const IdentifierInfo &II,
6011                    SourceLocation IdLoc);
6012
6013  /// \brief Called when the parser has parsed a C++ typename
6014  /// specifier that ends in a template-id, e.g.,
6015  /// "typename MetaFun::template apply<T1, T2>".
6016  ///
6017  /// \param S The scope in which this typename type occurs.
6018  /// \param TypenameLoc the location of the 'typename' keyword
6019  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6020  /// \param TemplateLoc the location of the 'template' keyword, if any.
6021  /// \param TemplateName The template name.
6022  /// \param TemplateNameLoc The location of the template name.
6023  /// \param LAngleLoc The location of the opening angle bracket  ('<').
6024  /// \param TemplateArgs The template arguments.
6025  /// \param RAngleLoc The location of the closing angle bracket  ('>').
6026  TypeResult
6027  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6028                    const CXXScopeSpec &SS,
6029                    SourceLocation TemplateLoc,
6030                    TemplateTy TemplateName,
6031                    SourceLocation TemplateNameLoc,
6032                    SourceLocation LAngleLoc,
6033                    ASTTemplateArgsPtr TemplateArgs,
6034                    SourceLocation RAngleLoc);
6035
6036  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6037                             SourceLocation KeywordLoc,
6038                             NestedNameSpecifierLoc QualifierLoc,
6039                             const IdentifierInfo &II,
6040                             SourceLocation IILoc);
6041
6042  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6043                                                    SourceLocation Loc,
6044                                                    DeclarationName Name);
6045  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6046
6047  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6048  bool RebuildTemplateParamsInCurrentInstantiation(
6049                                                TemplateParameterList *Params);
6050
6051  std::string
6052  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6053                                  const TemplateArgumentList &Args);
6054
6055  std::string
6056  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6057                                  const TemplateArgument *Args,
6058                                  unsigned NumArgs);
6059
6060  //===--------------------------------------------------------------------===//
6061  // C++ Variadic Templates (C++0x [temp.variadic])
6062  //===--------------------------------------------------------------------===//
6063
6064  /// Determine whether an unexpanded parameter pack might be permitted in this
6065  /// location. Useful for error recovery.
6066  bool isUnexpandedParameterPackPermitted();
6067
6068  /// \brief The context in which an unexpanded parameter pack is
6069  /// being diagnosed.
6070  ///
6071  /// Note that the values of this enumeration line up with the first
6072  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6073  enum UnexpandedParameterPackContext {
6074    /// \brief An arbitrary expression.
6075    UPPC_Expression = 0,
6076
6077    /// \brief The base type of a class type.
6078    UPPC_BaseType,
6079
6080    /// \brief The type of an arbitrary declaration.
6081    UPPC_DeclarationType,
6082
6083    /// \brief The type of a data member.
6084    UPPC_DataMemberType,
6085
6086    /// \brief The size of a bit-field.
6087    UPPC_BitFieldWidth,
6088
6089    /// \brief The expression in a static assertion.
6090    UPPC_StaticAssertExpression,
6091
6092    /// \brief The fixed underlying type of an enumeration.
6093    UPPC_FixedUnderlyingType,
6094
6095    /// \brief The enumerator value.
6096    UPPC_EnumeratorValue,
6097
6098    /// \brief A using declaration.
6099    UPPC_UsingDeclaration,
6100
6101    /// \brief A friend declaration.
6102    UPPC_FriendDeclaration,
6103
6104    /// \brief A declaration qualifier.
6105    UPPC_DeclarationQualifier,
6106
6107    /// \brief An initializer.
6108    UPPC_Initializer,
6109
6110    /// \brief A default argument.
6111    UPPC_DefaultArgument,
6112
6113    /// \brief The type of a non-type template parameter.
6114    UPPC_NonTypeTemplateParameterType,
6115
6116    /// \brief The type of an exception.
6117    UPPC_ExceptionType,
6118
6119    /// \brief Partial specialization.
6120    UPPC_PartialSpecialization,
6121
6122    /// \brief Microsoft __if_exists.
6123    UPPC_IfExists,
6124
6125    /// \brief Microsoft __if_not_exists.
6126    UPPC_IfNotExists,
6127
6128    /// \brief Lambda expression.
6129    UPPC_Lambda,
6130
6131    /// \brief Block expression,
6132    UPPC_Block
6133  };
6134
6135  /// \brief Diagnose unexpanded parameter packs.
6136  ///
6137  /// \param Loc The location at which we should emit the diagnostic.
6138  ///
6139  /// \param UPPC The context in which we are diagnosing unexpanded
6140  /// parameter packs.
6141  ///
6142  /// \param Unexpanded the set of unexpanded parameter packs.
6143  ///
6144  /// \returns true if an error occurred, false otherwise.
6145  bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6146                                        UnexpandedParameterPackContext UPPC,
6147                                  ArrayRef<UnexpandedParameterPack> Unexpanded);
6148
6149  /// \brief If the given type contains an unexpanded parameter pack,
6150  /// diagnose the error.
6151  ///
6152  /// \param Loc The source location where a diagnostc should be emitted.
6153  ///
6154  /// \param T The type that is being checked for unexpanded parameter
6155  /// packs.
6156  ///
6157  /// \returns true if an error occurred, false otherwise.
6158  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6159                                       UnexpandedParameterPackContext UPPC);
6160
6161  /// \brief If the given expression contains an unexpanded parameter
6162  /// pack, diagnose the error.
6163  ///
6164  /// \param E The expression that is being checked for unexpanded
6165  /// parameter packs.
6166  ///
6167  /// \returns true if an error occurred, false otherwise.
6168  bool DiagnoseUnexpandedParameterPack(Expr *E,
6169                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
6170
6171  /// \brief If the given nested-name-specifier contains an unexpanded
6172  /// parameter pack, diagnose the error.
6173  ///
6174  /// \param SS The nested-name-specifier that is being checked for
6175  /// unexpanded parameter packs.
6176  ///
6177  /// \returns true if an error occurred, false otherwise.
6178  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6179                                       UnexpandedParameterPackContext UPPC);
6180
6181  /// \brief If the given name contains an unexpanded parameter pack,
6182  /// diagnose the error.
6183  ///
6184  /// \param NameInfo The name (with source location information) that
6185  /// is being checked for unexpanded parameter packs.
6186  ///
6187  /// \returns true if an error occurred, false otherwise.
6188  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6189                                       UnexpandedParameterPackContext UPPC);
6190
6191  /// \brief If the given template name contains an unexpanded parameter pack,
6192  /// diagnose the error.
6193  ///
6194  /// \param Loc The location of the template name.
6195  ///
6196  /// \param Template The template name that is being checked for unexpanded
6197  /// parameter packs.
6198  ///
6199  /// \returns true if an error occurred, false otherwise.
6200  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6201                                       TemplateName Template,
6202                                       UnexpandedParameterPackContext UPPC);
6203
6204  /// \brief If the given template argument contains an unexpanded parameter
6205  /// pack, diagnose the error.
6206  ///
6207  /// \param Arg The template argument that is being checked for unexpanded
6208  /// parameter packs.
6209  ///
6210  /// \returns true if an error occurred, false otherwise.
6211  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6212                                       UnexpandedParameterPackContext UPPC);
6213
6214  /// \brief Collect the set of unexpanded parameter packs within the given
6215  /// template argument.
6216  ///
6217  /// \param Arg The template argument that will be traversed to find
6218  /// unexpanded parameter packs.
6219  void collectUnexpandedParameterPacks(TemplateArgument Arg,
6220                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6221
6222  /// \brief Collect the set of unexpanded parameter packs within the given
6223  /// template argument.
6224  ///
6225  /// \param Arg The template argument that will be traversed to find
6226  /// unexpanded parameter packs.
6227  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6228                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6229
6230  /// \brief Collect the set of unexpanded parameter packs within the given
6231  /// type.
6232  ///
6233  /// \param T The type that will be traversed to find
6234  /// unexpanded parameter packs.
6235  void collectUnexpandedParameterPacks(QualType T,
6236                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6237
6238  /// \brief Collect the set of unexpanded parameter packs within the given
6239  /// type.
6240  ///
6241  /// \param TL The type that will be traversed to find
6242  /// unexpanded parameter packs.
6243  void collectUnexpandedParameterPacks(TypeLoc TL,
6244                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6245
6246  /// \brief Collect the set of unexpanded parameter packs within the given
6247  /// nested-name-specifier.
6248  ///
6249  /// \param SS The nested-name-specifier that will be traversed to find
6250  /// unexpanded parameter packs.
6251  void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
6252                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6253
6254  /// \brief Collect the set of unexpanded parameter packs within the given
6255  /// name.
6256  ///
6257  /// \param NameInfo The name that will be traversed to find
6258  /// unexpanded parameter packs.
6259  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6260                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6261
6262  /// \brief Invoked when parsing a template argument followed by an
6263  /// ellipsis, which creates a pack expansion.
6264  ///
6265  /// \param Arg The template argument preceding the ellipsis, which
6266  /// may already be invalid.
6267  ///
6268  /// \param EllipsisLoc The location of the ellipsis.
6269  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6270                                            SourceLocation EllipsisLoc);
6271
6272  /// \brief Invoked when parsing a type followed by an ellipsis, which
6273  /// creates a pack expansion.
6274  ///
6275  /// \param Type The type preceding the ellipsis, which will become
6276  /// the pattern of the pack expansion.
6277  ///
6278  /// \param EllipsisLoc The location of the ellipsis.
6279  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6280
6281  /// \brief Construct a pack expansion type from the pattern of the pack
6282  /// expansion.
6283  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6284                                     SourceLocation EllipsisLoc,
6285                                     Optional<unsigned> NumExpansions);
6286
6287  /// \brief Construct a pack expansion type from the pattern of the pack
6288  /// expansion.
6289  QualType CheckPackExpansion(QualType Pattern,
6290                              SourceRange PatternRange,
6291                              SourceLocation EllipsisLoc,
6292                              Optional<unsigned> NumExpansions);
6293
6294  /// \brief Invoked when parsing an expression followed by an ellipsis, which
6295  /// creates a pack expansion.
6296  ///
6297  /// \param Pattern The expression preceding the ellipsis, which will become
6298  /// the pattern of the pack expansion.
6299  ///
6300  /// \param EllipsisLoc The location of the ellipsis.
6301  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6302
6303  /// \brief Invoked when parsing an expression followed by an ellipsis, which
6304  /// creates a pack expansion.
6305  ///
6306  /// \param Pattern The expression preceding the ellipsis, which will become
6307  /// the pattern of the pack expansion.
6308  ///
6309  /// \param EllipsisLoc The location of the ellipsis.
6310  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6311                                Optional<unsigned> NumExpansions);
6312
6313  /// \brief Determine whether we could expand a pack expansion with the
6314  /// given set of parameter packs into separate arguments by repeatedly
6315  /// transforming the pattern.
6316  ///
6317  /// \param EllipsisLoc The location of the ellipsis that identifies the
6318  /// pack expansion.
6319  ///
6320  /// \param PatternRange The source range that covers the entire pattern of
6321  /// the pack expansion.
6322  ///
6323  /// \param Unexpanded The set of unexpanded parameter packs within the
6324  /// pattern.
6325  ///
6326  /// \param ShouldExpand Will be set to \c true if the transformer should
6327  /// expand the corresponding pack expansions into separate arguments. When
6328  /// set, \c NumExpansions must also be set.
6329  ///
6330  /// \param RetainExpansion Whether the caller should add an unexpanded
6331  /// pack expansion after all of the expanded arguments. This is used
6332  /// when extending explicitly-specified template argument packs per
6333  /// C++0x [temp.arg.explicit]p9.
6334  ///
6335  /// \param NumExpansions The number of separate arguments that will be in
6336  /// the expanded form of the corresponding pack expansion. This is both an
6337  /// input and an output parameter, which can be set by the caller if the
6338  /// number of expansions is known a priori (e.g., due to a prior substitution)
6339  /// and will be set by the callee when the number of expansions is known.
6340  /// The callee must set this value when \c ShouldExpand is \c true; it may
6341  /// set this value in other cases.
6342  ///
6343  /// \returns true if an error occurred (e.g., because the parameter packs
6344  /// are to be instantiated with arguments of different lengths), false
6345  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6346  /// must be set.
6347  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6348                                       SourceRange PatternRange,
6349                             ArrayRef<UnexpandedParameterPack> Unexpanded,
6350                             const MultiLevelTemplateArgumentList &TemplateArgs,
6351                                       bool &ShouldExpand,
6352                                       bool &RetainExpansion,
6353                                       Optional<unsigned> &NumExpansions);
6354
6355  /// \brief Determine the number of arguments in the given pack expansion
6356  /// type.
6357  ///
6358  /// This routine assumes that the number of arguments in the expansion is
6359  /// consistent across all of the unexpanded parameter packs in its pattern.
6360  ///
6361  /// Returns an empty Optional if the type can't be expanded.
6362  Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6363      const MultiLevelTemplateArgumentList &TemplateArgs);
6364
6365  /// \brief Determine whether the given declarator contains any unexpanded
6366  /// parameter packs.
6367  ///
6368  /// This routine is used by the parser to disambiguate function declarators
6369  /// with an ellipsis prior to the ')', e.g.,
6370  ///
6371  /// \code
6372  ///   void f(T...);
6373  /// \endcode
6374  ///
6375  /// To determine whether we have an (unnamed) function parameter pack or
6376  /// a variadic function.
6377  ///
6378  /// \returns true if the declarator contains any unexpanded parameter packs,
6379  /// false otherwise.
6380  bool containsUnexpandedParameterPacks(Declarator &D);
6381
6382  /// \brief Returns the pattern of the pack expansion for a template argument.
6383  ///
6384  /// \param OrigLoc The template argument to expand.
6385  ///
6386  /// \param Ellipsis Will be set to the location of the ellipsis.
6387  ///
6388  /// \param NumExpansions Will be set to the number of expansions that will
6389  /// be generated from this pack expansion, if known a priori.
6390  TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6391      TemplateArgumentLoc OrigLoc,
6392      SourceLocation &Ellipsis,
6393      Optional<unsigned> &NumExpansions) const;
6394
6395  //===--------------------------------------------------------------------===//
6396  // C++ Template Argument Deduction (C++ [temp.deduct])
6397  //===--------------------------------------------------------------------===//
6398
6399  QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6400
6401  /// \brief Describes the result of template argument deduction.
6402  ///
6403  /// The TemplateDeductionResult enumeration describes the result of
6404  /// template argument deduction, as returned from
6405  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6406  /// structure provides additional information about the results of
6407  /// template argument deduction, e.g., the deduced template argument
6408  /// list (if successful) or the specific template parameters or
6409  /// deduced arguments that were involved in the failure.
6410  enum TemplateDeductionResult {
6411    /// \brief Template argument deduction was successful.
6412    TDK_Success = 0,
6413    /// \brief The declaration was invalid; do nothing.
6414    TDK_Invalid,
6415    /// \brief Template argument deduction exceeded the maximum template
6416    /// instantiation depth (which has already been diagnosed).
6417    TDK_InstantiationDepth,
6418    /// \brief Template argument deduction did not deduce a value
6419    /// for every template parameter.
6420    TDK_Incomplete,
6421    /// \brief Template argument deduction produced inconsistent
6422    /// deduced values for the given template parameter.
6423    TDK_Inconsistent,
6424    /// \brief Template argument deduction failed due to inconsistent
6425    /// cv-qualifiers on a template parameter type that would
6426    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6427    /// but were given a non-const "X".
6428    TDK_Underqualified,
6429    /// \brief Substitution of the deduced template argument values
6430    /// resulted in an error.
6431    TDK_SubstitutionFailure,
6432    /// \brief After substituting deduced template arguments, a dependent
6433    /// parameter type did not match the corresponding argument.
6434    TDK_DeducedMismatch,
6435    /// \brief A non-depnedent component of the parameter did not match the
6436    /// corresponding component of the argument.
6437    TDK_NonDeducedMismatch,
6438    /// \brief When performing template argument deduction for a function
6439    /// template, there were too many call arguments.
6440    TDK_TooManyArguments,
6441    /// \brief When performing template argument deduction for a function
6442    /// template, there were too few call arguments.
6443    TDK_TooFewArguments,
6444    /// \brief The explicitly-specified template arguments were not valid
6445    /// template arguments for the given template.
6446    TDK_InvalidExplicitArguments,
6447    /// \brief The arguments included an overloaded function name that could
6448    /// not be resolved to a suitable function.
6449    TDK_FailedOverloadResolution,
6450    /// \brief Deduction failed; that's all we know.
6451    TDK_MiscellaneousDeductionFailure
6452  };
6453
6454  TemplateDeductionResult
6455  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6456                          const TemplateArgumentList &TemplateArgs,
6457                          sema::TemplateDeductionInfo &Info);
6458
6459  TemplateDeductionResult
6460  DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6461                          const TemplateArgumentList &TemplateArgs,
6462                          sema::TemplateDeductionInfo &Info);
6463
6464  TemplateDeductionResult SubstituteExplicitTemplateArguments(
6465      FunctionTemplateDecl *FunctionTemplate,
6466      TemplateArgumentListInfo &ExplicitTemplateArgs,
6467      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6468      SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6469      sema::TemplateDeductionInfo &Info);
6470
6471  /// brief A function argument from which we performed template argument
6472  // deduction for a call.
6473  struct OriginalCallArg {
6474    OriginalCallArg(QualType OriginalParamType,
6475                    unsigned ArgIdx,
6476                    QualType OriginalArgType)
6477      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6478        OriginalArgType(OriginalArgType) { }
6479
6480    QualType OriginalParamType;
6481    unsigned ArgIdx;
6482    QualType OriginalArgType;
6483  };
6484
6485  TemplateDeductionResult
6486  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6487                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6488                                  unsigned NumExplicitlySpecified,
6489                                  FunctionDecl *&Specialization,
6490                                  sema::TemplateDeductionInfo &Info,
6491           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6492                                  bool PartialOverloading = false);
6493
6494  TemplateDeductionResult
6495  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6496                          TemplateArgumentListInfo *ExplicitTemplateArgs,
6497                          ArrayRef<Expr *> Args,
6498                          FunctionDecl *&Specialization,
6499                          sema::TemplateDeductionInfo &Info,
6500                          bool PartialOverloading = false);
6501
6502  TemplateDeductionResult
6503  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6504                          TemplateArgumentListInfo *ExplicitTemplateArgs,
6505                          QualType ArgFunctionType,
6506                          FunctionDecl *&Specialization,
6507                          sema::TemplateDeductionInfo &Info,
6508                          bool InOverloadResolution = false);
6509
6510  TemplateDeductionResult
6511  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6512                          QualType ToType,
6513                          CXXConversionDecl *&Specialization,
6514                          sema::TemplateDeductionInfo &Info);
6515
6516  TemplateDeductionResult
6517  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6518                          TemplateArgumentListInfo *ExplicitTemplateArgs,
6519                          FunctionDecl *&Specialization,
6520                          sema::TemplateDeductionInfo &Info,
6521                          bool InOverloadResolution = false);
6522
6523  /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6524  QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6525  /// \brief Substitute Replacement for auto in TypeWithAuto
6526  TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6527                                          QualType Replacement);
6528
6529  /// \brief Result type of DeduceAutoType.
6530  enum DeduceAutoResult {
6531    DAR_Succeeded,
6532    DAR_Failed,
6533    DAR_FailedAlreadyDiagnosed
6534  };
6535
6536  DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6537                                  QualType &Result);
6538  DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6539                                  QualType &Result);
6540  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6541  bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6542                        bool Diagnose = true);
6543
6544  QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6545                                        QualType Type, TypeSourceInfo *TSI,
6546                                        SourceRange Range, bool DirectInit,
6547                                        Expr *Init);
6548
6549  TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6550
6551  bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6552                                        SourceLocation ReturnLoc,
6553                                        Expr *&RetExpr, AutoType *AT);
6554
6555  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6556                                                   FunctionTemplateDecl *FT2,
6557                                                   SourceLocation Loc,
6558                                           TemplatePartialOrderingContext TPOC,
6559                                                   unsigned NumCallArguments1,
6560                                                   unsigned NumCallArguments2);
6561  UnresolvedSetIterator
6562  getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6563                     TemplateSpecCandidateSet &FailedCandidates,
6564                     SourceLocation Loc,
6565                     const PartialDiagnostic &NoneDiag,
6566                     const PartialDiagnostic &AmbigDiag,
6567                     const PartialDiagnostic &CandidateDiag,
6568                     bool Complain = true, QualType TargetType = QualType());
6569
6570  ClassTemplatePartialSpecializationDecl *
6571  getMoreSpecializedPartialSpecialization(
6572                                  ClassTemplatePartialSpecializationDecl *PS1,
6573                                  ClassTemplatePartialSpecializationDecl *PS2,
6574                                  SourceLocation Loc);
6575
6576  VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6577      VarTemplatePartialSpecializationDecl *PS1,
6578      VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6579
6580  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6581                                  bool OnlyDeduced,
6582                                  unsigned Depth,
6583                                  llvm::SmallBitVector &Used);
6584  void MarkDeducedTemplateParameters(
6585                                  const FunctionTemplateDecl *FunctionTemplate,
6586                                  llvm::SmallBitVector &Deduced) {
6587    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6588  }
6589  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6590                                  const FunctionTemplateDecl *FunctionTemplate,
6591                                  llvm::SmallBitVector &Deduced);
6592
6593  //===--------------------------------------------------------------------===//
6594  // C++ Template Instantiation
6595  //
6596
6597  MultiLevelTemplateArgumentList
6598  getTemplateInstantiationArgs(NamedDecl *D,
6599                               const TemplateArgumentList *Innermost = nullptr,
6600                               bool RelativeToPrimary = false,
6601                               const FunctionDecl *Pattern = nullptr);
6602
6603  /// \brief A template instantiation that is currently in progress.
6604  struct ActiveTemplateInstantiation {
6605    /// \brief The kind of template instantiation we are performing
6606    enum InstantiationKind {
6607      /// We are instantiating a template declaration. The entity is
6608      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6609      TemplateInstantiation,
6610
6611      /// We are instantiating a default argument for a template
6612      /// parameter. The Entity is the template, and
6613      /// TemplateArgs/NumTemplateArguments provides the template
6614      /// arguments as specified.
6615      /// FIXME: Use a TemplateArgumentList
6616      DefaultTemplateArgumentInstantiation,
6617
6618      /// We are instantiating a default argument for a function.
6619      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6620      /// provides the template arguments as specified.
6621      DefaultFunctionArgumentInstantiation,
6622
6623      /// We are substituting explicit template arguments provided for
6624      /// a function template. The entity is a FunctionTemplateDecl.
6625      ExplicitTemplateArgumentSubstitution,
6626
6627      /// We are substituting template argument determined as part of
6628      /// template argument deduction for either a class template
6629      /// partial specialization or a function template. The
6630      /// Entity is either a ClassTemplatePartialSpecializationDecl or
6631      /// a FunctionTemplateDecl.
6632      DeducedTemplateArgumentSubstitution,
6633
6634      /// We are substituting prior template arguments into a new
6635      /// template parameter. The template parameter itself is either a
6636      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6637      PriorTemplateArgumentSubstitution,
6638
6639      /// We are checking the validity of a default template argument that
6640      /// has been used when naming a template-id.
6641      DefaultTemplateArgumentChecking,
6642
6643      /// We are instantiating the exception specification for a function
6644      /// template which was deferred until it was needed.
6645      ExceptionSpecInstantiation
6646    } Kind;
6647
6648    /// \brief The point of instantiation within the source code.
6649    SourceLocation PointOfInstantiation;
6650
6651    /// \brief The template (or partial specialization) in which we are
6652    /// performing the instantiation, for substitutions of prior template
6653    /// arguments.
6654    NamedDecl *Template;
6655
6656    /// \brief The entity that is being instantiated.
6657    Decl *Entity;
6658
6659    /// \brief The list of template arguments we are substituting, if they
6660    /// are not part of the entity.
6661    const TemplateArgument *TemplateArgs;
6662
6663    /// \brief The number of template arguments in TemplateArgs.
6664    unsigned NumTemplateArgs;
6665
6666    ArrayRef<TemplateArgument> template_arguments() const {
6667      return {TemplateArgs, NumTemplateArgs};
6668    }
6669
6670    /// \brief The template deduction info object associated with the
6671    /// substitution or checking of explicit or deduced template arguments.
6672    sema::TemplateDeductionInfo *DeductionInfo;
6673
6674    /// \brief The source range that covers the construct that cause
6675    /// the instantiation, e.g., the template-id that causes a class
6676    /// template instantiation.
6677    SourceRange InstantiationRange;
6678
6679    ActiveTemplateInstantiation()
6680      : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6681        TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6682
6683    /// \brief Determines whether this template is an actual instantiation
6684    /// that should be counted toward the maximum instantiation depth.
6685    bool isInstantiationRecord() const;
6686
6687    friend bool operator==(const ActiveTemplateInstantiation &X,
6688                           const ActiveTemplateInstantiation &Y) {
6689      if (X.Kind != Y.Kind)
6690        return false;
6691
6692      if (X.Entity != Y.Entity)
6693        return false;
6694
6695      switch (X.Kind) {
6696      case TemplateInstantiation:
6697      case ExceptionSpecInstantiation:
6698        return true;
6699
6700      case PriorTemplateArgumentSubstitution:
6701      case DefaultTemplateArgumentChecking:
6702        return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6703
6704      case DefaultTemplateArgumentInstantiation:
6705      case ExplicitTemplateArgumentSubstitution:
6706      case DeducedTemplateArgumentSubstitution:
6707      case DefaultFunctionArgumentInstantiation:
6708        return X.TemplateArgs == Y.TemplateArgs;
6709
6710      }
6711
6712      llvm_unreachable("Invalid InstantiationKind!");
6713    }
6714
6715    friend bool operator!=(const ActiveTemplateInstantiation &X,
6716                           const ActiveTemplateInstantiation &Y) {
6717      return !(X == Y);
6718    }
6719  };
6720
6721  /// \brief List of active template instantiations.
6722  ///
6723  /// This vector is treated as a stack. As one template instantiation
6724  /// requires another template instantiation, additional
6725  /// instantiations are pushed onto the stack up to a
6726  /// user-configurable limit LangOptions::InstantiationDepth.
6727  SmallVector<ActiveTemplateInstantiation, 16>
6728    ActiveTemplateInstantiations;
6729
6730  /// \brief Extra modules inspected when performing a lookup during a template
6731  /// instantiation. Computed lazily.
6732  SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6733
6734  /// \brief Cache of additional modules that should be used for name lookup
6735  /// within the current template instantiation. Computed lazily; use
6736  /// getLookupModules() to get a complete set.
6737  llvm::DenseSet<Module*> LookupModulesCache;
6738
6739  /// \brief Get the set of additional modules that should be checked during
6740  /// name lookup. A module and its imports become visible when instanting a
6741  /// template defined within it.
6742  llvm::DenseSet<Module*> &getLookupModules();
6743
6744  /// \brief Map from the most recent declaration of a namespace to the most
6745  /// recent visible declaration of that namespace.
6746  llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
6747
6748  /// \brief Whether we are in a SFINAE context that is not associated with
6749  /// template instantiation.
6750  ///
6751  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6752  /// of a template instantiation or template argument deduction.
6753  bool InNonInstantiationSFINAEContext;
6754
6755  /// \brief The number of ActiveTemplateInstantiation entries in
6756  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6757  /// therefore, should not be counted as part of the instantiation depth.
6758  unsigned NonInstantiationEntries;
6759
6760  /// \brief The last template from which a template instantiation
6761  /// error or warning was produced.
6762  ///
6763  /// This value is used to suppress printing of redundant template
6764  /// instantiation backtraces when there are multiple errors in the
6765  /// same instantiation. FIXME: Does this belong in Sema? It's tough
6766  /// to implement it anywhere else.
6767  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6768
6769  /// \brief The current index into pack expansion arguments that will be
6770  /// used for substitution of parameter packs.
6771  ///
6772  /// The pack expansion index will be -1 to indicate that parameter packs
6773  /// should be instantiated as themselves. Otherwise, the index specifies
6774  /// which argument within the parameter pack will be used for substitution.
6775  int ArgumentPackSubstitutionIndex;
6776
6777  /// \brief RAII object used to change the argument pack substitution index
6778  /// within a \c Sema object.
6779  ///
6780  /// See \c ArgumentPackSubstitutionIndex for more information.
6781  class ArgumentPackSubstitutionIndexRAII {
6782    Sema &Self;
6783    int OldSubstitutionIndex;
6784
6785  public:
6786    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6787      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6788      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6789    }
6790
6791    ~ArgumentPackSubstitutionIndexRAII() {
6792      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6793    }
6794  };
6795
6796  friend class ArgumentPackSubstitutionRAII;
6797
6798  /// \brief For each declaration that involved template argument deduction, the
6799  /// set of diagnostics that were suppressed during that template argument
6800  /// deduction.
6801  ///
6802  /// FIXME: Serialize this structure to the AST file.
6803  typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6804    SuppressedDiagnosticsMap;
6805  SuppressedDiagnosticsMap SuppressedDiagnostics;
6806
6807  /// \brief A stack object to be created when performing template
6808  /// instantiation.
6809  ///
6810  /// Construction of an object of type \c InstantiatingTemplate
6811  /// pushes the current instantiation onto the stack of active
6812  /// instantiations. If the size of this stack exceeds the maximum
6813  /// number of recursive template instantiations, construction
6814  /// produces an error and evaluates true.
6815  ///
6816  /// Destruction of this object will pop the named instantiation off
6817  /// the stack.
6818  struct InstantiatingTemplate {
6819    /// \brief Note that we are instantiating a class template,
6820    /// function template, variable template, alias template,
6821    /// or a member thereof.
6822    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6823                          Decl *Entity,
6824                          SourceRange InstantiationRange = SourceRange());
6825
6826    struct ExceptionSpecification {};
6827    /// \brief Note that we are instantiating an exception specification
6828    /// of a function template.
6829    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6830                          FunctionDecl *Entity, ExceptionSpecification,
6831                          SourceRange InstantiationRange = SourceRange());
6832
6833    /// \brief Note that we are instantiating a default argument in a
6834    /// template-id.
6835    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6836                          TemplateDecl *Template,
6837                          ArrayRef<TemplateArgument> TemplateArgs,
6838                          SourceRange InstantiationRange = SourceRange());
6839
6840    /// \brief Note that we are instantiating a default argument in a
6841    /// template-id.
6842    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6843                          FunctionTemplateDecl *FunctionTemplate,
6844                          ArrayRef<TemplateArgument> TemplateArgs,
6845                          ActiveTemplateInstantiation::InstantiationKind Kind,
6846                          sema::TemplateDeductionInfo &DeductionInfo,
6847                          SourceRange InstantiationRange = SourceRange());
6848
6849    /// \brief Note that we are instantiating as part of template
6850    /// argument deduction for a class template partial
6851    /// specialization.
6852    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6853                          ClassTemplatePartialSpecializationDecl *PartialSpec,
6854                          ArrayRef<TemplateArgument> TemplateArgs,
6855                          sema::TemplateDeductionInfo &DeductionInfo,
6856                          SourceRange InstantiationRange = SourceRange());
6857
6858    /// \brief Note that we are instantiating as part of template
6859    /// argument deduction for a variable template partial
6860    /// specialization.
6861    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6862                          VarTemplatePartialSpecializationDecl *PartialSpec,
6863                          ArrayRef<TemplateArgument> TemplateArgs,
6864                          sema::TemplateDeductionInfo &DeductionInfo,
6865                          SourceRange InstantiationRange = SourceRange());
6866
6867    /// \brief Note that we are instantiating a default argument for a function
6868    /// parameter.
6869    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6870                          ParmVarDecl *Param,
6871                          ArrayRef<TemplateArgument> TemplateArgs,
6872                          SourceRange InstantiationRange = SourceRange());
6873
6874    /// \brief Note that we are substituting prior template arguments into a
6875    /// non-type parameter.
6876    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6877                          NamedDecl *Template,
6878                          NonTypeTemplateParmDecl *Param,
6879                          ArrayRef<TemplateArgument> TemplateArgs,
6880                          SourceRange InstantiationRange);
6881
6882    /// \brief Note that we are substituting prior template arguments into a
6883    /// template template parameter.
6884    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6885                          NamedDecl *Template,
6886                          TemplateTemplateParmDecl *Param,
6887                          ArrayRef<TemplateArgument> TemplateArgs,
6888                          SourceRange InstantiationRange);
6889
6890    /// \brief Note that we are checking the default template argument
6891    /// against the template parameter for a given template-id.
6892    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6893                          TemplateDecl *Template,
6894                          NamedDecl *Param,
6895                          ArrayRef<TemplateArgument> TemplateArgs,
6896                          SourceRange InstantiationRange);
6897
6898
6899    /// \brief Note that we have finished instantiating this template.
6900    void Clear();
6901
6902    ~InstantiatingTemplate() { Clear(); }
6903
6904    /// \brief Determines whether we have exceeded the maximum
6905    /// recursive template instantiations.
6906    bool isInvalid() const { return Invalid; }
6907
6908  private:
6909    Sema &SemaRef;
6910    bool Invalid;
6911    bool SavedInNonInstantiationSFINAEContext;
6912    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6913                                 SourceRange InstantiationRange);
6914
6915    InstantiatingTemplate(
6916        Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
6917        SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6918        Decl *Entity, NamedDecl *Template = nullptr,
6919        ArrayRef<TemplateArgument> TemplateArgs = None,
6920        sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6921
6922    InstantiatingTemplate(const InstantiatingTemplate&) = delete;
6923
6924    InstantiatingTemplate&
6925    operator=(const InstantiatingTemplate&) = delete;
6926  };
6927
6928  void PrintInstantiationStack();
6929
6930  /// \brief Determines whether we are currently in a context where
6931  /// template argument substitution failures are not considered
6932  /// errors.
6933  ///
6934  /// \returns An empty \c Optional if we're not in a SFINAE context.
6935  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6936  /// template-deduction context object, which can be used to capture
6937  /// diagnostics that will be suppressed.
6938  Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6939
6940  /// \brief Determines whether we are currently in a context that
6941  /// is not evaluated as per C++ [expr] p5.
6942  bool isUnevaluatedContext() const {
6943    assert(!ExprEvalContexts.empty() &&
6944           "Must be in an expression evaluation context");
6945    return ExprEvalContexts.back().isUnevaluated();
6946  }
6947
6948  /// \brief RAII class used to determine whether SFINAE has
6949  /// trapped any errors that occur during template argument
6950  /// deduction.
6951  class SFINAETrap {
6952    Sema &SemaRef;
6953    unsigned PrevSFINAEErrors;
6954    bool PrevInNonInstantiationSFINAEContext;
6955    bool PrevAccessCheckingSFINAE;
6956
6957  public:
6958    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6959      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6960        PrevInNonInstantiationSFINAEContext(
6961                                      SemaRef.InNonInstantiationSFINAEContext),
6962        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6963    {
6964      if (!SemaRef.isSFINAEContext())
6965        SemaRef.InNonInstantiationSFINAEContext = true;
6966      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6967    }
6968
6969    ~SFINAETrap() {
6970      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6971      SemaRef.InNonInstantiationSFINAEContext
6972        = PrevInNonInstantiationSFINAEContext;
6973      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6974    }
6975
6976    /// \brief Determine whether any SFINAE errors have been trapped.
6977    bool hasErrorOccurred() const {
6978      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6979    }
6980  };
6981
6982  /// \brief RAII class used to indicate that we are performing provisional
6983  /// semantic analysis to determine the validity of a construct, so
6984  /// typo-correction and diagnostics in the immediate context (not within
6985  /// implicitly-instantiated templates) should be suppressed.
6986  class TentativeAnalysisScope {
6987    Sema &SemaRef;
6988    // FIXME: Using a SFINAETrap for this is a hack.
6989    SFINAETrap Trap;
6990    bool PrevDisableTypoCorrection;
6991  public:
6992    explicit TentativeAnalysisScope(Sema &SemaRef)
6993        : SemaRef(SemaRef), Trap(SemaRef, true),
6994          PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6995      SemaRef.DisableTypoCorrection = true;
6996    }
6997    ~TentativeAnalysisScope() {
6998      SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6999    }
7000  };
7001
7002  /// \brief The current instantiation scope used to store local
7003  /// variables.
7004  LocalInstantiationScope *CurrentInstantiationScope;
7005
7006  /// \brief Tracks whether we are in a context where typo correction is
7007  /// disabled.
7008  bool DisableTypoCorrection;
7009
7010  /// \brief The number of typos corrected by CorrectTypo.
7011  unsigned TyposCorrected;
7012
7013  typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7014  typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7015
7016  /// \brief A cache containing identifiers for which typo correction failed and
7017  /// their locations, so that repeated attempts to correct an identifier in a
7018  /// given location are ignored if typo correction already failed for it.
7019  IdentifierSourceLocations TypoCorrectionFailures;
7020
7021  /// \brief Worker object for performing CFG-based warnings.
7022  sema::AnalysisBasedWarnings AnalysisWarnings;
7023  threadSafety::BeforeSet *ThreadSafetyDeclCache;
7024
7025  /// \brief An entity for which implicit template instantiation is required.
7026  ///
7027  /// The source location associated with the declaration is the first place in
7028  /// the source code where the declaration was "used". It is not necessarily
7029  /// the point of instantiation (which will be either before or after the
7030  /// namespace-scope declaration that triggered this implicit instantiation),
7031  /// However, it is the location that diagnostics should generally refer to,
7032  /// because users will need to know what code triggered the instantiation.
7033  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7034
7035  /// \brief The queue of implicit template instantiations that are required
7036  /// but have not yet been performed.
7037  std::deque<PendingImplicitInstantiation> PendingInstantiations;
7038
7039  class SavePendingInstantiationsAndVTableUsesRAII {
7040  public:
7041    SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7042        : S(S), Enabled(Enabled) {
7043      if (!Enabled) return;
7044
7045      SavedPendingInstantiations.swap(S.PendingInstantiations);
7046      SavedVTableUses.swap(S.VTableUses);
7047    }
7048
7049    ~SavePendingInstantiationsAndVTableUsesRAII() {
7050      if (!Enabled) return;
7051
7052      // Restore the set of pending vtables.
7053      assert(S.VTableUses.empty() &&
7054             "VTableUses should be empty before it is discarded.");
7055      S.VTableUses.swap(SavedVTableUses);
7056
7057      // Restore the set of pending implicit instantiations.
7058      assert(S.PendingInstantiations.empty() &&
7059             "PendingInstantiations should be empty before it is discarded.");
7060      S.PendingInstantiations.swap(SavedPendingInstantiations);
7061    }
7062
7063  private:
7064    Sema &S;
7065    SmallVector<VTableUse, 16> SavedVTableUses;
7066    std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7067    bool Enabled;
7068  };
7069
7070  /// \brief The queue of implicit template instantiations that are required
7071  /// and must be performed within the current local scope.
7072  ///
7073  /// This queue is only used for member functions of local classes in
7074  /// templates, which must be instantiated in the same scope as their
7075  /// enclosing function, so that they can reference function-local
7076  /// types, static variables, enumerators, etc.
7077  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7078
7079  class SavePendingLocalImplicitInstantiationsRAII {
7080  public:
7081    SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7082      SavedPendingLocalImplicitInstantiations.swap(
7083          S.PendingLocalImplicitInstantiations);
7084    }
7085
7086    ~SavePendingLocalImplicitInstantiationsRAII() {
7087      assert(S.PendingLocalImplicitInstantiations.empty() &&
7088             "there shouldn't be any pending local implicit instantiations");
7089      SavedPendingLocalImplicitInstantiations.swap(
7090          S.PendingLocalImplicitInstantiations);
7091    }
7092
7093  private:
7094    Sema &S;
7095    std::deque<PendingImplicitInstantiation>
7096    SavedPendingLocalImplicitInstantiations;
7097  };
7098
7099  /// A helper class for building up ExtParameterInfos.
7100  class ExtParameterInfoBuilder {
7101    SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7102    bool HasInteresting = false;
7103
7104  public:
7105    /// Set the ExtParameterInfo for the parameter at the given index,
7106    ///
7107    void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7108      assert(Infos.size() <= index);
7109      Infos.resize(index);
7110      Infos.push_back(info);
7111
7112      if (!HasInteresting)
7113        HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7114    }
7115
7116    /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7117    /// ExtParameterInfo array we've built up.
7118    const FunctionProtoType::ExtParameterInfo *
7119    getPointerOrNull(unsigned numParams) {
7120      if (!HasInteresting) return nullptr;
7121      Infos.resize(numParams);
7122      return Infos.data();
7123    }
7124  };
7125
7126  void PerformPendingInstantiations(bool LocalOnly = false);
7127
7128  TypeSourceInfo *SubstType(TypeSourceInfo *T,
7129                            const MultiLevelTemplateArgumentList &TemplateArgs,
7130                            SourceLocation Loc, DeclarationName Entity);
7131
7132  QualType SubstType(QualType T,
7133                     const MultiLevelTemplateArgumentList &TemplateArgs,
7134                     SourceLocation Loc, DeclarationName Entity);
7135
7136  TypeSourceInfo *SubstType(TypeLoc TL,
7137                            const MultiLevelTemplateArgumentList &TemplateArgs,
7138                            SourceLocation Loc, DeclarationName Entity);
7139
7140  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7141                            const MultiLevelTemplateArgumentList &TemplateArgs,
7142                                        SourceLocation Loc,
7143                                        DeclarationName Entity,
7144                                        CXXRecordDecl *ThisContext,
7145                                        unsigned ThisTypeQuals);
7146  void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7147                          const MultiLevelTemplateArgumentList &Args);
7148  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7149                            const MultiLevelTemplateArgumentList &TemplateArgs,
7150                                int indexAdjustment,
7151                                Optional<unsigned> NumExpansions,
7152                                bool ExpectParameterPack);
7153  bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7154                      const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7155                      const MultiLevelTemplateArgumentList &TemplateArgs,
7156                      SmallVectorImpl<QualType> &ParamTypes,
7157                      SmallVectorImpl<ParmVarDecl *> *OutParams,
7158                      ExtParameterInfoBuilder &ParamInfos);
7159  ExprResult SubstExpr(Expr *E,
7160                       const MultiLevelTemplateArgumentList &TemplateArgs);
7161
7162  /// \brief Substitute the given template arguments into a list of
7163  /// expressions, expanding pack expansions if required.
7164  ///
7165  /// \param Exprs The list of expressions to substitute into.
7166  ///
7167  /// \param IsCall Whether this is some form of call, in which case
7168  /// default arguments will be dropped.
7169  ///
7170  /// \param TemplateArgs The set of template arguments to substitute.
7171  ///
7172  /// \param Outputs Will receive all of the substituted arguments.
7173  ///
7174  /// \returns true if an error occurred, false otherwise.
7175  bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7176                  const MultiLevelTemplateArgumentList &TemplateArgs,
7177                  SmallVectorImpl<Expr *> &Outputs);
7178
7179  StmtResult SubstStmt(Stmt *S,
7180                       const MultiLevelTemplateArgumentList &TemplateArgs);
7181
7182  Decl *SubstDecl(Decl *D, DeclContext *Owner,
7183                  const MultiLevelTemplateArgumentList &TemplateArgs);
7184
7185  ExprResult SubstInitializer(Expr *E,
7186                       const MultiLevelTemplateArgumentList &TemplateArgs,
7187                       bool CXXDirectInit);
7188
7189  bool
7190  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7191                      CXXRecordDecl *Pattern,
7192                      const MultiLevelTemplateArgumentList &TemplateArgs);
7193
7194  bool
7195  InstantiateClass(SourceLocation PointOfInstantiation,
7196                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7197                   const MultiLevelTemplateArgumentList &TemplateArgs,
7198                   TemplateSpecializationKind TSK,
7199                   bool Complain = true);
7200
7201  bool InstantiateEnum(SourceLocation PointOfInstantiation,
7202                       EnumDecl *Instantiation, EnumDecl *Pattern,
7203                       const MultiLevelTemplateArgumentList &TemplateArgs,
7204                       TemplateSpecializationKind TSK);
7205
7206  bool InstantiateInClassInitializer(
7207      SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7208      FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7209
7210  struct LateInstantiatedAttribute {
7211    const Attr *TmplAttr;
7212    LocalInstantiationScope *Scope;
7213    Decl *NewDecl;
7214
7215    LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7216                              Decl *D)
7217      : TmplAttr(A), Scope(S), NewDecl(D)
7218    { }
7219  };
7220  typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7221
7222  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7223                        const Decl *Pattern, Decl *Inst,
7224                        LateInstantiatedAttrVec *LateAttrs = nullptr,
7225                        LocalInstantiationScope *OuterMostScope = nullptr);
7226
7227  bool
7228  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7229                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
7230                           TemplateSpecializationKind TSK,
7231                           bool Complain = true);
7232
7233  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7234                               CXXRecordDecl *Instantiation,
7235                            const MultiLevelTemplateArgumentList &TemplateArgs,
7236                               TemplateSpecializationKind TSK);
7237
7238  void InstantiateClassTemplateSpecializationMembers(
7239                                          SourceLocation PointOfInstantiation,
7240                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
7241                                                TemplateSpecializationKind TSK);
7242
7243  NestedNameSpecifierLoc
7244  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7245                           const MultiLevelTemplateArgumentList &TemplateArgs);
7246
7247  DeclarationNameInfo
7248  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7249                           const MultiLevelTemplateArgumentList &TemplateArgs);
7250  TemplateName
7251  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7252                    SourceLocation Loc,
7253                    const MultiLevelTemplateArgumentList &TemplateArgs);
7254  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7255             TemplateArgumentListInfo &Result,
7256             const MultiLevelTemplateArgumentList &TemplateArgs);
7257
7258  void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7259                                FunctionDecl *Function);
7260  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7261                                     FunctionDecl *Function,
7262                                     bool Recursive = false,
7263                                     bool DefinitionRequired = false,
7264                                     bool AtEndOfTU = false);
7265  VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7266      VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7267      const TemplateArgumentList &TemplateArgList,
7268      const TemplateArgumentListInfo &TemplateArgsInfo,
7269      SmallVectorImpl<TemplateArgument> &Converted,
7270      SourceLocation PointOfInstantiation, void *InsertPos,
7271      LateInstantiatedAttrVec *LateAttrs = nullptr,
7272      LocalInstantiationScope *StartingScope = nullptr);
7273  VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7274      VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7275      const MultiLevelTemplateArgumentList &TemplateArgs);
7276  void
7277  BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7278                             const MultiLevelTemplateArgumentList &TemplateArgs,
7279                             LateInstantiatedAttrVec *LateAttrs,
7280                             DeclContext *Owner,
7281                             LocalInstantiationScope *StartingScope,
7282                             bool InstantiatingVarTemplate = false);
7283  void InstantiateVariableInitializer(
7284      VarDecl *Var, VarDecl *OldVar,
7285      const MultiLevelTemplateArgumentList &TemplateArgs);
7286  void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7287                                     VarDecl *Var, bool Recursive = false,
7288                                     bool DefinitionRequired = false,
7289                                     bool AtEndOfTU = false);
7290  void InstantiateStaticDataMemberDefinition(
7291                                     SourceLocation PointOfInstantiation,
7292                                     VarDecl *Var,
7293                                     bool Recursive = false,
7294                                     bool DefinitionRequired = false);
7295
7296  void InstantiateMemInitializers(CXXConstructorDecl *New,
7297                                  const CXXConstructorDecl *Tmpl,
7298                            const MultiLevelTemplateArgumentList &TemplateArgs);
7299
7300  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7301                          const MultiLevelTemplateArgumentList &TemplateArgs);
7302  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7303                          const MultiLevelTemplateArgumentList &TemplateArgs);
7304
7305  // Objective-C declarations.
7306  enum ObjCContainerKind {
7307    OCK_None = -1,
7308    OCK_Interface = 0,
7309    OCK_Protocol,
7310    OCK_Category,
7311    OCK_ClassExtension,
7312    OCK_Implementation,
7313    OCK_CategoryImplementation
7314  };
7315  ObjCContainerKind getObjCContainerKind() const;
7316
7317  DeclResult actOnObjCTypeParam(Scope *S,
7318                                ObjCTypeParamVariance variance,
7319                                SourceLocation varianceLoc,
7320                                unsigned index,
7321                                IdentifierInfo *paramName,
7322                                SourceLocation paramLoc,
7323                                SourceLocation colonLoc,
7324                                ParsedType typeBound);
7325
7326  ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7327                                            ArrayRef<Decl *> typeParams,
7328                                            SourceLocation rAngleLoc);
7329  void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7330
7331  Decl *ActOnStartClassInterface(Scope *S,
7332                                 SourceLocation AtInterfaceLoc,
7333                                 IdentifierInfo *ClassName,
7334                                 SourceLocation ClassLoc,
7335                                 ObjCTypeParamList *typeParamList,
7336                                 IdentifierInfo *SuperName,
7337                                 SourceLocation SuperLoc,
7338                                 ArrayRef<ParsedType> SuperTypeArgs,
7339                                 SourceRange SuperTypeArgsRange,
7340                                 Decl * const *ProtoRefs,
7341                                 unsigned NumProtoRefs,
7342                                 const SourceLocation *ProtoLocs,
7343                                 SourceLocation EndProtoLoc,
7344                                 AttributeList *AttrList);
7345
7346  void ActOnSuperClassOfClassInterface(Scope *S,
7347                                       SourceLocation AtInterfaceLoc,
7348                                       ObjCInterfaceDecl *IDecl,
7349                                       IdentifierInfo *ClassName,
7350                                       SourceLocation ClassLoc,
7351                                       IdentifierInfo *SuperName,
7352                                       SourceLocation SuperLoc,
7353                                       ArrayRef<ParsedType> SuperTypeArgs,
7354                                       SourceRange SuperTypeArgsRange);
7355
7356  void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7357                               IdentifierInfo *SuperName,
7358                               SourceLocation SuperLoc);
7359
7360  Decl *ActOnCompatibilityAlias(
7361                    SourceLocation AtCompatibilityAliasLoc,
7362                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
7363                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
7364
7365  bool CheckForwardProtocolDeclarationForCircularDependency(
7366    IdentifierInfo *PName,
7367    SourceLocation &PLoc, SourceLocation PrevLoc,
7368    const ObjCList<ObjCProtocolDecl> &PList);
7369
7370  Decl *ActOnStartProtocolInterface(
7371                    SourceLocation AtProtoInterfaceLoc,
7372                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7373                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7374                    const SourceLocation *ProtoLocs,
7375                    SourceLocation EndProtoLoc,
7376                    AttributeList *AttrList);
7377
7378  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7379                                    IdentifierInfo *ClassName,
7380                                    SourceLocation ClassLoc,
7381                                    ObjCTypeParamList *typeParamList,
7382                                    IdentifierInfo *CategoryName,
7383                                    SourceLocation CategoryLoc,
7384                                    Decl * const *ProtoRefs,
7385                                    unsigned NumProtoRefs,
7386                                    const SourceLocation *ProtoLocs,
7387                                    SourceLocation EndProtoLoc);
7388
7389  Decl *ActOnStartClassImplementation(
7390                    SourceLocation AtClassImplLoc,
7391                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
7392                    IdentifierInfo *SuperClassname,
7393                    SourceLocation SuperClassLoc);
7394
7395  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7396                                         IdentifierInfo *ClassName,
7397                                         SourceLocation ClassLoc,
7398                                         IdentifierInfo *CatName,
7399                                         SourceLocation CatLoc);
7400
7401  DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7402                                               ArrayRef<Decl *> Decls);
7403
7404  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7405                   IdentifierInfo **IdentList,
7406                   SourceLocation *IdentLocs,
7407                   ArrayRef<ObjCTypeParamList *> TypeParamLists,
7408                   unsigned NumElts);
7409
7410  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7411                                        ArrayRef<IdentifierLocPair> IdentList,
7412                                        AttributeList *attrList);
7413
7414  void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7415                               ArrayRef<IdentifierLocPair> ProtocolId,
7416                               SmallVectorImpl<Decl *> &Protocols);
7417
7418  void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7419                                    SourceLocation ProtocolLoc,
7420                                    IdentifierInfo *TypeArgId,
7421                                    SourceLocation TypeArgLoc,
7422                                    bool SelectProtocolFirst = false);
7423
7424  /// Given a list of identifiers (and their locations), resolve the
7425  /// names to either Objective-C protocol qualifiers or type
7426  /// arguments, as appropriate.
7427  void actOnObjCTypeArgsOrProtocolQualifiers(
7428         Scope *S,
7429         ParsedType baseType,
7430         SourceLocation lAngleLoc,
7431         ArrayRef<IdentifierInfo *> identifiers,
7432         ArrayRef<SourceLocation> identifierLocs,
7433         SourceLocation rAngleLoc,
7434         SourceLocation &typeArgsLAngleLoc,
7435         SmallVectorImpl<ParsedType> &typeArgs,
7436         SourceLocation &typeArgsRAngleLoc,
7437         SourceLocation &protocolLAngleLoc,
7438         SmallVectorImpl<Decl *> &protocols,
7439         SourceLocation &protocolRAngleLoc,
7440         bool warnOnIncompleteProtocols);
7441
7442  /// Build a an Objective-C protocol-qualified 'id' type where no
7443  /// base type was specified.
7444  TypeResult actOnObjCProtocolQualifierType(
7445               SourceLocation lAngleLoc,
7446               ArrayRef<Decl *> protocols,
7447               ArrayRef<SourceLocation> protocolLocs,
7448               SourceLocation rAngleLoc);
7449
7450  /// Build a specialized and/or protocol-qualified Objective-C type.
7451  TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7452               Scope *S,
7453               SourceLocation Loc,
7454               ParsedType BaseType,
7455               SourceLocation TypeArgsLAngleLoc,
7456               ArrayRef<ParsedType> TypeArgs,
7457               SourceLocation TypeArgsRAngleLoc,
7458               SourceLocation ProtocolLAngleLoc,
7459               ArrayRef<Decl *> Protocols,
7460               ArrayRef<SourceLocation> ProtocolLocs,
7461               SourceLocation ProtocolRAngleLoc);
7462
7463  /// Build an Objective-C object pointer type.
7464  QualType BuildObjCObjectType(QualType BaseType,
7465                               SourceLocation Loc,
7466                               SourceLocation TypeArgsLAngleLoc,
7467                               ArrayRef<TypeSourceInfo *> TypeArgs,
7468                               SourceLocation TypeArgsRAngleLoc,
7469                               SourceLocation ProtocolLAngleLoc,
7470                               ArrayRef<ObjCProtocolDecl *> Protocols,
7471                               ArrayRef<SourceLocation> ProtocolLocs,
7472                               SourceLocation ProtocolRAngleLoc,
7473                               bool FailOnError = false);
7474
7475  /// Check the application of the Objective-C '__kindof' qualifier to
7476  /// the given type.
7477  bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7478
7479  /// Ensure attributes are consistent with type.
7480  /// \param [in, out] Attributes The attributes to check; they will
7481  /// be modified to be consistent with \p PropertyTy.
7482  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7483                                   SourceLocation Loc,
7484                                   unsigned &Attributes,
7485                                   bool propertyInPrimaryClass);
7486
7487  /// Process the specified property declaration and create decls for the
7488  /// setters and getters as needed.
7489  /// \param property The property declaration being processed
7490  void ProcessPropertyDecl(ObjCPropertyDecl *property);
7491
7492
7493  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7494                                ObjCPropertyDecl *SuperProperty,
7495                                const IdentifierInfo *Name,
7496                                bool OverridingProtocolProperty);
7497
7498  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7499                                        ObjCInterfaceDecl *ID);
7500
7501  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7502                   ArrayRef<Decl *> allMethods = None,
7503                   ArrayRef<DeclGroupPtrTy> allTUVars = None);
7504
7505  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7506                      SourceLocation LParenLoc,
7507                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
7508                      Selector GetterSel, Selector SetterSel,
7509                      tok::ObjCKeywordKind MethodImplKind,
7510                      DeclContext *lexicalDC = nullptr);
7511
7512  Decl *ActOnPropertyImplDecl(Scope *S,
7513                              SourceLocation AtLoc,
7514                              SourceLocation PropertyLoc,
7515                              bool ImplKind,
7516                              IdentifierInfo *PropertyId,
7517                              IdentifierInfo *PropertyIvar,
7518                              SourceLocation PropertyIvarLoc,
7519                              ObjCPropertyQueryKind QueryKind);
7520
7521  enum ObjCSpecialMethodKind {
7522    OSMK_None,
7523    OSMK_Alloc,
7524    OSMK_New,
7525    OSMK_Copy,
7526    OSMK_RetainingInit,
7527    OSMK_NonRetainingInit
7528  };
7529
7530  struct ObjCArgInfo {
7531    IdentifierInfo *Name;
7532    SourceLocation NameLoc;
7533    // The Type is null if no type was specified, and the DeclSpec is invalid
7534    // in this case.
7535    ParsedType Type;
7536    ObjCDeclSpec DeclSpec;
7537
7538    /// ArgAttrs - Attribute list for this argument.
7539    AttributeList *ArgAttrs;
7540  };
7541
7542  Decl *ActOnMethodDeclaration(
7543    Scope *S,
7544    SourceLocation BeginLoc, // location of the + or -.
7545    SourceLocation EndLoc,   // location of the ; or {.
7546    tok::TokenKind MethodType,
7547    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7548    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7549    // optional arguments. The number of types/arguments is obtained
7550    // from the Sel.getNumArgs().
7551    ObjCArgInfo *ArgInfo,
7552    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7553    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7554    bool isVariadic, bool MethodDefinition);
7555
7556  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7557                                              const ObjCObjectPointerType *OPT,
7558                                              bool IsInstance);
7559  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7560                                           bool IsInstance);
7561
7562  bool CheckARCMethodDecl(ObjCMethodDecl *method);
7563  bool inferObjCARCLifetime(ValueDecl *decl);
7564
7565  ExprResult
7566  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7567                            Expr *BaseExpr,
7568                            SourceLocation OpLoc,
7569                            DeclarationName MemberName,
7570                            SourceLocation MemberLoc,
7571                            SourceLocation SuperLoc, QualType SuperType,
7572                            bool Super);
7573
7574  ExprResult
7575  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7576                            IdentifierInfo &propertyName,
7577                            SourceLocation receiverNameLoc,
7578                            SourceLocation propertyNameLoc);
7579
7580  ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7581
7582  /// \brief Describes the kind of message expression indicated by a message
7583  /// send that starts with an identifier.
7584  enum ObjCMessageKind {
7585    /// \brief The message is sent to 'super'.
7586    ObjCSuperMessage,
7587    /// \brief The message is an instance message.
7588    ObjCInstanceMessage,
7589    /// \brief The message is a class message, and the identifier is a type
7590    /// name.
7591    ObjCClassMessage
7592  };
7593
7594  ObjCMessageKind getObjCMessageKind(Scope *S,
7595                                     IdentifierInfo *Name,
7596                                     SourceLocation NameLoc,
7597                                     bool IsSuper,
7598                                     bool HasTrailingDot,
7599                                     ParsedType &ReceiverType);
7600
7601  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7602                               Selector Sel,
7603                               SourceLocation LBracLoc,
7604                               ArrayRef<SourceLocation> SelectorLocs,
7605                               SourceLocation RBracLoc,
7606                               MultiExprArg Args);
7607
7608  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7609                               QualType ReceiverType,
7610                               SourceLocation SuperLoc,
7611                               Selector Sel,
7612                               ObjCMethodDecl *Method,
7613                               SourceLocation LBracLoc,
7614                               ArrayRef<SourceLocation> SelectorLocs,
7615                               SourceLocation RBracLoc,
7616                               MultiExprArg Args,
7617                               bool isImplicit = false);
7618
7619  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7620                                       bool isSuperReceiver,
7621                                       SourceLocation Loc,
7622                                       Selector Sel,
7623                                       ObjCMethodDecl *Method,
7624                                       MultiExprArg Args);
7625
7626  ExprResult ActOnClassMessage(Scope *S,
7627                               ParsedType Receiver,
7628                               Selector Sel,
7629                               SourceLocation LBracLoc,
7630                               ArrayRef<SourceLocation> SelectorLocs,
7631                               SourceLocation RBracLoc,
7632                               MultiExprArg Args);
7633
7634  ExprResult BuildInstanceMessage(Expr *Receiver,
7635                                  QualType ReceiverType,
7636                                  SourceLocation SuperLoc,
7637                                  Selector Sel,
7638                                  ObjCMethodDecl *Method,
7639                                  SourceLocation LBracLoc,
7640                                  ArrayRef<SourceLocation> SelectorLocs,
7641                                  SourceLocation RBracLoc,
7642                                  MultiExprArg Args,
7643                                  bool isImplicit = false);
7644
7645  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7646                                          QualType ReceiverType,
7647                                          SourceLocation Loc,
7648                                          Selector Sel,
7649                                          ObjCMethodDecl *Method,
7650                                          MultiExprArg Args);
7651
7652  ExprResult ActOnInstanceMessage(Scope *S,
7653                                  Expr *Receiver,
7654                                  Selector Sel,
7655                                  SourceLocation LBracLoc,
7656                                  ArrayRef<SourceLocation> SelectorLocs,
7657                                  SourceLocation RBracLoc,
7658                                  MultiExprArg Args);
7659
7660  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7661                                  ObjCBridgeCastKind Kind,
7662                                  SourceLocation BridgeKeywordLoc,
7663                                  TypeSourceInfo *TSInfo,
7664                                  Expr *SubExpr);
7665
7666  ExprResult ActOnObjCBridgedCast(Scope *S,
7667                                  SourceLocation LParenLoc,
7668                                  ObjCBridgeCastKind Kind,
7669                                  SourceLocation BridgeKeywordLoc,
7670                                  ParsedType Type,
7671                                  SourceLocation RParenLoc,
7672                                  Expr *SubExpr);
7673
7674  void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7675
7676  void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7677
7678  bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7679                                     CastKind &Kind);
7680
7681  bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7682                                        QualType DestType, QualType SrcType,
7683                                        ObjCInterfaceDecl *&RelatedClass,
7684                                        ObjCMethodDecl *&ClassMethod,
7685                                        ObjCMethodDecl *&InstanceMethod,
7686                                        TypedefNameDecl *&TDNDecl,
7687                                        bool CfToNs, bool Diagnose = true);
7688
7689  bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7690                                         QualType DestType, QualType SrcType,
7691                                         Expr *&SrcExpr, bool Diagnose = true);
7692
7693  bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
7694                                          bool Diagnose = true);
7695
7696  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7697
7698  /// \brief Check whether the given new method is a valid override of the
7699  /// given overridden method, and set any properties that should be inherited.
7700  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7701                               const ObjCMethodDecl *Overridden);
7702
7703  /// \brief Describes the compatibility of a result type with its method.
7704  enum ResultTypeCompatibilityKind {
7705    RTC_Compatible,
7706    RTC_Incompatible,
7707    RTC_Unknown
7708  };
7709
7710  void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7711                                ObjCInterfaceDecl *CurrentClass,
7712                                ResultTypeCompatibilityKind RTC);
7713
7714  enum PragmaOptionsAlignKind {
7715    POAK_Native,  // #pragma options align=native
7716    POAK_Natural, // #pragma options align=natural
7717    POAK_Packed,  // #pragma options align=packed
7718    POAK_Power,   // #pragma options align=power
7719    POAK_Mac68k,  // #pragma options align=mac68k
7720    POAK_Reset    // #pragma options align=reset
7721  };
7722
7723  /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7724  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7725                               SourceLocation PragmaLoc);
7726
7727  /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7728  void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
7729                       StringRef SlotLabel, Expr *Alignment);
7730
7731  /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7732  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7733
7734  /// ActOnPragmaMSComment - Called on well formed
7735  /// \#pragma comment(kind, "arg").
7736  void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
7737                            StringRef Arg);
7738
7739  /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7740  /// pointers_to_members(representation method[, general purpose
7741  /// representation]).
7742  void ActOnPragmaMSPointersToMembers(
7743      LangOptions::PragmaMSPointersToMembersKind Kind,
7744      SourceLocation PragmaLoc);
7745
7746  /// \brief Called on well formed \#pragma vtordisp().
7747  void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
7748                             SourceLocation PragmaLoc,
7749                             MSVtorDispAttr::Mode Value);
7750
7751  enum PragmaSectionKind {
7752    PSK_DataSeg,
7753    PSK_BSSSeg,
7754    PSK_ConstSeg,
7755    PSK_CodeSeg,
7756  };
7757
7758  bool UnifySection(StringRef SectionName,
7759                    int SectionFlags,
7760                    DeclaratorDecl *TheDecl);
7761  bool UnifySection(StringRef SectionName,
7762                    int SectionFlags,
7763                    SourceLocation PragmaSectionLocation);
7764
7765  /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7766  void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7767                        PragmaMsStackAction Action,
7768                        llvm::StringRef StackSlotLabel,
7769                        StringLiteral *SegmentName,
7770                        llvm::StringRef PragmaName);
7771
7772  /// \brief Called on well formed \#pragma section().
7773  void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7774                            int SectionFlags, StringLiteral *SegmentName);
7775
7776  /// \brief Called on well-formed \#pragma init_seg().
7777  void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7778                            StringLiteral *SegmentName);
7779
7780  /// \brief Called on #pragma clang __debug dump II
7781  void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
7782
7783  /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7784  void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
7785                                 StringRef Value);
7786
7787  /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7788  void ActOnPragmaUnused(const Token &Identifier,
7789                         Scope *curScope,
7790                         SourceLocation PragmaLoc);
7791
7792  /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7793  void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7794                             SourceLocation PragmaLoc);
7795
7796  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7797                                 SourceLocation Loc);
7798  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7799
7800  /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7801  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7802                         SourceLocation PragmaLoc,
7803                         SourceLocation WeakNameLoc);
7804
7805  /// ActOnPragmaRedefineExtname - Called on well formed
7806  /// \#pragma redefine_extname oldname newname.
7807  void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7808                                  IdentifierInfo* AliasName,
7809                                  SourceLocation PragmaLoc,
7810                                  SourceLocation WeakNameLoc,
7811                                  SourceLocation AliasNameLoc);
7812
7813  /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7814  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7815                            IdentifierInfo* AliasName,
7816                            SourceLocation PragmaLoc,
7817                            SourceLocation WeakNameLoc,
7818                            SourceLocation AliasNameLoc);
7819
7820  /// ActOnPragmaFPContract - Called on well formed
7821  /// \#pragma {STDC,OPENCL} FP_CONTRACT
7822  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7823
7824  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7825  /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7826  void AddAlignmentAttributesForRecord(RecordDecl *RD);
7827
7828  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7829  void AddMsStructLayoutForRecord(RecordDecl *RD);
7830
7831  /// FreePackedContext - Deallocate and null out PackContext.
7832  void FreePackedContext();
7833
7834  /// PushNamespaceVisibilityAttr - Note that we've entered a
7835  /// namespace with a visibility attribute.
7836  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7837                                   SourceLocation Loc);
7838
7839  /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7840  /// add an appropriate visibility attribute.
7841  void AddPushedVisibilityAttribute(Decl *RD);
7842
7843  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7844  /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7845  void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7846
7847  /// FreeVisContext - Deallocate and null out VisContext.
7848  void FreeVisContext();
7849
7850  /// AddCFAuditedAttribute - Check whether we're currently within
7851  /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7852  /// the appropriate attribute.
7853  void AddCFAuditedAttribute(Decl *D);
7854
7855  /// \brief Called on well formed \#pragma clang optimize.
7856  void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7857
7858  /// \brief Get the location for the currently active "\#pragma clang optimize
7859  /// off". If this location is invalid, then the state of the pragma is "on".
7860  SourceLocation getOptimizeOffPragmaLocation() const {
7861    return OptimizeOffPragmaLocation;
7862  }
7863
7864  /// \brief Only called on function definitions; if there is a pragma in scope
7865  /// with the effect of a range-based optnone, consider marking the function
7866  /// with attribute optnone.
7867  void AddRangeBasedOptnone(FunctionDecl *FD);
7868
7869  /// \brief Adds the 'optnone' attribute to the function declaration if there
7870  /// are no conflicts; Loc represents the location causing the 'optnone'
7871  /// attribute to be added (usually because of a pragma).
7872  void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7873
7874  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7875  void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7876                      unsigned SpellingListIndex, bool IsPackExpansion);
7877  void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7878                      unsigned SpellingListIndex, bool IsPackExpansion);
7879
7880  /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7881  /// declaration.
7882  void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7883                            unsigned SpellingListIndex);
7884
7885  /// AddAlignValueAttr - Adds an align_value attribute to a particular
7886  /// declaration.
7887  void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7888                         unsigned SpellingListIndex);
7889
7890  /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
7891  /// declaration.
7892  void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
7893                           Expr *MinBlocks, unsigned SpellingListIndex);
7894
7895  /// AddModeAttr - Adds a mode attribute to a particular declaration.
7896  void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
7897                   unsigned SpellingListIndex, bool InInstantiation = false);
7898
7899  void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
7900                           ParameterABI ABI, unsigned SpellingListIndex);
7901
7902  void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
7903                         unsigned SpellingListIndex, bool isNSConsumed,
7904                         bool isTemplateInstantiation);
7905
7906  //===--------------------------------------------------------------------===//
7907  // C++ Coroutines TS
7908  //
7909  ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7910  ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7911  StmtResult ActOnCoreturnStmt(SourceLocation KwLoc, Expr *E);
7912
7913  ExprResult BuildCoawaitExpr(SourceLocation KwLoc, Expr *E);
7914  ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
7915  StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E);
7916
7917  void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
7918
7919  //===--------------------------------------------------------------------===//
7920  // OpenMP directives and clauses.
7921  //
7922private:
7923  void *VarDataSharingAttributesStack;
7924  /// Set to true inside '#pragma omp declare target' region.
7925  bool IsInOpenMPDeclareTargetContext = false;
7926  /// \brief Initialization of data-sharing attributes stack.
7927  void InitDataSharingAttributesStack();
7928  void DestroyDataSharingAttributesStack();
7929  ExprResult
7930  VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
7931                                        bool StrictlyPositive = true);
7932  /// Returns OpenMP nesting level for current directive.
7933  unsigned getOpenMPNestingLevel() const;
7934
7935public:
7936  /// \brief Return true if the provided declaration \a VD should be captured by
7937  /// reference.
7938  /// \param Level Relative level of nested OpenMP construct for that the check
7939  /// is performed.
7940  bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
7941
7942  /// \brief Check if the specified variable is used in one of the private
7943  /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
7944  /// constructs.
7945  VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
7946  ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7947                                   ExprObjectKind OK, SourceLocation Loc);
7948
7949  /// \brief Check if the specified variable is used in 'private' clause.
7950  /// \param Level Relative level of nested OpenMP construct for that the check
7951  /// is performed.
7952  bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
7953
7954  /// \brief Check if the specified variable is captured  by 'target' directive.
7955  /// \param Level Relative level of nested OpenMP construct for that the check
7956  /// is performed.
7957  bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
7958
7959  ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7960                                                    Expr *Op);
7961  /// \brief Called on start of new data sharing attribute block.
7962  void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7963                           const DeclarationNameInfo &DirName, Scope *CurScope,
7964                           SourceLocation Loc);
7965  /// \brief Start analysis of clauses.
7966  void StartOpenMPClause(OpenMPClauseKind K);
7967  /// \brief End analysis of clauses.
7968  void EndOpenMPClause();
7969  /// \brief Called on end of data sharing attribute block.
7970  void EndOpenMPDSABlock(Stmt *CurDirective);
7971
7972  /// \brief Check if the current region is an OpenMP loop region and if it is,
7973  /// mark loop control variable, used in \p Init for loop initialization, as
7974  /// private by default.
7975  /// \param Init First part of the for loop.
7976  void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
7977
7978  // OpenMP directives and clauses.
7979  /// \brief Called on correct id-expression from the '#pragma omp
7980  /// threadprivate'.
7981  ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7982                                     CXXScopeSpec &ScopeSpec,
7983                                     const DeclarationNameInfo &Id);
7984  /// \brief Called on well-formed '#pragma omp threadprivate'.
7985  DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7986                                     SourceLocation Loc,
7987                                     ArrayRef<Expr *> VarList);
7988  /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7989  OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7990                                     SourceLocation Loc,
7991                                     ArrayRef<Expr *> VarList);
7992  /// \brief Check if the specified type is allowed to be used in 'omp declare
7993  /// reduction' construct.
7994  QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
7995                                           TypeResult ParsedType);
7996  /// \brief Called on start of '#pragma omp declare reduction'.
7997  DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
7998      Scope *S, DeclContext *DC, DeclarationName Name,
7999      ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8000      AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8001  /// \brief Initialize declare reduction construct initializer.
8002  void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8003  /// \brief Finish current declare reduction construct initializer.
8004  void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8005  /// \brief Initialize declare reduction construct initializer.
8006  void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8007  /// \brief Finish current declare reduction construct initializer.
8008  void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8009  /// \brief Called at the end of '#pragma omp declare reduction'.
8010  DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8011      Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8012
8013  /// Called on the start of target region i.e. '#pragma omp declare target'.
8014  bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8015  /// Called at the end of target region i.e. '#pragme omp end declare target'.
8016  void ActOnFinishOpenMPDeclareTargetDirective();
8017  /// Called on correct id-expression from the '#pragma omp declare target'.
8018  void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8019                                    const DeclarationNameInfo &Id,
8020                                    OMPDeclareTargetDeclAttr::MapTypeTy MT,
8021                                    NamedDeclSetType &SameDirectiveDecls);
8022  /// Check declaration inside target region.
8023  void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8024  /// Return true inside OpenMP target region.
8025  bool isInOpenMPDeclareTargetContext() const {
8026    return IsInOpenMPDeclareTargetContext;
8027  }
8028
8029  /// \brief Initialization of captured region for OpenMP region.
8030  void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8031  /// \brief End of OpenMP region.
8032  ///
8033  /// \param S Statement associated with the current OpenMP region.
8034  /// \param Clauses List of clauses for the current OpenMP region.
8035  ///
8036  /// \returns Statement for finished OpenMP region.
8037  StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8038  StmtResult ActOnOpenMPExecutableDirective(
8039      OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8040      OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8041      Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8042  /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8043  /// of the  associated statement.
8044  StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8045                                          Stmt *AStmt,
8046                                          SourceLocation StartLoc,
8047                                          SourceLocation EndLoc);
8048  /// \brief Called on well-formed '\#pragma omp simd' after parsing
8049  /// of the associated statement.
8050  StmtResult ActOnOpenMPSimdDirective(
8051      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8052      SourceLocation EndLoc,
8053      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8054  /// \brief Called on well-formed '\#pragma omp for' after parsing
8055  /// of the associated statement.
8056  StmtResult ActOnOpenMPForDirective(
8057      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8058      SourceLocation EndLoc,
8059      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8060  /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8061  /// of the associated statement.
8062  StmtResult ActOnOpenMPForSimdDirective(
8063      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8064      SourceLocation EndLoc,
8065      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8066  /// \brief Called on well-formed '\#pragma omp sections' after parsing
8067  /// of the associated statement.
8068  StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8069                                          Stmt *AStmt, SourceLocation StartLoc,
8070                                          SourceLocation EndLoc);
8071  /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8072  /// associated statement.
8073  StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8074                                         SourceLocation EndLoc);
8075  /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8076  /// associated statement.
8077  StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8078                                        Stmt *AStmt, SourceLocation StartLoc,
8079                                        SourceLocation EndLoc);
8080  /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8081  /// associated statement.
8082  StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8083                                        SourceLocation EndLoc);
8084  /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8085  /// associated statement.
8086  StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8087                                          ArrayRef<OMPClause *> Clauses,
8088                                          Stmt *AStmt, SourceLocation StartLoc,
8089                                          SourceLocation EndLoc);
8090  /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8091  /// of the  associated statement.
8092  StmtResult ActOnOpenMPParallelForDirective(
8093      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8094      SourceLocation EndLoc,
8095      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8096  /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8097  /// parsing of the  associated statement.
8098  StmtResult ActOnOpenMPParallelForSimdDirective(
8099      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8100      SourceLocation EndLoc,
8101      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8102  /// \brief Called on well-formed '\#pragma omp parallel sections' after
8103  /// parsing of the  associated statement.
8104  StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8105                                                  Stmt *AStmt,
8106                                                  SourceLocation StartLoc,
8107                                                  SourceLocation EndLoc);
8108  /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8109  /// associated statement.
8110  StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8111                                      Stmt *AStmt, SourceLocation StartLoc,
8112                                      SourceLocation EndLoc);
8113  /// \brief Called on well-formed '\#pragma omp taskyield'.
8114  StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8115                                           SourceLocation EndLoc);
8116  /// \brief Called on well-formed '\#pragma omp barrier'.
8117  StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8118                                         SourceLocation EndLoc);
8119  /// \brief Called on well-formed '\#pragma omp taskwait'.
8120  StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8121                                          SourceLocation EndLoc);
8122  /// \brief Called on well-formed '\#pragma omp taskgroup'.
8123  StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8124                                           SourceLocation EndLoc);
8125  /// \brief Called on well-formed '\#pragma omp flush'.
8126  StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8127                                       SourceLocation StartLoc,
8128                                       SourceLocation EndLoc);
8129  /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8130  /// associated statement.
8131  StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8132                                         Stmt *AStmt, SourceLocation StartLoc,
8133                                         SourceLocation EndLoc);
8134  /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8135  /// associated statement.
8136  StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8137                                        Stmt *AStmt, SourceLocation StartLoc,
8138                                        SourceLocation EndLoc);
8139  /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8140  /// associated statement.
8141  StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8142                                        Stmt *AStmt, SourceLocation StartLoc,
8143                                        SourceLocation EndLoc);
8144  /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8145  /// the associated statement.
8146  StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8147                                            Stmt *AStmt, SourceLocation StartLoc,
8148                                            SourceLocation EndLoc);
8149  /// \brief Called on well-formed '\#pragma omp target enter data' after
8150  /// parsing of the associated statement.
8151  StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8152                                                 SourceLocation StartLoc,
8153                                                 SourceLocation EndLoc);
8154  /// \brief Called on well-formed '\#pragma omp target exit data' after
8155  /// parsing of the associated statement.
8156  StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8157                                                SourceLocation StartLoc,
8158                                                SourceLocation EndLoc);
8159  /// \brief Called on well-formed '\#pragma omp target parallel' after
8160  /// parsing of the associated statement.
8161  StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8162                                                Stmt *AStmt,
8163                                                SourceLocation StartLoc,
8164                                                SourceLocation EndLoc);
8165  /// \brief Called on well-formed '\#pragma omp target parallel for' after
8166  /// parsing of the  associated statement.
8167  StmtResult ActOnOpenMPTargetParallelForDirective(
8168      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8169      SourceLocation EndLoc,
8170      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8171  /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8172  /// associated statement.
8173  StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8174                                       Stmt *AStmt, SourceLocation StartLoc,
8175                                       SourceLocation EndLoc);
8176  /// \brief Called on well-formed '\#pragma omp cancellation point'.
8177  StmtResult
8178  ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8179                                        SourceLocation EndLoc,
8180                                        OpenMPDirectiveKind CancelRegion);
8181  /// \brief Called on well-formed '\#pragma omp cancel'.
8182  StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8183                                        SourceLocation StartLoc,
8184                                        SourceLocation EndLoc,
8185                                        OpenMPDirectiveKind CancelRegion);
8186  /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8187  /// associated statement.
8188  StmtResult ActOnOpenMPTaskLoopDirective(
8189      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8190      SourceLocation EndLoc,
8191      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8192  /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8193  /// the associated statement.
8194  StmtResult ActOnOpenMPTaskLoopSimdDirective(
8195      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8196      SourceLocation EndLoc,
8197      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8198  /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8199  /// of the associated statement.
8200  StmtResult ActOnOpenMPDistributeDirective(
8201      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8202      SourceLocation EndLoc,
8203      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8204  /// \brief Called on well-formed '\#pragma omp target update'.
8205  StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8206                                              SourceLocation StartLoc,
8207                                              SourceLocation EndLoc);
8208  /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8209  /// parsing of the associated statement.
8210  StmtResult ActOnOpenMPDistributeParallelForDirective(
8211      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8212      SourceLocation EndLoc,
8213      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8214  /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8215  /// after parsing of the associated statement.
8216  StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8217      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8218      SourceLocation EndLoc,
8219      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8220  /// \brief Called on well-formed '\#pragma omp distribute simd' after
8221  /// parsing of the associated statement.
8222  StmtResult ActOnOpenMPDistributeSimdDirective(
8223      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8224      SourceLocation EndLoc,
8225      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8226  /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8227  /// parsing of the associated statement.
8228  StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8229      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8230      SourceLocation EndLoc,
8231      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8232
8233  /// Checks correctness of linear modifiers.
8234  bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8235                                 SourceLocation LinLoc);
8236  /// Checks that the specified declaration matches requirements for the linear
8237  /// decls.
8238  bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8239                             OpenMPLinearClauseKind LinKind, QualType Type);
8240
8241  /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8242  /// the associated method/function.
8243  DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8244      DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8245      Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8246      ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8247      ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8248
8249  OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8250                                         Expr *Expr,
8251                                         SourceLocation StartLoc,
8252                                         SourceLocation LParenLoc,
8253                                         SourceLocation EndLoc);
8254  /// \brief Called on well-formed 'if' clause.
8255  OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8256                                 Expr *Condition, SourceLocation StartLoc,
8257                                 SourceLocation LParenLoc,
8258                                 SourceLocation NameModifierLoc,
8259                                 SourceLocation ColonLoc,
8260                                 SourceLocation EndLoc);
8261  /// \brief Called on well-formed 'final' clause.
8262  OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8263                                    SourceLocation LParenLoc,
8264                                    SourceLocation EndLoc);
8265  /// \brief Called on well-formed 'num_threads' clause.
8266  OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8267                                         SourceLocation StartLoc,
8268                                         SourceLocation LParenLoc,
8269                                         SourceLocation EndLoc);
8270  /// \brief Called on well-formed 'safelen' clause.
8271  OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8272                                      SourceLocation StartLoc,
8273                                      SourceLocation LParenLoc,
8274                                      SourceLocation EndLoc);
8275  /// \brief Called on well-formed 'simdlen' clause.
8276  OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8277                                      SourceLocation LParenLoc,
8278                                      SourceLocation EndLoc);
8279  /// \brief Called on well-formed 'collapse' clause.
8280  OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8281                                       SourceLocation StartLoc,
8282                                       SourceLocation LParenLoc,
8283                                       SourceLocation EndLoc);
8284  /// \brief Called on well-formed 'ordered' clause.
8285  OMPClause *
8286  ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8287                           SourceLocation LParenLoc = SourceLocation(),
8288                           Expr *NumForLoops = nullptr);
8289  /// \brief Called on well-formed 'grainsize' clause.
8290  OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8291                                        SourceLocation LParenLoc,
8292                                        SourceLocation EndLoc);
8293  /// \brief Called on well-formed 'num_tasks' clause.
8294  OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8295                                       SourceLocation LParenLoc,
8296                                       SourceLocation EndLoc);
8297  /// \brief Called on well-formed 'hint' clause.
8298  OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8299                                   SourceLocation LParenLoc,
8300                                   SourceLocation EndLoc);
8301
8302  OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8303                                     unsigned Argument,
8304                                     SourceLocation ArgumentLoc,
8305                                     SourceLocation StartLoc,
8306                                     SourceLocation LParenLoc,
8307                                     SourceLocation EndLoc);
8308  /// \brief Called on well-formed 'default' clause.
8309  OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8310                                      SourceLocation KindLoc,
8311                                      SourceLocation StartLoc,
8312                                      SourceLocation LParenLoc,
8313                                      SourceLocation EndLoc);
8314  /// \brief Called on well-formed 'proc_bind' clause.
8315  OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8316                                       SourceLocation KindLoc,
8317                                       SourceLocation StartLoc,
8318                                       SourceLocation LParenLoc,
8319                                       SourceLocation EndLoc);
8320
8321  OMPClause *ActOnOpenMPSingleExprWithArgClause(
8322      OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8323      SourceLocation StartLoc, SourceLocation LParenLoc,
8324      ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8325      SourceLocation EndLoc);
8326  /// \brief Called on well-formed 'schedule' clause.
8327  OMPClause *ActOnOpenMPScheduleClause(
8328      OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8329      OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8330      SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8331      SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8332
8333  OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8334                               SourceLocation EndLoc);
8335  /// \brief Called on well-formed 'nowait' clause.
8336  OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8337                                     SourceLocation EndLoc);
8338  /// \brief Called on well-formed 'untied' clause.
8339  OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8340                                     SourceLocation EndLoc);
8341  /// \brief Called on well-formed 'mergeable' clause.
8342  OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8343                                        SourceLocation EndLoc);
8344  /// \brief Called on well-formed 'read' clause.
8345  OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8346                                   SourceLocation EndLoc);
8347  /// \brief Called on well-formed 'write' clause.
8348  OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8349                                    SourceLocation EndLoc);
8350  /// \brief Called on well-formed 'update' clause.
8351  OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8352                                     SourceLocation EndLoc);
8353  /// \brief Called on well-formed 'capture' clause.
8354  OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8355                                      SourceLocation EndLoc);
8356  /// \brief Called on well-formed 'seq_cst' clause.
8357  OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8358                                     SourceLocation EndLoc);
8359  /// \brief Called on well-formed 'threads' clause.
8360  OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8361                                      SourceLocation EndLoc);
8362  /// \brief Called on well-formed 'simd' clause.
8363  OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8364                                   SourceLocation EndLoc);
8365  /// \brief Called on well-formed 'nogroup' clause.
8366  OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8367                                      SourceLocation EndLoc);
8368
8369  OMPClause *ActOnOpenMPVarListClause(
8370      OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8371      SourceLocation StartLoc, SourceLocation LParenLoc,
8372      SourceLocation ColonLoc, SourceLocation EndLoc,
8373      CXXScopeSpec &ReductionIdScopeSpec,
8374      const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8375      OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8376      OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8377      SourceLocation DepLinMapLoc);
8378  /// \brief Called on well-formed 'private' clause.
8379  OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8380                                      SourceLocation StartLoc,
8381                                      SourceLocation LParenLoc,
8382                                      SourceLocation EndLoc);
8383  /// \brief Called on well-formed 'firstprivate' clause.
8384  OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8385                                           SourceLocation StartLoc,
8386                                           SourceLocation LParenLoc,
8387                                           SourceLocation EndLoc);
8388  /// \brief Called on well-formed 'lastprivate' clause.
8389  OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8390                                          SourceLocation StartLoc,
8391                                          SourceLocation LParenLoc,
8392                                          SourceLocation EndLoc);
8393  /// \brief Called on well-formed 'shared' clause.
8394  OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8395                                     SourceLocation StartLoc,
8396                                     SourceLocation LParenLoc,
8397                                     SourceLocation EndLoc);
8398  /// \brief Called on well-formed 'reduction' clause.
8399  OMPClause *ActOnOpenMPReductionClause(
8400      ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8401      SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8402      CXXScopeSpec &ReductionIdScopeSpec,
8403      const DeclarationNameInfo &ReductionId,
8404      ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8405  /// \brief Called on well-formed 'linear' clause.
8406  OMPClause *
8407  ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8408                          SourceLocation StartLoc, SourceLocation LParenLoc,
8409                          OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8410                          SourceLocation ColonLoc, SourceLocation EndLoc);
8411  /// \brief Called on well-formed 'aligned' clause.
8412  OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8413                                      Expr *Alignment,
8414                                      SourceLocation StartLoc,
8415                                      SourceLocation LParenLoc,
8416                                      SourceLocation ColonLoc,
8417                                      SourceLocation EndLoc);
8418  /// \brief Called on well-formed 'copyin' clause.
8419  OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8420                                     SourceLocation StartLoc,
8421                                     SourceLocation LParenLoc,
8422                                     SourceLocation EndLoc);
8423  /// \brief Called on well-formed 'copyprivate' clause.
8424  OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8425                                          SourceLocation StartLoc,
8426                                          SourceLocation LParenLoc,
8427                                          SourceLocation EndLoc);
8428  /// \brief Called on well-formed 'flush' pseudo clause.
8429  OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8430                                    SourceLocation StartLoc,
8431                                    SourceLocation LParenLoc,
8432                                    SourceLocation EndLoc);
8433  /// \brief Called on well-formed 'depend' clause.
8434  OMPClause *
8435  ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8436                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8437                          SourceLocation StartLoc, SourceLocation LParenLoc,
8438                          SourceLocation EndLoc);
8439  /// \brief Called on well-formed 'device' clause.
8440  OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8441                                     SourceLocation LParenLoc,
8442                                     SourceLocation EndLoc);
8443  /// \brief Called on well-formed 'map' clause.
8444  OMPClause *
8445  ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8446                       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8447                       SourceLocation MapLoc, SourceLocation ColonLoc,
8448                       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8449                       SourceLocation LParenLoc, SourceLocation EndLoc);
8450  /// \brief Called on well-formed 'num_teams' clause.
8451  OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8452                                       SourceLocation LParenLoc,
8453                                       SourceLocation EndLoc);
8454  /// \brief Called on well-formed 'thread_limit' clause.
8455  OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8456                                          SourceLocation StartLoc,
8457                                          SourceLocation LParenLoc,
8458                                          SourceLocation EndLoc);
8459  /// \brief Called on well-formed 'priority' clause.
8460  OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8461                                       SourceLocation LParenLoc,
8462                                       SourceLocation EndLoc);
8463  /// \brief Called on well-formed 'dist_schedule' clause.
8464  OMPClause *ActOnOpenMPDistScheduleClause(
8465      OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8466      SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8467      SourceLocation CommaLoc, SourceLocation EndLoc);
8468  /// \brief Called on well-formed 'defaultmap' clause.
8469  OMPClause *ActOnOpenMPDefaultmapClause(
8470      OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8471      SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8472      SourceLocation KindLoc, SourceLocation EndLoc);
8473  /// \brief Called on well-formed 'to' clause.
8474  OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8475                                 SourceLocation StartLoc,
8476                                 SourceLocation LParenLoc,
8477                                 SourceLocation EndLoc);
8478  /// \brief Called on well-formed 'from' clause.
8479  OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8480                                   SourceLocation StartLoc,
8481                                   SourceLocation LParenLoc,
8482                                   SourceLocation EndLoc);
8483  /// Called on well-formed 'use_device_ptr' clause.
8484  OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8485                                           SourceLocation StartLoc,
8486                                           SourceLocation LParenLoc,
8487                                           SourceLocation EndLoc);
8488  /// Called on well-formed 'is_device_ptr' clause.
8489  OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8490                                          SourceLocation StartLoc,
8491                                          SourceLocation LParenLoc,
8492                                          SourceLocation EndLoc);
8493
8494  /// \brief The kind of conversion being performed.
8495  enum CheckedConversionKind {
8496    /// \brief An implicit conversion.
8497    CCK_ImplicitConversion,
8498    /// \brief A C-style cast.
8499    CCK_CStyleCast,
8500    /// \brief A functional-style cast.
8501    CCK_FunctionalCast,
8502    /// \brief A cast other than a C-style cast.
8503    CCK_OtherCast
8504  };
8505
8506  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8507  /// cast.  If there is already an implicit cast, merge into the existing one.
8508  /// If isLvalue, the result of the cast is an lvalue.
8509  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8510                               ExprValueKind VK = VK_RValue,
8511                               const CXXCastPath *BasePath = nullptr,
8512                               CheckedConversionKind CCK
8513                                  = CCK_ImplicitConversion);
8514
8515  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8516  /// to the conversion from scalar type ScalarTy to the Boolean type.
8517  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8518
8519  /// IgnoredValueConversions - Given that an expression's result is
8520  /// syntactically ignored, perform any conversions that are
8521  /// required.
8522  ExprResult IgnoredValueConversions(Expr *E);
8523
8524  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8525  // functions and arrays to their respective pointers (C99 6.3.2.1).
8526  ExprResult UsualUnaryConversions(Expr *E);
8527
8528  /// CallExprUnaryConversions - a special case of an unary conversion
8529  /// performed on a function designator of a call expression.
8530  ExprResult CallExprUnaryConversions(Expr *E);
8531
8532  // DefaultFunctionArrayConversion - converts functions and arrays
8533  // to their respective pointers (C99 6.3.2.1).
8534  ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8535
8536  // DefaultFunctionArrayLvalueConversion - converts functions and
8537  // arrays to their respective pointers and performs the
8538  // lvalue-to-rvalue conversion.
8539  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8540                                                  bool Diagnose = true);
8541
8542  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8543  // the operand.  This is DefaultFunctionArrayLvalueConversion,
8544  // except that it assumes the operand isn't of function or array
8545  // type.
8546  ExprResult DefaultLvalueConversion(Expr *E);
8547
8548  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8549  // do not have a prototype. Integer promotions are performed on each
8550  // argument, and arguments that have type float are promoted to double.
8551  ExprResult DefaultArgumentPromotion(Expr *E);
8552
8553  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8554  enum VariadicCallType {
8555    VariadicFunction,
8556    VariadicBlock,
8557    VariadicMethod,
8558    VariadicConstructor,
8559    VariadicDoesNotApply
8560  };
8561
8562  VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8563                                       const FunctionProtoType *Proto,
8564                                       Expr *Fn);
8565
8566  // Used for determining in which context a type is allowed to be passed to a
8567  // vararg function.
8568  enum VarArgKind {
8569    VAK_Valid,
8570    VAK_ValidInCXX11,
8571    VAK_Undefined,
8572    VAK_MSVCUndefined,
8573    VAK_Invalid
8574  };
8575
8576  // Determines which VarArgKind fits an expression.
8577  VarArgKind isValidVarArgType(const QualType &Ty);
8578
8579  /// Check to see if the given expression is a valid argument to a variadic
8580  /// function, issuing a diagnostic if not.
8581  void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8582
8583  /// Check to see if a given expression could have '.c_str()' called on it.
8584  bool hasCStrMethod(const Expr *E);
8585
8586  /// GatherArgumentsForCall - Collector argument expressions for various
8587  /// form of call prototypes.
8588  bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8589                              const FunctionProtoType *Proto,
8590                              unsigned FirstParam, ArrayRef<Expr *> Args,
8591                              SmallVectorImpl<Expr *> &AllArgs,
8592                              VariadicCallType CallType = VariadicDoesNotApply,
8593                              bool AllowExplicit = false,
8594                              bool IsListInitialization = false);
8595
8596  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8597  // will create a runtime trap if the resulting type is not a POD type.
8598  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8599                                              FunctionDecl *FDecl);
8600
8601  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8602  // operands and then handles various conversions that are common to binary
8603  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8604  // routine returns the first non-arithmetic type found. The client is
8605  // responsible for emitting appropriate error diagnostics.
8606  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8607                                      bool IsCompAssign = false);
8608
8609  /// AssignConvertType - All of the 'assignment' semantic checks return this
8610  /// enum to indicate whether the assignment was allowed.  These checks are
8611  /// done for simple assignments, as well as initialization, return from
8612  /// function, argument passing, etc.  The query is phrased in terms of a
8613  /// source and destination type.
8614  enum AssignConvertType {
8615    /// Compatible - the types are compatible according to the standard.
8616    Compatible,
8617
8618    /// PointerToInt - The assignment converts a pointer to an int, which we
8619    /// accept as an extension.
8620    PointerToInt,
8621
8622    /// IntToPointer - The assignment converts an int to a pointer, which we
8623    /// accept as an extension.
8624    IntToPointer,
8625
8626    /// FunctionVoidPointer - The assignment is between a function pointer and
8627    /// void*, which the standard doesn't allow, but we accept as an extension.
8628    FunctionVoidPointer,
8629
8630    /// IncompatiblePointer - The assignment is between two pointers types that
8631    /// are not compatible, but we accept them as an extension.
8632    IncompatiblePointer,
8633
8634    /// IncompatiblePointer - The assignment is between two pointers types which
8635    /// point to integers which have a different sign, but are otherwise
8636    /// identical. This is a subset of the above, but broken out because it's by
8637    /// far the most common case of incompatible pointers.
8638    IncompatiblePointerSign,
8639
8640    /// CompatiblePointerDiscardsQualifiers - The assignment discards
8641    /// c/v/r qualifiers, which we accept as an extension.
8642    CompatiblePointerDiscardsQualifiers,
8643
8644    /// IncompatiblePointerDiscardsQualifiers - The assignment
8645    /// discards qualifiers that we don't permit to be discarded,
8646    /// like address spaces.
8647    IncompatiblePointerDiscardsQualifiers,
8648
8649    /// IncompatibleNestedPointerQualifiers - The assignment is between two
8650    /// nested pointer types, and the qualifiers other than the first two
8651    /// levels differ e.g. char ** -> const char **, but we accept them as an
8652    /// extension.
8653    IncompatibleNestedPointerQualifiers,
8654
8655    /// IncompatibleVectors - The assignment is between two vector types that
8656    /// have the same size, which we accept as an extension.
8657    IncompatibleVectors,
8658
8659    /// IntToBlockPointer - The assignment converts an int to a block
8660    /// pointer. We disallow this.
8661    IntToBlockPointer,
8662
8663    /// IncompatibleBlockPointer - The assignment is between two block
8664    /// pointers types that are not compatible.
8665    IncompatibleBlockPointer,
8666
8667    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8668    /// id type and something else (that is incompatible with it). For example,
8669    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8670    IncompatibleObjCQualifiedId,
8671
8672    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8673    /// object with __weak qualifier.
8674    IncompatibleObjCWeakRef,
8675
8676    /// Incompatible - We reject this conversion outright, it is invalid to
8677    /// represent it in the AST.
8678    Incompatible
8679  };
8680
8681  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8682  /// assignment conversion type specified by ConvTy.  This returns true if the
8683  /// conversion was invalid or false if the conversion was accepted.
8684  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8685                                SourceLocation Loc,
8686                                QualType DstType, QualType SrcType,
8687                                Expr *SrcExpr, AssignmentAction Action,
8688                                bool *Complained = nullptr);
8689
8690  /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8691  /// enum. If AllowMask is true, then we also allow the complement of a valid
8692  /// value, to be used as a mask.
8693  bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8694                         bool AllowMask) const;
8695
8696  /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8697  /// integer not in the range of enum values.
8698  void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8699                              Expr *SrcExpr);
8700
8701  /// CheckAssignmentConstraints - Perform type checking for assignment,
8702  /// argument passing, variable initialization, and function return values.
8703  /// C99 6.5.16.
8704  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8705                                               QualType LHSType,
8706                                               QualType RHSType);
8707
8708  /// Check assignment constraints and optionally prepare for a conversion of
8709  /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8710  /// is true.
8711  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8712                                               ExprResult &RHS,
8713                                               CastKind &Kind,
8714                                               bool ConvertRHS = true);
8715
8716  // CheckSingleAssignmentConstraints - Currently used by
8717  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
8718  // this routine performs the default function/array converions, if ConvertRHS
8719  // is true.
8720  AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
8721                                                     ExprResult &RHS,
8722                                                     bool Diagnose = true,
8723                                                     bool DiagnoseCFAudited = false,
8724                                                     bool ConvertRHS = true);
8725
8726  // \brief If the lhs type is a transparent union, check whether we
8727  // can initialize the transparent union with the given expression.
8728  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8729                                                             ExprResult &RHS);
8730
8731  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8732
8733  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8734
8735  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8736                                       AssignmentAction Action,
8737                                       bool AllowExplicit = false);
8738  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8739                                       AssignmentAction Action,
8740                                       bool AllowExplicit,
8741                                       ImplicitConversionSequence& ICS);
8742  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8743                                       const ImplicitConversionSequence& ICS,
8744                                       AssignmentAction Action,
8745                                       CheckedConversionKind CCK
8746                                          = CCK_ImplicitConversion);
8747  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8748                                       const StandardConversionSequence& SCS,
8749                                       AssignmentAction Action,
8750                                       CheckedConversionKind CCK);
8751
8752  /// the following "Check" methods will return a valid/converted QualType
8753  /// or a null QualType (indicating an error diagnostic was issued).
8754
8755  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8756  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8757                           ExprResult &RHS);
8758  QualType CheckPointerToMemberOperands( // C++ 5.5
8759    ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8760    SourceLocation OpLoc, bool isIndirect);
8761  QualType CheckMultiplyDivideOperands( // C99 6.5.5
8762    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8763    bool IsDivide);
8764  QualType CheckRemainderOperands( // C99 6.5.5
8765    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8766    bool IsCompAssign = false);
8767  QualType CheckAdditionOperands( // C99 6.5.6
8768    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8769    BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
8770  QualType CheckSubtractionOperands( // C99 6.5.6
8771    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8772    QualType* CompLHSTy = nullptr);
8773  QualType CheckShiftOperands( // C99 6.5.7
8774    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8775    BinaryOperatorKind Opc, bool IsCompAssign = false);
8776  QualType CheckCompareOperands( // C99 6.5.8/9
8777    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8778    BinaryOperatorKind Opc, bool isRelational);
8779  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8780    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8781    bool IsCompAssign = false);
8782  QualType CheckLogicalOperands( // C99 6.5.[13,14]
8783    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8784    BinaryOperatorKind Opc);
8785  // CheckAssignmentOperands is used for both simple and compound assignment.
8786  // For simple assignment, pass both expressions and a null converted type.
8787  // For compound assignment, pass both expressions and the converted type.
8788  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8789    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8790
8791  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8792                                     UnaryOperatorKind Opcode, Expr *Op);
8793  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8794                                         BinaryOperatorKind Opcode,
8795                                         Expr *LHS, Expr *RHS);
8796  ExprResult checkPseudoObjectRValue(Expr *E);
8797  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8798
8799  QualType CheckConditionalOperands( // C99 6.5.15
8800    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8801    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8802  QualType CXXCheckConditionalOperands( // C++ 5.16
8803    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8804    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8805  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8806                                    bool *NonStandardCompositeType = nullptr);
8807  QualType FindCompositePointerType(SourceLocation Loc,
8808                                    ExprResult &E1, ExprResult &E2,
8809                                    bool *NonStandardCompositeType = nullptr) {
8810    Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8811    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8812                                                  NonStandardCompositeType);
8813    E1 = E1Tmp;
8814    E2 = E2Tmp;
8815    return Composite;
8816  }
8817
8818  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8819                                        SourceLocation QuestionLoc);
8820
8821  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8822                                  SourceLocation QuestionLoc);
8823
8824  void DiagnoseAlwaysNonNullPointer(Expr *E,
8825                                    Expr::NullPointerConstantKind NullType,
8826                                    bool IsEqual, SourceRange Range);
8827
8828  /// type checking for vector binary operators.
8829  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8830                               SourceLocation Loc, bool IsCompAssign,
8831                               bool AllowBothBool, bool AllowBoolConversion);
8832  QualType GetSignedVectorType(QualType V);
8833  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8834                                      SourceLocation Loc, bool isRelational);
8835  QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8836                                      SourceLocation Loc);
8837
8838  bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8839  bool isLaxVectorConversion(QualType srcType, QualType destType);
8840
8841  /// type checking declaration initializers (C99 6.7.8)
8842  bool CheckForConstantInitializer(Expr *e, QualType t);
8843
8844  // type checking C++ declaration initializers (C++ [dcl.init]).
8845
8846  /// ReferenceCompareResult - Expresses the result of comparing two
8847  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8848  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8849  enum ReferenceCompareResult {
8850    /// Ref_Incompatible - The two types are incompatible, so direct
8851    /// reference binding is not possible.
8852    Ref_Incompatible = 0,
8853    /// Ref_Related - The two types are reference-related, which means
8854    /// that their unqualified forms (T1 and T2) are either the same
8855    /// or T1 is a base class of T2.
8856    Ref_Related,
8857    /// Ref_Compatible_With_Added_Qualification - The two types are
8858    /// reference-compatible with added qualification, meaning that
8859    /// they are reference-compatible and the qualifiers on T1 (cv1)
8860    /// are greater than the qualifiers on T2 (cv2).
8861    Ref_Compatible_With_Added_Qualification,
8862    /// Ref_Compatible - The two types are reference-compatible and
8863    /// have equivalent qualifiers (cv1 == cv2).
8864    Ref_Compatible
8865  };
8866
8867  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8868                                                      QualType T1, QualType T2,
8869                                                      bool &DerivedToBase,
8870                                                      bool &ObjCConversion,
8871                                                bool &ObjCLifetimeConversion);
8872
8873  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8874                                 Expr *CastExpr, CastKind &CastKind,
8875                                 ExprValueKind &VK, CXXCastPath &Path);
8876
8877  /// \brief Force an expression with unknown-type to an expression of the
8878  /// given type.
8879  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8880
8881  /// \brief Type-check an expression that's being passed to an
8882  /// __unknown_anytype parameter.
8883  ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8884                                Expr *result, QualType &paramType);
8885
8886  // CheckVectorCast - check type constraints for vectors.
8887  // Since vectors are an extension, there are no C standard reference for this.
8888  // We allow casting between vectors and integer datatypes of the same size.
8889  // returns true if the cast is invalid
8890  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8891                       CastKind &Kind);
8892
8893  /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
8894  /// implicit casts if necessary.
8895  ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8896
8897  // CheckExtVectorCast - check type constraints for extended vectors.
8898  // Since vectors are an extension, there are no C standard reference for this.
8899  // We allow casting between vectors and integer datatypes of the same size,
8900  // or vectors and the element type of that vector.
8901  // returns the cast expr
8902  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8903                                CastKind &Kind);
8904
8905  ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8906                                        SourceLocation LParenLoc,
8907                                        Expr *CastExpr,
8908                                        SourceLocation RParenLoc);
8909
8910  enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
8911
8912  /// \brief Checks for invalid conversions and casts between
8913  /// retainable pointers and other pointer kinds.
8914  ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8915                                             QualType castType, Expr *&op,
8916                                             CheckedConversionKind CCK,
8917                                             bool Diagnose = true,
8918                                             bool DiagnoseCFAudited = false,
8919                                             BinaryOperatorKind Opc = BO_PtrMemD
8920                                             );
8921
8922  Expr *stripARCUnbridgedCast(Expr *e);
8923  void diagnoseARCUnbridgedCast(Expr *e);
8924
8925  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8926                                             QualType ExprType);
8927
8928  /// checkRetainCycles - Check whether an Objective-C message send
8929  /// might create an obvious retain cycle.
8930  void checkRetainCycles(ObjCMessageExpr *msg);
8931  void checkRetainCycles(Expr *receiver, Expr *argument);
8932  void checkRetainCycles(VarDecl *Var, Expr *Init);
8933
8934  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8935  /// to weak/__unsafe_unretained type.
8936  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8937
8938  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8939  /// to weak/__unsafe_unretained expression.
8940  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8941
8942  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8943  /// \param Method - May be null.
8944  /// \param [out] ReturnType - The return type of the send.
8945  /// \return true iff there were any incompatible types.
8946  bool CheckMessageArgumentTypes(QualType ReceiverType,
8947                                 MultiExprArg Args, Selector Sel,
8948                                 ArrayRef<SourceLocation> SelectorLocs,
8949                                 ObjCMethodDecl *Method, bool isClassMessage,
8950                                 bool isSuperMessage,
8951                                 SourceLocation lbrac, SourceLocation rbrac,
8952                                 SourceRange RecRange,
8953                                 QualType &ReturnType, ExprValueKind &VK);
8954
8955  /// \brief Determine the result of a message send expression based on
8956  /// the type of the receiver, the method expected to receive the message,
8957  /// and the form of the message send.
8958  QualType getMessageSendResultType(QualType ReceiverType,
8959                                    ObjCMethodDecl *Method,
8960                                    bool isClassMessage, bool isSuperMessage);
8961
8962  /// \brief If the given expression involves a message send to a method
8963  /// with a related result type, emit a note describing what happened.
8964  void EmitRelatedResultTypeNote(const Expr *E);
8965
8966  /// \brief Given that we had incompatible pointer types in a return
8967  /// statement, check whether we're in a method with a related result
8968  /// type, and if so, emit a note describing what happened.
8969  void EmitRelatedResultTypeNoteForReturn(QualType destType);
8970
8971  class ConditionResult {
8972    Decl *ConditionVar;
8973    FullExprArg Condition;
8974    bool Invalid;
8975    bool HasKnownValue;
8976    bool KnownValue;
8977
8978    friend class Sema;
8979    ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
8980                    bool IsConstexpr)
8981        : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
8982          HasKnownValue(IsConstexpr && Condition.get() &&
8983                        !Condition.get()->isValueDependent()),
8984          KnownValue(HasKnownValue &&
8985                     !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
8986    explicit ConditionResult(bool Invalid)
8987        : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
8988          HasKnownValue(false), KnownValue(false) {}
8989
8990  public:
8991    ConditionResult() : ConditionResult(false) {}
8992    bool isInvalid() const { return Invalid; }
8993    std::pair<VarDecl *, Expr *> get() const {
8994      return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
8995                            Condition.get());
8996    }
8997    llvm::Optional<bool> getKnownValue() const {
8998      if (!HasKnownValue)
8999        return None;
9000      return KnownValue;
9001    }
9002  };
9003  static ConditionResult ConditionError() { return ConditionResult(true); }
9004
9005  enum class ConditionKind {
9006    Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9007    ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9008    Switch       ///< An integral condition for a 'switch' statement.
9009  };
9010
9011  ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9012                                 Expr *SubExpr, ConditionKind CK);
9013
9014  ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9015                                         SourceLocation StmtLoc,
9016                                         ConditionKind CK);
9017
9018  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9019
9020  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9021                                    SourceLocation StmtLoc,
9022                                    ConditionKind CK);
9023  ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9024
9025  /// CheckBooleanCondition - Diagnose problems involving the use of
9026  /// the given expression as a boolean condition (e.g. in an if
9027  /// statement).  Also performs the standard function and array
9028  /// decays, possibly changing the input variable.
9029  ///
9030  /// \param Loc - A location associated with the condition, e.g. the
9031  /// 'if' keyword.
9032  /// \return true iff there were any errors
9033  ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9034                                   bool IsConstexpr = false);
9035
9036  /// DiagnoseAssignmentAsCondition - Given that an expression is
9037  /// being used as a boolean condition, warn if it's an assignment.
9038  void DiagnoseAssignmentAsCondition(Expr *E);
9039
9040  /// \brief Redundant parentheses over an equality comparison can indicate
9041  /// that the user intended an assignment used as condition.
9042  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9043
9044  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9045  ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9046
9047  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9048  /// the specified width and sign.  If an overflow occurs, detect it and emit
9049  /// the specified diagnostic.
9050  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9051                                          unsigned NewWidth, bool NewSign,
9052                                          SourceLocation Loc, unsigned DiagID);
9053
9054  /// Checks that the Objective-C declaration is declared in the global scope.
9055  /// Emits an error and marks the declaration as invalid if it's not declared
9056  /// in the global scope.
9057  bool CheckObjCDeclScope(Decl *D);
9058
9059  /// \brief Abstract base class used for diagnosing integer constant
9060  /// expression violations.
9061  class VerifyICEDiagnoser {
9062  public:
9063    bool Suppress;
9064
9065    VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9066
9067    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9068    virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9069    virtual ~VerifyICEDiagnoser() { }
9070  };
9071
9072  /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9073  /// and reports the appropriate diagnostics. Returns false on success.
9074  /// Can optionally return the value of the expression.
9075  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9076                                             VerifyICEDiagnoser &Diagnoser,
9077                                             bool AllowFold = true);
9078  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9079                                             unsigned DiagID,
9080                                             bool AllowFold = true);
9081  ExprResult VerifyIntegerConstantExpression(Expr *E,
9082                                             llvm::APSInt *Result = nullptr);
9083
9084  /// VerifyBitField - verifies that a bit field expression is an ICE and has
9085  /// the correct width, and that the field type is valid.
9086  /// Returns false on success.
9087  /// Can optionally return whether the bit-field is of width 0
9088  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9089                            QualType FieldTy, bool IsMsStruct,
9090                            Expr *BitWidth, bool *ZeroWidth = nullptr);
9091
9092  enum CUDAFunctionTarget {
9093    CFT_Device,
9094    CFT_Global,
9095    CFT_Host,
9096    CFT_HostDevice,
9097    CFT_InvalidTarget
9098  };
9099
9100  CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
9101
9102  // CUDA function call preference. Must be ordered numerically from
9103  // worst to best.
9104  enum CUDAFunctionPreference {
9105    CFP_Never,      // Invalid caller/callee combination.
9106    CFP_WrongSide,  // Calls from host-device to host or device
9107                    // function that do not match current compilation
9108                    // mode. Only in effect if
9109                    // LangOpts.CUDADisableTargetCallChecks is true.
9110    CFP_HostDevice, // Any calls to host/device functions.
9111    CFP_SameSide,   // Calls from host-device to host or device
9112                    // function matching current compilation mode.
9113    CFP_Native,     // host-to-host or device-to-device calls.
9114  };
9115
9116  /// Identifies relative preference of a given Caller/Callee
9117  /// combination, based on their host/device attributes.
9118  /// \param Caller function which needs address of \p Callee.
9119  ///               nullptr in case of global context.
9120  /// \param Callee target function
9121  ///
9122  /// \returns preference value for particular Caller/Callee combination.
9123  CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9124                                                const FunctionDecl *Callee);
9125
9126  /// Determines whether Caller may invoke Callee, based on their CUDA
9127  /// host/device attributes.  Returns true if the call is not allowed.
9128  bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
9129    return IdentifyCUDAPreference(Caller, Callee) == CFP_Never;
9130  }
9131
9132  /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9133  /// depending on FD and the current compilation settings.
9134  void maybeAddCUDAHostDeviceAttrs(Scope *S, FunctionDecl *FD,
9135                                   const LookupResult &Previous);
9136
9137  /// Finds a function in \p Matches with highest calling priority
9138  /// from \p Caller context and erases all functions with lower
9139  /// calling priority.
9140  void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
9141                                SmallVectorImpl<FunctionDecl *> &Matches);
9142  void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
9143                                SmallVectorImpl<DeclAccessPair> &Matches);
9144  void EraseUnwantedCUDAMatches(
9145      const FunctionDecl *Caller,
9146      SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9147
9148  /// Given a implicit special member, infer its CUDA target from the
9149  /// calls it needs to make to underlying base/field special members.
9150  /// \param ClassDecl the class for which the member is being created.
9151  /// \param CSM the kind of special member.
9152  /// \param MemberDecl the special member itself.
9153  /// \param ConstRHS true if this is a copy operation with a const object on
9154  ///        its RHS.
9155  /// \param Diagnose true if this call should emit diagnostics.
9156  /// \return true if there was an error inferring.
9157  /// The result of this call is implicit CUDA target attribute(s) attached to
9158  /// the member declaration.
9159  bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9160                                               CXXSpecialMember CSM,
9161                                               CXXMethodDecl *MemberDecl,
9162                                               bool ConstRHS,
9163                                               bool Diagnose);
9164
9165  /// \return true if \p CD can be considered empty according to CUDA
9166  /// (E.2.3.1 in CUDA 7.5 Programming guide).
9167  bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9168  bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9169
9170  /// \name Code completion
9171  //@{
9172  /// \brief Describes the context in which code completion occurs.
9173  enum ParserCompletionContext {
9174    /// \brief Code completion occurs at top-level or namespace context.
9175    PCC_Namespace,
9176    /// \brief Code completion occurs within a class, struct, or union.
9177    PCC_Class,
9178    /// \brief Code completion occurs within an Objective-C interface, protocol,
9179    /// or category.
9180    PCC_ObjCInterface,
9181    /// \brief Code completion occurs within an Objective-C implementation or
9182    /// category implementation
9183    PCC_ObjCImplementation,
9184    /// \brief Code completion occurs within the list of instance variables
9185    /// in an Objective-C interface, protocol, category, or implementation.
9186    PCC_ObjCInstanceVariableList,
9187    /// \brief Code completion occurs following one or more template
9188    /// headers.
9189    PCC_Template,
9190    /// \brief Code completion occurs following one or more template
9191    /// headers within a class.
9192    PCC_MemberTemplate,
9193    /// \brief Code completion occurs within an expression.
9194    PCC_Expression,
9195    /// \brief Code completion occurs within a statement, which may
9196    /// also be an expression or a declaration.
9197    PCC_Statement,
9198    /// \brief Code completion occurs at the beginning of the
9199    /// initialization statement (or expression) in a for loop.
9200    PCC_ForInit,
9201    /// \brief Code completion occurs within the condition of an if,
9202    /// while, switch, or for statement.
9203    PCC_Condition,
9204    /// \brief Code completion occurs within the body of a function on a
9205    /// recovery path, where we do not have a specific handle on our position
9206    /// in the grammar.
9207    PCC_RecoveryInFunction,
9208    /// \brief Code completion occurs where only a type is permitted.
9209    PCC_Type,
9210    /// \brief Code completion occurs in a parenthesized expression, which
9211    /// might also be a type cast.
9212    PCC_ParenthesizedExpression,
9213    /// \brief Code completion occurs within a sequence of declaration
9214    /// specifiers within a function, method, or block.
9215    PCC_LocalDeclarationSpecifiers
9216  };
9217
9218  void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9219  void CodeCompleteOrdinaryName(Scope *S,
9220                                ParserCompletionContext CompletionContext);
9221  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9222                            bool AllowNonIdentifiers,
9223                            bool AllowNestedNameSpecifiers);
9224
9225  struct CodeCompleteExpressionData;
9226  void CodeCompleteExpression(Scope *S,
9227                              const CodeCompleteExpressionData &Data);
9228  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9229                                       SourceLocation OpLoc,
9230                                       bool IsArrow);
9231  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9232  void CodeCompleteTag(Scope *S, unsigned TagSpec);
9233  void CodeCompleteTypeQualifiers(DeclSpec &DS);
9234  void CodeCompleteBracketDeclarator(Scope *S);
9235  void CodeCompleteCase(Scope *S);
9236  void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9237  void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9238                               ArrayRef<Expr *> Args);
9239  void CodeCompleteInitializer(Scope *S, Decl *D);
9240  void CodeCompleteReturn(Scope *S);
9241  void CodeCompleteAfterIf(Scope *S);
9242  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9243
9244  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9245                               bool EnteringContext);
9246  void CodeCompleteUsing(Scope *S);
9247  void CodeCompleteUsingDirective(Scope *S);
9248  void CodeCompleteNamespaceDecl(Scope *S);
9249  void CodeCompleteNamespaceAliasDecl(Scope *S);
9250  void CodeCompleteOperatorName(Scope *S);
9251  void CodeCompleteConstructorInitializer(
9252                                Decl *Constructor,
9253                                ArrayRef<CXXCtorInitializer *> Initializers);
9254
9255  void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9256                                    bool AfterAmpersand);
9257
9258  void CodeCompleteObjCAtDirective(Scope *S);
9259  void CodeCompleteObjCAtVisibility(Scope *S);
9260  void CodeCompleteObjCAtStatement(Scope *S);
9261  void CodeCompleteObjCAtExpression(Scope *S);
9262  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9263  void CodeCompleteObjCPropertyGetter(Scope *S);
9264  void CodeCompleteObjCPropertySetter(Scope *S);
9265  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9266                                   bool IsParameter);
9267  void CodeCompleteObjCMessageReceiver(Scope *S);
9268  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9269                                    ArrayRef<IdentifierInfo *> SelIdents,
9270                                    bool AtArgumentExpression);
9271  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9272                                    ArrayRef<IdentifierInfo *> SelIdents,
9273                                    bool AtArgumentExpression,
9274                                    bool IsSuper = false);
9275  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9276                                       ArrayRef<IdentifierInfo *> SelIdents,
9277                                       bool AtArgumentExpression,
9278                                       ObjCInterfaceDecl *Super = nullptr);
9279  void CodeCompleteObjCForCollection(Scope *S,
9280                                     DeclGroupPtrTy IterationVar);
9281  void CodeCompleteObjCSelector(Scope *S,
9282                                ArrayRef<IdentifierInfo *> SelIdents);
9283  void CodeCompleteObjCProtocolReferences(
9284                                         ArrayRef<IdentifierLocPair> Protocols);
9285  void CodeCompleteObjCProtocolDecl(Scope *S);
9286  void CodeCompleteObjCInterfaceDecl(Scope *S);
9287  void CodeCompleteObjCSuperclass(Scope *S,
9288                                  IdentifierInfo *ClassName,
9289                                  SourceLocation ClassNameLoc);
9290  void CodeCompleteObjCImplementationDecl(Scope *S);
9291  void CodeCompleteObjCInterfaceCategory(Scope *S,
9292                                         IdentifierInfo *ClassName,
9293                                         SourceLocation ClassNameLoc);
9294  void CodeCompleteObjCImplementationCategory(Scope *S,
9295                                              IdentifierInfo *ClassName,
9296                                              SourceLocation ClassNameLoc);
9297  void CodeCompleteObjCPropertyDefinition(Scope *S);
9298  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9299                                              IdentifierInfo *PropertyName);
9300  void CodeCompleteObjCMethodDecl(Scope *S,
9301                                  bool IsInstanceMethod,
9302                                  ParsedType ReturnType);
9303  void CodeCompleteObjCMethodDeclSelector(Scope *S,
9304                                          bool IsInstanceMethod,
9305                                          bool AtParameterName,
9306                                          ParsedType ReturnType,
9307                                          ArrayRef<IdentifierInfo *> SelIdents);
9308  void CodeCompletePreprocessorDirective(bool InConditional);
9309  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9310  void CodeCompletePreprocessorMacroName(bool IsDefinition);
9311  void CodeCompletePreprocessorExpression();
9312  void CodeCompletePreprocessorMacroArgument(Scope *S,
9313                                             IdentifierInfo *Macro,
9314                                             MacroInfo *MacroInfo,
9315                                             unsigned Argument);
9316  void CodeCompleteNaturalLanguage();
9317  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
9318                                   CodeCompletionTUInfo &CCTUInfo,
9319                  SmallVectorImpl<CodeCompletionResult> &Results);
9320  //@}
9321
9322  //===--------------------------------------------------------------------===//
9323  // Extra semantic analysis beyond the C type system
9324
9325public:
9326  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
9327                                                unsigned ByteNo) const;
9328
9329private:
9330  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9331                        const ArraySubscriptExpr *ASE=nullptr,
9332                        bool AllowOnePastEnd=true, bool IndexNegated=false);
9333  void CheckArrayAccess(const Expr *E);
9334  // Used to grab the relevant information from a FormatAttr and a
9335  // FunctionDeclaration.
9336  struct FormatStringInfo {
9337    unsigned FormatIdx;
9338    unsigned FirstDataArg;
9339    bool HasVAListArg;
9340  };
9341
9342  static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
9343                                  FormatStringInfo *FSI);
9344  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
9345                         const FunctionProtoType *Proto);
9346  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
9347                           ArrayRef<const Expr *> Args);
9348  bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
9349                        const FunctionProtoType *Proto);
9350  bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
9351  void CheckConstructorCall(FunctionDecl *FDecl,
9352                            ArrayRef<const Expr *> Args,
9353                            const FunctionProtoType *Proto,
9354                            SourceLocation Loc);
9355
9356  void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
9357                 ArrayRef<const Expr *> Args, bool IsMemberFunction,
9358                 SourceLocation Loc, SourceRange Range,
9359                 VariadicCallType CallType);
9360
9361  bool CheckObjCString(Expr *Arg);
9362
9363  ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
9364                                      unsigned BuiltinID, CallExpr *TheCall);
9365
9366  bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
9367                                    unsigned MaxWidth);
9368  bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9369  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9370
9371  bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9372  bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9373  bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9374  bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9375  bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9376
9377  bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
9378  bool SemaBuiltinVAStart(CallExpr *TheCall);
9379  bool SemaBuiltinMSVAStart(CallExpr *TheCall);
9380  bool SemaBuiltinVAStartARM(CallExpr *Call);
9381  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
9382  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
9383
9384public:
9385  // Used by C++ template instantiation.
9386  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
9387  ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
9388                                   SourceLocation BuiltinLoc,
9389                                   SourceLocation RParenLoc);
9390
9391private:
9392  bool SemaBuiltinPrefetch(CallExpr *TheCall);
9393  bool SemaBuiltinAssume(CallExpr *TheCall);
9394  bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
9395  bool SemaBuiltinLongjmp(CallExpr *TheCall);
9396  bool SemaBuiltinSetjmp(CallExpr *TheCall);
9397  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
9398  ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
9399  ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
9400                                     AtomicExpr::AtomicOp Op);
9401  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
9402                              llvm::APSInt &Result);
9403  bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
9404                                   int Low, int High);
9405  bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
9406                                int ArgNum, unsigned ExpectedFieldNum,
9407                                bool AllowName);
9408public:
9409  enum FormatStringType {
9410    FST_Scanf,
9411    FST_Printf,
9412    FST_NSString,
9413    FST_Strftime,
9414    FST_Strfmon,
9415    FST_Kprintf,
9416    FST_FreeBSDKPrintf,
9417    FST_OSTrace,
9418    FST_Unknown
9419  };
9420  static FormatStringType GetFormatStringType(const FormatAttr *Format);
9421
9422  bool FormatStringHasSArg(const StringLiteral *FExpr);
9423
9424  static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
9425
9426private:
9427  bool CheckFormatArguments(const FormatAttr *Format,
9428                            ArrayRef<const Expr *> Args,
9429                            bool IsCXXMember,
9430                            VariadicCallType CallType,
9431                            SourceLocation Loc, SourceRange Range,
9432                            llvm::SmallBitVector &CheckedVarArgs);
9433  bool CheckFormatArguments(ArrayRef<const Expr *> Args,
9434                            bool HasVAListArg, unsigned format_idx,
9435                            unsigned firstDataArg, FormatStringType Type,
9436                            VariadicCallType CallType,
9437                            SourceLocation Loc, SourceRange range,
9438                            llvm::SmallBitVector &CheckedVarArgs);
9439
9440  void CheckAbsoluteValueFunction(const CallExpr *Call,
9441                                  const FunctionDecl *FDecl,
9442                                  IdentifierInfo *FnInfo);
9443
9444  void CheckMemaccessArguments(const CallExpr *Call,
9445                               unsigned BId,
9446                               IdentifierInfo *FnName);
9447
9448  void CheckStrlcpycatArguments(const CallExpr *Call,
9449                                IdentifierInfo *FnName);
9450
9451  void CheckStrncatArguments(const CallExpr *Call,
9452                             IdentifierInfo *FnName);
9453
9454  void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9455                          SourceLocation ReturnLoc,
9456                          bool isObjCMethod = false,
9457                          const AttrVec *Attrs = nullptr,
9458                          const FunctionDecl *FD = nullptr);
9459
9460  void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
9461  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
9462  void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
9463  void CheckForIntOverflow(Expr *E);
9464  void CheckUnsequencedOperations(Expr *E);
9465
9466  /// \brief Perform semantic checks on a completed expression. This will either
9467  /// be a full-expression or a default argument expression.
9468  void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
9469                          bool IsConstexpr = false);
9470
9471  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
9472                                   Expr *Init);
9473
9474  /// \brief Check if the given expression contains 'break' or 'continue'
9475  /// statement that produces control flow different from GCC.
9476  void CheckBreakContinueBinding(Expr *E);
9477
9478  /// \brief Check whether receiver is mutable ObjC container which
9479  /// attempts to add itself into the container
9480  void CheckObjCCircularContainer(ObjCMessageExpr *Message);
9481
9482  void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9483  void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9484                                 bool DeleteWasArrayForm);
9485public:
9486  /// \brief Register a magic integral constant to be used as a type tag.
9487  void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9488                                  uint64_t MagicValue, QualType Type,
9489                                  bool LayoutCompatible, bool MustBeNull);
9490
9491  struct TypeTagData {
9492    TypeTagData() {}
9493
9494    TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
9495        Type(Type), LayoutCompatible(LayoutCompatible),
9496        MustBeNull(MustBeNull)
9497    {}
9498
9499    QualType Type;
9500
9501    /// If true, \c Type should be compared with other expression's types for
9502    /// layout-compatibility.
9503    unsigned LayoutCompatible : 1;
9504    unsigned MustBeNull : 1;
9505  };
9506
9507  /// A pair of ArgumentKind identifier and magic value.  This uniquely
9508  /// identifies the magic value.
9509  typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
9510
9511private:
9512  /// \brief A map from magic value to type information.
9513  std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
9514      TypeTagForDatatypeMagicValues;
9515
9516  /// \brief Peform checks on a call of a function with argument_with_type_tag
9517  /// or pointer_with_type_tag attributes.
9518  void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9519                                const Expr * const *ExprArgs);
9520
9521  /// \brief The parser's current scope.
9522  ///
9523  /// The parser maintains this state here.
9524  Scope *CurScope;
9525
9526  mutable IdentifierInfo *Ident_super;
9527  mutable IdentifierInfo *Ident___float128;
9528
9529  /// Nullability type specifiers.
9530  IdentifierInfo *Ident__Nonnull = nullptr;
9531  IdentifierInfo *Ident__Nullable = nullptr;
9532  IdentifierInfo *Ident__Null_unspecified = nullptr;
9533
9534  IdentifierInfo *Ident_NSError = nullptr;
9535
9536protected:
9537  friend class Parser;
9538  friend class InitializationSequence;
9539  friend class ASTReader;
9540  friend class ASTDeclReader;
9541  friend class ASTWriter;
9542
9543public:
9544  /// Retrieve the keyword associated
9545  IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
9546
9547  /// The struct behind the CFErrorRef pointer.
9548  RecordDecl *CFError = nullptr;
9549
9550  /// Retrieve the identifier "NSError".
9551  IdentifierInfo *getNSErrorIdent();
9552
9553  /// \brief Retrieve the parser's current scope.
9554  ///
9555  /// This routine must only be used when it is certain that semantic analysis
9556  /// and the parser are in precisely the same context, which is not the case
9557  /// when, e.g., we are performing any kind of template instantiation.
9558  /// Therefore, the only safe places to use this scope are in the parser
9559  /// itself and in routines directly invoked from the parser and *never* from
9560  /// template substitution or instantiation.
9561  Scope *getCurScope() const { return CurScope; }
9562
9563  void incrementMSManglingNumber() const {
9564    return CurScope->incrementMSManglingNumber();
9565  }
9566
9567  IdentifierInfo *getSuperIdentifier() const;
9568  IdentifierInfo *getFloat128Identifier() const;
9569
9570  Decl *getObjCDeclContext() const;
9571
9572  DeclContext *getCurLexicalContext() const {
9573    return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
9574  }
9575
9576  AvailabilityResult getCurContextAvailability() const;
9577
9578  const DeclContext *getCurObjCLexicalContext() const {
9579    const DeclContext *DC = getCurLexicalContext();
9580    // A category implicitly has the attribute of the interface.
9581    if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
9582      DC = CatD->getClassInterface();
9583    return DC;
9584  }
9585
9586  /// \brief To be used for checking whether the arguments being passed to
9587  /// function exceeds the number of parameters expected for it.
9588  static bool TooManyArguments(size_t NumParams, size_t NumArgs,
9589                               bool PartialOverloading = false) {
9590    // We check whether we're just after a comma in code-completion.
9591    if (NumArgs > 0 && PartialOverloading)
9592      return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
9593    return NumArgs > NumParams;
9594  }
9595
9596  // Emitting members of dllexported classes is delayed until the class
9597  // (including field initializers) is fully parsed.
9598  SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
9599};
9600
9601/// \brief RAII object that enters a new expression evaluation context.
9602class EnterExpressionEvaluationContext {
9603  Sema &Actions;
9604  bool Entered = true;
9605
9606public:
9607  EnterExpressionEvaluationContext(Sema &Actions,
9608                                   Sema::ExpressionEvaluationContext NewContext,
9609                                   Decl *LambdaContextDecl = nullptr,
9610                                   bool IsDecltype = false,
9611                                   bool ShouldEnter = true)
9612      : Actions(Actions), Entered(ShouldEnter) {
9613    if (Entered)
9614      Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
9615                                              IsDecltype);
9616  }
9617  EnterExpressionEvaluationContext(Sema &Actions,
9618                                   Sema::ExpressionEvaluationContext NewContext,
9619                                   Sema::ReuseLambdaContextDecl_t,
9620                                   bool IsDecltype = false)
9621    : Actions(Actions) {
9622    Actions.PushExpressionEvaluationContext(NewContext,
9623                                            Sema::ReuseLambdaContextDecl,
9624                                            IsDecltype);
9625  }
9626
9627  ~EnterExpressionEvaluationContext() {
9628    if (Entered)
9629      Actions.PopExpressionEvaluationContext();
9630  }
9631};
9632
9633DeductionFailureInfo
9634MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
9635                         sema::TemplateDeductionInfo &Info);
9636
9637/// \brief Contains a late templated function.
9638/// Will be parsed at the end of the translation unit, used by Sema & Parser.
9639struct LateParsedTemplate {
9640  CachedTokens Toks;
9641  /// \brief The template function declaration to be late parsed.
9642  Decl *D;
9643};
9644
9645} // end namespace clang
9646
9647#endif
9648