]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Sema/Sema.h
Merge ^/head r304236 through r304536.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Sema / Sema.h
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/Availability.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExternalASTSource.h"
24 #include "clang/AST/LocInfoType.h"
25 #include "clang/AST/MangleNumberingContext.h"
26 #include "clang/AST/NSAPI.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/ExpressionTraits.h"
30 #include "clang/Basic/LangOptions.h"
31 #include "clang/Basic/Module.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Basic/PragmaKinds.h"
34 #include "clang/Basic/Specifiers.h"
35 #include "clang/Basic/TemplateKinds.h"
36 #include "clang/Basic/TypeTraits.h"
37 #include "clang/Sema/AnalysisBasedWarnings.h"
38 #include "clang/Sema/CleanupInfo.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/ExternalSemaSource.h"
41 #include "clang/Sema/IdentifierResolver.h"
42 #include "clang/Sema/ObjCMethodList.h"
43 #include "clang/Sema/Ownership.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/TypoCorrection.h"
47 #include "clang/Sema/Weak.h"
48 #include "llvm/ADT/ArrayRef.h"
49 #include "llvm/ADT/Optional.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/TinyPtrVector.h"
54 #include <deque>
55 #include <memory>
56 #include <string>
57 #include <vector>
58
59 namespace llvm {
60   class APSInt;
61   template <typename ValueT> struct DenseMapInfo;
62   template <typename ValueT, typename ValueInfoT> class DenseSet;
63   class SmallBitVector;
64   class InlineAsmIdentifierInfo;
65 }
66
67 namespace clang {
68   class ADLResult;
69   class ASTConsumer;
70   class ASTContext;
71   class ASTMutationListener;
72   class ASTReader;
73   class ASTWriter;
74   class ArrayType;
75   class AttributeList;
76   class BlockDecl;
77   class CapturedDecl;
78   class CXXBasePath;
79   class CXXBasePaths;
80   class CXXBindTemporaryExpr;
81   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
82   class CXXConstructorDecl;
83   class CXXConversionDecl;
84   class CXXDeleteExpr;
85   class CXXDestructorDecl;
86   class CXXFieldCollector;
87   class CXXMemberCallExpr;
88   class CXXMethodDecl;
89   class CXXScopeSpec;
90   class CXXTemporary;
91   class CXXTryStmt;
92   class CallExpr;
93   class ClassTemplateDecl;
94   class ClassTemplatePartialSpecializationDecl;
95   class ClassTemplateSpecializationDecl;
96   class VarTemplatePartialSpecializationDecl;
97   class CodeCompleteConsumer;
98   class CodeCompletionAllocator;
99   class CodeCompletionTUInfo;
100   class CodeCompletionResult;
101   class Decl;
102   class DeclAccessPair;
103   class DeclContext;
104   class DeclRefExpr;
105   class DeclaratorDecl;
106   class DeducedTemplateArgument;
107   class DependentDiagnostic;
108   class DesignatedInitExpr;
109   class Designation;
110   class EnableIfAttr;
111   class EnumConstantDecl;
112   class Expr;
113   class ExtVectorType;
114   class FormatAttr;
115   class FriendDecl;
116   class FunctionDecl;
117   class FunctionProtoType;
118   class FunctionTemplateDecl;
119   class ImplicitConversionSequence;
120   class InitListExpr;
121   class InitializationKind;
122   class InitializationSequence;
123   class InitializedEntity;
124   class IntegerLiteral;
125   class LabelStmt;
126   class LambdaExpr;
127   class LangOptions;
128   class LocalInstantiationScope;
129   class LookupResult;
130   class MacroInfo;
131   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
132   class ModuleLoader;
133   class MultiLevelTemplateArgumentList;
134   class NamedDecl;
135   class ObjCCategoryDecl;
136   class ObjCCategoryImplDecl;
137   class ObjCCompatibleAliasDecl;
138   class ObjCContainerDecl;
139   class ObjCImplDecl;
140   class ObjCImplementationDecl;
141   class ObjCInterfaceDecl;
142   class ObjCIvarDecl;
143   template <class T> class ObjCList;
144   class ObjCMessageExpr;
145   class ObjCMethodDecl;
146   class ObjCPropertyDecl;
147   class ObjCProtocolDecl;
148   class OMPThreadPrivateDecl;
149   class OMPDeclareReductionDecl;
150   class OMPDeclareSimdDecl;
151   class OMPClause;
152   struct OverloadCandidate;
153   class OverloadCandidateSet;
154   class OverloadExpr;
155   class ParenListExpr;
156   class ParmVarDecl;
157   class Preprocessor;
158   class PseudoDestructorTypeStorage;
159   class PseudoObjectExpr;
160   class QualType;
161   class StandardConversionSequence;
162   class Stmt;
163   class StringLiteral;
164   class SwitchStmt;
165   class TemplateArgument;
166   class TemplateArgumentList;
167   class TemplateArgumentLoc;
168   class TemplateDecl;
169   class TemplateParameterList;
170   class TemplatePartialOrderingContext;
171   class TemplateTemplateParmDecl;
172   class Token;
173   class TypeAliasDecl;
174   class TypedefDecl;
175   class TypedefNameDecl;
176   class TypeLoc;
177   class TypoCorrectionConsumer;
178   class UnqualifiedId;
179   class UnresolvedLookupExpr;
180   class UnresolvedMemberExpr;
181   class UnresolvedSetImpl;
182   class UnresolvedSetIterator;
183   class UsingDecl;
184   class UsingShadowDecl;
185   class ValueDecl;
186   class VarDecl;
187   class VarTemplateSpecializationDecl;
188   class VisibilityAttr;
189   class VisibleDeclConsumer;
190   class IndirectFieldDecl;
191   struct DeductionFailureInfo;
192   class TemplateSpecCandidateSet;
193
194 namespace sema {
195   class AccessedEntity;
196   class BlockScopeInfo;
197   class CapturedRegionScopeInfo;
198   class CapturingScopeInfo;
199   class CompoundScopeInfo;
200   class DelayedDiagnostic;
201   class DelayedDiagnosticPool;
202   class FunctionScopeInfo;
203   class LambdaScopeInfo;
204   class PossiblyUnreachableDiag;
205   class TemplateDeductionInfo;
206 }
207
208 namespace threadSafety {
209   class BeforeSet;
210   void threadSafetyCleanup(BeforeSet* Cache);
211 }
212
213 // FIXME: No way to easily map from TemplateTypeParmTypes to
214 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
215 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
216                   SourceLocation> UnexpandedParameterPack;
217
218 /// Describes whether we've seen any nullability information for the given
219 /// file.
220 struct FileNullability {
221   /// The first pointer declarator (of any pointer kind) in the file that does
222   /// not have a corresponding nullability annotation.
223   SourceLocation PointerLoc;
224
225   /// Which kind of pointer declarator we saw.
226   uint8_t PointerKind;
227
228   /// Whether we saw any type nullability annotations in the given file.
229   bool SawTypeNullability = false;
230 };
231
232 /// A mapping from file IDs to a record of whether we've seen nullability
233 /// information in that file.
234 class FileNullabilityMap {
235   /// A mapping from file IDs to the nullability information for each file ID.
236   llvm::DenseMap<FileID, FileNullability> Map;
237
238   /// A single-element cache based on the file ID.
239   struct {
240     FileID File;
241     FileNullability Nullability;
242   } Cache;
243
244 public:
245   FileNullability &operator[](FileID file) {
246     // Check the single-element cache.
247     if (file == Cache.File)
248       return Cache.Nullability;
249
250     // It's not in the single-element cache; flush the cache if we have one.
251     if (!Cache.File.isInvalid()) {
252       Map[Cache.File] = Cache.Nullability;
253     }
254
255     // Pull this entry into the cache.
256     Cache.File = file;
257     Cache.Nullability = Map[file];
258     return Cache.Nullability;
259   }
260 };
261
262 /// Sema - This implements semantic analysis and AST building for C.
263 class Sema {
264   Sema(const Sema &) = delete;
265   void operator=(const Sema &) = delete;
266
267   ///\brief Source of additional semantic information.
268   ExternalSemaSource *ExternalSource;
269
270   ///\brief Whether Sema has generated a multiplexer and has to delete it.
271   bool isMultiplexExternalSource;
272
273   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
274
275   bool isVisibleSlow(const NamedDecl *D);
276
277   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
278                                     const NamedDecl *New) {
279     // We are about to link these. It is now safe to compute the linkage of
280     // the new decl. If the new decl has external linkage, we will
281     // link it with the hidden decl (which also has external linkage) and
282     // it will keep having external linkage. If it has internal linkage, we
283     // will not link it. Since it has no previous decls, it will remain
284     // with internal linkage.
285     return isVisible(Old) || New->isExternallyVisible();
286   }
287   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
288
289 public:
290   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
291   typedef OpaquePtr<TemplateName> TemplateTy;
292   typedef OpaquePtr<QualType> TypeTy;
293
294   OpenCLOptions OpenCLFeatures;
295   FPOptions FPFeatures;
296
297   const LangOptions &LangOpts;
298   Preprocessor &PP;
299   ASTContext &Context;
300   ASTConsumer &Consumer;
301   DiagnosticsEngine &Diags;
302   SourceManager &SourceMgr;
303
304   /// \brief Flag indicating whether or not to collect detailed statistics.
305   bool CollectStats;
306
307   /// \brief Code-completion consumer.
308   CodeCompleteConsumer *CodeCompleter;
309
310   /// CurContext - This is the current declaration context of parsing.
311   DeclContext *CurContext;
312
313   /// \brief Generally null except when we temporarily switch decl contexts,
314   /// like in \see ActOnObjCTemporaryExitContainerContext.
315   DeclContext *OriginalLexicalContext;
316
317   /// VAListTagName - The declaration name corresponding to __va_list_tag.
318   /// This is used as part of a hack to omit that class from ADL results.
319   DeclarationName VAListTagName;
320
321   bool MSStructPragmaOn; // True when \#pragma ms_struct on
322
323   /// \brief Controls member pointer representation format under the MS ABI.
324   LangOptions::PragmaMSPointersToMembersKind
325       MSPointerToMemberRepresentationMethod;
326
327   /// Stack of active SEH __finally scopes.  Can be empty.
328   SmallVector<Scope*, 2> CurrentSEHFinally;
329
330   /// \brief Source location for newly created implicit MSInheritanceAttrs
331   SourceLocation ImplicitMSInheritanceAttrLoc;
332
333   enum PragmaMsStackAction {
334     PSK_Reset     = 0x0,                // #pragma ()
335     PSK_Set       = 0x1,                // #pragma (value)
336     PSK_Push      = 0x2,                // #pragma (push[, id])
337     PSK_Pop       = 0x4,                // #pragma (pop[, id])
338     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
339     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
340     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
341   };
342
343   template<typename ValueType>
344   struct PragmaStack {
345     struct Slot {
346       llvm::StringRef StackSlotLabel;
347       ValueType Value;
348       SourceLocation PragmaLocation;
349       Slot(llvm::StringRef StackSlotLabel,
350            ValueType Value,
351            SourceLocation PragmaLocation)
352         : StackSlotLabel(StackSlotLabel), Value(Value),
353           PragmaLocation(PragmaLocation) {}
354     };
355     void Act(SourceLocation PragmaLocation,
356              PragmaMsStackAction Action,
357              llvm::StringRef StackSlotLabel,
358              ValueType Value);
359
360     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
361     // method body to restore the stacks on exit, so it works like this:
362     //
363     //   struct S {
364     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
365     //     void Method {}
366     //     #pragma <name>(pop, InternalPragmaSlot)
367     //   };
368     //
369     // It works even with #pragma vtordisp, although MSVC doesn't support
370     //   #pragma vtordisp(push [, id], n)
371     // syntax.
372     //
373     // Push / pop a named sentinel slot.
374     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
375       assert((Action == PSK_Push || Action == PSK_Pop) &&
376              "Can only push / pop #pragma stack sentinels!");
377       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
378     }
379
380     // Constructors.
381     explicit PragmaStack(const ValueType &Default)
382         : DefaultValue(Default), CurrentValue(Default) {}
383
384     SmallVector<Slot, 2> Stack;
385     ValueType DefaultValue; // Value used for PSK_Reset action.
386     ValueType CurrentValue;
387     SourceLocation CurrentPragmaLocation;
388   };
389   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
390   // we shouldn't do so if they're in a module).
391
392   /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
393   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
394   ///
395   /// 0: Suppress all vtordisps
396   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
397   ///    structors
398   /// 2: Always insert vtordisps to support RTTI on partially constructed
399   ///    objects
400   PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
401   // #pragma pack.
402   // Sentinel to represent when the stack is set to mac68k alignment.
403   static const unsigned kMac68kAlignmentSentinel = ~0U;
404   PragmaStack<unsigned> PackStack;
405   // Segment #pragmas.
406   PragmaStack<StringLiteral *> DataSegStack;
407   PragmaStack<StringLiteral *> BSSSegStack;
408   PragmaStack<StringLiteral *> ConstSegStack;
409   PragmaStack<StringLiteral *> CodeSegStack;
410
411   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
412   // Actions should be performed only if we enter / exit a C++ method body.
413   class PragmaStackSentinelRAII {
414   public:
415     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
416     ~PragmaStackSentinelRAII();
417
418   private:
419     Sema &S;
420     StringRef SlotLabel;
421     bool ShouldAct;
422   };
423
424   /// A mapping that describes the nullability we've seen in each header file.
425   FileNullabilityMap NullabilityMap;
426
427   /// Last section used with #pragma init_seg.
428   StringLiteral *CurInitSeg;
429   SourceLocation CurInitSegLoc;
430
431   /// VisContext - Manages the stack for \#pragma GCC visibility.
432   void *VisContext; // Really a "PragmaVisStack*"
433
434   /// \brief This represents the last location of a "#pragma clang optimize off"
435   /// directive if such a directive has not been closed by an "on" yet. If
436   /// optimizations are currently "on", this is set to an invalid location.
437   SourceLocation OptimizeOffPragmaLocation;
438
439   /// \brief Flag indicating if Sema is building a recovery call expression.
440   ///
441   /// This flag is used to avoid building recovery call expressions
442   /// if Sema is already doing so, which would cause infinite recursions.
443   bool IsBuildingRecoveryCallExpr;
444
445   /// Used to control the generation of ExprWithCleanups.
446   CleanupInfo Cleanup;
447
448   /// ExprCleanupObjects - This is the stack of objects requiring
449   /// cleanup that are created by the current full expression.  The
450   /// element type here is ExprWithCleanups::Object.
451   SmallVector<BlockDecl*, 8> ExprCleanupObjects;
452
453   /// \brief Store a list of either DeclRefExprs or MemberExprs
454   ///  that contain a reference to a variable (constant) that may or may not
455   ///  be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
456   ///  and discarded value conversions have been applied to all subexpressions 
457   ///  of the enclosing full expression.  This is cleared at the end of each 
458   ///  full expression. 
459   llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
460
461   /// \brief Stack containing information about each of the nested
462   /// function, block, and method scopes that are currently active.
463   ///
464   /// This array is never empty.  Clients should ignore the first
465   /// element, which is used to cache a single FunctionScopeInfo
466   /// that's used to parse every top-level function.
467   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
468
469   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
470                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
471     ExtVectorDeclsType;
472
473   /// ExtVectorDecls - This is a list all the extended vector types. This allows
474   /// us to associate a raw vector type with one of the ext_vector type names.
475   /// This is only necessary for issuing pretty diagnostics.
476   ExtVectorDeclsType ExtVectorDecls;
477
478   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
479   std::unique_ptr<CXXFieldCollector> FieldCollector;
480
481   typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
482
483   /// \brief Set containing all declared private fields that are not used.
484   NamedDeclSetType UnusedPrivateFields;
485
486   /// \brief Set containing all typedefs that are likely unused.
487   llvm::SmallSetVector<const TypedefNameDecl *, 4>
488       UnusedLocalTypedefNameCandidates;
489
490   /// \brief Delete-expressions to be analyzed at the end of translation unit
491   ///
492   /// This list contains class members, and locations of delete-expressions
493   /// that could not be proven as to whether they mismatch with new-expression
494   /// used in initializer of the field.
495   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
496   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
497   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
498
499   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
500
501   /// PureVirtualClassDiagSet - a set of class declarations which we have
502   /// emitted a list of pure virtual functions. Used to prevent emitting the
503   /// same list more than once.
504   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
505
506   /// ParsingInitForAutoVars - a set of declarations with auto types for which
507   /// we are currently parsing the initializer.
508   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
509
510   /// \brief Look for a locally scoped extern "C" declaration by the given name.
511   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
512
513   typedef LazyVector<VarDecl *, ExternalSemaSource,
514                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
515     TentativeDefinitionsType;
516
517   /// \brief All the tentative definitions encountered in the TU.
518   TentativeDefinitionsType TentativeDefinitions;
519
520   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
521                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
522     UnusedFileScopedDeclsType;
523
524   /// \brief The set of file scoped decls seen so far that have not been used
525   /// and must warn if not used. Only contains the first declaration.
526   UnusedFileScopedDeclsType UnusedFileScopedDecls;
527
528   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
529                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
530     DelegatingCtorDeclsType;
531
532   /// \brief All the delegating constructors seen so far in the file, used for
533   /// cycle detection at the end of the TU.
534   DelegatingCtorDeclsType DelegatingCtorDecls;
535
536   /// \brief All the overriding functions seen during a class definition
537   /// that had their exception spec checks delayed, plus the overridden
538   /// function.
539   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
540     DelayedExceptionSpecChecks;
541
542   /// \brief All the members seen during a class definition which were both
543   /// explicitly defaulted and had explicitly-specified exception
544   /// specifications, along with the function type containing their
545   /// user-specified exception specification. Those exception specifications
546   /// were overridden with the default specifications, but we still need to
547   /// check whether they are compatible with the default specification, and
548   /// we can't do that until the nesting set of class definitions is complete.
549   SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
550     DelayedDefaultedMemberExceptionSpecs;
551
552   typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *>
553       LateParsedTemplateMapT;
554   LateParsedTemplateMapT LateParsedTemplateMap;
555
556   /// \brief Callback to the parser to parse templated functions when needed.
557   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
558   typedef void LateTemplateParserCleanupCB(void *P);
559   LateTemplateParserCB *LateTemplateParser;
560   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
561   void *OpaqueParser;
562
563   void SetLateTemplateParser(LateTemplateParserCB *LTP,
564                              LateTemplateParserCleanupCB *LTPCleanup,
565                              void *P) {
566     LateTemplateParser = LTP;
567     LateTemplateParserCleanup = LTPCleanup;
568     OpaqueParser = P;
569   }
570
571   class DelayedDiagnostics;
572
573   class DelayedDiagnosticsState {
574     sema::DelayedDiagnosticPool *SavedPool;
575     friend class Sema::DelayedDiagnostics;
576   };
577   typedef DelayedDiagnosticsState ParsingDeclState;
578   typedef DelayedDiagnosticsState ProcessingContextState;
579
580   /// A class which encapsulates the logic for delaying diagnostics
581   /// during parsing and other processing.
582   class DelayedDiagnostics {
583     /// \brief The current pool of diagnostics into which delayed
584     /// diagnostics should go.
585     sema::DelayedDiagnosticPool *CurPool;
586
587   public:
588     DelayedDiagnostics() : CurPool(nullptr) {}
589
590     /// Adds a delayed diagnostic.
591     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
592
593     /// Determines whether diagnostics should be delayed.
594     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
595
596     /// Returns the current delayed-diagnostics pool.
597     sema::DelayedDiagnosticPool *getCurrentPool() const {
598       return CurPool;
599     }
600
601     /// Enter a new scope.  Access and deprecation diagnostics will be
602     /// collected in this pool.
603     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
604       DelayedDiagnosticsState state;
605       state.SavedPool = CurPool;
606       CurPool = &pool;
607       return state;
608     }
609
610     /// Leave a delayed-diagnostic state that was previously pushed.
611     /// Do not emit any of the diagnostics.  This is performed as part
612     /// of the bookkeeping of popping a pool "properly".
613     void popWithoutEmitting(DelayedDiagnosticsState state) {
614       CurPool = state.SavedPool;
615     }
616
617     /// Enter a new scope where access and deprecation diagnostics are
618     /// not delayed.
619     DelayedDiagnosticsState pushUndelayed() {
620       DelayedDiagnosticsState state;
621       state.SavedPool = CurPool;
622       CurPool = nullptr;
623       return state;
624     }
625
626     /// Undo a previous pushUndelayed().
627     void popUndelayed(DelayedDiagnosticsState state) {
628       assert(CurPool == nullptr);
629       CurPool = state.SavedPool;
630     }
631   } DelayedDiagnostics;
632
633   /// A RAII object to temporarily push a declaration context.
634   class ContextRAII {
635   private:
636     Sema &S;
637     DeclContext *SavedContext;
638     ProcessingContextState SavedContextState;
639     QualType SavedCXXThisTypeOverride;
640
641   public:
642     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
643       : S(S), SavedContext(S.CurContext),
644         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
645         SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
646     {
647       assert(ContextToPush && "pushing null context");
648       S.CurContext = ContextToPush;
649       if (NewThisContext)
650         S.CXXThisTypeOverride = QualType();
651     }
652
653     void pop() {
654       if (!SavedContext) return;
655       S.CurContext = SavedContext;
656       S.DelayedDiagnostics.popUndelayed(SavedContextState);
657       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
658       SavedContext = nullptr;
659     }
660
661     ~ContextRAII() {
662       pop();
663     }
664   };
665
666   /// \brief RAII object to handle the state changes required to synthesize
667   /// a function body.
668   class SynthesizedFunctionScope {
669     Sema &S;
670     Sema::ContextRAII SavedContext;
671     
672   public:
673     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
674       : S(S), SavedContext(S, DC) 
675     {
676       S.PushFunctionScope();
677       S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
678     }
679     
680     ~SynthesizedFunctionScope() {
681       S.PopExpressionEvaluationContext();
682       S.PopFunctionScopeInfo();
683     }
684   };
685
686   /// WeakUndeclaredIdentifiers - Identifiers contained in
687   /// \#pragma weak before declared. rare. may alias another
688   /// identifier, declared or undeclared
689   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
690
691   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
692   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
693   /// to define functions that occur in multiple standards to call the version
694   /// in the currently selected standard.
695   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
696
697
698   /// \brief Load weak undeclared identifiers from the external source.
699   void LoadExternalWeakUndeclaredIdentifiers();
700
701   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
702   /// \#pragma weak during processing of other Decls.
703   /// I couldn't figure out a clean way to generate these in-line, so
704   /// we store them here and handle separately -- which is a hack.
705   /// It would be best to refactor this.
706   SmallVector<Decl*,2> WeakTopLevelDecl;
707
708   IdentifierResolver IdResolver;
709
710   /// Translation Unit Scope - useful to Objective-C actions that need
711   /// to lookup file scope declarations in the "ordinary" C decl namespace.
712   /// For example, user-defined classes, built-in "id" type, etc.
713   Scope *TUScope;
714
715   /// \brief The C++ "std" namespace, where the standard library resides.
716   LazyDeclPtr StdNamespace;
717
718   /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
719   /// standard library.
720   LazyDeclPtr StdBadAlloc;
721
722   /// \brief The C++ "std::initializer_list" template, which is defined in
723   /// \<initializer_list>.
724   ClassTemplateDecl *StdInitializerList;
725
726   /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
727   RecordDecl *CXXTypeInfoDecl;
728
729   /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
730   RecordDecl *MSVCGuidDecl;
731
732   /// \brief Caches identifiers/selectors for NSFoundation APIs.
733   std::unique_ptr<NSAPI> NSAPIObj;
734
735   /// \brief The declaration of the Objective-C NSNumber class.
736   ObjCInterfaceDecl *NSNumberDecl;
737
738   /// \brief The declaration of the Objective-C NSValue class.
739   ObjCInterfaceDecl *NSValueDecl;
740
741   /// \brief Pointer to NSNumber type (NSNumber *).
742   QualType NSNumberPointer;
743
744   /// \brief Pointer to NSValue type (NSValue *).
745   QualType NSValuePointer;
746
747   /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
748   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
749
750   /// \brief The declaration of the Objective-C NSString class.
751   ObjCInterfaceDecl *NSStringDecl;
752
753   /// \brief Pointer to NSString type (NSString *).
754   QualType NSStringPointer;
755
756   /// \brief The declaration of the stringWithUTF8String: method.
757   ObjCMethodDecl *StringWithUTF8StringMethod;
758
759   /// \brief The declaration of the valueWithBytes:objCType: method.
760   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
761
762   /// \brief The declaration of the Objective-C NSArray class.
763   ObjCInterfaceDecl *NSArrayDecl;
764
765   /// \brief The declaration of the arrayWithObjects:count: method.
766   ObjCMethodDecl *ArrayWithObjectsMethod;
767
768   /// \brief The declaration of the Objective-C NSDictionary class.
769   ObjCInterfaceDecl *NSDictionaryDecl;
770
771   /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
772   ObjCMethodDecl *DictionaryWithObjectsMethod;
773
774   /// \brief id<NSCopying> type.
775   QualType QIDNSCopying;
776
777   /// \brief will hold 'respondsToSelector:'
778   Selector RespondsToSelectorSel;
779
780   /// \brief counter for internal MS Asm label names.
781   unsigned MSAsmLabelNameCounter;
782
783   /// A flag to remember whether the implicit forms of operator new and delete
784   /// have been declared.
785   bool GlobalNewDeleteDeclared;
786
787   /// A flag to indicate that we're in a context that permits abstract
788   /// references to fields.  This is really a 
789   bool AllowAbstractFieldReference;
790
791   /// \brief Describes how the expressions currently being parsed are
792   /// evaluated at run-time, if at all.
793   enum ExpressionEvaluationContext {
794     /// \brief The current expression and its subexpressions occur within an
795     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
796     /// \c sizeof, where the type of the expression may be significant but
797     /// no code will be generated to evaluate the value of the expression at
798     /// run time.
799     Unevaluated,
800
801     /// \brief The current expression occurs within a discarded statement.
802     /// This behaves largely similarly to an unevaluated operand in preventing
803     /// definitions from being required, but not in other ways.
804     DiscardedStatement,
805
806     /// \brief The current expression occurs within an unevaluated
807     /// operand that unconditionally permits abstract references to
808     /// fields, such as a SIZE operator in MS-style inline assembly.
809     UnevaluatedAbstract,
810
811     /// \brief The current context is "potentially evaluated" in C++11 terms,
812     /// but the expression is evaluated at compile-time (like the values of
813     /// cases in a switch statement).
814     ConstantEvaluated,
815
816     /// \brief The current expression is potentially evaluated at run time,
817     /// which means that code may be generated to evaluate the value of the
818     /// expression at run time.
819     PotentiallyEvaluated,
820
821     /// \brief The current expression is potentially evaluated, but any
822     /// declarations referenced inside that expression are only used if
823     /// in fact the current expression is used.
824     ///
825     /// This value is used when parsing default function arguments, for which
826     /// we would like to provide diagnostics (e.g., passing non-POD arguments
827     /// through varargs) but do not want to mark declarations as "referenced"
828     /// until the default argument is used.
829     PotentiallyEvaluatedIfUsed
830   };
831
832   /// \brief Data structure used to record current or nested
833   /// expression evaluation contexts.
834   struct ExpressionEvaluationContextRecord {
835     /// \brief The expression evaluation context.
836     ExpressionEvaluationContext Context;
837
838     /// \brief Whether the enclosing context needed a cleanup.
839     CleanupInfo ParentCleanup;
840
841     /// \brief Whether we are in a decltype expression.
842     bool IsDecltype;
843
844     /// \brief The number of active cleanup objects when we entered
845     /// this expression evaluation context.
846     unsigned NumCleanupObjects;
847
848     /// \brief The number of typos encountered during this expression evaluation
849     /// context (i.e. the number of TypoExprs created).
850     unsigned NumTypos;
851
852     llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
853
854     /// \brief The lambdas that are present within this context, if it
855     /// is indeed an unevaluated context.
856     SmallVector<LambdaExpr *, 2> Lambdas;
857
858     /// \brief The declaration that provides context for lambda expressions
859     /// and block literals if the normal declaration context does not
860     /// suffice, e.g., in a default function argument.
861     Decl *ManglingContextDecl;
862
863     /// \brief The context information used to mangle lambda expressions
864     /// and block literals within this context.
865     ///
866     /// This mangling information is allocated lazily, since most contexts
867     /// do not have lambda expressions or block literals.
868     IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
869
870     /// \brief If we are processing a decltype type, a set of call expressions
871     /// for which we have deferred checking the completeness of the return type.
872     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
873
874     /// \brief If we are processing a decltype type, a set of temporary binding
875     /// expressions for which we have deferred checking the destructor.
876     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
877
878     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
879                                       unsigned NumCleanupObjects,
880                                       CleanupInfo ParentCleanup,
881                                       Decl *ManglingContextDecl,
882                                       bool IsDecltype)
883       : Context(Context), ParentCleanup(ParentCleanup),
884         IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
885         NumTypos(0),
886         ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
887
888     /// \brief Retrieve the mangling numbering context, used to consistently
889     /// number constructs like lambdas for mangling.
890     MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
891
892     bool isUnevaluated() const {
893       return Context == Unevaluated || Context == UnevaluatedAbstract;
894     }
895   };
896
897   /// A stack of expression evaluation contexts.
898   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
899
900   /// \brief Compute the mangling number context for a lambda expression or
901   /// block literal.
902   ///
903   /// \param DC - The DeclContext containing the lambda expression or
904   /// block literal.
905   /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
906   /// associated with the context, if relevant.
907   MangleNumberingContext *getCurrentMangleNumberContext(
908     const DeclContext *DC,
909     Decl *&ManglingContextDecl);
910
911
912   /// SpecialMemberOverloadResult - The overloading result for a special member
913   /// function.
914   ///
915   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
916   /// integer are used to determine whether overload resolution succeeded.
917   class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
918   public:
919     enum Kind {
920       NoMemberOrDeleted,
921       Ambiguous,
922       Success
923     };
924
925   private:
926     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
927
928   public:
929     SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
930       : FastFoldingSetNode(ID)
931     {}
932
933     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
934     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
935
936     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
937     void setKind(Kind K) { Pair.setInt(K); }
938   };
939
940   /// \brief A cache of special member function overload resolution results
941   /// for C++ records.
942   llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
943
944   /// \brief A cache of the flags available in enumerations with the flag_bits
945   /// attribute.
946   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
947
948   /// \brief The kind of translation unit we are processing.
949   ///
950   /// When we're processing a complete translation unit, Sema will perform
951   /// end-of-translation-unit semantic tasks (such as creating
952   /// initializers for tentative definitions in C) once parsing has
953   /// completed. Modules and precompiled headers perform different kinds of
954   /// checks.
955   TranslationUnitKind TUKind;
956
957   llvm::BumpPtrAllocator BumpAlloc;
958
959   /// \brief The number of SFINAE diagnostics that have been trapped.
960   unsigned NumSFINAEErrors;
961
962   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
963     UnparsedDefaultArgInstantiationsMap;
964
965   /// \brief A mapping from parameters with unparsed default arguments to the
966   /// set of instantiations of each parameter.
967   ///
968   /// This mapping is a temporary data structure used when parsing
969   /// nested class templates or nested classes of class templates,
970   /// where we might end up instantiating an inner class before the
971   /// default arguments of its methods have been parsed.
972   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
973
974   // Contains the locations of the beginning of unparsed default
975   // argument locations.
976   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
977
978   /// UndefinedInternals - all the used, undefined objects which require a
979   /// definition in this translation unit.
980   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
981
982   /// Obtain a sorted list of functions that are undefined but ODR-used.
983   void getUndefinedButUsed(
984       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
985
986   /// Retrieves list of suspicious delete-expressions that will be checked at
987   /// the end of translation unit.
988   const llvm::MapVector<FieldDecl *, DeleteLocs> &
989   getMismatchingDeleteExpressions() const;
990
991   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
992   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
993
994   /// Method Pool - allows efficient lookup when typechecking messages to "id".
995   /// We need to maintain a list, since selectors can have differing signatures
996   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
997   /// of selectors are "overloaded").
998   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
999   /// methods inside categories with a particular selector.
1000   GlobalMethodPool MethodPool;
1001
1002   /// Method selectors used in a \@selector expression. Used for implementation
1003   /// of -Wselector.
1004   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1005
1006   /// Kinds of C++ special members.
1007   enum CXXSpecialMember {
1008     CXXDefaultConstructor,
1009     CXXCopyConstructor,
1010     CXXMoveConstructor,
1011     CXXCopyAssignment,
1012     CXXMoveAssignment,
1013     CXXDestructor,
1014     CXXInvalid
1015   };
1016
1017   typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1018
1019   /// The C++ special members which we are currently in the process of
1020   /// declaring. If this process recursively triggers the declaration of the
1021   /// same special member, we should act as if it is not yet declared.
1022   llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1023
1024   void ReadMethodPool(Selector Sel);
1025   void updateOutOfDateSelector(Selector Sel);
1026
1027   /// Private Helper predicate to check for 'self'.
1028   bool isSelfExpr(Expr *RExpr);
1029   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1030
1031   /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1032   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1033   /// should not be used elsewhere.
1034   void EmitCurrentDiagnostic(unsigned DiagID);
1035
1036   /// Records and restores the FP_CONTRACT state on entry/exit of compound
1037   /// statements.
1038   class FPContractStateRAII {
1039   public:
1040     FPContractStateRAII(Sema& S)
1041       : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
1042     ~FPContractStateRAII() {
1043       S.FPFeatures.fp_contract = OldFPContractState;
1044     }
1045   private:
1046     Sema& S;
1047     bool OldFPContractState : 1;
1048   };
1049
1050   void addImplicitTypedef(StringRef Name, QualType T);
1051
1052 public:
1053   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1054        TranslationUnitKind TUKind = TU_Complete,
1055        CodeCompleteConsumer *CompletionConsumer = nullptr);
1056   ~Sema();
1057
1058   /// \brief Perform initialization that occurs after the parser has been
1059   /// initialized but before it parses anything.
1060   void Initialize();
1061
1062   const LangOptions &getLangOpts() const { return LangOpts; }
1063   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1064   FPOptions     &getFPOptions() { return FPFeatures; }
1065
1066   DiagnosticsEngine &getDiagnostics() const { return Diags; }
1067   SourceManager &getSourceManager() const { return SourceMgr; }
1068   Preprocessor &getPreprocessor() const { return PP; }
1069   ASTContext &getASTContext() const { return Context; }
1070   ASTConsumer &getASTConsumer() const { return Consumer; }
1071   ASTMutationListener *getASTMutationListener() const;
1072   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1073
1074   ///\brief Registers an external source. If an external source already exists,
1075   /// creates a multiplex external source and appends to it.
1076   ///
1077   ///\param[in] E - A non-null external sema source.
1078   ///
1079   void addExternalSource(ExternalSemaSource *E);
1080
1081   void PrintStats() const;
1082
1083   /// \brief Helper class that creates diagnostics with optional
1084   /// template instantiation stacks.
1085   ///
1086   /// This class provides a wrapper around the basic DiagnosticBuilder
1087   /// class that emits diagnostics. SemaDiagnosticBuilder is
1088   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1089   /// does) and, if the diagnostic comes from inside a template
1090   /// instantiation, printing the template instantiation stack as
1091   /// well.
1092   class SemaDiagnosticBuilder : public DiagnosticBuilder {
1093     Sema &SemaRef;
1094     unsigned DiagID;
1095
1096   public:
1097     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1098       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1099
1100     // This is a cunning lie. DiagnosticBuilder actually performs move
1101     // construction in its copy constructor (but due to varied uses, it's not
1102     // possible to conveniently express this as actual move construction). So
1103     // the default copy ctor here is fine, because the base class disables the
1104     // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1105     // in that case anwyay.
1106     SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1107
1108     ~SemaDiagnosticBuilder() {
1109       // If we aren't active, there is nothing to do.
1110       if (!isActive()) return;
1111
1112       // Otherwise, we need to emit the diagnostic. First flush the underlying
1113       // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1114       // won't emit the diagnostic in its own destructor.
1115       //
1116       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1117       // do its own needless checks to see if the diagnostic needs to be
1118       // emitted. However, because we take care to ensure that the builder
1119       // objects never escape, a sufficiently smart compiler will be able to
1120       // eliminate that code.
1121       FlushCounts();
1122       Clear();
1123
1124       // Dispatch to Sema to emit the diagnostic.
1125       SemaRef.EmitCurrentDiagnostic(DiagID);
1126     }
1127
1128     /// Teach operator<< to produce an object of the correct type.
1129     template<typename T>
1130     friend const SemaDiagnosticBuilder &operator<<(
1131         const SemaDiagnosticBuilder &Diag, const T &Value) {
1132       const DiagnosticBuilder &BaseDiag = Diag;
1133       BaseDiag << Value;
1134       return Diag;
1135     }
1136   };
1137
1138   /// \brief Emit a diagnostic.
1139   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1140     DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1141     return SemaDiagnosticBuilder(DB, *this, DiagID);
1142   }
1143
1144   /// \brief Emit a partial diagnostic.
1145   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1146
1147   /// \brief Build a partial diagnostic.
1148   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1149
1150   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1151
1152   /// \brief Get a string to suggest for zero-initialization of a type.
1153   std::string
1154   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1155   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1156
1157   /// \brief Calls \c Lexer::getLocForEndOfToken()
1158   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1159
1160   /// \brief Retrieve the module loader associated with the preprocessor.
1161   ModuleLoader &getModuleLoader() const;
1162
1163   void emitAndClearUnusedLocalTypedefWarnings();
1164
1165   void ActOnEndOfTranslationUnit();
1166
1167   void CheckDelegatingCtorCycles();
1168
1169   Scope *getScopeForContext(DeclContext *Ctx);
1170
1171   void PushFunctionScope();
1172   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1173   sema::LambdaScopeInfo *PushLambdaScope();
1174
1175   /// \brief This is used to inform Sema what the current TemplateParameterDepth
1176   /// is during Parsing.  Currently it is used to pass on the depth
1177   /// when parsing generic lambda 'auto' parameters.
1178   void RecordParsingTemplateParameterDepth(unsigned Depth);
1179   
1180   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1181                                RecordDecl *RD,
1182                                CapturedRegionKind K);
1183   void
1184   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1185                        const Decl *D = nullptr,
1186                        const BlockExpr *blkExpr = nullptr);
1187
1188   sema::FunctionScopeInfo *getCurFunction() const {
1189     return FunctionScopes.back();
1190   }
1191   
1192   sema::FunctionScopeInfo *getEnclosingFunction() const {
1193     if (FunctionScopes.empty())
1194       return nullptr;
1195     
1196     for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1197       if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1198         continue;
1199       return FunctionScopes[e];
1200     }
1201     return nullptr;
1202   }
1203   
1204   template <typename ExprT>
1205   void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1206     if (!isUnevaluatedContext())
1207       getCurFunction()->recordUseOfWeak(E, IsRead);
1208   }
1209   
1210   void PushCompoundScope();
1211   void PopCompoundScope();
1212
1213   sema::CompoundScopeInfo &getCurCompoundScope() const;
1214
1215   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1216
1217   /// \brief Retrieve the current block, if any.
1218   sema::BlockScopeInfo *getCurBlock();
1219
1220   /// \brief Retrieve the current lambda scope info, if any.
1221   sema::LambdaScopeInfo *getCurLambda();
1222
1223   /// \brief Retrieve the current generic lambda info, if any.
1224   sema::LambdaScopeInfo *getCurGenericLambda();
1225
1226   /// \brief Retrieve the current captured region, if any.
1227   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1228
1229   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1230   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1231
1232   void ActOnComment(SourceRange Comment);
1233
1234   //===--------------------------------------------------------------------===//
1235   // Type Analysis / Processing: SemaType.cpp.
1236   //
1237
1238   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1239                               const DeclSpec *DS = nullptr);
1240   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1241                               const DeclSpec *DS = nullptr);
1242   QualType BuildPointerType(QualType T,
1243                             SourceLocation Loc, DeclarationName Entity);
1244   QualType BuildReferenceType(QualType T, bool LValueRef,
1245                               SourceLocation Loc, DeclarationName Entity);
1246   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1247                           Expr *ArraySize, unsigned Quals,
1248                           SourceRange Brackets, DeclarationName Entity);
1249   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1250                               SourceLocation AttrLoc);
1251
1252   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1253
1254   /// \brief Build a function type.
1255   ///
1256   /// This routine checks the function type according to C++ rules and
1257   /// under the assumption that the result type and parameter types have
1258   /// just been instantiated from a template. It therefore duplicates
1259   /// some of the behavior of GetTypeForDeclarator, but in a much
1260   /// simpler form that is only suitable for this narrow use case.
1261   ///
1262   /// \param T The return type of the function.
1263   ///
1264   /// \param ParamTypes The parameter types of the function. This array
1265   /// will be modified to account for adjustments to the types of the
1266   /// function parameters.
1267   ///
1268   /// \param Loc The location of the entity whose type involves this
1269   /// function type or, if there is no such entity, the location of the
1270   /// type that will have function type.
1271   ///
1272   /// \param Entity The name of the entity that involves the function
1273   /// type, if known.
1274   ///
1275   /// \param EPI Extra information about the function type. Usually this will
1276   /// be taken from an existing function with the same prototype.
1277   ///
1278   /// \returns A suitable function type, if there are no errors. The
1279   /// unqualified type will always be a FunctionProtoType.
1280   /// Otherwise, returns a NULL type.
1281   QualType BuildFunctionType(QualType T,
1282                              MutableArrayRef<QualType> ParamTypes,
1283                              SourceLocation Loc, DeclarationName Entity,
1284                              const FunctionProtoType::ExtProtoInfo &EPI);
1285
1286   QualType BuildMemberPointerType(QualType T, QualType Class,
1287                                   SourceLocation Loc,
1288                                   DeclarationName Entity);
1289   QualType BuildBlockPointerType(QualType T,
1290                                  SourceLocation Loc, DeclarationName Entity);
1291   QualType BuildParenType(QualType T);
1292   QualType BuildAtomicType(QualType T, SourceLocation Loc);
1293   QualType BuildPipeType(QualType T,
1294                          SourceLocation Loc);
1295
1296   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1297   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1298   TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1299                                                TypeSourceInfo *ReturnTypeInfo);
1300
1301   /// \brief Package the given type and TSI into a ParsedType.
1302   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1303   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1304   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1305   static QualType GetTypeFromParser(ParsedType Ty,
1306                                     TypeSourceInfo **TInfo = nullptr);
1307   CanThrowResult canThrow(const Expr *E);
1308   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1309                                                 const FunctionProtoType *FPT);
1310   void UpdateExceptionSpec(FunctionDecl *FD,
1311                            const FunctionProtoType::ExceptionSpecInfo &ESI);
1312   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1313   bool CheckDistantExceptionSpec(QualType T);
1314   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1315   bool CheckEquivalentExceptionSpec(
1316       const FunctionProtoType *Old, SourceLocation OldLoc,
1317       const FunctionProtoType *New, SourceLocation NewLoc);
1318   bool CheckEquivalentExceptionSpec(
1319       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1320       const FunctionProtoType *Old, SourceLocation OldLoc,
1321       const FunctionProtoType *New, SourceLocation NewLoc,
1322       bool *MissingExceptionSpecification = nullptr,
1323       bool *MissingEmptyExceptionSpecification = nullptr,
1324       bool AllowNoexceptAllMatchWithNoSpec = false,
1325       bool IsOperatorNew = false);
1326   bool CheckExceptionSpecSubset(
1327       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1328       const FunctionProtoType *Superset, SourceLocation SuperLoc,
1329       const FunctionProtoType *Subset, SourceLocation SubLoc);
1330   bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1331       const FunctionProtoType *Target, SourceLocation TargetLoc,
1332       const FunctionProtoType *Source, SourceLocation SourceLoc);
1333
1334   TypeResult ActOnTypeName(Scope *S, Declarator &D);
1335
1336   /// \brief The parser has parsed the context-sensitive type 'instancetype'
1337   /// in an Objective-C message declaration. Return the appropriate type.
1338   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1339
1340   /// \brief Abstract class used to diagnose incomplete types.
1341   struct TypeDiagnoser {
1342     TypeDiagnoser() {}
1343
1344     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1345     virtual ~TypeDiagnoser() {}
1346   };
1347
1348   static int getPrintable(int I) { return I; }
1349   static unsigned getPrintable(unsigned I) { return I; }
1350   static bool getPrintable(bool B) { return B; }
1351   static const char * getPrintable(const char *S) { return S; }
1352   static StringRef getPrintable(StringRef S) { return S; }
1353   static const std::string &getPrintable(const std::string &S) { return S; }
1354   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1355     return II;
1356   }
1357   static DeclarationName getPrintable(DeclarationName N) { return N; }
1358   static QualType getPrintable(QualType T) { return T; }
1359   static SourceRange getPrintable(SourceRange R) { return R; }
1360   static SourceRange getPrintable(SourceLocation L) { return L; }
1361   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1362   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1363
1364   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1365     unsigned DiagID;
1366     std::tuple<const Ts &...> Args;
1367
1368     template <std::size_t... Is>
1369     void emit(const SemaDiagnosticBuilder &DB,
1370               llvm::index_sequence<Is...>) const {
1371       // Apply all tuple elements to the builder in order.
1372       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1373       (void)Dummy;
1374     }
1375
1376   public:
1377     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1378         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1379       assert(DiagID != 0 && "no diagnostic for type diagnoser");
1380     }
1381
1382     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1383       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1384       emit(DB, llvm::index_sequence_for<Ts...>());
1385       DB << T;
1386     }
1387   };
1388
1389 private:
1390   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1391                                TypeDiagnoser *Diagnoser);
1392
1393   VisibleModuleSet VisibleModules;
1394   llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
1395
1396   Module *CachedFakeTopLevelModule;
1397
1398 public:
1399   /// \brief Get the module owning an entity.
1400   Module *getOwningModule(Decl *Entity);
1401
1402   /// \brief Make a merged definition of an existing hidden definition \p ND
1403   /// visible at the specified location.
1404   void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1405
1406   bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1407
1408   /// Determine whether a declaration is visible to name lookup.
1409   bool isVisible(const NamedDecl *D) {
1410     return !D->isHidden() || isVisibleSlow(D);
1411   }
1412
1413   /// Determine whether any declaration of an entity is visible.
1414   bool
1415   hasVisibleDeclaration(const NamedDecl *D,
1416                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1417     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1418   }
1419   bool hasVisibleDeclarationSlow(const NamedDecl *D,
1420                                  llvm::SmallVectorImpl<Module *> *Modules);
1421
1422   bool hasVisibleMergedDefinition(NamedDecl *Def);
1423
1424   /// Determine if \p D has a visible definition. If not, suggest a declaration
1425   /// that should be made visible to expose the definition.
1426   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1427                             bool OnlyNeedComplete = false);
1428   bool hasVisibleDefinition(const NamedDecl *D) {
1429     NamedDecl *Hidden;
1430     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1431   }
1432
1433   /// Determine if the template parameter \p D has a visible default argument.
1434   bool
1435   hasVisibleDefaultArgument(const NamedDecl *D,
1436                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1437
1438   /// Determine if there is a visible declaration of \p D that is a member
1439   /// specialization declaration (as opposed to an instantiated declaration).
1440   bool hasVisibleMemberSpecialization(
1441       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1442
1443   /// Determine if \p A and \p B are equivalent internal linkage declarations
1444   /// from different modules, and thus an ambiguity error can be downgraded to
1445   /// an extension warning.
1446   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1447                                               const NamedDecl *B);
1448   void diagnoseEquivalentInternalLinkageDeclarations(
1449       SourceLocation Loc, const NamedDecl *D,
1450       ArrayRef<const NamedDecl *> Equiv);
1451
1452   bool isCompleteType(SourceLocation Loc, QualType T) {
1453     return !RequireCompleteTypeImpl(Loc, T, nullptr);
1454   }
1455   bool RequireCompleteType(SourceLocation Loc, QualType T,
1456                            TypeDiagnoser &Diagnoser);
1457   bool RequireCompleteType(SourceLocation Loc, QualType T,
1458                            unsigned DiagID);
1459
1460   template <typename... Ts>
1461   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1462                            const Ts &...Args) {
1463     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1464     return RequireCompleteType(Loc, T, Diagnoser);
1465   }
1466
1467   void completeExprArrayBound(Expr *E);
1468   bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1469   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1470
1471   template <typename... Ts>
1472   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1473     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1474     return RequireCompleteExprType(E, Diagnoser);
1475   }
1476
1477   bool RequireLiteralType(SourceLocation Loc, QualType T,
1478                           TypeDiagnoser &Diagnoser);
1479   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1480
1481   template <typename... Ts>
1482   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1483                           const Ts &...Args) {
1484     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1485     return RequireLiteralType(Loc, T, Diagnoser);
1486   }
1487
1488   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1489                              const CXXScopeSpec &SS, QualType T);
1490
1491   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1492   /// If AsUnevaluated is false, E is treated as though it were an evaluated
1493   /// context, such as when building a type for decltype(auto).
1494   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1495                              bool AsUnevaluated = true);
1496   QualType BuildUnaryTransformType(QualType BaseType,
1497                                    UnaryTransformType::UTTKind UKind,
1498                                    SourceLocation Loc);
1499
1500   //===--------------------------------------------------------------------===//
1501   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1502   //
1503
1504   struct SkipBodyInfo {
1505     SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1506     bool ShouldSkip;
1507     NamedDecl *Previous;
1508   };
1509
1510   /// List of decls defined in a function prototype. This contains EnumConstants
1511   /// that incorrectly end up in translation unit scope because there is no
1512   /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1513   /// them into the FunctionDecl.
1514   std::vector<NamedDecl*> DeclsInPrototypeScope;
1515
1516   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1517
1518   void DiagnoseUseOfUnimplementedSelectors();
1519
1520   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1521
1522   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1523                          Scope *S, CXXScopeSpec *SS = nullptr,
1524                          bool isClassName = false, bool HasTrailingDot = false,
1525                          ParsedType ObjectType = nullptr,
1526                          bool IsCtorOrDtorName = false,
1527                          bool WantNontrivialTypeSourceInfo = false,
1528                          IdentifierInfo **CorrectedII = nullptr);
1529   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1530   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1531   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1532                                SourceLocation IILoc,
1533                                Scope *S,
1534                                CXXScopeSpec *SS,
1535                                ParsedType &SuggestedType,
1536                                bool AllowClassTemplates = false);
1537
1538   /// Attempt to behave like MSVC in situations where lookup of an unqualified
1539   /// type name has failed in a dependent context. In these situations, we
1540   /// automatically form a DependentTypeName that will retry lookup in a related
1541   /// scope during instantiation.
1542   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1543                                       SourceLocation NameLoc,
1544                                       bool IsTemplateTypeArg);
1545
1546   /// \brief Describes the result of the name lookup and resolution performed
1547   /// by \c ClassifyName().
1548   enum NameClassificationKind {
1549     NC_Unknown,
1550     NC_Error,
1551     NC_Keyword,
1552     NC_Type,
1553     NC_Expression,
1554     NC_NestedNameSpecifier,
1555     NC_TypeTemplate,
1556     NC_VarTemplate,
1557     NC_FunctionTemplate
1558   };
1559
1560   class NameClassification {
1561     NameClassificationKind Kind;
1562     ExprResult Expr;
1563     TemplateName Template;
1564     ParsedType Type;
1565     const IdentifierInfo *Keyword;
1566
1567     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1568
1569   public:
1570     NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1571
1572     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1573
1574     NameClassification(const IdentifierInfo *Keyword)
1575       : Kind(NC_Keyword), Keyword(Keyword) { }
1576
1577     static NameClassification Error() {
1578       return NameClassification(NC_Error);
1579     }
1580
1581     static NameClassification Unknown() {
1582       return NameClassification(NC_Unknown);
1583     }
1584
1585     static NameClassification NestedNameSpecifier() {
1586       return NameClassification(NC_NestedNameSpecifier);
1587     }
1588
1589     static NameClassification TypeTemplate(TemplateName Name) {
1590       NameClassification Result(NC_TypeTemplate);
1591       Result.Template = Name;
1592       return Result;
1593     }
1594
1595     static NameClassification VarTemplate(TemplateName Name) {
1596       NameClassification Result(NC_VarTemplate);
1597       Result.Template = Name;
1598       return Result;
1599     }
1600
1601     static NameClassification FunctionTemplate(TemplateName Name) {
1602       NameClassification Result(NC_FunctionTemplate);
1603       Result.Template = Name;
1604       return Result;
1605     }
1606
1607     NameClassificationKind getKind() const { return Kind; }
1608
1609     ParsedType getType() const {
1610       assert(Kind == NC_Type);
1611       return Type;
1612     }
1613
1614     ExprResult getExpression() const {
1615       assert(Kind == NC_Expression);
1616       return Expr;
1617     }
1618
1619     TemplateName getTemplateName() const {
1620       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1621              Kind == NC_VarTemplate);
1622       return Template;
1623     }
1624
1625     TemplateNameKind getTemplateNameKind() const {
1626       switch (Kind) {
1627       case NC_TypeTemplate:
1628         return TNK_Type_template;
1629       case NC_FunctionTemplate:
1630         return TNK_Function_template;
1631       case NC_VarTemplate:
1632         return TNK_Var_template;
1633       default:
1634         llvm_unreachable("unsupported name classification.");
1635       }
1636     }
1637   };
1638
1639   /// \brief Perform name lookup on the given name, classifying it based on
1640   /// the results of name lookup and the following token.
1641   ///
1642   /// This routine is used by the parser to resolve identifiers and help direct
1643   /// parsing. When the identifier cannot be found, this routine will attempt
1644   /// to correct the typo and classify based on the resulting name.
1645   ///
1646   /// \param S The scope in which we're performing name lookup.
1647   ///
1648   /// \param SS The nested-name-specifier that precedes the name.
1649   ///
1650   /// \param Name The identifier. If typo correction finds an alternative name,
1651   /// this pointer parameter will be updated accordingly.
1652   ///
1653   /// \param NameLoc The location of the identifier.
1654   ///
1655   /// \param NextToken The token following the identifier. Used to help
1656   /// disambiguate the name.
1657   ///
1658   /// \param IsAddressOfOperand True if this name is the operand of a unary
1659   ///        address of ('&') expression, assuming it is classified as an
1660   ///        expression.
1661   ///
1662   /// \param CCC The correction callback, if typo correction is desired.
1663   NameClassification
1664   ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1665                SourceLocation NameLoc, const Token &NextToken,
1666                bool IsAddressOfOperand,
1667                std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1668
1669   Decl *ActOnDeclarator(Scope *S, Declarator &D);
1670
1671   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1672                               MultiTemplateParamsArg TemplateParameterLists);
1673   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1674   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1675   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1676                                     DeclarationName Name,
1677                                     SourceLocation Loc);
1678   void
1679   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1680                             SourceLocation FallbackLoc,
1681                             SourceLocation ConstQualLoc = SourceLocation(),
1682                             SourceLocation VolatileQualLoc = SourceLocation(),
1683                             SourceLocation RestrictQualLoc = SourceLocation(),
1684                             SourceLocation AtomicQualLoc = SourceLocation(),
1685                             SourceLocation UnalignedQualLoc = SourceLocation());
1686
1687   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1688   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1689   void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1690   void CheckShadow(Scope *S, VarDecl *D);
1691
1692   /// Warn if 'E', which is an expression that is about to be modified, refers
1693   /// to a shadowing declaration.
1694   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1695
1696 private:
1697   /// Map of current shadowing declarations to shadowed declarations. Warn if
1698   /// it looks like the user is trying to modify the shadowing declaration.
1699   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1700
1701 public:
1702   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1703   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1704   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1705                                     TypedefNameDecl *NewTD);
1706   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1707   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1708                                     TypeSourceInfo *TInfo,
1709                                     LookupResult &Previous);
1710   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1711                                   LookupResult &Previous, bool &Redeclaration);
1712   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1713                                      TypeSourceInfo *TInfo,
1714                                      LookupResult &Previous,
1715                                      MultiTemplateParamsArg TemplateParamLists,
1716                                      bool &AddToScope);
1717   // Returns true if the variable declaration is a redeclaration
1718   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1719   void CheckVariableDeclarationType(VarDecl *NewVD);
1720   void CheckCompleteVariableDeclaration(VarDecl *var);
1721   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1722
1723   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1724                                      TypeSourceInfo *TInfo,
1725                                      LookupResult &Previous,
1726                                      MultiTemplateParamsArg TemplateParamLists,
1727                                      bool &AddToScope);
1728   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1729
1730   bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1731   bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1732
1733   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1734   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1735                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1736   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1737                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1738   // Returns true if the function declaration is a redeclaration
1739   bool CheckFunctionDeclaration(Scope *S,
1740                                 FunctionDecl *NewFD, LookupResult &Previous,
1741                                 bool IsExplicitSpecialization);
1742   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1743   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1744   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1745   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1746                                           SourceLocation Loc,
1747                                           QualType T);
1748   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1749                               SourceLocation NameLoc, IdentifierInfo *Name,
1750                               QualType T, TypeSourceInfo *TSInfo,
1751                               StorageClass SC);
1752   void ActOnParamDefaultArgument(Decl *param,
1753                                  SourceLocation EqualLoc,
1754                                  Expr *defarg);
1755   void ActOnParamUnparsedDefaultArgument(Decl *param,
1756                                          SourceLocation EqualLoc,
1757                                          SourceLocation ArgLoc);
1758   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1759   bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1760                                SourceLocation EqualLoc);
1761
1762   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1763                             bool TypeMayContainAuto);
1764   void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1765   void ActOnInitializerError(Decl *Dcl);
1766   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1767   void ActOnCXXForRangeDecl(Decl *D);
1768   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1769                                         IdentifierInfo *Ident,
1770                                         ParsedAttributes &Attrs,
1771                                         SourceLocation AttrEnd);
1772   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1773   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1774   void FinalizeDeclaration(Decl *D);
1775   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1776                                          ArrayRef<Decl *> Group);
1777   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1778                                       bool TypeMayContainAuto = true);
1779
1780   /// Should be called on all declarations that might have attached
1781   /// documentation comments.
1782   void ActOnDocumentableDecl(Decl *D);
1783   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1784
1785   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1786                                        SourceLocation LocAfterDecls);
1787   void CheckForFunctionRedefinition(
1788       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1789       SkipBodyInfo *SkipBody = nullptr);
1790   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1791                                 MultiTemplateParamsArg TemplateParamLists,
1792                                 SkipBodyInfo *SkipBody = nullptr);
1793   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1794                                 SkipBodyInfo *SkipBody = nullptr);
1795   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1796   bool isObjCMethodDecl(Decl *D) {
1797     return D && isa<ObjCMethodDecl>(D);
1798   }
1799
1800   /// \brief Determine whether we can delay parsing the body of a function or
1801   /// function template until it is used, assuming we don't care about emitting
1802   /// code for that function.
1803   ///
1804   /// This will be \c false if we may need the body of the function in the
1805   /// middle of parsing an expression (where it's impractical to switch to
1806   /// parsing a different function), for instance, if it's constexpr in C++11
1807   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1808   bool canDelayFunctionBody(const Declarator &D);
1809
1810   /// \brief Determine whether we can skip parsing the body of a function
1811   /// definition, assuming we don't care about analyzing its body or emitting
1812   /// code for that function.
1813   ///
1814   /// This will be \c false only if we may need the body of the function in
1815   /// order to parse the rest of the program (for instance, if it is
1816   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1817   bool canSkipFunctionBody(Decl *D);
1818
1819   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1820   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1821   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1822   Decl *ActOnSkippedFunctionBody(Decl *Decl);
1823   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1824
1825   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1826   /// attribute for which parsing is delayed.
1827   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1828
1829   /// \brief Diagnose any unused parameters in the given sequence of
1830   /// ParmVarDecl pointers.
1831   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1832
1833   /// \brief Diagnose whether the size of parameters or return value of a
1834   /// function or obj-c method definition is pass-by-value and larger than a
1835   /// specified threshold.
1836   void
1837   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1838                                          QualType ReturnTy, NamedDecl *D);
1839
1840   void DiagnoseInvalidJumps(Stmt *Body);
1841   Decl *ActOnFileScopeAsmDecl(Expr *expr,
1842                               SourceLocation AsmLoc,
1843                               SourceLocation RParenLoc);
1844
1845   /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1846   Decl *ActOnEmptyDeclaration(Scope *S,
1847                               AttributeList *AttrList,
1848                               SourceLocation SemiLoc);
1849
1850   /// \brief The parser has processed a module import declaration.
1851   ///
1852   /// \param AtLoc The location of the '@' symbol, if any.
1853   ///
1854   /// \param ImportLoc The location of the 'import' keyword.
1855   ///
1856   /// \param Path The module access path.
1857   DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1858                                ModuleIdPath Path);
1859
1860   /// \brief The parser has processed a module import translated from a
1861   /// #include or similar preprocessing directive.
1862   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1863
1864   /// \brief The parsed has entered a submodule.
1865   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1866   /// \brief The parser has left a submodule.
1867   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1868
1869   /// \brief Check if module import may be found in the current context,
1870   /// emit error if not.
1871   void diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc);
1872
1873   /// \brief Create an implicit import of the given module at the given
1874   /// source location, for error recovery, if possible.
1875   ///
1876   /// This routine is typically used when an entity found by name lookup
1877   /// is actually hidden within a module that we know about but the user
1878   /// has forgotten to import.
1879   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1880                                                   Module *Mod);
1881
1882   /// Kinds of missing import. Note, the values of these enumerators correspond
1883   /// to %select values in diagnostics.
1884   enum class MissingImportKind {
1885     Declaration,
1886     Definition,
1887     DefaultArgument,
1888     ExplicitSpecialization,
1889     PartialSpecialization
1890   };
1891
1892   /// \brief Diagnose that the specified declaration needs to be visible but
1893   /// isn't, and suggest a module import that would resolve the problem.
1894   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1895                              MissingImportKind MIK, bool Recover = true);
1896   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1897                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1898                              MissingImportKind MIK, bool Recover);
1899
1900   /// \brief We've found a use of a templated declaration that would trigger an
1901   /// implicit instantiation. Check that any relevant explicit specializations
1902   /// and partial specializations are visible, and diagnose if not.
1903   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
1904
1905   /// \brief We've found a use of a template specialization that would select a
1906   /// partial specialization. Check that the partial specialization is visible,
1907   /// and diagnose if not.
1908   void checkPartialSpecializationVisibility(SourceLocation Loc,
1909                                             NamedDecl *Spec);
1910
1911   /// \brief Retrieve a suitable printing policy.
1912   PrintingPolicy getPrintingPolicy() const {
1913     return getPrintingPolicy(Context, PP);
1914   }
1915
1916   /// \brief Retrieve a suitable printing policy.
1917   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1918                                           const Preprocessor &PP);
1919
1920   /// Scope actions.
1921   void ActOnPopScope(SourceLocation Loc, Scope *S);
1922   void ActOnTranslationUnitScope(Scope *S);
1923
1924   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
1925                                    RecordDecl *&AnonRecord);
1926   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
1927                                    MultiTemplateParamsArg TemplateParams,
1928                                    bool IsExplicitInstantiation,
1929                                    RecordDecl *&AnonRecord);
1930
1931   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1932                                     AccessSpecifier AS,
1933                                     RecordDecl *Record,
1934                                     const PrintingPolicy &Policy);
1935
1936   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1937                                        RecordDecl *Record);
1938
1939   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1940                                     TagTypeKind NewTag, bool isDefinition,
1941                                     SourceLocation NewTagLoc,
1942                                     const IdentifierInfo *Name);
1943
1944   enum TagUseKind {
1945     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
1946     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
1947     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
1948     TUK_Friend       // Friend declaration:  'friend struct foo;'
1949   };
1950
1951   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1952                  SourceLocation KWLoc, CXXScopeSpec &SS,
1953                  IdentifierInfo *Name, SourceLocation NameLoc,
1954                  AttributeList *Attr, AccessSpecifier AS,
1955                  SourceLocation ModulePrivateLoc,
1956                  MultiTemplateParamsArg TemplateParameterLists,
1957                  bool &OwnedDecl, bool &IsDependent,
1958                  SourceLocation ScopedEnumKWLoc,
1959                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
1960                  bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
1961
1962   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1963                                 unsigned TagSpec, SourceLocation TagLoc,
1964                                 CXXScopeSpec &SS,
1965                                 IdentifierInfo *Name, SourceLocation NameLoc,
1966                                 AttributeList *Attr,
1967                                 MultiTemplateParamsArg TempParamLists);
1968
1969   TypeResult ActOnDependentTag(Scope *S,
1970                                unsigned TagSpec,
1971                                TagUseKind TUK,
1972                                const CXXScopeSpec &SS,
1973                                IdentifierInfo *Name,
1974                                SourceLocation TagLoc,
1975                                SourceLocation NameLoc);
1976
1977   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1978                  IdentifierInfo *ClassName,
1979                  SmallVectorImpl<Decl *> &Decls);
1980   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1981                    Declarator &D, Expr *BitfieldWidth);
1982
1983   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1984                          Declarator &D, Expr *BitfieldWidth,
1985                          InClassInitStyle InitStyle,
1986                          AccessSpecifier AS);
1987   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1988                                    SourceLocation DeclStart,
1989                                    Declarator &D, Expr *BitfieldWidth,
1990                                    InClassInitStyle InitStyle,
1991                                    AccessSpecifier AS,
1992                                    AttributeList *MSPropertyAttr);
1993
1994   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1995                             TypeSourceInfo *TInfo,
1996                             RecordDecl *Record, SourceLocation Loc,
1997                             bool Mutable, Expr *BitfieldWidth,
1998                             InClassInitStyle InitStyle,
1999                             SourceLocation TSSL,
2000                             AccessSpecifier AS, NamedDecl *PrevDecl,
2001                             Declarator *D = nullptr);
2002
2003   bool CheckNontrivialField(FieldDecl *FD);
2004   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2005   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2006                               bool Diagnose = false);
2007   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2008   void ActOnLastBitfield(SourceLocation DeclStart,
2009                          SmallVectorImpl<Decl *> &AllIvarDecls);
2010   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2011                   Declarator &D, Expr *BitfieldWidth,
2012                   tok::ObjCKeywordKind visibility);
2013
2014   // This is used for both record definitions and ObjC interface declarations.
2015   void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2016                    ArrayRef<Decl *> Fields,
2017                    SourceLocation LBrac, SourceLocation RBrac,
2018                    AttributeList *AttrList);
2019
2020   /// ActOnTagStartDefinition - Invoked when we have entered the
2021   /// scope of a tag's definition (e.g., for an enumeration, class,
2022   /// struct, or union).
2023   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2024
2025   typedef void *SkippedDefinitionContext;
2026
2027   /// \brief Invoked when we enter a tag definition that we're skipping.
2028   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2029
2030   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2031
2032   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2033   /// C++ record definition's base-specifiers clause and are starting its
2034   /// member declarations.
2035   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2036                                        SourceLocation FinalLoc,
2037                                        bool IsFinalSpelledSealed,
2038                                        SourceLocation LBraceLoc);
2039
2040   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2041   /// the definition of a tag (enumeration, class, struct, or union).
2042   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2043                                 SourceRange BraceRange);
2044
2045   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2046
2047   void ActOnObjCContainerFinishDefinition();
2048
2049   /// \brief Invoked when we must temporarily exit the objective-c container
2050   /// scope for parsing/looking-up C constructs.
2051   ///
2052   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2053   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2054   void ActOnObjCReenterContainerContext(DeclContext *DC);
2055
2056   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2057   /// error parsing the definition of a tag.
2058   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2059
2060   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2061                                       EnumConstantDecl *LastEnumConst,
2062                                       SourceLocation IdLoc,
2063                                       IdentifierInfo *Id,
2064                                       Expr *val);
2065   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2066   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2067                               QualType EnumUnderlyingTy,
2068                               bool EnumUnderlyingIsImplicit,
2069                               const EnumDecl *Prev);
2070
2071   /// Determine whether the body of an anonymous enumeration should be skipped.
2072   /// \param II The name of the first enumerator.
2073   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2074                                       SourceLocation IILoc);
2075
2076   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2077                           SourceLocation IdLoc, IdentifierInfo *Id,
2078                           AttributeList *Attrs,
2079                           SourceLocation EqualLoc, Expr *Val);
2080   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2081                      Decl *EnumDecl,
2082                      ArrayRef<Decl *> Elements,
2083                      Scope *S, AttributeList *Attr);
2084
2085   DeclContext *getContainingDC(DeclContext *DC);
2086
2087   /// Set the current declaration context until it gets popped.
2088   void PushDeclContext(Scope *S, DeclContext *DC);
2089   void PopDeclContext();
2090
2091   /// EnterDeclaratorContext - Used when we must lookup names in the context
2092   /// of a declarator's nested name specifier.
2093   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2094   void ExitDeclaratorContext(Scope *S);
2095
2096   /// Push the parameters of D, which must be a function, into scope.
2097   void ActOnReenterFunctionContext(Scope* S, Decl* D);
2098   void ActOnExitFunctionContext();
2099
2100   DeclContext *getFunctionLevelDeclContext();
2101
2102   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2103   /// to the function decl for the function being parsed.  If we're currently
2104   /// in a 'block', this returns the containing context.
2105   FunctionDecl *getCurFunctionDecl();
2106
2107   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2108   /// the method decl for the method being parsed.  If we're currently
2109   /// in a 'block', this returns the containing context.
2110   ObjCMethodDecl *getCurMethodDecl();
2111
2112   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2113   /// or C function we're in, otherwise return null.  If we're currently
2114   /// in a 'block', this returns the containing context.
2115   NamedDecl *getCurFunctionOrMethodDecl();
2116
2117   /// Add this decl to the scope shadowed decl chains.
2118   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2119
2120   /// \brief Make the given externally-produced declaration visible at the
2121   /// top level scope.
2122   ///
2123   /// \param D The externally-produced declaration to push.
2124   ///
2125   /// \param Name The name of the externally-produced declaration.
2126   void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2127
2128   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2129   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2130   /// true if 'D' belongs to the given declaration context.
2131   ///
2132   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2133   ///        enclosing namespace set of the context, rather than contained
2134   ///        directly within it.
2135   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2136                      bool AllowInlineNamespace = false);
2137
2138   /// Finds the scope corresponding to the given decl context, if it
2139   /// happens to be an enclosing scope.  Otherwise return NULL.
2140   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2141
2142   /// Subroutines of ActOnDeclarator().
2143   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2144                                 TypeSourceInfo *TInfo);
2145   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2146
2147   /// \brief Describes the kind of merge to perform for availability
2148   /// attributes (including "deprecated", "unavailable", and "availability").
2149   enum AvailabilityMergeKind {
2150     /// \brief Don't merge availability attributes at all.
2151     AMK_None,
2152     /// \brief Merge availability attributes for a redeclaration, which requires
2153     /// an exact match.
2154     AMK_Redeclaration,
2155     /// \brief Merge availability attributes for an override, which requires
2156     /// an exact match or a weakening of constraints.
2157     AMK_Override,
2158     /// \brief Merge availability attributes for an implementation of
2159     /// a protocol requirement.
2160     AMK_ProtocolImplementation,
2161   };
2162
2163   /// Attribute merging methods. Return true if a new attribute was added.
2164   AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2165                                           IdentifierInfo *Platform,
2166                                           bool Implicit,
2167                                           VersionTuple Introduced,
2168                                           VersionTuple Deprecated,
2169                                           VersionTuple Obsoleted,
2170                                           bool IsUnavailable,
2171                                           StringRef Message,
2172                                           bool IsStrict, StringRef Replacement,
2173                                           AvailabilityMergeKind AMK,
2174                                           unsigned AttrSpellingListIndex);
2175   TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2176                                        TypeVisibilityAttr::VisibilityType Vis,
2177                                               unsigned AttrSpellingListIndex);
2178   VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2179                                       VisibilityAttr::VisibilityType Vis,
2180                                       unsigned AttrSpellingListIndex);
2181   DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2182                                     unsigned AttrSpellingListIndex);
2183   DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2184                                     unsigned AttrSpellingListIndex);
2185   MSInheritanceAttr *
2186   mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2187                          unsigned AttrSpellingListIndex,
2188                          MSInheritanceAttr::Spelling SemanticSpelling);
2189   FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2190                               IdentifierInfo *Format, int FormatIdx,
2191                               int FirstArg, unsigned AttrSpellingListIndex);
2192   SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2193                                 unsigned AttrSpellingListIndex);
2194   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2195                                           IdentifierInfo *Ident,
2196                                           unsigned AttrSpellingListIndex);
2197   MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2198                                 unsigned AttrSpellingListIndex);
2199   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2200                                           unsigned AttrSpellingListIndex);
2201   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2202                                                 IdentifierInfo *Ident,
2203                                                 unsigned AttrSpellingListIndex);
2204   CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2205                               unsigned AttrSpellingListIndex);
2206
2207   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2208                            AvailabilityMergeKind AMK = AMK_Redeclaration);
2209   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2210                             LookupResult &OldDecls);
2211   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2212                          bool MergeTypeWithOld);
2213   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2214                                     Scope *S, bool MergeTypeWithOld);
2215   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2216   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2217   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2218   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2219   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2220
2221   // AssignmentAction - This is used by all the assignment diagnostic functions
2222   // to represent what is actually causing the operation
2223   enum AssignmentAction {
2224     AA_Assigning,
2225     AA_Passing,
2226     AA_Returning,
2227     AA_Converting,
2228     AA_Initializing,
2229     AA_Sending,
2230     AA_Casting,
2231     AA_Passing_CFAudited
2232   };
2233
2234   /// C++ Overloading.
2235   enum OverloadKind {
2236     /// This is a legitimate overload: the existing declarations are
2237     /// functions or function templates with different signatures.
2238     Ovl_Overload,
2239
2240     /// This is not an overload because the signature exactly matches
2241     /// an existing declaration.
2242     Ovl_Match,
2243
2244     /// This is not an overload because the lookup results contain a
2245     /// non-function.
2246     Ovl_NonFunction
2247   };
2248   OverloadKind CheckOverload(Scope *S,
2249                              FunctionDecl *New,
2250                              const LookupResult &OldDecls,
2251                              NamedDecl *&OldDecl,
2252                              bool IsForUsingDecl);
2253   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2254                   bool ConsiderCudaAttrs = true);
2255
2256   /// \brief Checks availability of the function depending on the current
2257   /// function context.Inside an unavailable function,unavailability is ignored.
2258   ///
2259   /// \returns true if \p FD is unavailable and current context is inside
2260   /// an available function, false otherwise.
2261   bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2262
2263   ImplicitConversionSequence
2264   TryImplicitConversion(Expr *From, QualType ToType,
2265                         bool SuppressUserConversions,
2266                         bool AllowExplicit,
2267                         bool InOverloadResolution,
2268                         bool CStyle,
2269                         bool AllowObjCWritebackConversion);
2270
2271   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2272   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2273   bool IsComplexPromotion(QualType FromType, QualType ToType);
2274   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2275                            bool InOverloadResolution,
2276                            QualType& ConvertedType, bool &IncompatibleObjC);
2277   bool isObjCPointerConversion(QualType FromType, QualType ToType,
2278                                QualType& ConvertedType, bool &IncompatibleObjC);
2279   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2280                                  QualType &ConvertedType);
2281   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2282                                 QualType& ConvertedType);
2283   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2284                                   const FunctionProtoType *NewType,
2285                                   unsigned *ArgPos = nullptr);
2286   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2287                                   QualType FromType, QualType ToType);
2288
2289   void maybeExtendBlockObject(ExprResult &E);
2290   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2291   bool CheckPointerConversion(Expr *From, QualType ToType,
2292                               CastKind &Kind,
2293                               CXXCastPath& BasePath,
2294                               bool IgnoreBaseAccess,
2295                               bool Diagnose = true);
2296   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2297                                  bool InOverloadResolution,
2298                                  QualType &ConvertedType);
2299   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2300                                     CastKind &Kind,
2301                                     CXXCastPath &BasePath,
2302                                     bool IgnoreBaseAccess);
2303   bool IsQualificationConversion(QualType FromType, QualType ToType,
2304                                  bool CStyle, bool &ObjCLifetimeConversion);
2305   bool IsNoReturnConversion(QualType FromType, QualType ToType,
2306                             QualType &ResultTy);
2307   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2308   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2309
2310   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2311                                              const VarDecl *NRVOCandidate,
2312                                              QualType ResultType,
2313                                              Expr *Value,
2314                                              bool AllowNRVO = true);
2315
2316   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2317                                     ExprResult Init);
2318   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2319                                        SourceLocation EqualLoc,
2320                                        ExprResult Init,
2321                                        bool TopLevelOfInitList = false,
2322                                        bool AllowExplicit = false);
2323   ExprResult PerformObjectArgumentInitialization(Expr *From,
2324                                                  NestedNameSpecifier *Qualifier,
2325                                                  NamedDecl *FoundDecl,
2326                                                  CXXMethodDecl *Method);
2327
2328   ExprResult PerformContextuallyConvertToBool(Expr *From);
2329   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2330
2331   /// Contexts in which a converted constant expression is required.
2332   enum CCEKind {
2333     CCEK_CaseValue,   ///< Expression in a case label.
2334     CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
2335     CCEK_TemplateArg, ///< Value of a non-type template parameter.
2336     CCEK_NewExpr,     ///< Constant expression in a noptr-new-declarator.
2337     CCEK_ConstexprIf  ///< Condition in a constexpr if statement.
2338   };
2339   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2340                                               llvm::APSInt &Value, CCEKind CCE);
2341   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2342                                               APValue &Value, CCEKind CCE);
2343
2344   /// \brief Abstract base class used to perform a contextual implicit
2345   /// conversion from an expression to any type passing a filter.
2346   class ContextualImplicitConverter {
2347   public:
2348     bool Suppress;
2349     bool SuppressConversion;
2350
2351     ContextualImplicitConverter(bool Suppress = false,
2352                                 bool SuppressConversion = false)
2353         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2354
2355     /// \brief Determine whether the specified type is a valid destination type
2356     /// for this conversion.
2357     virtual bool match(QualType T) = 0;
2358
2359     /// \brief Emits a diagnostic complaining that the expression does not have
2360     /// integral or enumeration type.
2361     virtual SemaDiagnosticBuilder
2362     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2363
2364     /// \brief Emits a diagnostic when the expression has incomplete class type.
2365     virtual SemaDiagnosticBuilder
2366     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2367
2368     /// \brief Emits a diagnostic when the only matching conversion function
2369     /// is explicit.
2370     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2371         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2372
2373     /// \brief Emits a note for the explicit conversion function.
2374     virtual SemaDiagnosticBuilder
2375     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2376
2377     /// \brief Emits a diagnostic when there are multiple possible conversion
2378     /// functions.
2379     virtual SemaDiagnosticBuilder
2380     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2381
2382     /// \brief Emits a note for one of the candidate conversions.
2383     virtual SemaDiagnosticBuilder
2384     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2385
2386     /// \brief Emits a diagnostic when we picked a conversion function
2387     /// (for cases when we are not allowed to pick a conversion function).
2388     virtual SemaDiagnosticBuilder diagnoseConversion(
2389         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2390
2391     virtual ~ContextualImplicitConverter() {}
2392   };
2393
2394   class ICEConvertDiagnoser : public ContextualImplicitConverter {
2395     bool AllowScopedEnumerations;
2396
2397   public:
2398     ICEConvertDiagnoser(bool AllowScopedEnumerations,
2399                         bool Suppress, bool SuppressConversion)
2400         : ContextualImplicitConverter(Suppress, SuppressConversion),
2401           AllowScopedEnumerations(AllowScopedEnumerations) {}
2402
2403     /// Match an integral or (possibly scoped) enumeration type.
2404     bool match(QualType T) override;
2405
2406     SemaDiagnosticBuilder
2407     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2408       return diagnoseNotInt(S, Loc, T);
2409     }
2410
2411     /// \brief Emits a diagnostic complaining that the expression does not have
2412     /// integral or enumeration type.
2413     virtual SemaDiagnosticBuilder
2414     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2415   };
2416
2417   /// Perform a contextual implicit conversion.
2418   ExprResult PerformContextualImplicitConversion(
2419       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2420
2421
2422   enum ObjCSubscriptKind {
2423     OS_Array,
2424     OS_Dictionary,
2425     OS_Error
2426   };
2427   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2428
2429   // Note that LK_String is intentionally after the other literals, as
2430   // this is used for diagnostics logic.
2431   enum ObjCLiteralKind {
2432     LK_Array,
2433     LK_Dictionary,
2434     LK_Numeric,
2435     LK_Boxed,
2436     LK_String,
2437     LK_Block,
2438     LK_None
2439   };
2440   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2441
2442   ExprResult PerformObjectMemberConversion(Expr *From,
2443                                            NestedNameSpecifier *Qualifier,
2444                                            NamedDecl *FoundDecl,
2445                                            NamedDecl *Member);
2446
2447   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2448   // TODO: make this is a typesafe union.
2449   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
2450   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2451
2452   void AddOverloadCandidate(FunctionDecl *Function,
2453                             DeclAccessPair FoundDecl,
2454                             ArrayRef<Expr *> Args,
2455                             OverloadCandidateSet& CandidateSet,
2456                             bool SuppressUserConversions = false,
2457                             bool PartialOverloading = false,
2458                             bool AllowExplicit = false);
2459   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2460                       ArrayRef<Expr *> Args,
2461                       OverloadCandidateSet &CandidateSet,
2462                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2463                       bool SuppressUserConversions = false,
2464                       bool PartialOverloading = false);
2465   void AddMethodCandidate(DeclAccessPair FoundDecl,
2466                           QualType ObjectType,
2467                           Expr::Classification ObjectClassification,
2468                           ArrayRef<Expr *> Args,
2469                           OverloadCandidateSet& CandidateSet,
2470                           bool SuppressUserConversion = false);
2471   void AddMethodCandidate(CXXMethodDecl *Method,
2472                           DeclAccessPair FoundDecl,
2473                           CXXRecordDecl *ActingContext, QualType ObjectType,
2474                           Expr::Classification ObjectClassification,
2475                           ArrayRef<Expr *> Args,
2476                           OverloadCandidateSet& CandidateSet,
2477                           bool SuppressUserConversions = false,
2478                           bool PartialOverloading = false);
2479   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2480                                   DeclAccessPair FoundDecl,
2481                                   CXXRecordDecl *ActingContext,
2482                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
2483                                   QualType ObjectType,
2484                                   Expr::Classification ObjectClassification,
2485                                   ArrayRef<Expr *> Args,
2486                                   OverloadCandidateSet& CandidateSet,
2487                                   bool SuppressUserConversions = false,
2488                                   bool PartialOverloading = false);
2489   void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2490                                     DeclAccessPair FoundDecl,
2491                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
2492                                     ArrayRef<Expr *> Args,
2493                                     OverloadCandidateSet& CandidateSet,
2494                                     bool SuppressUserConversions = false,
2495                                     bool PartialOverloading = false);
2496   void AddConversionCandidate(CXXConversionDecl *Conversion,
2497                               DeclAccessPair FoundDecl,
2498                               CXXRecordDecl *ActingContext,
2499                               Expr *From, QualType ToType,
2500                               OverloadCandidateSet& CandidateSet,
2501                               bool AllowObjCConversionOnExplicit);
2502   void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2503                                       DeclAccessPair FoundDecl,
2504                                       CXXRecordDecl *ActingContext,
2505                                       Expr *From, QualType ToType,
2506                                       OverloadCandidateSet &CandidateSet,
2507                                       bool AllowObjCConversionOnExplicit);
2508   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2509                              DeclAccessPair FoundDecl,
2510                              CXXRecordDecl *ActingContext,
2511                              const FunctionProtoType *Proto,
2512                              Expr *Object, ArrayRef<Expr *> Args,
2513                              OverloadCandidateSet& CandidateSet);
2514   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2515                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
2516                                    OverloadCandidateSet& CandidateSet,
2517                                    SourceRange OpRange = SourceRange());
2518   void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2519                            ArrayRef<Expr *> Args, 
2520                            OverloadCandidateSet& CandidateSet,
2521                            bool IsAssignmentOperator = false,
2522                            unsigned NumContextualBoolArguments = 0);
2523   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2524                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
2525                                     OverloadCandidateSet& CandidateSet);
2526   void AddArgumentDependentLookupCandidates(DeclarationName Name,
2527                                             SourceLocation Loc,
2528                                             ArrayRef<Expr *> Args,
2529                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2530                                             OverloadCandidateSet& CandidateSet,
2531                                             bool PartialOverloading = false);
2532
2533   // Emit as a 'note' the specific overload candidate
2534   void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2535                              QualType DestType = QualType(),
2536                              bool TakingAddress = false);
2537
2538   // Emit as a series of 'note's all template and non-templates identified by
2539   // the expression Expr
2540   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2541                                  bool TakingAddress = false);
2542
2543   /// Check the enable_if expressions on the given function. Returns the first
2544   /// failing attribute, or NULL if they were all successful.
2545   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2546                               bool MissingImplicitThis = false);
2547
2548   /// Returns whether the given function's address can be taken or not,
2549   /// optionally emitting a diagnostic if the address can't be taken.
2550   ///
2551   /// Returns false if taking the address of the function is illegal.
2552   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2553                                          bool Complain = false,
2554                                          SourceLocation Loc = SourceLocation());
2555
2556   // [PossiblyAFunctionType]  -->   [Return]
2557   // NonFunctionType --> NonFunctionType
2558   // R (A) --> R(A)
2559   // R (*)(A) --> R (A)
2560   // R (&)(A) --> R (A)
2561   // R (S::*)(A) --> R (A)
2562   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2563
2564   FunctionDecl *
2565   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2566                                      QualType TargetType,
2567                                      bool Complain,
2568                                      DeclAccessPair &Found,
2569                                      bool *pHadMultipleCandidates = nullptr);
2570
2571   FunctionDecl *
2572   resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2573                                               DeclAccessPair &FoundResult);
2574
2575   bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
2576
2577   FunctionDecl *
2578   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2579                                               bool Complain = false,
2580                                               DeclAccessPair *Found = nullptr);
2581
2582   bool ResolveAndFixSingleFunctionTemplateSpecialization(
2583                       ExprResult &SrcExpr,
2584                       bool DoFunctionPointerConverion = false,
2585                       bool Complain = false,
2586                       SourceRange OpRangeForComplaining = SourceRange(),
2587                       QualType DestTypeForComplaining = QualType(),
2588                       unsigned DiagIDForComplaining = 0);
2589
2590
2591   Expr *FixOverloadedFunctionReference(Expr *E,
2592                                        DeclAccessPair FoundDecl,
2593                                        FunctionDecl *Fn);
2594   ExprResult FixOverloadedFunctionReference(ExprResult,
2595                                             DeclAccessPair FoundDecl,
2596                                             FunctionDecl *Fn);
2597
2598   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2599                                    ArrayRef<Expr *> Args,
2600                                    OverloadCandidateSet &CandidateSet,
2601                                    bool PartialOverloading = false);
2602
2603   // An enum used to represent the different possible results of building a
2604   // range-based for loop.
2605   enum ForRangeStatus {
2606     FRS_Success,
2607     FRS_NoViableFunction,
2608     FRS_DiagnosticIssued
2609   };
2610
2611   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2612                                            SourceLocation RangeLoc,
2613                                            const DeclarationNameInfo &NameInfo,
2614                                            LookupResult &MemberLookup,
2615                                            OverloadCandidateSet *CandidateSet,
2616                                            Expr *Range, ExprResult *CallExpr);
2617
2618   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2619                                      UnresolvedLookupExpr *ULE,
2620                                      SourceLocation LParenLoc,
2621                                      MultiExprArg Args,
2622                                      SourceLocation RParenLoc,
2623                                      Expr *ExecConfig,
2624                                      bool AllowTypoCorrection=true,
2625                                      bool CalleesAddressIsTaken=false);
2626
2627   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2628                               MultiExprArg Args, SourceLocation RParenLoc,
2629                               OverloadCandidateSet *CandidateSet,
2630                               ExprResult *Result);
2631
2632   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2633                                      UnaryOperatorKind Opc,
2634                                      const UnresolvedSetImpl &Fns,
2635                                      Expr *input);
2636
2637   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2638                                    BinaryOperatorKind Opc,
2639                                    const UnresolvedSetImpl &Fns,
2640                                    Expr *LHS, Expr *RHS);
2641
2642   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2643                                                 SourceLocation RLoc,
2644                                                 Expr *Base,Expr *Idx);
2645
2646   ExprResult
2647   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2648                             SourceLocation LParenLoc,
2649                             MultiExprArg Args,
2650                             SourceLocation RParenLoc);
2651   ExprResult
2652   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2653                                MultiExprArg Args,
2654                                SourceLocation RParenLoc);
2655
2656   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2657                                       SourceLocation OpLoc,
2658                                       bool *NoArrowOperatorFound = nullptr);
2659
2660   /// CheckCallReturnType - Checks that a call expression's return type is
2661   /// complete. Returns true on failure. The location passed in is the location
2662   /// that best represents the call.
2663   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2664                            CallExpr *CE, FunctionDecl *FD);
2665
2666   /// Helpers for dealing with blocks and functions.
2667   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2668                                 bool CheckParameterNames);
2669   void CheckCXXDefaultArguments(FunctionDecl *FD);
2670   void CheckExtraCXXDefaultArguments(Declarator &D);
2671   Scope *getNonFieldDeclScope(Scope *S);
2672
2673   /// \name Name lookup
2674   ///
2675   /// These routines provide name lookup that is used during semantic
2676   /// analysis to resolve the various kinds of names (identifiers,
2677   /// overloaded operator names, constructor names, etc.) into zero or
2678   /// more declarations within a particular scope. The major entry
2679   /// points are LookupName, which performs unqualified name lookup,
2680   /// and LookupQualifiedName, which performs qualified name lookup.
2681   ///
2682   /// All name lookup is performed based on some specific criteria,
2683   /// which specify what names will be visible to name lookup and how
2684   /// far name lookup should work. These criteria are important both
2685   /// for capturing language semantics (certain lookups will ignore
2686   /// certain names, for example) and for performance, since name
2687   /// lookup is often a bottleneck in the compilation of C++. Name
2688   /// lookup criteria is specified via the LookupCriteria enumeration.
2689   ///
2690   /// The results of name lookup can vary based on the kind of name
2691   /// lookup performed, the current language, and the translation
2692   /// unit. In C, for example, name lookup will either return nothing
2693   /// (no entity found) or a single declaration. In C++, name lookup
2694   /// can additionally refer to a set of overloaded functions or
2695   /// result in an ambiguity. All of the possible results of name
2696   /// lookup are captured by the LookupResult class, which provides
2697   /// the ability to distinguish among them.
2698   //@{
2699
2700   /// @brief Describes the kind of name lookup to perform.
2701   enum LookupNameKind {
2702     /// Ordinary name lookup, which finds ordinary names (functions,
2703     /// variables, typedefs, etc.) in C and most kinds of names
2704     /// (functions, variables, members, types, etc.) in C++.
2705     LookupOrdinaryName = 0,
2706     /// Tag name lookup, which finds the names of enums, classes,
2707     /// structs, and unions.
2708     LookupTagName,
2709     /// Label name lookup.
2710     LookupLabel,
2711     /// Member name lookup, which finds the names of
2712     /// class/struct/union members.
2713     LookupMemberName,
2714     /// Look up of an operator name (e.g., operator+) for use with
2715     /// operator overloading. This lookup is similar to ordinary name
2716     /// lookup, but will ignore any declarations that are class members.
2717     LookupOperatorName,
2718     /// Look up of a name that precedes the '::' scope resolution
2719     /// operator in C++. This lookup completely ignores operator, object,
2720     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2721     LookupNestedNameSpecifierName,
2722     /// Look up a namespace name within a C++ using directive or
2723     /// namespace alias definition, ignoring non-namespace names (C++
2724     /// [basic.lookup.udir]p1).
2725     LookupNamespaceName,
2726     /// Look up all declarations in a scope with the given name,
2727     /// including resolved using declarations.  This is appropriate
2728     /// for checking redeclarations for a using declaration.
2729     LookupUsingDeclName,
2730     /// Look up an ordinary name that is going to be redeclared as a
2731     /// name with linkage. This lookup ignores any declarations that
2732     /// are outside of the current scope unless they have linkage. See
2733     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2734     LookupRedeclarationWithLinkage,
2735     /// Look up a friend of a local class. This lookup does not look
2736     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2737     LookupLocalFriendName,
2738     /// Look up the name of an Objective-C protocol.
2739     LookupObjCProtocolName,
2740     /// Look up implicit 'self' parameter of an objective-c method.
2741     LookupObjCImplicitSelfParam,
2742     /// \brief Look up the name of an OpenMP user-defined reduction operation.
2743     LookupOMPReductionName,
2744     /// \brief Look up any declaration with any name.
2745     LookupAnyName
2746   };
2747
2748   /// \brief Specifies whether (or how) name lookup is being performed for a
2749   /// redeclaration (vs. a reference).
2750   enum RedeclarationKind {
2751     /// \brief The lookup is a reference to this name that is not for the
2752     /// purpose of redeclaring the name.
2753     NotForRedeclaration = 0,
2754     /// \brief The lookup results will be used for redeclaration of a name,
2755     /// if an entity by that name already exists.
2756     ForRedeclaration
2757   };
2758
2759   /// \brief The possible outcomes of name lookup for a literal operator.
2760   enum LiteralOperatorLookupResult {
2761     /// \brief The lookup resulted in an error.
2762     LOLR_Error,
2763     /// \brief The lookup found a single 'cooked' literal operator, which
2764     /// expects a normal literal to be built and passed to it.
2765     LOLR_Cooked,
2766     /// \brief The lookup found a single 'raw' literal operator, which expects
2767     /// a string literal containing the spelling of the literal token.
2768     LOLR_Raw,
2769     /// \brief The lookup found an overload set of literal operator templates,
2770     /// which expect the characters of the spelling of the literal token to be
2771     /// passed as a non-type template argument pack.
2772     LOLR_Template,
2773     /// \brief The lookup found an overload set of literal operator templates,
2774     /// which expect the character type and characters of the spelling of the
2775     /// string literal token to be passed as template arguments.
2776     LOLR_StringTemplate
2777   };
2778
2779   SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2780                                                    CXXSpecialMember SM,
2781                                                    bool ConstArg,
2782                                                    bool VolatileArg,
2783                                                    bool RValueThis,
2784                                                    bool ConstThis,
2785                                                    bool VolatileThis);
2786
2787   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2788   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2789       TypoRecoveryCallback;
2790
2791 private:
2792   bool CppLookupName(LookupResult &R, Scope *S);
2793
2794   struct TypoExprState {
2795     std::unique_ptr<TypoCorrectionConsumer> Consumer;
2796     TypoDiagnosticGenerator DiagHandler;
2797     TypoRecoveryCallback RecoveryHandler;
2798     TypoExprState();
2799     TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
2800     TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
2801   };
2802
2803   /// \brief The set of unhandled TypoExprs and their associated state.
2804   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2805
2806   /// \brief Creates a new TypoExpr AST node.
2807   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2808                               TypoDiagnosticGenerator TDG,
2809                               TypoRecoveryCallback TRC);
2810
2811   // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2812   //
2813   // The boolean value will be true to indicate that the namespace was loaded
2814   // from an AST/PCH file, or false otherwise.
2815   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2816
2817   /// \brief Whether we have already loaded known namespaces from an extenal
2818   /// source.
2819   bool LoadedExternalKnownNamespaces;
2820
2821   /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2822   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2823   /// should be skipped entirely.
2824   std::unique_ptr<TypoCorrectionConsumer>
2825   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2826                              Sema::LookupNameKind LookupKind, Scope *S,
2827                              CXXScopeSpec *SS,
2828                              std::unique_ptr<CorrectionCandidateCallback> CCC,
2829                              DeclContext *MemberContext, bool EnteringContext,
2830                              const ObjCObjectPointerType *OPT,
2831                              bool ErrorRecovery);
2832
2833 public:
2834   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2835
2836   /// \brief Clears the state of the given TypoExpr.
2837   void clearDelayedTypo(TypoExpr *TE);
2838
2839   /// \brief Look up a name, looking for a single declaration.  Return
2840   /// null if the results were absent, ambiguous, or overloaded.
2841   ///
2842   /// It is preferable to use the elaborated form and explicitly handle
2843   /// ambiguity and overloaded.
2844   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2845                               SourceLocation Loc,
2846                               LookupNameKind NameKind,
2847                               RedeclarationKind Redecl
2848                                 = NotForRedeclaration);
2849   bool LookupName(LookupResult &R, Scope *S,
2850                   bool AllowBuiltinCreation = false);
2851   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2852                            bool InUnqualifiedLookup = false);
2853   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2854                            CXXScopeSpec &SS);
2855   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2856                         bool AllowBuiltinCreation = false,
2857                         bool EnteringContext = false);
2858   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2859                                    RedeclarationKind Redecl
2860                                      = NotForRedeclaration);
2861   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2862
2863   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2864                                     QualType T1, QualType T2,
2865                                     UnresolvedSetImpl &Functions);
2866   void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2867                                             DeclAccessPair Operator,
2868                                             QualType T1, QualType T2);
2869
2870   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2871                                  SourceLocation GnuLabelLoc = SourceLocation());
2872
2873   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2874   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2875   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2876                                                unsigned Quals);
2877   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2878                                          bool RValueThis, unsigned ThisQuals);
2879   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2880                                               unsigned Quals);
2881   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2882                                         bool RValueThis, unsigned ThisQuals);
2883   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2884
2885   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2886   LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2887                                                     ArrayRef<QualType> ArgTys,
2888                                                     bool AllowRaw,
2889                                                     bool AllowTemplate,
2890                                                     bool AllowStringTemplate);
2891   bool isKnownName(StringRef name);
2892
2893   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2894                                ArrayRef<Expr *> Args, ADLResult &Functions);
2895
2896   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2897                           VisibleDeclConsumer &Consumer,
2898                           bool IncludeGlobalScope = true);
2899   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2900                           VisibleDeclConsumer &Consumer,
2901                           bool IncludeGlobalScope = true);
2902
2903   enum CorrectTypoKind {
2904     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
2905     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2906   };
2907
2908   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2909                              Sema::LookupNameKind LookupKind,
2910                              Scope *S, CXXScopeSpec *SS,
2911                              std::unique_ptr<CorrectionCandidateCallback> CCC,
2912                              CorrectTypoKind Mode,
2913                              DeclContext *MemberContext = nullptr,
2914                              bool EnteringContext = false,
2915                              const ObjCObjectPointerType *OPT = nullptr,
2916                              bool RecordFailure = true);
2917
2918   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
2919                                Sema::LookupNameKind LookupKind, Scope *S,
2920                                CXXScopeSpec *SS,
2921                                std::unique_ptr<CorrectionCandidateCallback> CCC,
2922                                TypoDiagnosticGenerator TDG,
2923                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
2924                                DeclContext *MemberContext = nullptr,
2925                                bool EnteringContext = false,
2926                                const ObjCObjectPointerType *OPT = nullptr);
2927
2928   /// \brief Process any TypoExprs in the given Expr and its children,
2929   /// generating diagnostics as appropriate and returning a new Expr if there
2930   /// were typos that were all successfully corrected and ExprError if one or
2931   /// more typos could not be corrected.
2932   ///
2933   /// \param E The Expr to check for TypoExprs.
2934   ///
2935   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
2936   /// initializer.
2937   ///
2938   /// \param Filter A function applied to a newly rebuilt Expr to determine if
2939   /// it is an acceptable/usable result from a single combination of typo
2940   /// corrections. As long as the filter returns ExprError, different
2941   /// combinations of corrections will be tried until all are exhausted.
2942   ExprResult
2943   CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
2944                             llvm::function_ref<ExprResult(Expr *)> Filter =
2945                                 [](Expr *E) -> ExprResult { return E; });
2946
2947   ExprResult
2948   CorrectDelayedTyposInExpr(Expr *E,
2949                             llvm::function_ref<ExprResult(Expr *)> Filter) {
2950     return CorrectDelayedTyposInExpr(E, nullptr, Filter);
2951   }
2952
2953   ExprResult
2954   CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
2955                             llvm::function_ref<ExprResult(Expr *)> Filter =
2956                                 [](Expr *E) -> ExprResult { return E; }) {
2957     return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
2958   }
2959
2960   ExprResult
2961   CorrectDelayedTyposInExpr(ExprResult ER,
2962                             llvm::function_ref<ExprResult(Expr *)> Filter) {
2963     return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
2964   }
2965
2966   void diagnoseTypo(const TypoCorrection &Correction,
2967                     const PartialDiagnostic &TypoDiag,
2968                     bool ErrorRecovery = true);
2969
2970   void diagnoseTypo(const TypoCorrection &Correction,
2971                     const PartialDiagnostic &TypoDiag,
2972                     const PartialDiagnostic &PrevNote,
2973                     bool ErrorRecovery = true);
2974
2975   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2976                                           ArrayRef<Expr *> Args,
2977                                    AssociatedNamespaceSet &AssociatedNamespaces,
2978                                    AssociatedClassSet &AssociatedClasses);
2979
2980   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2981                             bool ConsiderLinkage, bool AllowInlineNamespace);
2982
2983   void DiagnoseAmbiguousLookup(LookupResult &Result);
2984   //@}
2985
2986   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2987                                           SourceLocation IdLoc,
2988                                           bool TypoCorrection = false);
2989   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2990                                  Scope *S, bool ForRedeclaration,
2991                                  SourceLocation Loc);
2992   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2993                                       Scope *S);
2994   void AddKnownFunctionAttributes(FunctionDecl *FD);
2995
2996   // More parsing and symbol table subroutines.
2997
2998   void ProcessPragmaWeak(Scope *S, Decl *D);
2999   // Decl attributes - this routine is the top level dispatcher.
3000   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3001   void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3002                                 bool IncludeCXX11Attributes = true);
3003   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3004                                       const AttributeList *AttrList);
3005
3006   void checkUnusedDeclAttributes(Declarator &D);
3007
3008   /// Determine if type T is a valid subject for a nonnull and similar
3009   /// attributes. By default, we look through references (the behavior used by
3010   /// nonnull), but if the second parameter is true, then we treat a reference
3011   /// type as valid.
3012   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3013
3014   bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3015   bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 
3016                             const FunctionDecl *FD = nullptr);
3017   bool CheckNoReturnAttr(const AttributeList &attr);
3018   bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3019                                       unsigned ArgNum, StringRef &Str,
3020                                       SourceLocation *ArgLocation = nullptr);
3021   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3022   void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3023   bool checkMSInheritanceAttrOnDefinition(
3024       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3025       MSInheritanceAttr::Spelling SemanticSpelling);
3026
3027   void CheckAlignasUnderalignment(Decl *D);
3028
3029   /// Adjust the calling convention of a method to be the ABI default if it
3030   /// wasn't specified explicitly.  This handles method types formed from
3031   /// function type typedefs and typename template arguments.
3032   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3033                               SourceLocation Loc);
3034
3035   // Check if there is an explicit attribute, but only look through parens.
3036   // The intent is to look for an attribute on the current declarator, but not
3037   // one that came from a typedef.
3038   bool hasExplicitCallingConv(QualType &T);
3039
3040   /// Get the outermost AttributedType node that sets a calling convention.
3041   /// Valid types should not have multiple attributes with different CCs.
3042   const AttributedType *getCallingConvAttributedType(QualType T) const;
3043
3044   /// Check whether a nullability type specifier can be added to the given
3045   /// type.
3046   ///
3047   /// \param type The type to which the nullability specifier will be
3048   /// added. On success, this type will be updated appropriately.
3049   ///
3050   /// \param nullability The nullability specifier to add.
3051   ///
3052   /// \param nullabilityLoc The location of the nullability specifier.
3053   ///
3054   /// \param isContextSensitive Whether this nullability specifier was
3055   /// written as a context-sensitive keyword (in an Objective-C
3056   /// method) or an Objective-C property attribute, rather than as an
3057   /// underscored type specifier.
3058   ///
3059   /// \returns true if nullability cannot be applied, false otherwise.
3060   bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3061                                      SourceLocation nullabilityLoc,
3062                                      bool isContextSensitive);
3063
3064   /// \brief Stmt attributes - this routine is the top level dispatcher.
3065   StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3066                                    SourceRange Range);
3067
3068   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3069                                    ObjCMethodDecl *MethodDecl,
3070                                    bool IsProtocolMethodDecl);
3071
3072   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3073                                    ObjCMethodDecl *Overridden,
3074                                    bool IsProtocolMethodDecl);
3075
3076   /// WarnExactTypedMethods - This routine issues a warning if method
3077   /// implementation declaration matches exactly that of its declaration.
3078   void WarnExactTypedMethods(ObjCMethodDecl *Method,
3079                              ObjCMethodDecl *MethodDecl,
3080                              bool IsProtocolMethodDecl);
3081
3082   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3083   typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
3084
3085   /// CheckImplementationIvars - This routine checks if the instance variables
3086   /// listed in the implelementation match those listed in the interface.
3087   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3088                                 ObjCIvarDecl **Fields, unsigned nIvars,
3089                                 SourceLocation Loc);
3090
3091   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3092   /// remains unimplemented in the class or category \@implementation.
3093   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3094                                  ObjCContainerDecl* IDecl,
3095                                  bool IncompleteImpl = false);
3096
3097   /// DiagnoseUnimplementedProperties - This routine warns on those properties
3098   /// which must be implemented by this implementation.
3099   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3100                                        ObjCContainerDecl *CDecl,
3101                                        bool SynthesizeProperties);
3102
3103   /// Diagnose any null-resettable synthesized setters.
3104   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3105
3106   /// DefaultSynthesizeProperties - This routine default synthesizes all
3107   /// properties which must be synthesized in the class's \@implementation.
3108   void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3109                                     ObjCInterfaceDecl *IDecl);
3110   void DefaultSynthesizeProperties(Scope *S, Decl *D);
3111
3112   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3113   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3114   /// declared in class 'IFace'.
3115   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3116                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3117   
3118   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3119   /// backs the property is not used in the property's accessor.
3120   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3121                                            const ObjCImplementationDecl *ImplD);
3122   
3123   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3124   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3125   /// It also returns ivar's property on success.
3126   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3127                                                const ObjCPropertyDecl *&PDecl) const;
3128   
3129   /// Called by ActOnProperty to handle \@property declarations in
3130   /// class extensions.
3131   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3132                       SourceLocation AtLoc,
3133                       SourceLocation LParenLoc,
3134                       FieldDeclarator &FD,
3135                       Selector GetterSel,
3136                       Selector SetterSel,
3137                       const bool isReadWrite,
3138                       unsigned &Attributes,
3139                       const unsigned AttributesAsWritten,
3140                       QualType T,
3141                       TypeSourceInfo *TSI,
3142                       tok::ObjCKeywordKind MethodImplKind);
3143
3144   /// Called by ActOnProperty and HandlePropertyInClassExtension to
3145   /// handle creating the ObjcPropertyDecl for a category or \@interface.
3146   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3147                                        ObjCContainerDecl *CDecl,
3148                                        SourceLocation AtLoc,
3149                                        SourceLocation LParenLoc,
3150                                        FieldDeclarator &FD,
3151                                        Selector GetterSel,
3152                                        Selector SetterSel,
3153                                        const bool isReadWrite,
3154                                        const unsigned Attributes,
3155                                        const unsigned AttributesAsWritten,
3156                                        QualType T,
3157                                        TypeSourceInfo *TSI,
3158                                        tok::ObjCKeywordKind MethodImplKind,
3159                                        DeclContext *lexicalDC = nullptr);
3160
3161   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3162   /// warning) when atomic property has one but not the other user-declared
3163   /// setter or getter.
3164   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3165                                        ObjCInterfaceDecl* IDecl);
3166
3167   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3168
3169   void DiagnoseMissingDesignatedInitOverrides(
3170                                           const ObjCImplementationDecl *ImplD,
3171                                           const ObjCInterfaceDecl *IFD);
3172
3173   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3174
3175   enum MethodMatchStrategy {
3176     MMS_loose,
3177     MMS_strict
3178   };
3179
3180   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3181   /// true, or false, accordingly.
3182   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3183                                   const ObjCMethodDecl *PrevMethod,
3184                                   MethodMatchStrategy strategy = MMS_strict);
3185
3186   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3187   /// or protocol against those declared in their implementations.
3188   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3189                                   const SelectorSet &ClsMap,
3190                                   SelectorSet &InsMapSeen,
3191                                   SelectorSet &ClsMapSeen,
3192                                   ObjCImplDecl* IMPDecl,
3193                                   ObjCContainerDecl* IDecl,
3194                                   bool &IncompleteImpl,
3195                                   bool ImmediateClass,
3196                                   bool WarnCategoryMethodImpl=false);
3197
3198   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3199   /// category matches with those implemented in its primary class and
3200   /// warns each time an exact match is found.
3201   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3202
3203   /// \brief Add the given method to the list of globally-known methods.
3204   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3205
3206 private:
3207   /// AddMethodToGlobalPool - Add an instance or factory method to the global
3208   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3209   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3210
3211   /// LookupMethodInGlobalPool - Returns the instance or factory method and
3212   /// optionally warns if there are multiple signatures.
3213   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3214                                            bool receiverIdOrClass,
3215                                            bool instance);
3216
3217 public:
3218   /// \brief - Returns instance or factory methods in global method pool for
3219   /// given selector. It checks the desired kind first, if none is found, and
3220   /// parameter checkTheOther is set, it then checks the other kind. If no such
3221   /// method or only one method is found, function returns false; otherwise, it
3222   /// returns true.
3223   bool
3224   CollectMultipleMethodsInGlobalPool(Selector Sel,
3225                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
3226                                      bool InstanceFirst, bool CheckTheOther,
3227                                      const ObjCObjectType *TypeBound = nullptr);
3228     
3229   bool
3230   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3231                                  SourceRange R, bool receiverIdOrClass,
3232                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
3233       
3234   void
3235   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3236                                      Selector Sel, SourceRange R,
3237                                      bool receiverIdOrClass);
3238
3239 private:
3240   /// \brief - Returns a selector which best matches given argument list or
3241   /// nullptr if none could be found
3242   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3243                                    bool IsInstance,
3244                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
3245     
3246
3247   /// \brief Record the typo correction failure and return an empty correction.
3248   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3249                                   bool RecordFailure = true) {
3250     if (RecordFailure)
3251       TypoCorrectionFailures[Typo].insert(TypoLoc);
3252     return TypoCorrection();
3253   }
3254
3255 public:
3256   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3257   /// unit are added to a global pool. This allows us to efficiently associate
3258   /// a selector with a method declaraation for purposes of typechecking
3259   /// messages sent to "id" (where the class of the object is unknown).
3260   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3261     AddMethodToGlobalPool(Method, impl, /*instance*/true);
3262   }
3263
3264   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3265   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3266     AddMethodToGlobalPool(Method, impl, /*instance*/false);
3267   }
3268
3269   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3270   /// pool.
3271   void AddAnyMethodToGlobalPool(Decl *D);
3272
3273   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3274   /// there are multiple signatures.
3275   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3276                                                    bool receiverIdOrClass=false) {
3277     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3278                                     /*instance*/true);
3279   }
3280
3281   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3282   /// there are multiple signatures.
3283   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3284                                                   bool receiverIdOrClass=false) {
3285     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3286                                     /*instance*/false);
3287   }
3288
3289   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3290                               QualType ObjectType=QualType());
3291   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3292   /// implementation.
3293   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3294
3295   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3296   /// initialization.
3297   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3298                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3299
3300   //===--------------------------------------------------------------------===//
3301   // Statement Parsing Callbacks: SemaStmt.cpp.
3302 public:
3303   class FullExprArg {
3304   public:
3305     FullExprArg() : E(nullptr) { }
3306     FullExprArg(Sema &actions) : E(nullptr) { }
3307
3308     ExprResult release() {
3309       return E;
3310     }
3311
3312     Expr *get() const { return E; }
3313
3314     Expr *operator->() {
3315       return E;
3316     }
3317
3318   private:
3319     // FIXME: No need to make the entire Sema class a friend when it's just
3320     // Sema::MakeFullExpr that needs access to the constructor below.
3321     friend class Sema;
3322
3323     explicit FullExprArg(Expr *expr) : E(expr) {}
3324
3325     Expr *E;
3326   };
3327
3328   FullExprArg MakeFullExpr(Expr *Arg) {
3329     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3330   }
3331   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3332     return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3333   }
3334   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3335     ExprResult FE =
3336       ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3337                           /*DiscardedValue*/ true);
3338     return FullExprArg(FE.get());
3339   }
3340
3341   StmtResult ActOnExprStmt(ExprResult Arg);
3342   StmtResult ActOnExprStmtError();
3343
3344   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3345                            bool HasLeadingEmptyMacro = false);
3346
3347   void ActOnStartOfCompoundStmt();
3348   void ActOnFinishOfCompoundStmt();
3349   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3350                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
3351
3352   /// \brief A RAII object to enter scope of a compound statement.
3353   class CompoundScopeRAII {
3354   public:
3355     CompoundScopeRAII(Sema &S): S(S) {
3356       S.ActOnStartOfCompoundStmt();
3357     }
3358
3359     ~CompoundScopeRAII() {
3360       S.ActOnFinishOfCompoundStmt();
3361     }
3362
3363   private:
3364     Sema &S;
3365   };
3366
3367   /// An RAII helper that pops function a function scope on exit.
3368   struct FunctionScopeRAII {
3369     Sema &S;
3370     bool Active;
3371     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3372     ~FunctionScopeRAII() {
3373       if (Active)
3374         S.PopFunctionScopeInfo();
3375     }
3376     void disable() { Active = false; }
3377   };
3378
3379   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3380                                    SourceLocation StartLoc,
3381                                    SourceLocation EndLoc);
3382   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3383   StmtResult ActOnForEachLValueExpr(Expr *E);
3384   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3385                                    SourceLocation DotDotDotLoc, Expr *RHSVal,
3386                                    SourceLocation ColonLoc);
3387   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3388
3389   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3390                                       SourceLocation ColonLoc,
3391                                       Stmt *SubStmt, Scope *CurScope);
3392   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3393                             SourceLocation ColonLoc, Stmt *SubStmt);
3394
3395   StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3396                                  ArrayRef<const Attr*> Attrs,
3397                                  Stmt *SubStmt);
3398
3399   class ConditionResult;
3400   StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3401                          Stmt *InitStmt,
3402                          ConditionResult Cond, Stmt *ThenVal,
3403                          SourceLocation ElseLoc, Stmt *ElseVal);
3404   StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3405                          Stmt *InitStmt,
3406                          ConditionResult Cond, Stmt *ThenVal,
3407                          SourceLocation ElseLoc, Stmt *ElseVal);
3408   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3409                                     Stmt *InitStmt,
3410                                     ConditionResult Cond);
3411   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3412                                            Stmt *Switch, Stmt *Body);
3413   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3414                             Stmt *Body);
3415   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3416                          SourceLocation WhileLoc, SourceLocation CondLParen,
3417                          Expr *Cond, SourceLocation CondRParen);
3418
3419   StmtResult ActOnForStmt(SourceLocation ForLoc,
3420                           SourceLocation LParenLoc,
3421                           Stmt *First,
3422                           ConditionResult Second,
3423                           FullExprArg Third,
3424                           SourceLocation RParenLoc,
3425                           Stmt *Body);
3426   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3427                                            Expr *collection);
3428   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3429                                         Stmt *First, Expr *collection,
3430                                         SourceLocation RParenLoc);
3431   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3432
3433   enum BuildForRangeKind {
3434     /// Initial building of a for-range statement.
3435     BFRK_Build,
3436     /// Instantiation or recovery rebuild of a for-range statement. Don't
3437     /// attempt any typo-correction.
3438     BFRK_Rebuild,
3439     /// Determining whether a for-range statement could be built. Avoid any
3440     /// unnecessary or irreversible actions.
3441     BFRK_Check
3442   };
3443
3444   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3445                                   SourceLocation CoawaitLoc,
3446                                   Stmt *LoopVar,
3447                                   SourceLocation ColonLoc, Expr *Collection,
3448                                   SourceLocation RParenLoc,
3449                                   BuildForRangeKind Kind);
3450   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3451                                   SourceLocation CoawaitLoc,
3452                                   SourceLocation ColonLoc,
3453                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3454                                   Expr *Cond, Expr *Inc,
3455                                   Stmt *LoopVarDecl,
3456                                   SourceLocation RParenLoc,
3457                                   BuildForRangeKind Kind);
3458   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3459
3460   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3461                            SourceLocation LabelLoc,
3462                            LabelDecl *TheDecl);
3463   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3464                                    SourceLocation StarLoc,
3465                                    Expr *DestExp);
3466   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3467   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3468
3469   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3470                                 CapturedRegionKind Kind, unsigned NumParams);
3471   typedef std::pair<StringRef, QualType> CapturedParamNameType;
3472   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3473                                 CapturedRegionKind Kind,
3474                                 ArrayRef<CapturedParamNameType> Params);
3475   StmtResult ActOnCapturedRegionEnd(Stmt *S);
3476   void ActOnCapturedRegionError();
3477   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3478                                            SourceLocation Loc,
3479                                            unsigned NumParams);
3480   VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3481                                    bool AllowParamOrMoveConstructible);
3482   bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3483                               bool AllowParamOrMoveConstructible);
3484
3485   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3486                              Scope *CurScope);
3487   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3488   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3489
3490   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3491                              bool IsVolatile, unsigned NumOutputs,
3492                              unsigned NumInputs, IdentifierInfo **Names,
3493                              MultiExprArg Constraints, MultiExprArg Exprs,
3494                              Expr *AsmString, MultiExprArg Clobbers,
3495                              SourceLocation RParenLoc);
3496
3497   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3498                                        SourceLocation TemplateKWLoc,
3499                                        UnqualifiedId &Id,
3500                                        llvm::InlineAsmIdentifierInfo &Info,
3501                                        bool IsUnevaluatedContext);
3502   bool LookupInlineAsmField(StringRef Base, StringRef Member,
3503                             unsigned &Offset, SourceLocation AsmLoc);
3504   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3505                                          llvm::InlineAsmIdentifierInfo &Info,
3506                                          SourceLocation AsmLoc);
3507   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3508                             ArrayRef<Token> AsmToks,
3509                             StringRef AsmString,
3510                             unsigned NumOutputs, unsigned NumInputs,
3511                             ArrayRef<StringRef> Constraints,
3512                             ArrayRef<StringRef> Clobbers,
3513                             ArrayRef<Expr*> Exprs,
3514                             SourceLocation EndLoc);
3515   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3516                                    SourceLocation Location,
3517                                    bool AlwaysCreate);
3518
3519   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3520                                   SourceLocation StartLoc,
3521                                   SourceLocation IdLoc, IdentifierInfo *Id,
3522                                   bool Invalid = false);
3523
3524   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3525
3526   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3527                                   Decl *Parm, Stmt *Body);
3528
3529   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3530
3531   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3532                                 MultiStmtArg Catch, Stmt *Finally);
3533
3534   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3535   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3536                                   Scope *CurScope);
3537   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3538                                             Expr *operand);
3539   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3540                                          Expr *SynchExpr,
3541                                          Stmt *SynchBody);
3542
3543   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3544
3545   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3546                                      SourceLocation StartLoc,
3547                                      SourceLocation IdLoc,
3548                                      IdentifierInfo *Id);
3549
3550   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3551
3552   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3553                                 Decl *ExDecl, Stmt *HandlerBlock);
3554   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3555                               ArrayRef<Stmt *> Handlers);
3556
3557   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3558                               SourceLocation TryLoc, Stmt *TryBlock,
3559                               Stmt *Handler);
3560   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3561                                  Expr *FilterExpr,
3562                                  Stmt *Block);
3563   void ActOnStartSEHFinallyBlock();
3564   void ActOnAbortSEHFinallyBlock();
3565   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3566   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3567
3568   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3569
3570   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3571
3572   /// \brief If it's a file scoped decl that must warn if not used, keep track
3573   /// of it.
3574   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3575
3576   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3577   /// whose result is unused, warn.
3578   void DiagnoseUnusedExprResult(const Stmt *S);
3579   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3580   void DiagnoseUnusedDecl(const NamedDecl *ND);
3581
3582   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3583   /// statement as a \p Body, and it is located on the same line.
3584   ///
3585   /// This helps prevent bugs due to typos, such as:
3586   ///     if (condition);
3587   ///       do_stuff();
3588   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3589                              const Stmt *Body,
3590                              unsigned DiagID);
3591
3592   /// Warn if a for/while loop statement \p S, which is followed by
3593   /// \p PossibleBody, has a suspicious null statement as a body.
3594   void DiagnoseEmptyLoopBody(const Stmt *S,
3595                              const Stmt *PossibleBody);
3596
3597   /// Warn if a value is moved to itself.
3598   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3599                         SourceLocation OpLoc);
3600
3601   /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3602   /// _Nonnull one.
3603   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3604                                            SourceLocation Loc);
3605
3606   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3607     return DelayedDiagnostics.push(pool);
3608   }
3609   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3610
3611   typedef ProcessingContextState ParsingClassState;
3612   ParsingClassState PushParsingClass() {
3613     return DelayedDiagnostics.pushUndelayed();
3614   }
3615   void PopParsingClass(ParsingClassState state) {
3616     DelayedDiagnostics.popUndelayed(state);
3617   }
3618
3619   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3620
3621   enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
3622
3623   void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
3624                                NamedDecl *D, StringRef Message,
3625                                SourceLocation Loc,
3626                                const ObjCInterfaceDecl *UnknownObjCClass,
3627                                const ObjCPropertyDecl  *ObjCProperty,
3628                                bool ObjCPropertyAccess);
3629
3630   bool makeUnavailableInSystemHeader(SourceLocation loc,
3631                                      UnavailableAttr::ImplicitReason reason);
3632
3633   //===--------------------------------------------------------------------===//
3634   // Expression Parsing Callbacks: SemaExpr.cpp.
3635
3636   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3637   bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3638                          const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3639                          bool ObjCPropertyAccess=false);
3640   void NoteDeletedFunction(FunctionDecl *FD);
3641   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3642   std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3643   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3644                                         ObjCMethodDecl *Getter,
3645                                         SourceLocation Loc);
3646   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3647                              ArrayRef<Expr *> Args);
3648
3649   void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3650                                        Decl *LambdaContextDecl = nullptr,
3651                                        bool IsDecltype = false);
3652   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3653   void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3654                                        ReuseLambdaContextDecl_t,
3655                                        bool IsDecltype = false);
3656   void PopExpressionEvaluationContext();
3657
3658   void DiscardCleanupsInEvaluationContext();
3659
3660   ExprResult TransformToPotentiallyEvaluated(Expr *E);
3661   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3662
3663   ExprResult ActOnConstantExpression(ExprResult Res);
3664
3665   // Functions for marking a declaration referenced.  These functions also
3666   // contain the relevant logic for marking if a reference to a function or
3667   // variable is an odr-use (in the C++11 sense).  There are separate variants
3668   // for expressions referring to a decl; these exist because odr-use marking
3669   // needs to be delayed for some constant variables when we build one of the
3670   // named expressions.
3671   //
3672   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3673   // should usually be true. This only needs to be set to false if the lack of
3674   // odr-use cannot be determined from the current context (for instance,
3675   // because the name denotes a virtual function and was written without an
3676   // explicit nested-name-specifier).
3677   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3678   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3679                               bool MightBeOdrUse = true);
3680   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3681   void MarkDeclRefReferenced(DeclRefExpr *E);
3682   void MarkMemberReferenced(MemberExpr *E);
3683
3684   void UpdateMarkingForLValueToRValue(Expr *E);
3685   void CleanupVarDeclMarking();
3686
3687   enum TryCaptureKind {
3688     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3689   };
3690
3691   /// \brief Try to capture the given variable.
3692   ///
3693   /// \param Var The variable to capture.
3694   ///
3695   /// \param Loc The location at which the capture occurs.
3696   ///
3697   /// \param Kind The kind of capture, which may be implicit (for either a
3698   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3699   ///
3700   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3701   /// an explicit lambda capture.
3702   ///
3703   /// \param BuildAndDiagnose Whether we are actually supposed to add the
3704   /// captures or diagnose errors. If false, this routine merely check whether
3705   /// the capture can occur without performing the capture itself or complaining
3706   /// if the variable cannot be captured.
3707   ///
3708   /// \param CaptureType Will be set to the type of the field used to capture
3709   /// this variable in the innermost block or lambda. Only valid when the
3710   /// variable can be captured.
3711   ///
3712   /// \param DeclRefType Will be set to the type of a reference to the capture
3713   /// from within the current scope. Only valid when the variable can be
3714   /// captured.
3715   ///
3716   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3717   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3718   /// This is useful when enclosing lambdas must speculatively capture 
3719   /// variables that may or may not be used in certain specializations of
3720   /// a nested generic lambda.
3721   /// 
3722   /// \returns true if an error occurred (i.e., the variable cannot be
3723   /// captured) and false if the capture succeeded.
3724   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3725                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3726                           QualType &CaptureType,
3727                           QualType &DeclRefType, 
3728                           const unsigned *const FunctionScopeIndexToStopAt);
3729
3730   /// \brief Try to capture the given variable.
3731   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3732                           TryCaptureKind Kind = TryCapture_Implicit,
3733                           SourceLocation EllipsisLoc = SourceLocation());
3734
3735   /// \brief Checks if the variable must be captured.
3736   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3737
3738   /// \brief Given a variable, determine the type that a reference to that
3739   /// variable will have in the given scope.
3740   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3741
3742   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3743   void MarkDeclarationsReferencedInExpr(Expr *E,
3744                                         bool SkipLocalVariables = false);
3745
3746   /// \brief Try to recover by turning the given expression into a
3747   /// call.  Returns true if recovery was attempted or an error was
3748   /// emitted; this may also leave the ExprResult invalid.
3749   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3750                             bool ForceComplain = false,
3751                             bool (*IsPlausibleResult)(QualType) = nullptr);
3752
3753   /// \brief Figure out if an expression could be turned into a call.
3754   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3755                      UnresolvedSetImpl &NonTemplateOverloads);
3756
3757   /// \brief Conditionally issue a diagnostic based on the current
3758   /// evaluation context.
3759   ///
3760   /// \param Statement If Statement is non-null, delay reporting the
3761   /// diagnostic until the function body is parsed, and then do a basic
3762   /// reachability analysis to determine if the statement is reachable.
3763   /// If it is unreachable, the diagnostic will not be emitted.
3764   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3765                            const PartialDiagnostic &PD);
3766
3767   // Primary Expressions.
3768   SourceRange getExprRange(Expr *E) const;
3769
3770   ExprResult ActOnIdExpression(
3771       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3772       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3773       std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3774       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3775
3776   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3777                               TemplateArgumentListInfo &Buffer,
3778                               DeclarationNameInfo &NameInfo,
3779                               const TemplateArgumentListInfo *&TemplateArgs);
3780
3781   bool
3782   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3783                       std::unique_ptr<CorrectionCandidateCallback> CCC,
3784                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3785                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3786
3787   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3788                                 IdentifierInfo *II,
3789                                 bool AllowBuiltinCreation=false);
3790
3791   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3792                                         SourceLocation TemplateKWLoc,
3793                                         const DeclarationNameInfo &NameInfo,
3794                                         bool isAddressOfOperand,
3795                                 const TemplateArgumentListInfo *TemplateArgs);
3796
3797   ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3798                               ExprValueKind VK,
3799                               SourceLocation Loc,
3800                               const CXXScopeSpec *SS = nullptr);
3801   ExprResult
3802   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3803                    const DeclarationNameInfo &NameInfo,
3804                    const CXXScopeSpec *SS = nullptr,
3805                    NamedDecl *FoundD = nullptr,
3806                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
3807   ExprResult
3808   BuildAnonymousStructUnionMemberReference(
3809       const CXXScopeSpec &SS,
3810       SourceLocation nameLoc,
3811       IndirectFieldDecl *indirectField,
3812       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3813       Expr *baseObjectExpr = nullptr,
3814       SourceLocation opLoc = SourceLocation());
3815
3816   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3817                                              SourceLocation TemplateKWLoc,
3818                                              LookupResult &R,
3819                                 const TemplateArgumentListInfo *TemplateArgs,
3820                                              const Scope *S);
3821   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3822                                      SourceLocation TemplateKWLoc,
3823                                      LookupResult &R,
3824                                 const TemplateArgumentListInfo *TemplateArgs,
3825                                      bool IsDefiniteInstance,
3826                                      const Scope *S);
3827   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3828                                   const LookupResult &R,
3829                                   bool HasTrailingLParen);
3830
3831   ExprResult
3832   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3833                                     const DeclarationNameInfo &NameInfo,
3834                                     bool IsAddressOfOperand, const Scope *S,
3835                                     TypeSourceInfo **RecoveryTSI = nullptr);
3836
3837   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3838                                        SourceLocation TemplateKWLoc,
3839                                 const DeclarationNameInfo &NameInfo,
3840                                 const TemplateArgumentListInfo *TemplateArgs);
3841
3842   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3843                                       LookupResult &R,
3844                                       bool NeedsADL,
3845                                       bool AcceptInvalidDecl = false);
3846   ExprResult BuildDeclarationNameExpr(
3847       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3848       NamedDecl *FoundD = nullptr,
3849       const TemplateArgumentListInfo *TemplateArgs = nullptr,
3850       bool AcceptInvalidDecl = false);
3851
3852   ExprResult BuildLiteralOperatorCall(LookupResult &R,
3853                       DeclarationNameInfo &SuffixInfo,
3854                       ArrayRef<Expr *> Args,
3855                       SourceLocation LitEndLoc,
3856                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3857
3858   ExprResult BuildPredefinedExpr(SourceLocation Loc,
3859                                  PredefinedExpr::IdentType IT);
3860   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3861   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3862
3863   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
3864
3865   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3866   ExprResult ActOnCharacterConstant(const Token &Tok,
3867                                     Scope *UDLScope = nullptr);
3868   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3869   ExprResult ActOnParenListExpr(SourceLocation L,
3870                                 SourceLocation R,
3871                                 MultiExprArg Val);
3872
3873   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3874   /// fragments (e.g. "foo" "bar" L"baz").
3875   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3876                                 Scope *UDLScope = nullptr);
3877
3878   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3879                                        SourceLocation DefaultLoc,
3880                                        SourceLocation RParenLoc,
3881                                        Expr *ControllingExpr,
3882                                        ArrayRef<ParsedType> ArgTypes,
3883                                        ArrayRef<Expr *> ArgExprs);
3884   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3885                                         SourceLocation DefaultLoc,
3886                                         SourceLocation RParenLoc,
3887                                         Expr *ControllingExpr,
3888                                         ArrayRef<TypeSourceInfo *> Types,
3889                                         ArrayRef<Expr *> Exprs);
3890
3891   // Binary/Unary Operators.  'Tok' is the token for the operator.
3892   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3893                                   Expr *InputExpr);
3894   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3895                           UnaryOperatorKind Opc, Expr *Input);
3896   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3897                           tok::TokenKind Op, Expr *Input);
3898
3899   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3900
3901   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3902                                             SourceLocation OpLoc,
3903                                             UnaryExprOrTypeTrait ExprKind,
3904                                             SourceRange R);
3905   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3906                                             UnaryExprOrTypeTrait ExprKind);
3907   ExprResult
3908     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3909                                   UnaryExprOrTypeTrait ExprKind,
3910                                   bool IsType, void *TyOrEx,
3911                                   SourceRange ArgRange);
3912
3913   ExprResult CheckPlaceholderExpr(Expr *E);
3914   bool CheckVecStepExpr(Expr *E);
3915
3916   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3917   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3918                                         SourceRange ExprRange,
3919                                         UnaryExprOrTypeTrait ExprKind);
3920   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3921                                           SourceLocation OpLoc,
3922                                           IdentifierInfo &Name,
3923                                           SourceLocation NameLoc,
3924                                           SourceLocation RParenLoc);
3925   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3926                                  tok::TokenKind Kind, Expr *Input);
3927
3928   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3929                                      Expr *Idx, SourceLocation RLoc);
3930   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3931                                              Expr *Idx, SourceLocation RLoc);
3932   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
3933                                       Expr *LowerBound, SourceLocation ColonLoc,
3934                                       Expr *Length, SourceLocation RBLoc);
3935
3936   // This struct is for use by ActOnMemberAccess to allow
3937   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3938   // changing the access operator from a '.' to a '->' (to see if that is the
3939   // change needed to fix an error about an unknown member, e.g. when the class
3940   // defines a custom operator->).
3941   struct ActOnMemberAccessExtraArgs {
3942     Scope *S;
3943     UnqualifiedId &Id;
3944     Decl *ObjCImpDecl;
3945   };
3946
3947   ExprResult BuildMemberReferenceExpr(
3948       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
3949       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3950       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
3951       const TemplateArgumentListInfo *TemplateArgs,
3952       const Scope *S,
3953       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3954
3955   ExprResult
3956   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
3957                            bool IsArrow, const CXXScopeSpec &SS,
3958                            SourceLocation TemplateKWLoc,
3959                            NamedDecl *FirstQualifierInScope, LookupResult &R,
3960                            const TemplateArgumentListInfo *TemplateArgs,
3961                            const Scope *S,
3962                            bool SuppressQualifierCheck = false,
3963                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3964
3965   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3966
3967   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3968                                      const CXXScopeSpec &SS,
3969                                      const LookupResult &R);
3970
3971   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3972                                       bool IsArrow, SourceLocation OpLoc,
3973                                       const CXXScopeSpec &SS,
3974                                       SourceLocation TemplateKWLoc,
3975                                       NamedDecl *FirstQualifierInScope,
3976                                const DeclarationNameInfo &NameInfo,
3977                                const TemplateArgumentListInfo *TemplateArgs);
3978
3979   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3980                                    SourceLocation OpLoc,
3981                                    tok::TokenKind OpKind,
3982                                    CXXScopeSpec &SS,
3983                                    SourceLocation TemplateKWLoc,
3984                                    UnqualifiedId &Member,
3985                                    Decl *ObjCImpDecl);
3986
3987   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3988   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3989                                FunctionDecl *FDecl,
3990                                const FunctionProtoType *Proto,
3991                                ArrayRef<Expr *> Args,
3992                                SourceLocation RParenLoc,
3993                                bool ExecConfig = false);
3994   void CheckStaticArrayArgument(SourceLocation CallLoc,
3995                                 ParmVarDecl *Param,
3996                                 const Expr *ArgExpr);
3997
3998   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3999   /// This provides the location of the left/right parens and a list of comma
4000   /// locations.
4001   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4002                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
4003                            Expr *ExecConfig = nullptr,
4004                            bool IsExecConfig = false);
4005   ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4006                                    SourceLocation LParenLoc,
4007                                    ArrayRef<Expr *> Arg,
4008                                    SourceLocation RParenLoc,
4009                                    Expr *Config = nullptr,
4010                                    bool IsExecConfig = false);
4011
4012   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4013                                      MultiExprArg ExecConfig,
4014                                      SourceLocation GGGLoc);
4015
4016   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4017                            Declarator &D, ParsedType &Ty,
4018                            SourceLocation RParenLoc, Expr *CastExpr);
4019   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4020                                  TypeSourceInfo *Ty,
4021                                  SourceLocation RParenLoc,
4022                                  Expr *Op);
4023   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4024
4025   /// \brief Build an altivec or OpenCL literal.
4026   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4027                                 SourceLocation RParenLoc, Expr *E,
4028                                 TypeSourceInfo *TInfo);
4029
4030   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4031
4032   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4033                                   ParsedType Ty,
4034                                   SourceLocation RParenLoc,
4035                                   Expr *InitExpr);
4036
4037   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4038                                       TypeSourceInfo *TInfo,
4039                                       SourceLocation RParenLoc,
4040                                       Expr *LiteralExpr);
4041
4042   ExprResult ActOnInitList(SourceLocation LBraceLoc,
4043                            MultiExprArg InitArgList,
4044                            SourceLocation RBraceLoc);
4045
4046   ExprResult ActOnDesignatedInitializer(Designation &Desig,
4047                                         SourceLocation Loc,
4048                                         bool GNUSyntax,
4049                                         ExprResult Init);
4050
4051 private:
4052   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4053
4054 public:
4055   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4056                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4057   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4058                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4059   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4060                                 Expr *LHSExpr, Expr *RHSExpr);
4061
4062   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4063
4064   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4065   /// in the case of a the GNU conditional expr extension.
4066   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4067                                 SourceLocation ColonLoc,
4068                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4069
4070   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4071   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4072                             LabelDecl *TheDecl);
4073
4074   void ActOnStartStmtExpr();
4075   ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4076                            SourceLocation RPLoc); // "({..})"
4077   void ActOnStmtExprError();
4078
4079   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4080   struct OffsetOfComponent {
4081     SourceLocation LocStart, LocEnd;
4082     bool isBrackets;  // true if [expr], false if .ident
4083     union {
4084       IdentifierInfo *IdentInfo;
4085       Expr *E;
4086     } U;
4087   };
4088
4089   /// __builtin_offsetof(type, a.b[123][456].c)
4090   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4091                                   TypeSourceInfo *TInfo,
4092                                   ArrayRef<OffsetOfComponent> Components,
4093                                   SourceLocation RParenLoc);
4094   ExprResult ActOnBuiltinOffsetOf(Scope *S,
4095                                   SourceLocation BuiltinLoc,
4096                                   SourceLocation TypeLoc,
4097                                   ParsedType ParsedArgTy,
4098                                   ArrayRef<OffsetOfComponent> Components,
4099                                   SourceLocation RParenLoc);
4100
4101   // __builtin_choose_expr(constExpr, expr1, expr2)
4102   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4103                              Expr *CondExpr, Expr *LHSExpr,
4104                              Expr *RHSExpr, SourceLocation RPLoc);
4105
4106   // __builtin_va_arg(expr, type)
4107   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4108                         SourceLocation RPLoc);
4109   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4110                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
4111
4112   // __null
4113   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4114
4115   bool CheckCaseExpression(Expr *E);
4116
4117   /// \brief Describes the result of an "if-exists" condition check.
4118   enum IfExistsResult {
4119     /// \brief The symbol exists.
4120     IER_Exists,
4121
4122     /// \brief The symbol does not exist.
4123     IER_DoesNotExist,
4124
4125     /// \brief The name is a dependent name, so the results will differ
4126     /// from one instantiation to the next.
4127     IER_Dependent,
4128
4129     /// \brief An error occurred.
4130     IER_Error
4131   };
4132
4133   IfExistsResult
4134   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4135                                const DeclarationNameInfo &TargetNameInfo);
4136
4137   IfExistsResult
4138   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4139                                bool IsIfExists, CXXScopeSpec &SS,
4140                                UnqualifiedId &Name);
4141
4142   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4143                                         bool IsIfExists,
4144                                         NestedNameSpecifierLoc QualifierLoc,
4145                                         DeclarationNameInfo NameInfo,
4146                                         Stmt *Nested);
4147   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4148                                         bool IsIfExists,
4149                                         CXXScopeSpec &SS, UnqualifiedId &Name,
4150                                         Stmt *Nested);
4151
4152   //===------------------------- "Block" Extension ------------------------===//
4153
4154   /// ActOnBlockStart - This callback is invoked when a block literal is
4155   /// started.
4156   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4157
4158   /// ActOnBlockArguments - This callback allows processing of block arguments.
4159   /// If there are no arguments, this is still invoked.
4160   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4161                            Scope *CurScope);
4162
4163   /// ActOnBlockError - If there is an error parsing a block, this callback
4164   /// is invoked to pop the information about the block from the action impl.
4165   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4166
4167   /// ActOnBlockStmtExpr - This is called when the body of a block statement
4168   /// literal was successfully completed.  ^(int x){...}
4169   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4170                                 Scope *CurScope);
4171
4172   //===---------------------------- Clang Extensions ----------------------===//
4173
4174   /// __builtin_convertvector(...)
4175   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4176                                     SourceLocation BuiltinLoc,
4177                                     SourceLocation RParenLoc);
4178
4179   //===---------------------------- OpenCL Features -----------------------===//
4180
4181   /// __builtin_astype(...)
4182   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4183                              SourceLocation BuiltinLoc,
4184                              SourceLocation RParenLoc);
4185
4186   //===---------------------------- C++ Features --------------------------===//
4187
4188   // Act on C++ namespaces
4189   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4190                                SourceLocation NamespaceLoc,
4191                                SourceLocation IdentLoc,
4192                                IdentifierInfo *Ident,
4193                                SourceLocation LBrace,
4194                                AttributeList *AttrList,
4195                                UsingDirectiveDecl * &UsingDecl);
4196   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4197
4198   NamespaceDecl *getStdNamespace() const;
4199   NamespaceDecl *getOrCreateStdNamespace();
4200
4201   CXXRecordDecl *getStdBadAlloc() const;
4202
4203   /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4204   /// it is and Element is not NULL, assigns the element type to Element.
4205   bool isStdInitializerList(QualType Ty, QualType *Element);
4206
4207   /// \brief Looks for the std::initializer_list template and instantiates it
4208   /// with Element, or emits an error if it's not found.
4209   ///
4210   /// \returns The instantiated template, or null on error.
4211   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4212
4213   /// \brief Determine whether Ctor is an initializer-list constructor, as
4214   /// defined in [dcl.init.list]p2.
4215   bool isInitListConstructor(const CXXConstructorDecl *Ctor);
4216
4217   Decl *ActOnUsingDirective(Scope *CurScope,
4218                             SourceLocation UsingLoc,
4219                             SourceLocation NamespcLoc,
4220                             CXXScopeSpec &SS,
4221                             SourceLocation IdentLoc,
4222                             IdentifierInfo *NamespcName,
4223                             AttributeList *AttrList);
4224
4225   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4226
4227   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4228                                SourceLocation NamespaceLoc,
4229                                SourceLocation AliasLoc,
4230                                IdentifierInfo *Alias,
4231                                CXXScopeSpec &SS,
4232                                SourceLocation IdentLoc,
4233                                IdentifierInfo *Ident);
4234
4235   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4236   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4237                             const LookupResult &PreviousDecls,
4238                             UsingShadowDecl *&PrevShadow);
4239   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4240                                         NamedDecl *Target,
4241                                         UsingShadowDecl *PrevDecl);
4242
4243   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4244                                    bool HasTypenameKeyword,
4245                                    const CXXScopeSpec &SS,
4246                                    SourceLocation NameLoc,
4247                                    const LookupResult &Previous);
4248   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4249                                const CXXScopeSpec &SS,
4250                                const DeclarationNameInfo &NameInfo,
4251                                SourceLocation NameLoc);
4252
4253   NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4254                                    SourceLocation UsingLoc,
4255                                    CXXScopeSpec &SS,
4256                                    DeclarationNameInfo NameInfo,
4257                                    AttributeList *AttrList,
4258                                    bool IsInstantiation,
4259                                    bool HasTypenameKeyword,
4260                                    SourceLocation TypenameLoc);
4261
4262   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4263
4264   /// Given a derived-class using shadow declaration for a constructor and the
4265   /// correspnding base class constructor, find or create the implicit
4266   /// synthesized derived class constructor to use for this initialization.
4267   CXXConstructorDecl *
4268   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4269                             ConstructorUsingShadowDecl *DerivedShadow);
4270
4271   Decl *ActOnUsingDeclaration(Scope *CurScope,
4272                               AccessSpecifier AS,
4273                               bool HasUsingKeyword,
4274                               SourceLocation UsingLoc,
4275                               CXXScopeSpec &SS,
4276                               UnqualifiedId &Name,
4277                               AttributeList *AttrList,
4278                               bool HasTypenameKeyword,
4279                               SourceLocation TypenameLoc);
4280   Decl *ActOnAliasDeclaration(Scope *CurScope,
4281                               AccessSpecifier AS,
4282                               MultiTemplateParamsArg TemplateParams,
4283                               SourceLocation UsingLoc,
4284                               UnqualifiedId &Name,
4285                               AttributeList *AttrList,
4286                               TypeResult Type,
4287                               Decl *DeclFromDeclSpec);
4288
4289   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4290   /// including handling of its default argument expressions.
4291   ///
4292   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4293   ExprResult
4294   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4295                         NamedDecl *FoundDecl,
4296                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4297                         bool HadMultipleCandidates, bool IsListInitialization,
4298                         bool IsStdInitListInitialization,
4299                         bool RequiresZeroInit, unsigned ConstructKind,
4300                         SourceRange ParenRange);
4301
4302   /// Build a CXXConstructExpr whose constructor has already been resolved if
4303   /// it denotes an inherited constructor.
4304   ExprResult
4305   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4306                         CXXConstructorDecl *Constructor, bool Elidable,
4307                         MultiExprArg Exprs,
4308                         bool HadMultipleCandidates, bool IsListInitialization,
4309                         bool IsStdInitListInitialization,
4310                         bool RequiresZeroInit, unsigned ConstructKind,
4311                         SourceRange ParenRange);
4312
4313   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4314   // the constructor can be elidable?
4315   ExprResult
4316   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4317                         NamedDecl *FoundDecl,
4318                         CXXConstructorDecl *Constructor, bool Elidable,
4319                         MultiExprArg Exprs, bool HadMultipleCandidates,
4320                         bool IsListInitialization,
4321                         bool IsStdInitListInitialization, bool RequiresZeroInit,
4322                         unsigned ConstructKind, SourceRange ParenRange);
4323
4324   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4325
4326   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4327   /// the default expr if needed.
4328   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4329                                     FunctionDecl *FD,
4330                                     ParmVarDecl *Param);
4331
4332   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4333   /// constructed variable.
4334   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4335
4336   /// \brief Helper class that collects exception specifications for
4337   /// implicitly-declared special member functions.
4338   class ImplicitExceptionSpecification {
4339     // Pointer to allow copying
4340     Sema *Self;
4341     // We order exception specifications thus:
4342     // noexcept is the most restrictive, but is only used in C++11.
4343     // throw() comes next.
4344     // Then a throw(collected exceptions)
4345     // Finally no specification, which is expressed as noexcept(false).
4346     // throw(...) is used instead if any called function uses it.
4347     ExceptionSpecificationType ComputedEST;
4348     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4349     SmallVector<QualType, 4> Exceptions;
4350
4351     void ClearExceptions() {
4352       ExceptionsSeen.clear();
4353       Exceptions.clear();
4354     }
4355
4356   public:
4357     explicit ImplicitExceptionSpecification(Sema &Self)
4358       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4359       if (!Self.getLangOpts().CPlusPlus11)
4360         ComputedEST = EST_DynamicNone;
4361     }
4362
4363     /// \brief Get the computed exception specification type.
4364     ExceptionSpecificationType getExceptionSpecType() const {
4365       assert(ComputedEST != EST_ComputedNoexcept &&
4366              "noexcept(expr) should not be a possible result");
4367       return ComputedEST;
4368     }
4369
4370     /// \brief The number of exceptions in the exception specification.
4371     unsigned size() const { return Exceptions.size(); }
4372
4373     /// \brief The set of exceptions in the exception specification.
4374     const QualType *data() const { return Exceptions.data(); }
4375
4376     /// \brief Integrate another called method into the collected data.
4377     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4378
4379     /// \brief Integrate an invoked expression into the collected data.
4380     void CalledExpr(Expr *E);
4381
4382     /// \brief Overwrite an EPI's exception specification with this
4383     /// computed exception specification.
4384     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4385       FunctionProtoType::ExceptionSpecInfo ESI;
4386       ESI.Type = getExceptionSpecType();
4387       if (ESI.Type == EST_Dynamic) {
4388         ESI.Exceptions = Exceptions;
4389       } else if (ESI.Type == EST_None) {
4390         /// C++11 [except.spec]p14:
4391         ///   The exception-specification is noexcept(false) if the set of
4392         ///   potential exceptions of the special member function contains "any"
4393         ESI.Type = EST_ComputedNoexcept;
4394         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4395                                                      tok::kw_false).get();
4396       }
4397       return ESI;
4398     }
4399   };
4400
4401   /// \brief Determine what sort of exception specification a defaulted
4402   /// copy constructor of a class will have.
4403   ImplicitExceptionSpecification
4404   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4405                                            CXXMethodDecl *MD);
4406
4407   /// \brief Determine what sort of exception specification a defaulted
4408   /// default constructor of a class will have, and whether the parameter
4409   /// will be const.
4410   ImplicitExceptionSpecification
4411   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4412
4413   /// \brief Determine what sort of exception specification a defautled
4414   /// copy assignment operator of a class will have, and whether the
4415   /// parameter will be const.
4416   ImplicitExceptionSpecification
4417   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4418
4419   /// \brief Determine what sort of exception specification a defaulted move
4420   /// constructor of a class will have.
4421   ImplicitExceptionSpecification
4422   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4423
4424   /// \brief Determine what sort of exception specification a defaulted move
4425   /// assignment operator of a class will have.
4426   ImplicitExceptionSpecification
4427   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4428
4429   /// \brief Determine what sort of exception specification a defaulted
4430   /// destructor of a class will have.
4431   ImplicitExceptionSpecification
4432   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4433
4434   /// \brief Determine what sort of exception specification an inheriting
4435   /// constructor of a class will have.
4436   ImplicitExceptionSpecification
4437   ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4438                                      CXXConstructorDecl *CD);
4439
4440   /// \brief Evaluate the implicit exception specification for a defaulted
4441   /// special member function.
4442   void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4443
4444   /// \brief Check the given exception-specification and update the
4445   /// exception specification information with the results.
4446   void checkExceptionSpecification(bool IsTopLevel,
4447                                    ExceptionSpecificationType EST,
4448                                    ArrayRef<ParsedType> DynamicExceptions,
4449                                    ArrayRef<SourceRange> DynamicExceptionRanges,
4450                                    Expr *NoexceptExpr,
4451                                    SmallVectorImpl<QualType> &Exceptions,
4452                                    FunctionProtoType::ExceptionSpecInfo &ESI);
4453
4454   /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4455   /// parse an exception specification to work around a libstdc++ bug.
4456   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4457
4458   /// \brief Add an exception-specification to the given member function
4459   /// (or member function template). The exception-specification was parsed
4460   /// after the method itself was declared.
4461   void actOnDelayedExceptionSpecification(Decl *Method,
4462          ExceptionSpecificationType EST,
4463          SourceRange SpecificationRange,
4464          ArrayRef<ParsedType> DynamicExceptions,
4465          ArrayRef<SourceRange> DynamicExceptionRanges,
4466          Expr *NoexceptExpr);
4467
4468   class InheritedConstructorInfo;
4469
4470   /// \brief Determine if a special member function should have a deleted
4471   /// definition when it is defaulted.
4472   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4473                                  InheritedConstructorInfo *ICI = nullptr,
4474                                  bool Diagnose = false);
4475
4476   /// \brief Declare the implicit default constructor for the given class.
4477   ///
4478   /// \param ClassDecl The class declaration into which the implicit
4479   /// default constructor will be added.
4480   ///
4481   /// \returns The implicitly-declared default constructor.
4482   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4483                                                      CXXRecordDecl *ClassDecl);
4484
4485   /// DefineImplicitDefaultConstructor - Checks for feasibility of
4486   /// defining this constructor as the default constructor.
4487   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4488                                         CXXConstructorDecl *Constructor);
4489
4490   /// \brief Declare the implicit destructor for the given class.
4491   ///
4492   /// \param ClassDecl The class declaration into which the implicit
4493   /// destructor will be added.
4494   ///
4495   /// \returns The implicitly-declared destructor.
4496   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4497
4498   /// DefineImplicitDestructor - Checks for feasibility of
4499   /// defining this destructor as the default destructor.
4500   void DefineImplicitDestructor(SourceLocation CurrentLocation,
4501                                 CXXDestructorDecl *Destructor);
4502
4503   /// \brief Build an exception spec for destructors that don't have one.
4504   ///
4505   /// C++11 says that user-defined destructors with no exception spec get one
4506   /// that looks as if the destructor was implicitly declared.
4507   void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4508                                      CXXDestructorDecl *Destructor);
4509
4510   /// \brief Define the specified inheriting constructor.
4511   void DefineInheritingConstructor(SourceLocation UseLoc,
4512                                    CXXConstructorDecl *Constructor);
4513
4514   /// \brief Declare the implicit copy constructor for the given class.
4515   ///
4516   /// \param ClassDecl The class declaration into which the implicit
4517   /// copy constructor will be added.
4518   ///
4519   /// \returns The implicitly-declared copy constructor.
4520   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4521
4522   /// DefineImplicitCopyConstructor - Checks for feasibility of
4523   /// defining this constructor as the copy constructor.
4524   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4525                                      CXXConstructorDecl *Constructor);
4526
4527   /// \brief Declare the implicit move constructor for the given class.
4528   ///
4529   /// \param ClassDecl The Class declaration into which the implicit
4530   /// move constructor will be added.
4531   ///
4532   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4533   /// declared.
4534   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4535
4536   /// DefineImplicitMoveConstructor - Checks for feasibility of
4537   /// defining this constructor as the move constructor.
4538   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4539                                      CXXConstructorDecl *Constructor);
4540
4541   /// \brief Declare the implicit copy assignment operator for the given class.
4542   ///
4543   /// \param ClassDecl The class declaration into which the implicit
4544   /// copy assignment operator will be added.
4545   ///
4546   /// \returns The implicitly-declared copy assignment operator.
4547   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4548
4549   /// \brief Defines an implicitly-declared copy assignment operator.
4550   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4551                                     CXXMethodDecl *MethodDecl);
4552
4553   /// \brief Declare the implicit move assignment operator for the given class.
4554   ///
4555   /// \param ClassDecl The Class declaration into which the implicit
4556   /// move assignment operator will be added.
4557   ///
4558   /// \returns The implicitly-declared move assignment operator, or NULL if it
4559   /// wasn't declared.
4560   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4561
4562   /// \brief Defines an implicitly-declared move assignment operator.
4563   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4564                                     CXXMethodDecl *MethodDecl);
4565
4566   /// \brief Force the declaration of any implicitly-declared members of this
4567   /// class.
4568   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4569
4570   /// \brief Check a completed declaration of an implicit special member.
4571   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4572
4573   /// \brief Determine whether the given function is an implicitly-deleted
4574   /// special member function.
4575   bool isImplicitlyDeleted(FunctionDecl *FD);
4576
4577   /// \brief Check whether 'this' shows up in the type of a static member
4578   /// function after the (naturally empty) cv-qualifier-seq would be.
4579   ///
4580   /// \returns true if an error occurred.
4581   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4582
4583   /// \brief Whether this' shows up in the exception specification of a static
4584   /// member function.
4585   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4586
4587   /// \brief Check whether 'this' shows up in the attributes of the given
4588   /// static member function.
4589   ///
4590   /// \returns true if an error occurred.
4591   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4592
4593   /// MaybeBindToTemporary - If the passed in expression has a record type with
4594   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4595   /// it simply returns the passed in expression.
4596   ExprResult MaybeBindToTemporary(Expr *E);
4597
4598   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4599                                MultiExprArg ArgsPtr,
4600                                SourceLocation Loc,
4601                                SmallVectorImpl<Expr*> &ConvertedArgs,
4602                                bool AllowExplicit = false,
4603                                bool IsListInitialization = false);
4604
4605   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4606                                           SourceLocation NameLoc,
4607                                           IdentifierInfo &Name);
4608
4609   ParsedType getDestructorName(SourceLocation TildeLoc,
4610                                IdentifierInfo &II, SourceLocation NameLoc,
4611                                Scope *S, CXXScopeSpec &SS,
4612                                ParsedType ObjectType,
4613                                bool EnteringContext);
4614
4615   ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4616
4617   // Checks that reinterpret casts don't have undefined behavior.
4618   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4619                                       bool IsDereference, SourceRange Range);
4620
4621   /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4622   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4623                                tok::TokenKind Kind,
4624                                SourceLocation LAngleBracketLoc,
4625                                Declarator &D,
4626                                SourceLocation RAngleBracketLoc,
4627                                SourceLocation LParenLoc,
4628                                Expr *E,
4629                                SourceLocation RParenLoc);
4630
4631   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4632                                tok::TokenKind Kind,
4633                                TypeSourceInfo *Ty,
4634                                Expr *E,
4635                                SourceRange AngleBrackets,
4636                                SourceRange Parens);
4637
4638   ExprResult BuildCXXTypeId(QualType TypeInfoType,
4639                             SourceLocation TypeidLoc,
4640                             TypeSourceInfo *Operand,
4641                             SourceLocation RParenLoc);
4642   ExprResult BuildCXXTypeId(QualType TypeInfoType,
4643                             SourceLocation TypeidLoc,
4644                             Expr *Operand,
4645                             SourceLocation RParenLoc);
4646
4647   /// ActOnCXXTypeid - Parse typeid( something ).
4648   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4649                             SourceLocation LParenLoc, bool isType,
4650                             void *TyOrExpr,
4651                             SourceLocation RParenLoc);
4652
4653   ExprResult BuildCXXUuidof(QualType TypeInfoType,
4654                             SourceLocation TypeidLoc,
4655                             TypeSourceInfo *Operand,
4656                             SourceLocation RParenLoc);
4657   ExprResult BuildCXXUuidof(QualType TypeInfoType,
4658                             SourceLocation TypeidLoc,
4659                             Expr *Operand,
4660                             SourceLocation RParenLoc);
4661
4662   /// ActOnCXXUuidof - Parse __uuidof( something ).
4663   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4664                             SourceLocation LParenLoc, bool isType,
4665                             void *TyOrExpr,
4666                             SourceLocation RParenLoc);
4667
4668   /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4669   ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4670                               tok::TokenKind Operator,
4671                               SourceLocation EllipsisLoc, Expr *RHS,
4672                               SourceLocation RParenLoc);
4673   ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4674                               BinaryOperatorKind Operator,
4675                               SourceLocation EllipsisLoc, Expr *RHS,
4676                               SourceLocation RParenLoc);
4677   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4678                                    BinaryOperatorKind Operator);
4679
4680   //// ActOnCXXThis -  Parse 'this' pointer.
4681   ExprResult ActOnCXXThis(SourceLocation loc);
4682
4683   /// \brief Try to retrieve the type of the 'this' pointer.
4684   ///
4685   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4686   QualType getCurrentThisType();
4687
4688   /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4689   /// current context not being a non-static member function. In such cases,
4690   /// this provides the type used for 'this'.
4691   QualType CXXThisTypeOverride;
4692
4693   /// \brief RAII object used to temporarily allow the C++ 'this' expression
4694   /// to be used, with the given qualifiers on the current class type.
4695   class CXXThisScopeRAII {
4696     Sema &S;
4697     QualType OldCXXThisTypeOverride;
4698     bool Enabled;
4699
4700   public:
4701     /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4702     /// using the given declaration (which is either a class template or a
4703     /// class) along with the given qualifiers.
4704     /// along with the qualifiers placed on '*this'.
4705     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4706                      bool Enabled = true);
4707
4708     ~CXXThisScopeRAII();
4709   };
4710
4711   /// \brief Make sure the value of 'this' is actually available in the current
4712   /// context, if it is a potentially evaluated context.
4713   ///
4714   /// \param Loc The location at which the capture of 'this' occurs.
4715   ///
4716   /// \param Explicit Whether 'this' is explicitly captured in a lambda
4717   /// capture list.
4718   ///
4719   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4720   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4721   /// This is useful when enclosing lambdas must speculatively capture 
4722   /// 'this' that may or may not be used in certain specializations of
4723   /// a nested generic lambda (depending on whether the name resolves to 
4724   /// a non-static member function or a static function).
4725   /// \return returns 'true' if failed, 'false' if success.
4726   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, 
4727       bool BuildAndDiagnose = true,
4728       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4729       bool ByCopy = false);
4730
4731   /// \brief Determine whether the given type is the type of *this that is used
4732   /// outside of the body of a member function for a type that is currently
4733   /// being defined.
4734   bool isThisOutsideMemberFunctionBody(QualType BaseType);
4735
4736   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4737   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4738
4739
4740   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4741   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4742
4743   ExprResult
4744   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4745                                  SourceLocation AtLoc, SourceLocation RParen);
4746
4747   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4748   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4749
4750   //// ActOnCXXThrow -  Parse throw expressions.
4751   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4752   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4753                            bool IsThrownVarInScope);
4754   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4755
4756   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4757   /// Can be interpreted either as function-style casting ("int(x)")
4758   /// or class type construction ("ClassType(x,y,z)")
4759   /// or creation of a value-initialized type ("int()").
4760   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4761                                        SourceLocation LParenLoc,
4762                                        MultiExprArg Exprs,
4763                                        SourceLocation RParenLoc);
4764
4765   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4766                                        SourceLocation LParenLoc,
4767                                        MultiExprArg Exprs,
4768                                        SourceLocation RParenLoc);
4769
4770   /// ActOnCXXNew - Parsed a C++ 'new' expression.
4771   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4772                          SourceLocation PlacementLParen,
4773                          MultiExprArg PlacementArgs,
4774                          SourceLocation PlacementRParen,
4775                          SourceRange TypeIdParens, Declarator &D,
4776                          Expr *Initializer);
4777   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4778                          SourceLocation PlacementLParen,
4779                          MultiExprArg PlacementArgs,
4780                          SourceLocation PlacementRParen,
4781                          SourceRange TypeIdParens,
4782                          QualType AllocType,
4783                          TypeSourceInfo *AllocTypeInfo,
4784                          Expr *ArraySize,
4785                          SourceRange DirectInitRange,
4786                          Expr *Initializer,
4787                          bool TypeMayContainAuto = true);
4788
4789   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4790                           SourceRange R);
4791   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4792                                bool UseGlobal, QualType AllocType, bool IsArray,
4793                                MultiExprArg PlaceArgs,
4794                                FunctionDecl *&OperatorNew,
4795                                FunctionDecl *&OperatorDelete);
4796   bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4797                               DeclarationName Name, MultiExprArg Args,
4798                               DeclContext *Ctx,
4799                               bool AllowMissing, FunctionDecl *&Operator,
4800                               bool Diagnose = true);
4801   void DeclareGlobalNewDelete();
4802   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4803                                        QualType Param1,
4804                                        QualType Param2 = QualType());
4805
4806   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4807                                 DeclarationName Name, FunctionDecl* &Operator,
4808                                 bool Diagnose = true);
4809   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4810                                               bool CanProvideSize,
4811                                               DeclarationName Name);
4812
4813   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4814   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4815                             bool UseGlobal, bool ArrayForm,
4816                             Expr *Operand);
4817   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4818                             bool IsDelete, bool CallCanBeVirtual,
4819                             bool WarnOnNonAbstractTypes,
4820                             SourceLocation DtorLoc);
4821
4822   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4823                                Expr *Operand, SourceLocation RParen);
4824   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4825                                   SourceLocation RParen);
4826
4827   /// \brief Parsed one of the type trait support pseudo-functions.
4828   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4829                             ArrayRef<ParsedType> Args,
4830                             SourceLocation RParenLoc);
4831   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4832                             ArrayRef<TypeSourceInfo *> Args,
4833                             SourceLocation RParenLoc);
4834
4835   /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4836   /// pseudo-functions.
4837   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4838                                  SourceLocation KWLoc,
4839                                  ParsedType LhsTy,
4840                                  Expr *DimExpr,
4841                                  SourceLocation RParen);
4842
4843   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4844                                  SourceLocation KWLoc,
4845                                  TypeSourceInfo *TSInfo,
4846                                  Expr *DimExpr,
4847                                  SourceLocation RParen);
4848
4849   /// ActOnExpressionTrait - Parsed one of the unary type trait support
4850   /// pseudo-functions.
4851   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4852                                   SourceLocation KWLoc,
4853                                   Expr *Queried,
4854                                   SourceLocation RParen);
4855
4856   ExprResult BuildExpressionTrait(ExpressionTrait OET,
4857                                   SourceLocation KWLoc,
4858                                   Expr *Queried,
4859                                   SourceLocation RParen);
4860
4861   ExprResult ActOnStartCXXMemberReference(Scope *S,
4862                                           Expr *Base,
4863                                           SourceLocation OpLoc,
4864                                           tok::TokenKind OpKind,
4865                                           ParsedType &ObjectType,
4866                                           bool &MayBePseudoDestructor);
4867
4868   ExprResult BuildPseudoDestructorExpr(Expr *Base,
4869                                        SourceLocation OpLoc,
4870                                        tok::TokenKind OpKind,
4871                                        const CXXScopeSpec &SS,
4872                                        TypeSourceInfo *ScopeType,
4873                                        SourceLocation CCLoc,
4874                                        SourceLocation TildeLoc,
4875                                      PseudoDestructorTypeStorage DestroyedType);
4876
4877   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4878                                        SourceLocation OpLoc,
4879                                        tok::TokenKind OpKind,
4880                                        CXXScopeSpec &SS,
4881                                        UnqualifiedId &FirstTypeName,
4882                                        SourceLocation CCLoc,
4883                                        SourceLocation TildeLoc,
4884                                        UnqualifiedId &SecondTypeName);
4885
4886   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4887                                        SourceLocation OpLoc,
4888                                        tok::TokenKind OpKind,
4889                                        SourceLocation TildeLoc,
4890                                        const DeclSpec& DS);
4891
4892   /// MaybeCreateExprWithCleanups - If the current full-expression
4893   /// requires any cleanups, surround it with a ExprWithCleanups node.
4894   /// Otherwise, just returns the passed-in expression.
4895   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4896   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4897   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4898
4899   MaterializeTemporaryExpr *
4900   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
4901                                  bool BoundToLvalueReference);
4902
4903   ExprResult ActOnFinishFullExpr(Expr *Expr) {
4904     return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4905                                           : SourceLocation());
4906   }
4907   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4908                                  bool DiscardedValue = false,
4909                                  bool IsConstexpr = false,
4910                                  bool IsLambdaInitCaptureInitializer = false);
4911   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4912
4913   // Marks SS invalid if it represents an incomplete type.
4914   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4915
4916   DeclContext *computeDeclContext(QualType T);
4917   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4918                                   bool EnteringContext = false);
4919   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4920   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4921
4922   /// \brief The parser has parsed a global nested-name-specifier '::'.
4923   ///
4924   /// \param CCLoc The location of the '::'.
4925   ///
4926   /// \param SS The nested-name-specifier, which will be updated in-place
4927   /// to reflect the parsed nested-name-specifier.
4928   ///
4929   /// \returns true if an error occurred, false otherwise.
4930   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
4931
4932   /// \brief The parser has parsed a '__super' nested-name-specifier.
4933   ///
4934   /// \param SuperLoc The location of the '__super' keyword.
4935   ///
4936   /// \param ColonColonLoc The location of the '::'.
4937   ///
4938   /// \param SS The nested-name-specifier, which will be updated in-place
4939   /// to reflect the parsed nested-name-specifier.
4940   ///
4941   /// \returns true if an error occurred, false otherwise.
4942   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
4943                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
4944
4945   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
4946                                        bool *CanCorrect = nullptr);
4947   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4948
4949   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4950                                     SourceLocation IdLoc,
4951                                     IdentifierInfo &II,
4952                                     ParsedType ObjectType);
4953
4954   bool BuildCXXNestedNameSpecifier(Scope *S,
4955                                    IdentifierInfo &Identifier,
4956                                    SourceLocation IdentifierLoc,
4957                                    SourceLocation CCLoc,
4958                                    QualType ObjectType,
4959                                    bool EnteringContext,
4960                                    CXXScopeSpec &SS,
4961                                    NamedDecl *ScopeLookupResult,
4962                                    bool ErrorRecoveryLookup,
4963                                    bool *IsCorrectedToColon = nullptr);
4964
4965   /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4966   ///
4967   /// \param S The scope in which this nested-name-specifier occurs.
4968   ///
4969   /// \param Identifier The identifier preceding the '::'.
4970   ///
4971   /// \param IdentifierLoc The location of the identifier.
4972   ///
4973   /// \param CCLoc The location of the '::'.
4974   ///
4975   /// \param ObjectType The type of the object, if we're parsing
4976   /// nested-name-specifier in a member access expression.
4977   ///
4978   /// \param EnteringContext Whether we're entering the context nominated by
4979   /// this nested-name-specifier.
4980   ///
4981   /// \param SS The nested-name-specifier, which is both an input
4982   /// parameter (the nested-name-specifier before this type) and an
4983   /// output parameter (containing the full nested-name-specifier,
4984   /// including this new type).
4985   ///
4986   /// \param ErrorRecoveryLookup If true, then this method is called to improve
4987   /// error recovery. In this case do not emit error message.
4988   ///
4989   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
4990   /// are allowed.  The bool value pointed by this parameter is set to 'true'
4991   /// if the identifier is treated as if it was followed by ':', not '::'.
4992   ///
4993   /// \returns true if an error occurred, false otherwise.
4994   bool ActOnCXXNestedNameSpecifier(Scope *S,
4995                                    IdentifierInfo &Identifier,
4996                                    SourceLocation IdentifierLoc,
4997                                    SourceLocation CCLoc,
4998                                    ParsedType ObjectType,
4999                                    bool EnteringContext,
5000                                    CXXScopeSpec &SS,
5001                                    bool ErrorRecoveryLookup = false,
5002                                    bool *IsCorrectedToColon = nullptr);
5003
5004   ExprResult ActOnDecltypeExpression(Expr *E);
5005
5006   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5007                                            const DeclSpec &DS,
5008                                            SourceLocation ColonColonLoc);
5009
5010   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5011                                  IdentifierInfo &Identifier,
5012                                  SourceLocation IdentifierLoc,
5013                                  SourceLocation ColonLoc,
5014                                  ParsedType ObjectType,
5015                                  bool EnteringContext);
5016
5017   /// \brief The parser has parsed a nested-name-specifier
5018   /// 'template[opt] template-name < template-args >::'.
5019   ///
5020   /// \param S The scope in which this nested-name-specifier occurs.
5021   ///
5022   /// \param SS The nested-name-specifier, which is both an input
5023   /// parameter (the nested-name-specifier before this type) and an
5024   /// output parameter (containing the full nested-name-specifier,
5025   /// including this new type).
5026   ///
5027   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5028   /// \param TemplateName the template name.
5029   /// \param TemplateNameLoc The location of the template name.
5030   /// \param LAngleLoc The location of the opening angle bracket  ('<').
5031   /// \param TemplateArgs The template arguments.
5032   /// \param RAngleLoc The location of the closing angle bracket  ('>').
5033   /// \param CCLoc The location of the '::'.
5034   ///
5035   /// \param EnteringContext Whether we're entering the context of the
5036   /// nested-name-specifier.
5037   ///
5038   ///
5039   /// \returns true if an error occurred, false otherwise.
5040   bool ActOnCXXNestedNameSpecifier(Scope *S,
5041                                    CXXScopeSpec &SS,
5042                                    SourceLocation TemplateKWLoc,
5043                                    TemplateTy TemplateName,
5044                                    SourceLocation TemplateNameLoc,
5045                                    SourceLocation LAngleLoc,
5046                                    ASTTemplateArgsPtr TemplateArgs,
5047                                    SourceLocation RAngleLoc,
5048                                    SourceLocation CCLoc,
5049                                    bool EnteringContext);
5050
5051   /// \brief Given a C++ nested-name-specifier, produce an annotation value
5052   /// that the parser can use later to reconstruct the given
5053   /// nested-name-specifier.
5054   ///
5055   /// \param SS A nested-name-specifier.
5056   ///
5057   /// \returns A pointer containing all of the information in the
5058   /// nested-name-specifier \p SS.
5059   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5060
5061   /// \brief Given an annotation pointer for a nested-name-specifier, restore
5062   /// the nested-name-specifier structure.
5063   ///
5064   /// \param Annotation The annotation pointer, produced by
5065   /// \c SaveNestedNameSpecifierAnnotation().
5066   ///
5067   /// \param AnnotationRange The source range corresponding to the annotation.
5068   ///
5069   /// \param SS The nested-name-specifier that will be updated with the contents
5070   /// of the annotation pointer.
5071   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5072                                             SourceRange AnnotationRange,
5073                                             CXXScopeSpec &SS);
5074
5075   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5076
5077   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5078   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5079   /// After this method is called, according to [C++ 3.4.3p3], names should be
5080   /// looked up in the declarator-id's scope, until the declarator is parsed and
5081   /// ActOnCXXExitDeclaratorScope is called.
5082   /// The 'SS' should be a non-empty valid CXXScopeSpec.
5083   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5084
5085   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5086   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5087   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5088   /// Used to indicate that names should revert to being looked up in the
5089   /// defining scope.
5090   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5091
5092   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5093   /// initializer for the declaration 'Dcl'.
5094   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5095   /// static data member of class X, names should be looked up in the scope of
5096   /// class X.
5097   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5098
5099   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5100   /// initializer for the declaration 'Dcl'.
5101   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5102
5103   /// \brief Create a new lambda closure type.
5104   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5105                                          TypeSourceInfo *Info,
5106                                          bool KnownDependent, 
5107                                          LambdaCaptureDefault CaptureDefault);
5108
5109   /// \brief Start the definition of a lambda expression.
5110   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5111                                        SourceRange IntroducerRange,
5112                                        TypeSourceInfo *MethodType,
5113                                        SourceLocation EndLoc,
5114                                        ArrayRef<ParmVarDecl *> Params);
5115
5116   /// \brief Endow the lambda scope info with the relevant properties.
5117   void buildLambdaScope(sema::LambdaScopeInfo *LSI, 
5118                         CXXMethodDecl *CallOperator,
5119                         SourceRange IntroducerRange,
5120                         LambdaCaptureDefault CaptureDefault,
5121                         SourceLocation CaptureDefaultLoc,
5122                         bool ExplicitParams,
5123                         bool ExplicitResultType,
5124                         bool Mutable);
5125
5126   /// \brief Perform initialization analysis of the init-capture and perform
5127   /// any implicit conversions such as an lvalue-to-rvalue conversion if
5128   /// not being used to initialize a reference.
5129   ParsedType actOnLambdaInitCaptureInitialization(
5130       SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5131       LambdaCaptureInitKind InitKind, Expr *&Init) {
5132     return ParsedType::make(buildLambdaInitCaptureInitialization(
5133         Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5134   }
5135   QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5136                                                 IdentifierInfo *Id,
5137                                                 bool DirectInit, Expr *&Init);
5138
5139   /// \brief Create a dummy variable within the declcontext of the lambda's
5140   ///  call operator, for name lookup purposes for a lambda init capture.
5141   ///  
5142   ///  CodeGen handles emission of lambda captures, ignoring these dummy
5143   ///  variables appropriately.
5144   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5145                                           QualType InitCaptureType,
5146                                           IdentifierInfo *Id,
5147                                           unsigned InitStyle, Expr *Init);
5148
5149   /// \brief Build the implicit field for an init-capture.
5150   FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5151
5152   /// \brief Note that we have finished the explicit captures for the
5153   /// given lambda.
5154   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5155
5156   /// \brief Introduce the lambda parameters into scope.
5157   void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5158
5159   /// \brief Deduce a block or lambda's return type based on the return
5160   /// statements present in the body.
5161   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5162
5163   /// ActOnStartOfLambdaDefinition - This is called just before we start
5164   /// parsing the body of a lambda; it analyzes the explicit captures and
5165   /// arguments, and sets up various data-structures for the body of the
5166   /// lambda.
5167   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5168                                     Declarator &ParamInfo, Scope *CurScope);
5169
5170   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5171   /// is invoked to pop the information about the lambda.
5172   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5173                         bool IsInstantiation = false);
5174
5175   /// ActOnLambdaExpr - This is called when the body of a lambda expression
5176   /// was successfully completed.
5177   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5178                              Scope *CurScope);
5179
5180   /// \brief Complete a lambda-expression having processed and attached the
5181   /// lambda body.
5182   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5183                              sema::LambdaScopeInfo *LSI);
5184
5185   /// \brief Define the "body" of the conversion from a lambda object to a
5186   /// function pointer.
5187   ///
5188   /// This routine doesn't actually define a sensible body; rather, it fills
5189   /// in the initialization expression needed to copy the lambda object into
5190   /// the block, and IR generation actually generates the real body of the
5191   /// block pointer conversion.
5192   void DefineImplicitLambdaToFunctionPointerConversion(
5193          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5194
5195   /// \brief Define the "body" of the conversion from a lambda object to a
5196   /// block pointer.
5197   ///
5198   /// This routine doesn't actually define a sensible body; rather, it fills
5199   /// in the initialization expression needed to copy the lambda object into
5200   /// the block, and IR generation actually generates the real body of the
5201   /// block pointer conversion.
5202   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5203                                                     CXXConversionDecl *Conv);
5204
5205   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5206                                            SourceLocation ConvLocation,
5207                                            CXXConversionDecl *Conv,
5208                                            Expr *Src);
5209
5210   // ParseObjCStringLiteral - Parse Objective-C string literals.
5211   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5212                                     ArrayRef<Expr *> Strings);
5213
5214   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5215
5216   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5217   /// numeric literal expression. Type of the expression will be "NSNumber *"
5218   /// or "id" if NSNumber is unavailable.
5219   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5220   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5221                                   bool Value);
5222   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5223
5224   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5225   /// '@' prefixed parenthesized expression. The type of the expression will
5226   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5227   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5228   /// "const char *" or C structure with attribute 'objc_boxable'.
5229   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5230
5231   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5232                                           Expr *IndexExpr,
5233                                           ObjCMethodDecl *getterMethod,
5234                                           ObjCMethodDecl *setterMethod);
5235
5236   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5237                                MutableArrayRef<ObjCDictionaryElement> Elements);
5238
5239   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5240                                   TypeSourceInfo *EncodedTypeInfo,
5241                                   SourceLocation RParenLoc);
5242   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5243                                     CXXConversionDecl *Method,
5244                                     bool HadMultipleCandidates);
5245
5246   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5247                                        SourceLocation EncodeLoc,
5248                                        SourceLocation LParenLoc,
5249                                        ParsedType Ty,
5250                                        SourceLocation RParenLoc);
5251
5252   /// ParseObjCSelectorExpression - Build selector expression for \@selector
5253   ExprResult ParseObjCSelectorExpression(Selector Sel,
5254                                          SourceLocation AtLoc,
5255                                          SourceLocation SelLoc,
5256                                          SourceLocation LParenLoc,
5257                                          SourceLocation RParenLoc,
5258                                          bool WarnMultipleSelectors);
5259
5260   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5261   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5262                                          SourceLocation AtLoc,
5263                                          SourceLocation ProtoLoc,
5264                                          SourceLocation LParenLoc,
5265                                          SourceLocation ProtoIdLoc,
5266                                          SourceLocation RParenLoc);
5267
5268   //===--------------------------------------------------------------------===//
5269   // C++ Declarations
5270   //
5271   Decl *ActOnStartLinkageSpecification(Scope *S,
5272                                        SourceLocation ExternLoc,
5273                                        Expr *LangStr,
5274                                        SourceLocation LBraceLoc);
5275   Decl *ActOnFinishLinkageSpecification(Scope *S,
5276                                         Decl *LinkageSpec,
5277                                         SourceLocation RBraceLoc);
5278
5279
5280   //===--------------------------------------------------------------------===//
5281   // C++ Classes
5282   //
5283   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5284                           const CXXScopeSpec *SS = nullptr);
5285   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5286
5287   bool ActOnAccessSpecifier(AccessSpecifier Access,
5288                             SourceLocation ASLoc,
5289                             SourceLocation ColonLoc,
5290                             AttributeList *Attrs = nullptr);
5291
5292   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5293                                  Declarator &D,
5294                                  MultiTemplateParamsArg TemplateParameterLists,
5295                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
5296                                  InClassInitStyle InitStyle);
5297
5298   void ActOnStartCXXInClassMemberInitializer();
5299   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5300                                               SourceLocation EqualLoc,
5301                                               Expr *Init);
5302
5303   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5304                                     Scope *S,
5305                                     CXXScopeSpec &SS,
5306                                     IdentifierInfo *MemberOrBase,
5307                                     ParsedType TemplateTypeTy,
5308                                     const DeclSpec &DS,
5309                                     SourceLocation IdLoc,
5310                                     SourceLocation LParenLoc,
5311                                     ArrayRef<Expr *> Args,
5312                                     SourceLocation RParenLoc,
5313                                     SourceLocation EllipsisLoc);
5314
5315   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5316                                     Scope *S,
5317                                     CXXScopeSpec &SS,
5318                                     IdentifierInfo *MemberOrBase,
5319                                     ParsedType TemplateTypeTy,
5320                                     const DeclSpec &DS,
5321                                     SourceLocation IdLoc,
5322                                     Expr *InitList,
5323                                     SourceLocation EllipsisLoc);
5324
5325   MemInitResult BuildMemInitializer(Decl *ConstructorD,
5326                                     Scope *S,
5327                                     CXXScopeSpec &SS,
5328                                     IdentifierInfo *MemberOrBase,
5329                                     ParsedType TemplateTypeTy,
5330                                     const DeclSpec &DS,
5331                                     SourceLocation IdLoc,
5332                                     Expr *Init,
5333                                     SourceLocation EllipsisLoc);
5334
5335   MemInitResult BuildMemberInitializer(ValueDecl *Member,
5336                                        Expr *Init,
5337                                        SourceLocation IdLoc);
5338
5339   MemInitResult BuildBaseInitializer(QualType BaseType,
5340                                      TypeSourceInfo *BaseTInfo,
5341                                      Expr *Init,
5342                                      CXXRecordDecl *ClassDecl,
5343                                      SourceLocation EllipsisLoc);
5344
5345   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5346                                            Expr *Init,
5347                                            CXXRecordDecl *ClassDecl);
5348
5349   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5350                                 CXXCtorInitializer *Initializer);
5351
5352   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5353                            ArrayRef<CXXCtorInitializer *> Initializers = None);
5354
5355   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5356
5357
5358   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5359   /// mark all the non-trivial destructors of its members and bases as
5360   /// referenced.
5361   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5362                                               CXXRecordDecl *Record);
5363
5364   /// \brief The list of classes whose vtables have been used within
5365   /// this translation unit, and the source locations at which the
5366   /// first use occurred.
5367   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5368
5369   /// \brief The list of vtables that are required but have not yet been
5370   /// materialized.
5371   SmallVector<VTableUse, 16> VTableUses;
5372
5373   /// \brief The set of classes whose vtables have been used within
5374   /// this translation unit, and a bit that will be true if the vtable is
5375   /// required to be emitted (otherwise, it should be emitted only if needed
5376   /// by code generation).
5377   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5378
5379   /// \brief Load any externally-stored vtable uses.
5380   void LoadExternalVTableUses();
5381
5382   /// \brief Note that the vtable for the given class was used at the
5383   /// given location.
5384   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5385                       bool DefinitionRequired = false);
5386
5387   /// \brief Mark the exception specifications of all virtual member functions
5388   /// in the given class as needed.
5389   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5390                                              const CXXRecordDecl *RD);
5391
5392   /// MarkVirtualMembersReferenced - Will mark all members of the given
5393   /// CXXRecordDecl referenced.
5394   void MarkVirtualMembersReferenced(SourceLocation Loc,
5395                                     const CXXRecordDecl *RD);
5396
5397   /// \brief Define all of the vtables that have been used in this
5398   /// translation unit and reference any virtual members used by those
5399   /// vtables.
5400   ///
5401   /// \returns true if any work was done, false otherwise.
5402   bool DefineUsedVTables();
5403
5404   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5405
5406   void ActOnMemInitializers(Decl *ConstructorDecl,
5407                             SourceLocation ColonLoc,
5408                             ArrayRef<CXXCtorInitializer*> MemInits,
5409                             bool AnyErrors);
5410
5411   /// \brief Check class-level dllimport/dllexport attribute. The caller must
5412   /// ensure that referenceDLLExportedClassMethods is called some point later
5413   /// when all outer classes of Class are complete.
5414   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5415
5416   void referenceDLLExportedClassMethods();
5417
5418   void propagateDLLAttrToBaseClassTemplate(
5419       CXXRecordDecl *Class, Attr *ClassAttr,
5420       ClassTemplateSpecializationDecl *BaseTemplateSpec,
5421       SourceLocation BaseLoc);
5422
5423   void CheckCompletedCXXClass(CXXRecordDecl *Record);
5424   void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5425                                          Decl *TagDecl,
5426                                          SourceLocation LBrac,
5427                                          SourceLocation RBrac,
5428                                          AttributeList *AttrList);
5429   void ActOnFinishCXXMemberDecls();
5430   void ActOnFinishCXXNonNestedClass(Decl *D);
5431
5432   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5433   unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5434   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5435   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5436   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5437   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5438   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5439   void ActOnFinishDelayedMemberInitializers(Decl *Record);
5440   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5441                                 CachedTokens &Toks);
5442   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5443   bool IsInsideALocalClassWithinATemplateFunction();
5444
5445   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5446                                      Expr *AssertExpr,
5447                                      Expr *AssertMessageExpr,
5448                                      SourceLocation RParenLoc);
5449   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5450                                      Expr *AssertExpr,
5451                                      StringLiteral *AssertMessageExpr,
5452                                      SourceLocation RParenLoc,
5453                                      bool Failed);
5454
5455   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5456                                   SourceLocation FriendLoc,
5457                                   TypeSourceInfo *TSInfo);
5458   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5459                             MultiTemplateParamsArg TemplateParams);
5460   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5461                                      MultiTemplateParamsArg TemplateParams);
5462
5463   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5464                                       StorageClass& SC);
5465   void CheckConstructor(CXXConstructorDecl *Constructor);
5466   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5467                                      StorageClass& SC);
5468   bool CheckDestructor(CXXDestructorDecl *Destructor);
5469   void CheckConversionDeclarator(Declarator &D, QualType &R,
5470                                  StorageClass& SC);
5471   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5472
5473   void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5474   void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5475                                                    const FunctionProtoType *T);
5476   void CheckDelayedMemberExceptionSpecs();
5477
5478   //===--------------------------------------------------------------------===//
5479   // C++ Derived Classes
5480   //
5481
5482   /// ActOnBaseSpecifier - Parsed a base specifier
5483   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5484                                        SourceRange SpecifierRange,
5485                                        bool Virtual, AccessSpecifier Access,
5486                                        TypeSourceInfo *TInfo,
5487                                        SourceLocation EllipsisLoc);
5488
5489   BaseResult ActOnBaseSpecifier(Decl *classdecl,
5490                                 SourceRange SpecifierRange,
5491                                 ParsedAttributes &Attrs,
5492                                 bool Virtual, AccessSpecifier Access,
5493                                 ParsedType basetype,
5494                                 SourceLocation BaseLoc,
5495                                 SourceLocation EllipsisLoc);
5496
5497   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5498                             MutableArrayRef<CXXBaseSpecifier *> Bases);
5499   void ActOnBaseSpecifiers(Decl *ClassDecl,
5500                            MutableArrayRef<CXXBaseSpecifier *> Bases);
5501
5502   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5503   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5504                      CXXBasePaths &Paths);
5505
5506   // FIXME: I don't like this name.
5507   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5508
5509   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5510                                     SourceLocation Loc, SourceRange Range,
5511                                     CXXCastPath *BasePath = nullptr,
5512                                     bool IgnoreAccess = false);
5513   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5514                                     unsigned InaccessibleBaseID,
5515                                     unsigned AmbigiousBaseConvID,
5516                                     SourceLocation Loc, SourceRange Range,
5517                                     DeclarationName Name,
5518                                     CXXCastPath *BasePath,
5519                                     bool IgnoreAccess = false);
5520
5521   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5522
5523   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5524                                          const CXXMethodDecl *Old);
5525
5526   /// CheckOverridingFunctionReturnType - Checks whether the return types are
5527   /// covariant, according to C++ [class.virtual]p5.
5528   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5529                                          const CXXMethodDecl *Old);
5530
5531   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5532   /// spec is a subset of base spec.
5533   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5534                                             const CXXMethodDecl *Old);
5535
5536   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5537
5538   /// CheckOverrideControl - Check C++11 override control semantics.
5539   void CheckOverrideControl(NamedDecl *D);
5540     
5541   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5542   /// not used in the declaration of an overriding method.
5543   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5544
5545   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5546   /// overrides a virtual member function marked 'final', according to
5547   /// C++11 [class.virtual]p4.
5548   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5549                                               const CXXMethodDecl *Old);
5550
5551
5552   //===--------------------------------------------------------------------===//
5553   // C++ Access Control
5554   //
5555
5556   enum AccessResult {
5557     AR_accessible,
5558     AR_inaccessible,
5559     AR_dependent,
5560     AR_delayed
5561   };
5562
5563   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5564                                 NamedDecl *PrevMemberDecl,
5565                                 AccessSpecifier LexicalAS);
5566
5567   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5568                                            DeclAccessPair FoundDecl);
5569   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5570                                            DeclAccessPair FoundDecl);
5571   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5572                                      SourceRange PlacementRange,
5573                                      CXXRecordDecl *NamingClass,
5574                                      DeclAccessPair FoundDecl,
5575                                      bool Diagnose = true);
5576   AccessResult CheckConstructorAccess(SourceLocation Loc,
5577                                       CXXConstructorDecl *D,
5578                                       DeclAccessPair FoundDecl,
5579                                       const InitializedEntity &Entity,
5580                                       bool IsCopyBindingRefToTemp = false);
5581   AccessResult CheckConstructorAccess(SourceLocation Loc,
5582                                       CXXConstructorDecl *D,
5583                                       DeclAccessPair FoundDecl,
5584                                       const InitializedEntity &Entity,
5585                                       const PartialDiagnostic &PDiag);
5586   AccessResult CheckDestructorAccess(SourceLocation Loc,
5587                                      CXXDestructorDecl *Dtor,
5588                                      const PartialDiagnostic &PDiag,
5589                                      QualType objectType = QualType());
5590   AccessResult CheckFriendAccess(NamedDecl *D);
5591   AccessResult CheckMemberAccess(SourceLocation UseLoc,
5592                                  CXXRecordDecl *NamingClass,
5593                                  DeclAccessPair Found);
5594   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5595                                          Expr *ObjectExpr,
5596                                          Expr *ArgExpr,
5597                                          DeclAccessPair FoundDecl);
5598   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5599                                           DeclAccessPair FoundDecl);
5600   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5601                                     QualType Base, QualType Derived,
5602                                     const CXXBasePath &Path,
5603                                     unsigned DiagID,
5604                                     bool ForceCheck = false,
5605                                     bool ForceUnprivileged = false);
5606   void CheckLookupAccess(const LookupResult &R);
5607   bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5608   bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5609                                             AccessSpecifier access,
5610                                             QualType objectType);
5611
5612   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5613                          const MultiLevelTemplateArgumentList &TemplateArgs);
5614   void PerformDependentDiagnostics(const DeclContext *Pattern,
5615                         const MultiLevelTemplateArgumentList &TemplateArgs);
5616
5617   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5618
5619   /// \brief When true, access checking violations are treated as SFINAE
5620   /// failures rather than hard errors.
5621   bool AccessCheckingSFINAE;
5622
5623   enum AbstractDiagSelID {
5624     AbstractNone = -1,
5625     AbstractReturnType,
5626     AbstractParamType,
5627     AbstractVariableType,
5628     AbstractFieldType,
5629     AbstractIvarType,
5630     AbstractSynthesizedIvarType,
5631     AbstractArrayType
5632   };
5633
5634   bool isAbstractType(SourceLocation Loc, QualType T);
5635   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5636                               TypeDiagnoser &Diagnoser);
5637   template <typename... Ts>
5638   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5639                               const Ts &...Args) {
5640     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5641     return RequireNonAbstractType(Loc, T, Diagnoser);
5642   }
5643
5644   void DiagnoseAbstractType(const CXXRecordDecl *RD);
5645
5646   //===--------------------------------------------------------------------===//
5647   // C++ Overloaded Operators [C++ 13.5]
5648   //
5649
5650   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5651
5652   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5653
5654   //===--------------------------------------------------------------------===//
5655   // C++ Templates [C++ 14]
5656   //
5657   void FilterAcceptableTemplateNames(LookupResult &R,
5658                                      bool AllowFunctionTemplates = true);
5659   bool hasAnyAcceptableTemplateNames(LookupResult &R,
5660                                      bool AllowFunctionTemplates = true);
5661
5662   void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5663                           QualType ObjectType, bool EnteringContext,
5664                           bool &MemberOfUnknownSpecialization);
5665
5666   TemplateNameKind isTemplateName(Scope *S,
5667                                   CXXScopeSpec &SS,
5668                                   bool hasTemplateKeyword,
5669                                   UnqualifiedId &Name,
5670                                   ParsedType ObjectType,
5671                                   bool EnteringContext,
5672                                   TemplateTy &Template,
5673                                   bool &MemberOfUnknownSpecialization);
5674
5675   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5676                                    SourceLocation IILoc,
5677                                    Scope *S,
5678                                    const CXXScopeSpec *SS,
5679                                    TemplateTy &SuggestedTemplate,
5680                                    TemplateNameKind &SuggestedKind);
5681
5682   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5683   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5684
5685   Decl *ActOnTypeParameter(Scope *S, bool Typename,
5686                            SourceLocation EllipsisLoc,
5687                            SourceLocation KeyLoc,
5688                            IdentifierInfo *ParamName,
5689                            SourceLocation ParamNameLoc,
5690                            unsigned Depth, unsigned Position,
5691                            SourceLocation EqualLoc,
5692                            ParsedType DefaultArg);
5693
5694   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5695   Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5696                                       unsigned Depth,
5697                                       unsigned Position,
5698                                       SourceLocation EqualLoc,
5699                                       Expr *DefaultArg);
5700   Decl *ActOnTemplateTemplateParameter(Scope *S,
5701                                        SourceLocation TmpLoc,
5702                                        TemplateParameterList *Params,
5703                                        SourceLocation EllipsisLoc,
5704                                        IdentifierInfo *ParamName,
5705                                        SourceLocation ParamNameLoc,
5706                                        unsigned Depth,
5707                                        unsigned Position,
5708                                        SourceLocation EqualLoc,
5709                                        ParsedTemplateArgument DefaultArg);
5710
5711   TemplateParameterList *
5712   ActOnTemplateParameterList(unsigned Depth,
5713                              SourceLocation ExportLoc,
5714                              SourceLocation TemplateLoc,
5715                              SourceLocation LAngleLoc,
5716                              ArrayRef<Decl *> Params,
5717                              SourceLocation RAngleLoc,
5718                              Expr *RequiresClause);
5719
5720   /// \brief The context in which we are checking a template parameter list.
5721   enum TemplateParamListContext {
5722     TPC_ClassTemplate,
5723     TPC_VarTemplate,
5724     TPC_FunctionTemplate,
5725     TPC_ClassTemplateMember,
5726     TPC_FriendClassTemplate,
5727     TPC_FriendFunctionTemplate,
5728     TPC_FriendFunctionTemplateDefinition,
5729     TPC_TypeAliasTemplate
5730   };
5731
5732   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5733                                   TemplateParameterList *OldParams,
5734                                   TemplateParamListContext TPC);
5735   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5736       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5737       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5738       ArrayRef<TemplateParameterList *> ParamLists,
5739       bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5740
5741   DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5742                                 SourceLocation KWLoc, CXXScopeSpec &SS,
5743                                 IdentifierInfo *Name, SourceLocation NameLoc,
5744                                 AttributeList *Attr,
5745                                 TemplateParameterList *TemplateParams,
5746                                 AccessSpecifier AS,
5747                                 SourceLocation ModulePrivateLoc,
5748                                 SourceLocation FriendLoc,
5749                                 unsigned NumOuterTemplateParamLists,
5750                             TemplateParameterList **OuterTemplateParamLists,
5751                                 SkipBodyInfo *SkipBody = nullptr);
5752
5753   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5754                                   TemplateArgumentListInfo &Out);
5755
5756   void NoteAllFoundTemplates(TemplateName Name);
5757
5758   QualType CheckTemplateIdType(TemplateName Template,
5759                                SourceLocation TemplateLoc,
5760                               TemplateArgumentListInfo &TemplateArgs);
5761
5762   TypeResult
5763   ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5764                       TemplateTy Template, SourceLocation TemplateLoc,
5765                       SourceLocation LAngleLoc,
5766                       ASTTemplateArgsPtr TemplateArgs,
5767                       SourceLocation RAngleLoc,
5768                       bool IsCtorOrDtorName = false);
5769
5770   /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5771   /// such as \c class T::template apply<U>.
5772   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5773                                     TypeSpecifierType TagSpec,
5774                                     SourceLocation TagLoc,
5775                                     CXXScopeSpec &SS,
5776                                     SourceLocation TemplateKWLoc,
5777                                     TemplateTy TemplateD,
5778                                     SourceLocation TemplateLoc,
5779                                     SourceLocation LAngleLoc,
5780                                     ASTTemplateArgsPtr TemplateArgsIn,
5781                                     SourceLocation RAngleLoc);
5782
5783   DeclResult ActOnVarTemplateSpecialization(
5784       Scope *S, Declarator &D, TypeSourceInfo *DI,
5785       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5786       StorageClass SC, bool IsPartialSpecialization);
5787
5788   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5789                                 SourceLocation TemplateLoc,
5790                                 SourceLocation TemplateNameLoc,
5791                                 const TemplateArgumentListInfo &TemplateArgs);
5792
5793   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5794                                 const DeclarationNameInfo &NameInfo,
5795                                 VarTemplateDecl *Template,
5796                                 SourceLocation TemplateLoc,
5797                                 const TemplateArgumentListInfo *TemplateArgs);
5798
5799   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5800                                  SourceLocation TemplateKWLoc,
5801                                  LookupResult &R,
5802                                  bool RequiresADL,
5803                                const TemplateArgumentListInfo *TemplateArgs);
5804
5805   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5806                                           SourceLocation TemplateKWLoc,
5807                                const DeclarationNameInfo &NameInfo,
5808                                const TemplateArgumentListInfo *TemplateArgs);
5809
5810   TemplateNameKind ActOnDependentTemplateName(Scope *S,
5811                                               CXXScopeSpec &SS,
5812                                               SourceLocation TemplateKWLoc,
5813                                               UnqualifiedId &Name,
5814                                               ParsedType ObjectType,
5815                                               bool EnteringContext,
5816                                               TemplateTy &Template);
5817
5818   DeclResult
5819   ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5820                                    SourceLocation KWLoc,
5821                                    SourceLocation ModulePrivateLoc,
5822                                    TemplateIdAnnotation &TemplateId,
5823                                    AttributeList *Attr,
5824                                  MultiTemplateParamsArg TemplateParameterLists,
5825                                    SkipBodyInfo *SkipBody = nullptr);
5826
5827   Decl *ActOnTemplateDeclarator(Scope *S,
5828                                 MultiTemplateParamsArg TemplateParameterLists,
5829                                 Declarator &D);
5830
5831   bool
5832   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5833                                          TemplateSpecializationKind NewTSK,
5834                                          NamedDecl *PrevDecl,
5835                                          TemplateSpecializationKind PrevTSK,
5836                                          SourceLocation PrevPtOfInstantiation,
5837                                          bool &SuppressNew);
5838
5839   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5840                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
5841                                                     LookupResult &Previous);
5842
5843   bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5844                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5845                                            LookupResult &Previous);
5846   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5847
5848   DeclResult
5849   ActOnExplicitInstantiation(Scope *S,
5850                              SourceLocation ExternLoc,
5851                              SourceLocation TemplateLoc,
5852                              unsigned TagSpec,
5853                              SourceLocation KWLoc,
5854                              const CXXScopeSpec &SS,
5855                              TemplateTy Template,
5856                              SourceLocation TemplateNameLoc,
5857                              SourceLocation LAngleLoc,
5858                              ASTTemplateArgsPtr TemplateArgs,
5859                              SourceLocation RAngleLoc,
5860                              AttributeList *Attr);
5861
5862   DeclResult
5863   ActOnExplicitInstantiation(Scope *S,
5864                              SourceLocation ExternLoc,
5865                              SourceLocation TemplateLoc,
5866                              unsigned TagSpec,
5867                              SourceLocation KWLoc,
5868                              CXXScopeSpec &SS,
5869                              IdentifierInfo *Name,
5870                              SourceLocation NameLoc,
5871                              AttributeList *Attr);
5872
5873   DeclResult ActOnExplicitInstantiation(Scope *S,
5874                                         SourceLocation ExternLoc,
5875                                         SourceLocation TemplateLoc,
5876                                         Declarator &D);
5877
5878   TemplateArgumentLoc
5879   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5880                                           SourceLocation TemplateLoc,
5881                                           SourceLocation RAngleLoc,
5882                                           Decl *Param,
5883                                           SmallVectorImpl<TemplateArgument>
5884                                             &Converted,
5885                                           bool &HasDefaultArg);
5886
5887   /// \brief Specifies the context in which a particular template
5888   /// argument is being checked.
5889   enum CheckTemplateArgumentKind {
5890     /// \brief The template argument was specified in the code or was
5891     /// instantiated with some deduced template arguments.
5892     CTAK_Specified,
5893
5894     /// \brief The template argument was deduced via template argument
5895     /// deduction.
5896     CTAK_Deduced,
5897
5898     /// \brief The template argument was deduced from an array bound
5899     /// via template argument deduction.
5900     CTAK_DeducedFromArrayBound
5901   };
5902
5903   bool CheckTemplateArgument(NamedDecl *Param,
5904                              TemplateArgumentLoc &Arg,
5905                              NamedDecl *Template,
5906                              SourceLocation TemplateLoc,
5907                              SourceLocation RAngleLoc,
5908                              unsigned ArgumentPackIndex,
5909                            SmallVectorImpl<TemplateArgument> &Converted,
5910                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
5911
5912   /// \brief Check that the given template arguments can be be provided to
5913   /// the given template, converting the arguments along the way.
5914   ///
5915   /// \param Template The template to which the template arguments are being
5916   /// provided.
5917   ///
5918   /// \param TemplateLoc The location of the template name in the source.
5919   ///
5920   /// \param TemplateArgs The list of template arguments. If the template is
5921   /// a template template parameter, this function may extend the set of
5922   /// template arguments to also include substituted, defaulted template
5923   /// arguments.
5924   ///
5925   /// \param PartialTemplateArgs True if the list of template arguments is
5926   /// intentionally partial, e.g., because we're checking just the initial
5927   /// set of template arguments.
5928   ///
5929   /// \param Converted Will receive the converted, canonicalized template
5930   /// arguments.
5931   ///
5932   /// \returns true if an error occurred, false otherwise.
5933   bool CheckTemplateArgumentList(TemplateDecl *Template,
5934                                  SourceLocation TemplateLoc,
5935                                  TemplateArgumentListInfo &TemplateArgs,
5936                                  bool PartialTemplateArgs,
5937                            SmallVectorImpl<TemplateArgument> &Converted);
5938
5939   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5940                                  TemplateArgumentLoc &Arg,
5941                            SmallVectorImpl<TemplateArgument> &Converted);
5942
5943   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5944                              TypeSourceInfo *Arg);
5945   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5946                                    QualType InstantiatedParamType, Expr *Arg,
5947                                    TemplateArgument &Converted,
5948                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
5949   bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5950                              TemplateArgumentLoc &Arg,
5951                              unsigned ArgumentPackIndex);
5952
5953   ExprResult
5954   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5955                                           QualType ParamType,
5956                                           SourceLocation Loc);
5957   ExprResult
5958   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5959                                               SourceLocation Loc);
5960
5961   /// \brief Enumeration describing how template parameter lists are compared
5962   /// for equality.
5963   enum TemplateParameterListEqualKind {
5964     /// \brief We are matching the template parameter lists of two templates
5965     /// that might be redeclarations.
5966     ///
5967     /// \code
5968     /// template<typename T> struct X;
5969     /// template<typename T> struct X;
5970     /// \endcode
5971     TPL_TemplateMatch,
5972
5973     /// \brief We are matching the template parameter lists of two template
5974     /// template parameters as part of matching the template parameter lists
5975     /// of two templates that might be redeclarations.
5976     ///
5977     /// \code
5978     /// template<template<int I> class TT> struct X;
5979     /// template<template<int Value> class Other> struct X;
5980     /// \endcode
5981     TPL_TemplateTemplateParmMatch,
5982
5983     /// \brief We are matching the template parameter lists of a template
5984     /// template argument against the template parameter lists of a template
5985     /// template parameter.
5986     ///
5987     /// \code
5988     /// template<template<int Value> class Metafun> struct X;
5989     /// template<int Value> struct integer_c;
5990     /// X<integer_c> xic;
5991     /// \endcode
5992     TPL_TemplateTemplateArgumentMatch
5993   };
5994
5995   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5996                                       TemplateParameterList *Old,
5997                                       bool Complain,
5998                                       TemplateParameterListEqualKind Kind,
5999                                       SourceLocation TemplateArgLoc
6000                                         = SourceLocation());
6001
6002   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6003
6004   /// \brief Called when the parser has parsed a C++ typename
6005   /// specifier, e.g., "typename T::type".
6006   ///
6007   /// \param S The scope in which this typename type occurs.
6008   /// \param TypenameLoc the location of the 'typename' keyword
6009   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6010   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6011   /// \param IdLoc the location of the identifier.
6012   TypeResult
6013   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6014                     const CXXScopeSpec &SS, const IdentifierInfo &II,
6015                     SourceLocation IdLoc);
6016
6017   /// \brief Called when the parser has parsed a C++ typename
6018   /// specifier that ends in a template-id, e.g.,
6019   /// "typename MetaFun::template apply<T1, T2>".
6020   ///
6021   /// \param S The scope in which this typename type occurs.
6022   /// \param TypenameLoc the location of the 'typename' keyword
6023   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6024   /// \param TemplateLoc the location of the 'template' keyword, if any.
6025   /// \param TemplateName The template name.
6026   /// \param TemplateNameLoc The location of the template name.
6027   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6028   /// \param TemplateArgs The template arguments.
6029   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6030   TypeResult
6031   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6032                     const CXXScopeSpec &SS,
6033                     SourceLocation TemplateLoc,
6034                     TemplateTy TemplateName,
6035                     SourceLocation TemplateNameLoc,
6036                     SourceLocation LAngleLoc,
6037                     ASTTemplateArgsPtr TemplateArgs,
6038                     SourceLocation RAngleLoc);
6039
6040   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6041                              SourceLocation KeywordLoc,
6042                              NestedNameSpecifierLoc QualifierLoc,
6043                              const IdentifierInfo &II,
6044                              SourceLocation IILoc);
6045
6046   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6047                                                     SourceLocation Loc,
6048                                                     DeclarationName Name);
6049   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6050
6051   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6052   bool RebuildTemplateParamsInCurrentInstantiation(
6053                                                 TemplateParameterList *Params);
6054
6055   std::string
6056   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6057                                   const TemplateArgumentList &Args);
6058
6059   std::string
6060   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6061                                   const TemplateArgument *Args,
6062                                   unsigned NumArgs);
6063
6064   //===--------------------------------------------------------------------===//
6065   // C++ Variadic Templates (C++0x [temp.variadic])
6066   //===--------------------------------------------------------------------===//
6067
6068   /// Determine whether an unexpanded parameter pack might be permitted in this
6069   /// location. Useful for error recovery.
6070   bool isUnexpandedParameterPackPermitted();
6071
6072   /// \brief The context in which an unexpanded parameter pack is
6073   /// being diagnosed.
6074   ///
6075   /// Note that the values of this enumeration line up with the first
6076   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6077   enum UnexpandedParameterPackContext {
6078     /// \brief An arbitrary expression.
6079     UPPC_Expression = 0,
6080
6081     /// \brief The base type of a class type.
6082     UPPC_BaseType,
6083
6084     /// \brief The type of an arbitrary declaration.
6085     UPPC_DeclarationType,
6086
6087     /// \brief The type of a data member.
6088     UPPC_DataMemberType,
6089
6090     /// \brief The size of a bit-field.
6091     UPPC_BitFieldWidth,
6092
6093     /// \brief The expression in a static assertion.
6094     UPPC_StaticAssertExpression,
6095
6096     /// \brief The fixed underlying type of an enumeration.
6097     UPPC_FixedUnderlyingType,
6098
6099     /// \brief The enumerator value.
6100     UPPC_EnumeratorValue,
6101
6102     /// \brief A using declaration.
6103     UPPC_UsingDeclaration,
6104
6105     /// \brief A friend declaration.
6106     UPPC_FriendDeclaration,
6107
6108     /// \brief A declaration qualifier.
6109     UPPC_DeclarationQualifier,
6110
6111     /// \brief An initializer.
6112     UPPC_Initializer,
6113
6114     /// \brief A default argument.
6115     UPPC_DefaultArgument,
6116
6117     /// \brief The type of a non-type template parameter.
6118     UPPC_NonTypeTemplateParameterType,
6119
6120     /// \brief The type of an exception.
6121     UPPC_ExceptionType,
6122
6123     /// \brief Partial specialization.
6124     UPPC_PartialSpecialization,
6125
6126     /// \brief Microsoft __if_exists.
6127     UPPC_IfExists,
6128
6129     /// \brief Microsoft __if_not_exists.
6130     UPPC_IfNotExists,
6131
6132     /// \brief Lambda expression.
6133     UPPC_Lambda,
6134
6135     /// \brief Block expression,
6136     UPPC_Block
6137   };
6138
6139   /// \brief Diagnose unexpanded parameter packs.
6140   ///
6141   /// \param Loc The location at which we should emit the diagnostic.
6142   ///
6143   /// \param UPPC The context in which we are diagnosing unexpanded
6144   /// parameter packs.
6145   ///
6146   /// \param Unexpanded the set of unexpanded parameter packs.
6147   ///
6148   /// \returns true if an error occurred, false otherwise.
6149   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6150                                         UnexpandedParameterPackContext UPPC,
6151                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
6152
6153   /// \brief If the given type contains an unexpanded parameter pack,
6154   /// diagnose the error.
6155   ///
6156   /// \param Loc The source location where a diagnostc should be emitted.
6157   ///
6158   /// \param T The type that is being checked for unexpanded parameter
6159   /// packs.
6160   ///
6161   /// \returns true if an error occurred, false otherwise.
6162   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6163                                        UnexpandedParameterPackContext UPPC);
6164
6165   /// \brief If the given expression contains an unexpanded parameter
6166   /// pack, diagnose the error.
6167   ///
6168   /// \param E The expression that is being checked for unexpanded
6169   /// parameter packs.
6170   ///
6171   /// \returns true if an error occurred, false otherwise.
6172   bool DiagnoseUnexpandedParameterPack(Expr *E,
6173                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
6174
6175   /// \brief If the given nested-name-specifier contains an unexpanded
6176   /// parameter pack, diagnose the error.
6177   ///
6178   /// \param SS The nested-name-specifier that is being checked for
6179   /// unexpanded parameter packs.
6180   ///
6181   /// \returns true if an error occurred, false otherwise.
6182   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6183                                        UnexpandedParameterPackContext UPPC);
6184
6185   /// \brief If the given name contains an unexpanded parameter pack,
6186   /// diagnose the error.
6187   ///
6188   /// \param NameInfo The name (with source location information) that
6189   /// is being checked for unexpanded parameter packs.
6190   ///
6191   /// \returns true if an error occurred, false otherwise.
6192   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6193                                        UnexpandedParameterPackContext UPPC);
6194
6195   /// \brief If the given template name contains an unexpanded parameter pack,
6196   /// diagnose the error.
6197   ///
6198   /// \param Loc The location of the template name.
6199   ///
6200   /// \param Template The template name that is being checked for unexpanded
6201   /// parameter packs.
6202   ///
6203   /// \returns true if an error occurred, false otherwise.
6204   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6205                                        TemplateName Template,
6206                                        UnexpandedParameterPackContext UPPC);
6207
6208   /// \brief If the given template argument contains an unexpanded parameter
6209   /// pack, diagnose the error.
6210   ///
6211   /// \param Arg The template argument that is being checked for unexpanded
6212   /// parameter packs.
6213   ///
6214   /// \returns true if an error occurred, false otherwise.
6215   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6216                                        UnexpandedParameterPackContext UPPC);
6217
6218   /// \brief Collect the set of unexpanded parameter packs within the given
6219   /// template argument.
6220   ///
6221   /// \param Arg The template argument that will be traversed to find
6222   /// unexpanded parameter packs.
6223   void collectUnexpandedParameterPacks(TemplateArgument Arg,
6224                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6225
6226   /// \brief Collect the set of unexpanded parameter packs within the given
6227   /// template argument.
6228   ///
6229   /// \param Arg The template argument that will be traversed to find
6230   /// unexpanded parameter packs.
6231   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6232                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6233
6234   /// \brief Collect the set of unexpanded parameter packs within the given
6235   /// type.
6236   ///
6237   /// \param T The type that will be traversed to find
6238   /// unexpanded parameter packs.
6239   void collectUnexpandedParameterPacks(QualType T,
6240                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6241
6242   /// \brief Collect the set of unexpanded parameter packs within the given
6243   /// type.
6244   ///
6245   /// \param TL The type that will be traversed to find
6246   /// unexpanded parameter packs.
6247   void collectUnexpandedParameterPacks(TypeLoc TL,
6248                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6249
6250   /// \brief Collect the set of unexpanded parameter packs within the given
6251   /// nested-name-specifier.
6252   ///
6253   /// \param SS The nested-name-specifier that will be traversed to find
6254   /// unexpanded parameter packs.
6255   void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
6256                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6257
6258   /// \brief Collect the set of unexpanded parameter packs within the given
6259   /// name.
6260   ///
6261   /// \param NameInfo The name that will be traversed to find
6262   /// unexpanded parameter packs.
6263   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6264                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6265
6266   /// \brief Invoked when parsing a template argument followed by an
6267   /// ellipsis, which creates a pack expansion.
6268   ///
6269   /// \param Arg The template argument preceding the ellipsis, which
6270   /// may already be invalid.
6271   ///
6272   /// \param EllipsisLoc The location of the ellipsis.
6273   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6274                                             SourceLocation EllipsisLoc);
6275
6276   /// \brief Invoked when parsing a type followed by an ellipsis, which
6277   /// creates a pack expansion.
6278   ///
6279   /// \param Type The type preceding the ellipsis, which will become
6280   /// the pattern of the pack expansion.
6281   ///
6282   /// \param EllipsisLoc The location of the ellipsis.
6283   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6284
6285   /// \brief Construct a pack expansion type from the pattern of the pack
6286   /// expansion.
6287   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6288                                      SourceLocation EllipsisLoc,
6289                                      Optional<unsigned> NumExpansions);
6290
6291   /// \brief Construct a pack expansion type from the pattern of the pack
6292   /// expansion.
6293   QualType CheckPackExpansion(QualType Pattern,
6294                               SourceRange PatternRange,
6295                               SourceLocation EllipsisLoc,
6296                               Optional<unsigned> NumExpansions);
6297
6298   /// \brief Invoked when parsing an expression followed by an ellipsis, which
6299   /// creates a pack expansion.
6300   ///
6301   /// \param Pattern The expression preceding the ellipsis, which will become
6302   /// the pattern of the pack expansion.
6303   ///
6304   /// \param EllipsisLoc The location of the ellipsis.
6305   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6306
6307   /// \brief Invoked when parsing an expression followed by an ellipsis, which
6308   /// creates a pack expansion.
6309   ///
6310   /// \param Pattern The expression preceding the ellipsis, which will become
6311   /// the pattern of the pack expansion.
6312   ///
6313   /// \param EllipsisLoc The location of the ellipsis.
6314   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6315                                 Optional<unsigned> NumExpansions);
6316
6317   /// \brief Determine whether we could expand a pack expansion with the
6318   /// given set of parameter packs into separate arguments by repeatedly
6319   /// transforming the pattern.
6320   ///
6321   /// \param EllipsisLoc The location of the ellipsis that identifies the
6322   /// pack expansion.
6323   ///
6324   /// \param PatternRange The source range that covers the entire pattern of
6325   /// the pack expansion.
6326   ///
6327   /// \param Unexpanded The set of unexpanded parameter packs within the
6328   /// pattern.
6329   ///
6330   /// \param ShouldExpand Will be set to \c true if the transformer should
6331   /// expand the corresponding pack expansions into separate arguments. When
6332   /// set, \c NumExpansions must also be set.
6333   ///
6334   /// \param RetainExpansion Whether the caller should add an unexpanded
6335   /// pack expansion after all of the expanded arguments. This is used
6336   /// when extending explicitly-specified template argument packs per
6337   /// C++0x [temp.arg.explicit]p9.
6338   ///
6339   /// \param NumExpansions The number of separate arguments that will be in
6340   /// the expanded form of the corresponding pack expansion. This is both an
6341   /// input and an output parameter, which can be set by the caller if the
6342   /// number of expansions is known a priori (e.g., due to a prior substitution)
6343   /// and will be set by the callee when the number of expansions is known.
6344   /// The callee must set this value when \c ShouldExpand is \c true; it may
6345   /// set this value in other cases.
6346   ///
6347   /// \returns true if an error occurred (e.g., because the parameter packs
6348   /// are to be instantiated with arguments of different lengths), false
6349   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6350   /// must be set.
6351   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6352                                        SourceRange PatternRange,
6353                              ArrayRef<UnexpandedParameterPack> Unexpanded,
6354                              const MultiLevelTemplateArgumentList &TemplateArgs,
6355                                        bool &ShouldExpand,
6356                                        bool &RetainExpansion,
6357                                        Optional<unsigned> &NumExpansions);
6358
6359   /// \brief Determine the number of arguments in the given pack expansion
6360   /// type.
6361   ///
6362   /// This routine assumes that the number of arguments in the expansion is
6363   /// consistent across all of the unexpanded parameter packs in its pattern.
6364   ///
6365   /// Returns an empty Optional if the type can't be expanded.
6366   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6367       const MultiLevelTemplateArgumentList &TemplateArgs);
6368
6369   /// \brief Determine whether the given declarator contains any unexpanded
6370   /// parameter packs.
6371   ///
6372   /// This routine is used by the parser to disambiguate function declarators
6373   /// with an ellipsis prior to the ')', e.g.,
6374   ///
6375   /// \code
6376   ///   void f(T...);
6377   /// \endcode
6378   ///
6379   /// To determine whether we have an (unnamed) function parameter pack or
6380   /// a variadic function.
6381   ///
6382   /// \returns true if the declarator contains any unexpanded parameter packs,
6383   /// false otherwise.
6384   bool containsUnexpandedParameterPacks(Declarator &D);
6385
6386   /// \brief Returns the pattern of the pack expansion for a template argument.
6387   ///
6388   /// \param OrigLoc The template argument to expand.
6389   ///
6390   /// \param Ellipsis Will be set to the location of the ellipsis.
6391   ///
6392   /// \param NumExpansions Will be set to the number of expansions that will
6393   /// be generated from this pack expansion, if known a priori.
6394   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6395       TemplateArgumentLoc OrigLoc,
6396       SourceLocation &Ellipsis,
6397       Optional<unsigned> &NumExpansions) const;
6398
6399   //===--------------------------------------------------------------------===//
6400   // C++ Template Argument Deduction (C++ [temp.deduct])
6401   //===--------------------------------------------------------------------===//
6402
6403   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6404
6405   /// \brief Describes the result of template argument deduction.
6406   ///
6407   /// The TemplateDeductionResult enumeration describes the result of
6408   /// template argument deduction, as returned from
6409   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6410   /// structure provides additional information about the results of
6411   /// template argument deduction, e.g., the deduced template argument
6412   /// list (if successful) or the specific template parameters or
6413   /// deduced arguments that were involved in the failure.
6414   enum TemplateDeductionResult {
6415     /// \brief Template argument deduction was successful.
6416     TDK_Success = 0,
6417     /// \brief The declaration was invalid; do nothing.
6418     TDK_Invalid,
6419     /// \brief Template argument deduction exceeded the maximum template
6420     /// instantiation depth (which has already been diagnosed).
6421     TDK_InstantiationDepth,
6422     /// \brief Template argument deduction did not deduce a value
6423     /// for every template parameter.
6424     TDK_Incomplete,
6425     /// \brief Template argument deduction produced inconsistent
6426     /// deduced values for the given template parameter.
6427     TDK_Inconsistent,
6428     /// \brief Template argument deduction failed due to inconsistent
6429     /// cv-qualifiers on a template parameter type that would
6430     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6431     /// but were given a non-const "X".
6432     TDK_Underqualified,
6433     /// \brief Substitution of the deduced template argument values
6434     /// resulted in an error.
6435     TDK_SubstitutionFailure,
6436     /// \brief After substituting deduced template arguments, a dependent
6437     /// parameter type did not match the corresponding argument.
6438     TDK_DeducedMismatch,
6439     /// \brief A non-depnedent component of the parameter did not match the
6440     /// corresponding component of the argument.
6441     TDK_NonDeducedMismatch,
6442     /// \brief When performing template argument deduction for a function
6443     /// template, there were too many call arguments.
6444     TDK_TooManyArguments,
6445     /// \brief When performing template argument deduction for a function
6446     /// template, there were too few call arguments.
6447     TDK_TooFewArguments,
6448     /// \brief The explicitly-specified template arguments were not valid
6449     /// template arguments for the given template.
6450     TDK_InvalidExplicitArguments,
6451     /// \brief The arguments included an overloaded function name that could
6452     /// not be resolved to a suitable function.
6453     TDK_FailedOverloadResolution,
6454     /// \brief Deduction failed; that's all we know.
6455     TDK_MiscellaneousDeductionFailure
6456   };
6457
6458   TemplateDeductionResult
6459   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6460                           const TemplateArgumentList &TemplateArgs,
6461                           sema::TemplateDeductionInfo &Info);
6462
6463   TemplateDeductionResult
6464   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6465                           const TemplateArgumentList &TemplateArgs,
6466                           sema::TemplateDeductionInfo &Info);
6467
6468   TemplateDeductionResult SubstituteExplicitTemplateArguments(
6469       FunctionTemplateDecl *FunctionTemplate,
6470       TemplateArgumentListInfo &ExplicitTemplateArgs,
6471       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6472       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6473       sema::TemplateDeductionInfo &Info);
6474
6475   /// brief A function argument from which we performed template argument
6476   // deduction for a call.
6477   struct OriginalCallArg {
6478     OriginalCallArg(QualType OriginalParamType,
6479                     unsigned ArgIdx,
6480                     QualType OriginalArgType)
6481       : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6482         OriginalArgType(OriginalArgType) { }
6483
6484     QualType OriginalParamType;
6485     unsigned ArgIdx;
6486     QualType OriginalArgType;
6487   };
6488
6489   TemplateDeductionResult
6490   FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6491                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6492                                   unsigned NumExplicitlySpecified,
6493                                   FunctionDecl *&Specialization,
6494                                   sema::TemplateDeductionInfo &Info,
6495            SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6496                                   bool PartialOverloading = false);
6497
6498   TemplateDeductionResult
6499   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6500                           TemplateArgumentListInfo *ExplicitTemplateArgs,
6501                           ArrayRef<Expr *> Args,
6502                           FunctionDecl *&Specialization,
6503                           sema::TemplateDeductionInfo &Info,
6504                           bool PartialOverloading = false);
6505
6506   TemplateDeductionResult
6507   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6508                           TemplateArgumentListInfo *ExplicitTemplateArgs,
6509                           QualType ArgFunctionType,
6510                           FunctionDecl *&Specialization,
6511                           sema::TemplateDeductionInfo &Info,
6512                           bool InOverloadResolution = false);
6513
6514   TemplateDeductionResult
6515   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6516                           QualType ToType,
6517                           CXXConversionDecl *&Specialization,
6518                           sema::TemplateDeductionInfo &Info);
6519
6520   TemplateDeductionResult
6521   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6522                           TemplateArgumentListInfo *ExplicitTemplateArgs,
6523                           FunctionDecl *&Specialization,
6524                           sema::TemplateDeductionInfo &Info,
6525                           bool InOverloadResolution = false);
6526
6527   /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6528   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6529   /// \brief Substitute Replacement for auto in TypeWithAuto
6530   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 
6531                                           QualType Replacement);
6532
6533   /// \brief Result type of DeduceAutoType.
6534   enum DeduceAutoResult {
6535     DAR_Succeeded,
6536     DAR_Failed,
6537     DAR_FailedAlreadyDiagnosed
6538   };
6539
6540   DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6541                                   QualType &Result);
6542   DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6543                                   QualType &Result);
6544   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6545   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6546                         bool Diagnose = true);
6547
6548   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6549                                         QualType Type, TypeSourceInfo *TSI,
6550                                         SourceRange Range, bool DirectInit,
6551                                         Expr *Init);
6552
6553   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6554
6555   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6556                                         SourceLocation ReturnLoc,
6557                                         Expr *&RetExpr, AutoType *AT);
6558
6559   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6560                                                    FunctionTemplateDecl *FT2,
6561                                                    SourceLocation Loc,
6562                                            TemplatePartialOrderingContext TPOC,
6563                                                    unsigned NumCallArguments1,
6564                                                    unsigned NumCallArguments2);
6565   UnresolvedSetIterator
6566   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6567                      TemplateSpecCandidateSet &FailedCandidates,
6568                      SourceLocation Loc,
6569                      const PartialDiagnostic &NoneDiag,
6570                      const PartialDiagnostic &AmbigDiag,
6571                      const PartialDiagnostic &CandidateDiag,
6572                      bool Complain = true, QualType TargetType = QualType());
6573
6574   ClassTemplatePartialSpecializationDecl *
6575   getMoreSpecializedPartialSpecialization(
6576                                   ClassTemplatePartialSpecializationDecl *PS1,
6577                                   ClassTemplatePartialSpecializationDecl *PS2,
6578                                   SourceLocation Loc);
6579
6580   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6581       VarTemplatePartialSpecializationDecl *PS1,
6582       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6583
6584   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6585                                   bool OnlyDeduced,
6586                                   unsigned Depth,
6587                                   llvm::SmallBitVector &Used);
6588   void MarkDeducedTemplateParameters(
6589                                   const FunctionTemplateDecl *FunctionTemplate,
6590                                   llvm::SmallBitVector &Deduced) {
6591     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6592   }
6593   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6594                                   const FunctionTemplateDecl *FunctionTemplate,
6595                                   llvm::SmallBitVector &Deduced);
6596
6597   //===--------------------------------------------------------------------===//
6598   // C++ Template Instantiation
6599   //
6600
6601   MultiLevelTemplateArgumentList
6602   getTemplateInstantiationArgs(NamedDecl *D,
6603                                const TemplateArgumentList *Innermost = nullptr,
6604                                bool RelativeToPrimary = false,
6605                                const FunctionDecl *Pattern = nullptr);
6606
6607   /// \brief A template instantiation that is currently in progress.
6608   struct ActiveTemplateInstantiation {
6609     /// \brief The kind of template instantiation we are performing
6610     enum InstantiationKind {
6611       /// We are instantiating a template declaration. The entity is
6612       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6613       TemplateInstantiation,
6614
6615       /// We are instantiating a default argument for a template
6616       /// parameter. The Entity is the template, and
6617       /// TemplateArgs/NumTemplateArguments provides the template
6618       /// arguments as specified.
6619       /// FIXME: Use a TemplateArgumentList
6620       DefaultTemplateArgumentInstantiation,
6621
6622       /// We are instantiating a default argument for a function.
6623       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6624       /// provides the template arguments as specified.
6625       DefaultFunctionArgumentInstantiation,
6626
6627       /// We are substituting explicit template arguments provided for
6628       /// a function template. The entity is a FunctionTemplateDecl.
6629       ExplicitTemplateArgumentSubstitution,
6630
6631       /// We are substituting template argument determined as part of
6632       /// template argument deduction for either a class template
6633       /// partial specialization or a function template. The
6634       /// Entity is either a ClassTemplatePartialSpecializationDecl or
6635       /// a FunctionTemplateDecl.
6636       DeducedTemplateArgumentSubstitution,
6637
6638       /// We are substituting prior template arguments into a new
6639       /// template parameter. The template parameter itself is either a
6640       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6641       PriorTemplateArgumentSubstitution,
6642
6643       /// We are checking the validity of a default template argument that
6644       /// has been used when naming a template-id.
6645       DefaultTemplateArgumentChecking,
6646
6647       /// We are instantiating the exception specification for a function
6648       /// template which was deferred until it was needed.
6649       ExceptionSpecInstantiation
6650     } Kind;
6651
6652     /// \brief The point of instantiation within the source code.
6653     SourceLocation PointOfInstantiation;
6654
6655     /// \brief The template (or partial specialization) in which we are
6656     /// performing the instantiation, for substitutions of prior template
6657     /// arguments.
6658     NamedDecl *Template;
6659
6660     /// \brief The entity that is being instantiated.
6661     Decl *Entity;
6662
6663     /// \brief The list of template arguments we are substituting, if they
6664     /// are not part of the entity.
6665     const TemplateArgument *TemplateArgs;
6666
6667     /// \brief The number of template arguments in TemplateArgs.
6668     unsigned NumTemplateArgs;
6669
6670     ArrayRef<TemplateArgument> template_arguments() const {
6671       return {TemplateArgs, NumTemplateArgs};
6672     }
6673
6674     /// \brief The template deduction info object associated with the
6675     /// substitution or checking of explicit or deduced template arguments.
6676     sema::TemplateDeductionInfo *DeductionInfo;
6677
6678     /// \brief The source range that covers the construct that cause
6679     /// the instantiation, e.g., the template-id that causes a class
6680     /// template instantiation.
6681     SourceRange InstantiationRange;
6682
6683     ActiveTemplateInstantiation()
6684       : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6685         TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6686
6687     /// \brief Determines whether this template is an actual instantiation
6688     /// that should be counted toward the maximum instantiation depth.
6689     bool isInstantiationRecord() const;
6690
6691     friend bool operator==(const ActiveTemplateInstantiation &X,
6692                            const ActiveTemplateInstantiation &Y) {
6693       if (X.Kind != Y.Kind)
6694         return false;
6695
6696       if (X.Entity != Y.Entity)
6697         return false;
6698
6699       switch (X.Kind) {
6700       case TemplateInstantiation:
6701       case ExceptionSpecInstantiation:
6702         return true;
6703
6704       case PriorTemplateArgumentSubstitution:
6705       case DefaultTemplateArgumentChecking:
6706         return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6707
6708       case DefaultTemplateArgumentInstantiation:
6709       case ExplicitTemplateArgumentSubstitution:
6710       case DeducedTemplateArgumentSubstitution:
6711       case DefaultFunctionArgumentInstantiation:
6712         return X.TemplateArgs == Y.TemplateArgs;
6713
6714       }
6715
6716       llvm_unreachable("Invalid InstantiationKind!");
6717     }
6718
6719     friend bool operator!=(const ActiveTemplateInstantiation &X,
6720                            const ActiveTemplateInstantiation &Y) {
6721       return !(X == Y);
6722     }
6723   };
6724
6725   /// \brief List of active template instantiations.
6726   ///
6727   /// This vector is treated as a stack. As one template instantiation
6728   /// requires another template instantiation, additional
6729   /// instantiations are pushed onto the stack up to a
6730   /// user-configurable limit LangOptions::InstantiationDepth.
6731   SmallVector<ActiveTemplateInstantiation, 16>
6732     ActiveTemplateInstantiations;
6733
6734   /// \brief Extra modules inspected when performing a lookup during a template
6735   /// instantiation. Computed lazily.
6736   SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6737
6738   /// \brief Cache of additional modules that should be used for name lookup
6739   /// within the current template instantiation. Computed lazily; use
6740   /// getLookupModules() to get a complete set.
6741   llvm::DenseSet<Module*> LookupModulesCache;
6742
6743   /// \brief Get the set of additional modules that should be checked during
6744   /// name lookup. A module and its imports become visible when instanting a
6745   /// template defined within it.
6746   llvm::DenseSet<Module*> &getLookupModules();
6747
6748   /// \brief Map from the most recent declaration of a namespace to the most
6749   /// recent visible declaration of that namespace.
6750   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
6751
6752   /// \brief Whether we are in a SFINAE context that is not associated with
6753   /// template instantiation.
6754   ///
6755   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6756   /// of a template instantiation or template argument deduction.
6757   bool InNonInstantiationSFINAEContext;
6758
6759   /// \brief The number of ActiveTemplateInstantiation entries in
6760   /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6761   /// therefore, should not be counted as part of the instantiation depth.
6762   unsigned NonInstantiationEntries;
6763
6764   /// \brief The last template from which a template instantiation
6765   /// error or warning was produced.
6766   ///
6767   /// This value is used to suppress printing of redundant template
6768   /// instantiation backtraces when there are multiple errors in the
6769   /// same instantiation. FIXME: Does this belong in Sema? It's tough
6770   /// to implement it anywhere else.
6771   ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6772
6773   /// \brief The current index into pack expansion arguments that will be
6774   /// used for substitution of parameter packs.
6775   ///
6776   /// The pack expansion index will be -1 to indicate that parameter packs
6777   /// should be instantiated as themselves. Otherwise, the index specifies
6778   /// which argument within the parameter pack will be used for substitution.
6779   int ArgumentPackSubstitutionIndex;
6780
6781   /// \brief RAII object used to change the argument pack substitution index
6782   /// within a \c Sema object.
6783   ///
6784   /// See \c ArgumentPackSubstitutionIndex for more information.
6785   class ArgumentPackSubstitutionIndexRAII {
6786     Sema &Self;
6787     int OldSubstitutionIndex;
6788
6789   public:
6790     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6791       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6792       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6793     }
6794
6795     ~ArgumentPackSubstitutionIndexRAII() {
6796       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6797     }
6798   };
6799
6800   friend class ArgumentPackSubstitutionRAII;
6801
6802   /// \brief For each declaration that involved template argument deduction, the
6803   /// set of diagnostics that were suppressed during that template argument
6804   /// deduction.
6805   ///
6806   /// FIXME: Serialize this structure to the AST file.
6807   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6808     SuppressedDiagnosticsMap;
6809   SuppressedDiagnosticsMap SuppressedDiagnostics;
6810
6811   /// \brief A stack object to be created when performing template
6812   /// instantiation.
6813   ///
6814   /// Construction of an object of type \c InstantiatingTemplate
6815   /// pushes the current instantiation onto the stack of active
6816   /// instantiations. If the size of this stack exceeds the maximum
6817   /// number of recursive template instantiations, construction
6818   /// produces an error and evaluates true.
6819   ///
6820   /// Destruction of this object will pop the named instantiation off
6821   /// the stack.
6822   struct InstantiatingTemplate {
6823     /// \brief Note that we are instantiating a class template,
6824     /// function template, variable template, alias template,
6825     /// or a member thereof.
6826     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6827                           Decl *Entity,
6828                           SourceRange InstantiationRange = SourceRange());
6829
6830     struct ExceptionSpecification {};
6831     /// \brief Note that we are instantiating an exception specification
6832     /// of a function template.
6833     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6834                           FunctionDecl *Entity, ExceptionSpecification,
6835                           SourceRange InstantiationRange = SourceRange());
6836
6837     /// \brief Note that we are instantiating a default argument in a
6838     /// template-id.
6839     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6840                           TemplateDecl *Template,
6841                           ArrayRef<TemplateArgument> TemplateArgs,
6842                           SourceRange InstantiationRange = SourceRange());
6843
6844     /// \brief Note that we are instantiating a default argument in a
6845     /// template-id.
6846     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6847                           FunctionTemplateDecl *FunctionTemplate,
6848                           ArrayRef<TemplateArgument> TemplateArgs,
6849                           ActiveTemplateInstantiation::InstantiationKind Kind,
6850                           sema::TemplateDeductionInfo &DeductionInfo,
6851                           SourceRange InstantiationRange = SourceRange());
6852
6853     /// \brief Note that we are instantiating as part of template
6854     /// argument deduction for a class template partial
6855     /// specialization.
6856     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6857                           ClassTemplatePartialSpecializationDecl *PartialSpec,
6858                           ArrayRef<TemplateArgument> TemplateArgs,
6859                           sema::TemplateDeductionInfo &DeductionInfo,
6860                           SourceRange InstantiationRange = SourceRange());
6861
6862     /// \brief Note that we are instantiating as part of template
6863     /// argument deduction for a variable template partial
6864     /// specialization.
6865     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6866                           VarTemplatePartialSpecializationDecl *PartialSpec,
6867                           ArrayRef<TemplateArgument> TemplateArgs,
6868                           sema::TemplateDeductionInfo &DeductionInfo,
6869                           SourceRange InstantiationRange = SourceRange());
6870
6871     /// \brief Note that we are instantiating a default argument for a function
6872     /// parameter.
6873     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6874                           ParmVarDecl *Param,
6875                           ArrayRef<TemplateArgument> TemplateArgs,
6876                           SourceRange InstantiationRange = SourceRange());
6877
6878     /// \brief Note that we are substituting prior template arguments into a
6879     /// non-type parameter.
6880     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6881                           NamedDecl *Template,
6882                           NonTypeTemplateParmDecl *Param,
6883                           ArrayRef<TemplateArgument> TemplateArgs,
6884                           SourceRange InstantiationRange);
6885
6886     /// \brief Note that we are substituting prior template arguments into a
6887     /// template template parameter.
6888     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6889                           NamedDecl *Template,
6890                           TemplateTemplateParmDecl *Param,
6891                           ArrayRef<TemplateArgument> TemplateArgs,
6892                           SourceRange InstantiationRange);
6893
6894     /// \brief Note that we are checking the default template argument
6895     /// against the template parameter for a given template-id.
6896     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6897                           TemplateDecl *Template,
6898                           NamedDecl *Param,
6899                           ArrayRef<TemplateArgument> TemplateArgs,
6900                           SourceRange InstantiationRange);
6901
6902
6903     /// \brief Note that we have finished instantiating this template.
6904     void Clear();
6905
6906     ~InstantiatingTemplate() { Clear(); }
6907
6908     /// \brief Determines whether we have exceeded the maximum
6909     /// recursive template instantiations.
6910     bool isInvalid() const { return Invalid; }
6911
6912   private:
6913     Sema &SemaRef;
6914     bool Invalid;
6915     bool SavedInNonInstantiationSFINAEContext;
6916     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6917                                  SourceRange InstantiationRange);
6918
6919     InstantiatingTemplate(
6920         Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
6921         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6922         Decl *Entity, NamedDecl *Template = nullptr,
6923         ArrayRef<TemplateArgument> TemplateArgs = None,
6924         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6925
6926     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
6927
6928     InstantiatingTemplate&
6929     operator=(const InstantiatingTemplate&) = delete;
6930   };
6931
6932   void PrintInstantiationStack();
6933
6934   /// \brief Determines whether we are currently in a context where
6935   /// template argument substitution failures are not considered
6936   /// errors.
6937   ///
6938   /// \returns An empty \c Optional if we're not in a SFINAE context.
6939   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6940   /// template-deduction context object, which can be used to capture
6941   /// diagnostics that will be suppressed.
6942   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6943
6944   /// \brief Determines whether we are currently in a context that
6945   /// is not evaluated as per C++ [expr] p5.
6946   bool isUnevaluatedContext() const {
6947     assert(!ExprEvalContexts.empty() &&
6948            "Must be in an expression evaluation context");
6949     return ExprEvalContexts.back().isUnevaluated();
6950   }
6951
6952   /// \brief RAII class used to determine whether SFINAE has
6953   /// trapped any errors that occur during template argument
6954   /// deduction.
6955   class SFINAETrap {
6956     Sema &SemaRef;
6957     unsigned PrevSFINAEErrors;
6958     bool PrevInNonInstantiationSFINAEContext;
6959     bool PrevAccessCheckingSFINAE;
6960
6961   public:
6962     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6963       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6964         PrevInNonInstantiationSFINAEContext(
6965                                       SemaRef.InNonInstantiationSFINAEContext),
6966         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6967     {
6968       if (!SemaRef.isSFINAEContext())
6969         SemaRef.InNonInstantiationSFINAEContext = true;
6970       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6971     }
6972
6973     ~SFINAETrap() {
6974       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6975       SemaRef.InNonInstantiationSFINAEContext
6976         = PrevInNonInstantiationSFINAEContext;
6977       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6978     }
6979
6980     /// \brief Determine whether any SFINAE errors have been trapped.
6981     bool hasErrorOccurred() const {
6982       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6983     }
6984   };
6985
6986   /// \brief RAII class used to indicate that we are performing provisional
6987   /// semantic analysis to determine the validity of a construct, so
6988   /// typo-correction and diagnostics in the immediate context (not within
6989   /// implicitly-instantiated templates) should be suppressed.
6990   class TentativeAnalysisScope {
6991     Sema &SemaRef;
6992     // FIXME: Using a SFINAETrap for this is a hack.
6993     SFINAETrap Trap;
6994     bool PrevDisableTypoCorrection;
6995   public:
6996     explicit TentativeAnalysisScope(Sema &SemaRef)
6997         : SemaRef(SemaRef), Trap(SemaRef, true),
6998           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6999       SemaRef.DisableTypoCorrection = true;
7000     }
7001     ~TentativeAnalysisScope() {
7002       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7003     }
7004   };
7005
7006   /// \brief The current instantiation scope used to store local
7007   /// variables.
7008   LocalInstantiationScope *CurrentInstantiationScope;
7009
7010   /// \brief Tracks whether we are in a context where typo correction is
7011   /// disabled.
7012   bool DisableTypoCorrection;
7013
7014   /// \brief The number of typos corrected by CorrectTypo.
7015   unsigned TyposCorrected;
7016
7017   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7018   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7019
7020   /// \brief A cache containing identifiers for which typo correction failed and
7021   /// their locations, so that repeated attempts to correct an identifier in a
7022   /// given location are ignored if typo correction already failed for it.
7023   IdentifierSourceLocations TypoCorrectionFailures;
7024
7025   /// \brief Worker object for performing CFG-based warnings.
7026   sema::AnalysisBasedWarnings AnalysisWarnings;
7027   threadSafety::BeforeSet *ThreadSafetyDeclCache;
7028
7029   /// \brief An entity for which implicit template instantiation is required.
7030   ///
7031   /// The source location associated with the declaration is the first place in
7032   /// the source code where the declaration was "used". It is not necessarily
7033   /// the point of instantiation (which will be either before or after the
7034   /// namespace-scope declaration that triggered this implicit instantiation),
7035   /// However, it is the location that diagnostics should generally refer to,
7036   /// because users will need to know what code triggered the instantiation.
7037   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7038
7039   /// \brief The queue of implicit template instantiations that are required
7040   /// but have not yet been performed.
7041   std::deque<PendingImplicitInstantiation> PendingInstantiations;
7042
7043   class SavePendingInstantiationsAndVTableUsesRAII {
7044   public:
7045     SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7046         : S(S), Enabled(Enabled) {
7047       if (!Enabled) return;
7048
7049       SavedPendingInstantiations.swap(S.PendingInstantiations);
7050       SavedVTableUses.swap(S.VTableUses);
7051     }
7052
7053     ~SavePendingInstantiationsAndVTableUsesRAII() {
7054       if (!Enabled) return;
7055
7056       // Restore the set of pending vtables.
7057       assert(S.VTableUses.empty() &&
7058              "VTableUses should be empty before it is discarded.");
7059       S.VTableUses.swap(SavedVTableUses);
7060
7061       // Restore the set of pending implicit instantiations.
7062       assert(S.PendingInstantiations.empty() &&
7063              "PendingInstantiations should be empty before it is discarded.");
7064       S.PendingInstantiations.swap(SavedPendingInstantiations);
7065     }
7066
7067   private:
7068     Sema &S;
7069     SmallVector<VTableUse, 16> SavedVTableUses;
7070     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7071     bool Enabled;
7072   };
7073
7074   /// \brief The queue of implicit template instantiations that are required
7075   /// and must be performed within the current local scope.
7076   ///
7077   /// This queue is only used for member functions of local classes in
7078   /// templates, which must be instantiated in the same scope as their
7079   /// enclosing function, so that they can reference function-local
7080   /// types, static variables, enumerators, etc.
7081   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7082
7083   class SavePendingLocalImplicitInstantiationsRAII {
7084   public:
7085     SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7086       SavedPendingLocalImplicitInstantiations.swap(
7087           S.PendingLocalImplicitInstantiations);
7088     }
7089
7090     ~SavePendingLocalImplicitInstantiationsRAII() {
7091       assert(S.PendingLocalImplicitInstantiations.empty() &&
7092              "there shouldn't be any pending local implicit instantiations");
7093       SavedPendingLocalImplicitInstantiations.swap(
7094           S.PendingLocalImplicitInstantiations);
7095     }
7096
7097   private:
7098     Sema &S;
7099     std::deque<PendingImplicitInstantiation>
7100     SavedPendingLocalImplicitInstantiations;
7101   };
7102
7103   /// A helper class for building up ExtParameterInfos.
7104   class ExtParameterInfoBuilder {
7105     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7106     bool HasInteresting = false;
7107
7108   public:
7109     /// Set the ExtParameterInfo for the parameter at the given index,
7110     /// 
7111     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7112       assert(Infos.size() <= index);
7113       Infos.resize(index);
7114       Infos.push_back(info);
7115
7116       if (!HasInteresting)
7117         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7118     }
7119
7120     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7121     /// ExtParameterInfo array we've built up.
7122     const FunctionProtoType::ExtParameterInfo *
7123     getPointerOrNull(unsigned numParams) {
7124       if (!HasInteresting) return nullptr;
7125       Infos.resize(numParams);
7126       return Infos.data();
7127     }
7128   };
7129
7130   void PerformPendingInstantiations(bool LocalOnly = false);
7131
7132   TypeSourceInfo *SubstType(TypeSourceInfo *T,
7133                             const MultiLevelTemplateArgumentList &TemplateArgs,
7134                             SourceLocation Loc, DeclarationName Entity);
7135
7136   QualType SubstType(QualType T,
7137                      const MultiLevelTemplateArgumentList &TemplateArgs,
7138                      SourceLocation Loc, DeclarationName Entity);
7139
7140   TypeSourceInfo *SubstType(TypeLoc TL,
7141                             const MultiLevelTemplateArgumentList &TemplateArgs,
7142                             SourceLocation Loc, DeclarationName Entity);
7143
7144   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7145                             const MultiLevelTemplateArgumentList &TemplateArgs,
7146                                         SourceLocation Loc,
7147                                         DeclarationName Entity,
7148                                         CXXRecordDecl *ThisContext,
7149                                         unsigned ThisTypeQuals);
7150   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7151                           const MultiLevelTemplateArgumentList &Args);
7152   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7153                             const MultiLevelTemplateArgumentList &TemplateArgs,
7154                                 int indexAdjustment,
7155                                 Optional<unsigned> NumExpansions,
7156                                 bool ExpectParameterPack);
7157   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7158                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7159                       const MultiLevelTemplateArgumentList &TemplateArgs,
7160                       SmallVectorImpl<QualType> &ParamTypes,
7161                       SmallVectorImpl<ParmVarDecl *> *OutParams,
7162                       ExtParameterInfoBuilder &ParamInfos);
7163   ExprResult SubstExpr(Expr *E,
7164                        const MultiLevelTemplateArgumentList &TemplateArgs);
7165
7166   /// \brief Substitute the given template arguments into a list of
7167   /// expressions, expanding pack expansions if required.
7168   ///
7169   /// \param Exprs The list of expressions to substitute into.
7170   ///
7171   /// \param IsCall Whether this is some form of call, in which case
7172   /// default arguments will be dropped.
7173   ///
7174   /// \param TemplateArgs The set of template arguments to substitute.
7175   ///
7176   /// \param Outputs Will receive all of the substituted arguments.
7177   ///
7178   /// \returns true if an error occurred, false otherwise.
7179   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7180                   const MultiLevelTemplateArgumentList &TemplateArgs,
7181                   SmallVectorImpl<Expr *> &Outputs);
7182
7183   StmtResult SubstStmt(Stmt *S,
7184                        const MultiLevelTemplateArgumentList &TemplateArgs);
7185
7186   Decl *SubstDecl(Decl *D, DeclContext *Owner,
7187                   const MultiLevelTemplateArgumentList &TemplateArgs);
7188
7189   ExprResult SubstInitializer(Expr *E,
7190                        const MultiLevelTemplateArgumentList &TemplateArgs,
7191                        bool CXXDirectInit);
7192
7193   bool
7194   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7195                       CXXRecordDecl *Pattern,
7196                       const MultiLevelTemplateArgumentList &TemplateArgs);
7197
7198   bool
7199   InstantiateClass(SourceLocation PointOfInstantiation,
7200                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7201                    const MultiLevelTemplateArgumentList &TemplateArgs,
7202                    TemplateSpecializationKind TSK,
7203                    bool Complain = true);
7204
7205   bool InstantiateEnum(SourceLocation PointOfInstantiation,
7206                        EnumDecl *Instantiation, EnumDecl *Pattern,
7207                        const MultiLevelTemplateArgumentList &TemplateArgs,
7208                        TemplateSpecializationKind TSK);
7209
7210   bool InstantiateInClassInitializer(
7211       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7212       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7213
7214   struct LateInstantiatedAttribute {
7215     const Attr *TmplAttr;
7216     LocalInstantiationScope *Scope;
7217     Decl *NewDecl;
7218
7219     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7220                               Decl *D)
7221       : TmplAttr(A), Scope(S), NewDecl(D)
7222     { }
7223   };
7224   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7225
7226   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7227                         const Decl *Pattern, Decl *Inst,
7228                         LateInstantiatedAttrVec *LateAttrs = nullptr,
7229                         LocalInstantiationScope *OuterMostScope = nullptr);
7230
7231   bool
7232   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7233                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
7234                            TemplateSpecializationKind TSK,
7235                            bool Complain = true);
7236
7237   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7238                                CXXRecordDecl *Instantiation,
7239                             const MultiLevelTemplateArgumentList &TemplateArgs,
7240                                TemplateSpecializationKind TSK);
7241
7242   void InstantiateClassTemplateSpecializationMembers(
7243                                           SourceLocation PointOfInstantiation,
7244                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
7245                                                 TemplateSpecializationKind TSK);
7246
7247   NestedNameSpecifierLoc
7248   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7249                            const MultiLevelTemplateArgumentList &TemplateArgs);
7250
7251   DeclarationNameInfo
7252   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7253                            const MultiLevelTemplateArgumentList &TemplateArgs);
7254   TemplateName
7255   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7256                     SourceLocation Loc,
7257                     const MultiLevelTemplateArgumentList &TemplateArgs);
7258   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7259              TemplateArgumentListInfo &Result,
7260              const MultiLevelTemplateArgumentList &TemplateArgs);
7261
7262   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7263                                 FunctionDecl *Function);
7264   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7265                                      FunctionDecl *Function,
7266                                      bool Recursive = false,
7267                                      bool DefinitionRequired = false,
7268                                      bool AtEndOfTU = false);
7269   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7270       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7271       const TemplateArgumentList &TemplateArgList,
7272       const TemplateArgumentListInfo &TemplateArgsInfo,
7273       SmallVectorImpl<TemplateArgument> &Converted,
7274       SourceLocation PointOfInstantiation, void *InsertPos,
7275       LateInstantiatedAttrVec *LateAttrs = nullptr,
7276       LocalInstantiationScope *StartingScope = nullptr);
7277   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7278       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7279       const MultiLevelTemplateArgumentList &TemplateArgs);
7280   void
7281   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7282                              const MultiLevelTemplateArgumentList &TemplateArgs,
7283                              LateInstantiatedAttrVec *LateAttrs,
7284                              DeclContext *Owner,
7285                              LocalInstantiationScope *StartingScope,
7286                              bool InstantiatingVarTemplate = false);
7287   void InstantiateVariableInitializer(
7288       VarDecl *Var, VarDecl *OldVar,
7289       const MultiLevelTemplateArgumentList &TemplateArgs);
7290   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7291                                      VarDecl *Var, bool Recursive = false,
7292                                      bool DefinitionRequired = false,
7293                                      bool AtEndOfTU = false);
7294   void InstantiateStaticDataMemberDefinition(
7295                                      SourceLocation PointOfInstantiation,
7296                                      VarDecl *Var,
7297                                      bool Recursive = false,
7298                                      bool DefinitionRequired = false);
7299
7300   void InstantiateMemInitializers(CXXConstructorDecl *New,
7301                                   const CXXConstructorDecl *Tmpl,
7302                             const MultiLevelTemplateArgumentList &TemplateArgs);
7303
7304   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7305                           const MultiLevelTemplateArgumentList &TemplateArgs);
7306   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7307                           const MultiLevelTemplateArgumentList &TemplateArgs);
7308
7309   // Objective-C declarations.
7310   enum ObjCContainerKind {
7311     OCK_None = -1,
7312     OCK_Interface = 0,
7313     OCK_Protocol,
7314     OCK_Category,
7315     OCK_ClassExtension,
7316     OCK_Implementation,
7317     OCK_CategoryImplementation
7318   };
7319   ObjCContainerKind getObjCContainerKind() const;
7320
7321   DeclResult actOnObjCTypeParam(Scope *S,
7322                                 ObjCTypeParamVariance variance,
7323                                 SourceLocation varianceLoc,
7324                                 unsigned index,
7325                                 IdentifierInfo *paramName,
7326                                 SourceLocation paramLoc,
7327                                 SourceLocation colonLoc,
7328                                 ParsedType typeBound);
7329
7330   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7331                                             ArrayRef<Decl *> typeParams,
7332                                             SourceLocation rAngleLoc);
7333   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7334
7335   Decl *ActOnStartClassInterface(Scope *S,
7336                                  SourceLocation AtInterfaceLoc,
7337                                  IdentifierInfo *ClassName,
7338                                  SourceLocation ClassLoc,
7339                                  ObjCTypeParamList *typeParamList,
7340                                  IdentifierInfo *SuperName,
7341                                  SourceLocation SuperLoc,
7342                                  ArrayRef<ParsedType> SuperTypeArgs,
7343                                  SourceRange SuperTypeArgsRange,
7344                                  Decl * const *ProtoRefs,
7345                                  unsigned NumProtoRefs,
7346                                  const SourceLocation *ProtoLocs,
7347                                  SourceLocation EndProtoLoc,
7348                                  AttributeList *AttrList);
7349     
7350   void ActOnSuperClassOfClassInterface(Scope *S,
7351                                        SourceLocation AtInterfaceLoc,
7352                                        ObjCInterfaceDecl *IDecl,
7353                                        IdentifierInfo *ClassName,
7354                                        SourceLocation ClassLoc,
7355                                        IdentifierInfo *SuperName,
7356                                        SourceLocation SuperLoc,
7357                                        ArrayRef<ParsedType> SuperTypeArgs,
7358                                        SourceRange SuperTypeArgsRange);
7359   
7360   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7361                                IdentifierInfo *SuperName,
7362                                SourceLocation SuperLoc);
7363
7364   Decl *ActOnCompatibilityAlias(
7365                     SourceLocation AtCompatibilityAliasLoc,
7366                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
7367                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
7368
7369   bool CheckForwardProtocolDeclarationForCircularDependency(
7370     IdentifierInfo *PName,
7371     SourceLocation &PLoc, SourceLocation PrevLoc,
7372     const ObjCList<ObjCProtocolDecl> &PList);
7373
7374   Decl *ActOnStartProtocolInterface(
7375                     SourceLocation AtProtoInterfaceLoc,
7376                     IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7377                     Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7378                     const SourceLocation *ProtoLocs,
7379                     SourceLocation EndProtoLoc,
7380                     AttributeList *AttrList);
7381
7382   Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7383                                     IdentifierInfo *ClassName,
7384                                     SourceLocation ClassLoc,
7385                                     ObjCTypeParamList *typeParamList,
7386                                     IdentifierInfo *CategoryName,
7387                                     SourceLocation CategoryLoc,
7388                                     Decl * const *ProtoRefs,
7389                                     unsigned NumProtoRefs,
7390                                     const SourceLocation *ProtoLocs,
7391                                     SourceLocation EndProtoLoc);
7392
7393   Decl *ActOnStartClassImplementation(
7394                     SourceLocation AtClassImplLoc,
7395                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
7396                     IdentifierInfo *SuperClassname,
7397                     SourceLocation SuperClassLoc);
7398
7399   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7400                                          IdentifierInfo *ClassName,
7401                                          SourceLocation ClassLoc,
7402                                          IdentifierInfo *CatName,
7403                                          SourceLocation CatLoc);
7404
7405   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7406                                                ArrayRef<Decl *> Decls);
7407
7408   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7409                    IdentifierInfo **IdentList,
7410                    SourceLocation *IdentLocs,
7411                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
7412                    unsigned NumElts);
7413
7414   DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7415                                         ArrayRef<IdentifierLocPair> IdentList,
7416                                         AttributeList *attrList);
7417
7418   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7419                                ArrayRef<IdentifierLocPair> ProtocolId,
7420                                SmallVectorImpl<Decl *> &Protocols);
7421
7422   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7423                                     SourceLocation ProtocolLoc,
7424                                     IdentifierInfo *TypeArgId,
7425                                     SourceLocation TypeArgLoc,
7426                                     bool SelectProtocolFirst = false);
7427
7428   /// Given a list of identifiers (and their locations), resolve the
7429   /// names to either Objective-C protocol qualifiers or type
7430   /// arguments, as appropriate.
7431   void actOnObjCTypeArgsOrProtocolQualifiers(
7432          Scope *S,
7433          ParsedType baseType,
7434          SourceLocation lAngleLoc,
7435          ArrayRef<IdentifierInfo *> identifiers,
7436          ArrayRef<SourceLocation> identifierLocs,
7437          SourceLocation rAngleLoc,
7438          SourceLocation &typeArgsLAngleLoc,
7439          SmallVectorImpl<ParsedType> &typeArgs,
7440          SourceLocation &typeArgsRAngleLoc,
7441          SourceLocation &protocolLAngleLoc,
7442          SmallVectorImpl<Decl *> &protocols,
7443          SourceLocation &protocolRAngleLoc,
7444          bool warnOnIncompleteProtocols);
7445
7446   /// Build a an Objective-C protocol-qualified 'id' type where no
7447   /// base type was specified.
7448   TypeResult actOnObjCProtocolQualifierType(
7449                SourceLocation lAngleLoc,
7450                ArrayRef<Decl *> protocols,
7451                ArrayRef<SourceLocation> protocolLocs,
7452                SourceLocation rAngleLoc);
7453
7454   /// Build a specialized and/or protocol-qualified Objective-C type.
7455   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7456                Scope *S,
7457                SourceLocation Loc,
7458                ParsedType BaseType,
7459                SourceLocation TypeArgsLAngleLoc,
7460                ArrayRef<ParsedType> TypeArgs,
7461                SourceLocation TypeArgsRAngleLoc,
7462                SourceLocation ProtocolLAngleLoc,
7463                ArrayRef<Decl *> Protocols,
7464                ArrayRef<SourceLocation> ProtocolLocs,
7465                SourceLocation ProtocolRAngleLoc);
7466
7467   /// Build an Objective-C object pointer type.
7468   QualType BuildObjCObjectType(QualType BaseType,
7469                                SourceLocation Loc,
7470                                SourceLocation TypeArgsLAngleLoc,
7471                                ArrayRef<TypeSourceInfo *> TypeArgs,
7472                                SourceLocation TypeArgsRAngleLoc,
7473                                SourceLocation ProtocolLAngleLoc,
7474                                ArrayRef<ObjCProtocolDecl *> Protocols,
7475                                ArrayRef<SourceLocation> ProtocolLocs,
7476                                SourceLocation ProtocolRAngleLoc,
7477                                bool FailOnError = false);
7478
7479   /// Check the application of the Objective-C '__kindof' qualifier to
7480   /// the given type.
7481   bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7482
7483   /// Ensure attributes are consistent with type.
7484   /// \param [in, out] Attributes The attributes to check; they will
7485   /// be modified to be consistent with \p PropertyTy.
7486   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7487                                    SourceLocation Loc,
7488                                    unsigned &Attributes,
7489                                    bool propertyInPrimaryClass);
7490
7491   /// Process the specified property declaration and create decls for the
7492   /// setters and getters as needed.
7493   /// \param property The property declaration being processed
7494   void ProcessPropertyDecl(ObjCPropertyDecl *property);
7495
7496
7497   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7498                                 ObjCPropertyDecl *SuperProperty,
7499                                 const IdentifierInfo *Name,
7500                                 bool OverridingProtocolProperty);
7501
7502   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7503                                         ObjCInterfaceDecl *ID);
7504
7505   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7506                    ArrayRef<Decl *> allMethods = None,
7507                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
7508
7509   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7510                       SourceLocation LParenLoc,
7511                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
7512                       Selector GetterSel, Selector SetterSel,
7513                       tok::ObjCKeywordKind MethodImplKind,
7514                       DeclContext *lexicalDC = nullptr);
7515
7516   Decl *ActOnPropertyImplDecl(Scope *S,
7517                               SourceLocation AtLoc,
7518                               SourceLocation PropertyLoc,
7519                               bool ImplKind,
7520                               IdentifierInfo *PropertyId,
7521                               IdentifierInfo *PropertyIvar,
7522                               SourceLocation PropertyIvarLoc,
7523                               ObjCPropertyQueryKind QueryKind);
7524
7525   enum ObjCSpecialMethodKind {
7526     OSMK_None,
7527     OSMK_Alloc,
7528     OSMK_New,
7529     OSMK_Copy,
7530     OSMK_RetainingInit,
7531     OSMK_NonRetainingInit
7532   };
7533
7534   struct ObjCArgInfo {
7535     IdentifierInfo *Name;
7536     SourceLocation NameLoc;
7537     // The Type is null if no type was specified, and the DeclSpec is invalid
7538     // in this case.
7539     ParsedType Type;
7540     ObjCDeclSpec DeclSpec;
7541
7542     /// ArgAttrs - Attribute list for this argument.
7543     AttributeList *ArgAttrs;
7544   };
7545
7546   Decl *ActOnMethodDeclaration(
7547     Scope *S,
7548     SourceLocation BeginLoc, // location of the + or -.
7549     SourceLocation EndLoc,   // location of the ; or {.
7550     tok::TokenKind MethodType,
7551     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7552     ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7553     // optional arguments. The number of types/arguments is obtained
7554     // from the Sel.getNumArgs().
7555     ObjCArgInfo *ArgInfo,
7556     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7557     AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7558     bool isVariadic, bool MethodDefinition);
7559
7560   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7561                                               const ObjCObjectPointerType *OPT,
7562                                               bool IsInstance);
7563   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7564                                            bool IsInstance);
7565
7566   bool CheckARCMethodDecl(ObjCMethodDecl *method);
7567   bool inferObjCARCLifetime(ValueDecl *decl);
7568
7569   ExprResult
7570   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7571                             Expr *BaseExpr,
7572                             SourceLocation OpLoc,
7573                             DeclarationName MemberName,
7574                             SourceLocation MemberLoc,
7575                             SourceLocation SuperLoc, QualType SuperType,
7576                             bool Super);
7577
7578   ExprResult
7579   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7580                             IdentifierInfo &propertyName,
7581                             SourceLocation receiverNameLoc,
7582                             SourceLocation propertyNameLoc);
7583
7584   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7585
7586   /// \brief Describes the kind of message expression indicated by a message
7587   /// send that starts with an identifier.
7588   enum ObjCMessageKind {
7589     /// \brief The message is sent to 'super'.
7590     ObjCSuperMessage,
7591     /// \brief The message is an instance message.
7592     ObjCInstanceMessage,
7593     /// \brief The message is a class message, and the identifier is a type
7594     /// name.
7595     ObjCClassMessage
7596   };
7597
7598   ObjCMessageKind getObjCMessageKind(Scope *S,
7599                                      IdentifierInfo *Name,
7600                                      SourceLocation NameLoc,
7601                                      bool IsSuper,
7602                                      bool HasTrailingDot,
7603                                      ParsedType &ReceiverType);
7604
7605   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7606                                Selector Sel,
7607                                SourceLocation LBracLoc,
7608                                ArrayRef<SourceLocation> SelectorLocs,
7609                                SourceLocation RBracLoc,
7610                                MultiExprArg Args);
7611
7612   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7613                                QualType ReceiverType,
7614                                SourceLocation SuperLoc,
7615                                Selector Sel,
7616                                ObjCMethodDecl *Method,
7617                                SourceLocation LBracLoc,
7618                                ArrayRef<SourceLocation> SelectorLocs,
7619                                SourceLocation RBracLoc,
7620                                MultiExprArg Args,
7621                                bool isImplicit = false);
7622
7623   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7624                                        bool isSuperReceiver,
7625                                        SourceLocation Loc,
7626                                        Selector Sel,
7627                                        ObjCMethodDecl *Method,
7628                                        MultiExprArg Args);
7629
7630   ExprResult ActOnClassMessage(Scope *S,
7631                                ParsedType Receiver,
7632                                Selector Sel,
7633                                SourceLocation LBracLoc,
7634                                ArrayRef<SourceLocation> SelectorLocs,
7635                                SourceLocation RBracLoc,
7636                                MultiExprArg Args);
7637
7638   ExprResult BuildInstanceMessage(Expr *Receiver,
7639                                   QualType ReceiverType,
7640                                   SourceLocation SuperLoc,
7641                                   Selector Sel,
7642                                   ObjCMethodDecl *Method,
7643                                   SourceLocation LBracLoc,
7644                                   ArrayRef<SourceLocation> SelectorLocs,
7645                                   SourceLocation RBracLoc,
7646                                   MultiExprArg Args,
7647                                   bool isImplicit = false);
7648
7649   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7650                                           QualType ReceiverType,
7651                                           SourceLocation Loc,
7652                                           Selector Sel,
7653                                           ObjCMethodDecl *Method,
7654                                           MultiExprArg Args);
7655
7656   ExprResult ActOnInstanceMessage(Scope *S,
7657                                   Expr *Receiver,
7658                                   Selector Sel,
7659                                   SourceLocation LBracLoc,
7660                                   ArrayRef<SourceLocation> SelectorLocs,
7661                                   SourceLocation RBracLoc,
7662                                   MultiExprArg Args);
7663
7664   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7665                                   ObjCBridgeCastKind Kind,
7666                                   SourceLocation BridgeKeywordLoc,
7667                                   TypeSourceInfo *TSInfo,
7668                                   Expr *SubExpr);
7669
7670   ExprResult ActOnObjCBridgedCast(Scope *S,
7671                                   SourceLocation LParenLoc,
7672                                   ObjCBridgeCastKind Kind,
7673                                   SourceLocation BridgeKeywordLoc,
7674                                   ParsedType Type,
7675                                   SourceLocation RParenLoc,
7676                                   Expr *SubExpr);
7677   
7678   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7679   
7680   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7681   
7682   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7683                                      CastKind &Kind);
7684   
7685   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7686                                         QualType DestType, QualType SrcType,
7687                                         ObjCInterfaceDecl *&RelatedClass,
7688                                         ObjCMethodDecl *&ClassMethod,
7689                                         ObjCMethodDecl *&InstanceMethod,
7690                                         TypedefNameDecl *&TDNDecl,
7691                                         bool CfToNs, bool Diagnose = true);
7692
7693   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7694                                          QualType DestType, QualType SrcType,
7695                                          Expr *&SrcExpr, bool Diagnose = true);
7696
7697   bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
7698                                           bool Diagnose = true);
7699
7700   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7701
7702   /// \brief Check whether the given new method is a valid override of the
7703   /// given overridden method, and set any properties that should be inherited.
7704   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7705                                const ObjCMethodDecl *Overridden);
7706
7707   /// \brief Describes the compatibility of a result type with its method.
7708   enum ResultTypeCompatibilityKind {
7709     RTC_Compatible,
7710     RTC_Incompatible,
7711     RTC_Unknown
7712   };
7713
7714   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7715                                 ObjCInterfaceDecl *CurrentClass,
7716                                 ResultTypeCompatibilityKind RTC);
7717
7718   enum PragmaOptionsAlignKind {
7719     POAK_Native,  // #pragma options align=native
7720     POAK_Natural, // #pragma options align=natural
7721     POAK_Packed,  // #pragma options align=packed
7722     POAK_Power,   // #pragma options align=power
7723     POAK_Mac68k,  // #pragma options align=mac68k
7724     POAK_Reset    // #pragma options align=reset
7725   };
7726
7727   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7728   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7729                                SourceLocation PragmaLoc);
7730
7731   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7732   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
7733                        StringRef SlotLabel, Expr *Alignment);
7734
7735   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7736   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7737
7738   /// ActOnPragmaMSComment - Called on well formed
7739   /// \#pragma comment(kind, "arg").
7740   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
7741                             StringRef Arg);
7742
7743   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7744   /// pointers_to_members(representation method[, general purpose
7745   /// representation]).
7746   void ActOnPragmaMSPointersToMembers(
7747       LangOptions::PragmaMSPointersToMembersKind Kind,
7748       SourceLocation PragmaLoc);
7749
7750   /// \brief Called on well formed \#pragma vtordisp().
7751   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
7752                              SourceLocation PragmaLoc,
7753                              MSVtorDispAttr::Mode Value);
7754
7755   enum PragmaSectionKind {
7756     PSK_DataSeg,
7757     PSK_BSSSeg,
7758     PSK_ConstSeg,
7759     PSK_CodeSeg,
7760   };
7761
7762   bool UnifySection(StringRef SectionName,
7763                     int SectionFlags,
7764                     DeclaratorDecl *TheDecl);
7765   bool UnifySection(StringRef SectionName,
7766                     int SectionFlags,
7767                     SourceLocation PragmaSectionLocation);
7768
7769   /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7770   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7771                         PragmaMsStackAction Action,
7772                         llvm::StringRef StackSlotLabel,
7773                         StringLiteral *SegmentName,
7774                         llvm::StringRef PragmaName);
7775
7776   /// \brief Called on well formed \#pragma section().
7777   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7778                             int SectionFlags, StringLiteral *SegmentName);
7779
7780   /// \brief Called on well-formed \#pragma init_seg().
7781   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7782                             StringLiteral *SegmentName);
7783
7784   /// \brief Called on #pragma clang __debug dump II
7785   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
7786
7787   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7788   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
7789                                  StringRef Value);
7790
7791   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7792   void ActOnPragmaUnused(const Token &Identifier,
7793                          Scope *curScope,
7794                          SourceLocation PragmaLoc);
7795
7796   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7797   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7798                              SourceLocation PragmaLoc);
7799
7800   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7801                                  SourceLocation Loc);
7802   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7803
7804   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7805   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7806                          SourceLocation PragmaLoc,
7807                          SourceLocation WeakNameLoc);
7808
7809   /// ActOnPragmaRedefineExtname - Called on well formed
7810   /// \#pragma redefine_extname oldname newname.
7811   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7812                                   IdentifierInfo* AliasName,
7813                                   SourceLocation PragmaLoc,
7814                                   SourceLocation WeakNameLoc,
7815                                   SourceLocation AliasNameLoc);
7816
7817   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7818   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7819                             IdentifierInfo* AliasName,
7820                             SourceLocation PragmaLoc,
7821                             SourceLocation WeakNameLoc,
7822                             SourceLocation AliasNameLoc);
7823
7824   /// ActOnPragmaFPContract - Called on well formed
7825   /// \#pragma {STDC,OPENCL} FP_CONTRACT
7826   void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7827
7828   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7829   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7830   void AddAlignmentAttributesForRecord(RecordDecl *RD);
7831
7832   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7833   void AddMsStructLayoutForRecord(RecordDecl *RD);
7834
7835   /// FreePackedContext - Deallocate and null out PackContext.
7836   void FreePackedContext();
7837
7838   /// PushNamespaceVisibilityAttr - Note that we've entered a
7839   /// namespace with a visibility attribute.
7840   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7841                                    SourceLocation Loc);
7842
7843   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7844   /// add an appropriate visibility attribute.
7845   void AddPushedVisibilityAttribute(Decl *RD);
7846
7847   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7848   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7849   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7850
7851   /// FreeVisContext - Deallocate and null out VisContext.
7852   void FreeVisContext();
7853
7854   /// AddCFAuditedAttribute - Check whether we're currently within
7855   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7856   /// the appropriate attribute.
7857   void AddCFAuditedAttribute(Decl *D);
7858
7859   /// \brief Called on well formed \#pragma clang optimize.
7860   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7861
7862   /// \brief Get the location for the currently active "\#pragma clang optimize
7863   /// off". If this location is invalid, then the state of the pragma is "on".
7864   SourceLocation getOptimizeOffPragmaLocation() const {
7865     return OptimizeOffPragmaLocation;
7866   }
7867
7868   /// \brief Only called on function definitions; if there is a pragma in scope
7869   /// with the effect of a range-based optnone, consider marking the function
7870   /// with attribute optnone.
7871   void AddRangeBasedOptnone(FunctionDecl *FD);
7872
7873   /// \brief Adds the 'optnone' attribute to the function declaration if there
7874   /// are no conflicts; Loc represents the location causing the 'optnone'
7875   /// attribute to be added (usually because of a pragma).
7876   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7877
7878   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7879   void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7880                       unsigned SpellingListIndex, bool IsPackExpansion);
7881   void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7882                       unsigned SpellingListIndex, bool IsPackExpansion);
7883
7884   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7885   /// declaration.
7886   void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7887                             unsigned SpellingListIndex);
7888
7889   /// AddAlignValueAttr - Adds an align_value attribute to a particular
7890   /// declaration.
7891   void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7892                          unsigned SpellingListIndex);
7893
7894   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
7895   /// declaration.
7896   void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
7897                            Expr *MinBlocks, unsigned SpellingListIndex);
7898
7899   /// AddModeAttr - Adds a mode attribute to a particular declaration.
7900   void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
7901                    unsigned SpellingListIndex, bool InInstantiation = false);
7902
7903   void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
7904                            ParameterABI ABI, unsigned SpellingListIndex);
7905
7906   void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
7907                          unsigned SpellingListIndex, bool isNSConsumed,
7908                          bool isTemplateInstantiation);
7909
7910   //===--------------------------------------------------------------------===//
7911   // C++ Coroutines TS
7912   //
7913   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7914   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7915   StmtResult ActOnCoreturnStmt(SourceLocation KwLoc, Expr *E);
7916
7917   ExprResult BuildCoawaitExpr(SourceLocation KwLoc, Expr *E);
7918   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
7919   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E);
7920
7921   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
7922
7923   //===--------------------------------------------------------------------===//
7924   // OpenMP directives and clauses.
7925   //
7926 private:
7927   void *VarDataSharingAttributesStack;
7928   /// Set to true inside '#pragma omp declare target' region.
7929   bool IsInOpenMPDeclareTargetContext = false;
7930   /// \brief Initialization of data-sharing attributes stack.
7931   void InitDataSharingAttributesStack();
7932   void DestroyDataSharingAttributesStack();
7933   ExprResult
7934   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
7935                                         bool StrictlyPositive = true);
7936   /// Returns OpenMP nesting level for current directive.
7937   unsigned getOpenMPNestingLevel() const;
7938
7939 public:
7940   /// \brief Return true if the provided declaration \a VD should be captured by
7941   /// reference.
7942   /// \param Level Relative level of nested OpenMP construct for that the check
7943   /// is performed.
7944   bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
7945
7946   /// \brief Check if the specified variable is used in one of the private
7947   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
7948   /// constructs.
7949   VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
7950   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7951                                    ExprObjectKind OK, SourceLocation Loc);
7952
7953   /// \brief Check if the specified variable is used in 'private' clause.
7954   /// \param Level Relative level of nested OpenMP construct for that the check
7955   /// is performed.
7956   bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
7957
7958   /// \brief Check if the specified variable is captured  by 'target' directive.
7959   /// \param Level Relative level of nested OpenMP construct for that the check
7960   /// is performed.
7961   bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
7962
7963   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7964                                                     Expr *Op);
7965   /// \brief Called on start of new data sharing attribute block.
7966   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7967                            const DeclarationNameInfo &DirName, Scope *CurScope,
7968                            SourceLocation Loc);
7969   /// \brief Start analysis of clauses.
7970   void StartOpenMPClause(OpenMPClauseKind K);
7971   /// \brief End analysis of clauses.
7972   void EndOpenMPClause();
7973   /// \brief Called on end of data sharing attribute block.
7974   void EndOpenMPDSABlock(Stmt *CurDirective);
7975
7976   /// \brief Check if the current region is an OpenMP loop region and if it is,
7977   /// mark loop control variable, used in \p Init for loop initialization, as
7978   /// private by default.
7979   /// \param Init First part of the for loop.
7980   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
7981
7982   // OpenMP directives and clauses.
7983   /// \brief Called on correct id-expression from the '#pragma omp
7984   /// threadprivate'.
7985   ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7986                                      CXXScopeSpec &ScopeSpec,
7987                                      const DeclarationNameInfo &Id);
7988   /// \brief Called on well-formed '#pragma omp threadprivate'.
7989   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7990                                      SourceLocation Loc,
7991                                      ArrayRef<Expr *> VarList);
7992   /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7993   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7994                                      SourceLocation Loc,
7995                                      ArrayRef<Expr *> VarList);
7996   /// \brief Check if the specified type is allowed to be used in 'omp declare
7997   /// reduction' construct.
7998   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
7999                                            TypeResult ParsedType);
8000   /// \brief Called on start of '#pragma omp declare reduction'.
8001   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8002       Scope *S, DeclContext *DC, DeclarationName Name,
8003       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8004       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8005   /// \brief Initialize declare reduction construct initializer.
8006   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8007   /// \brief Finish current declare reduction construct initializer.
8008   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8009   /// \brief Initialize declare reduction construct initializer.
8010   void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8011   /// \brief Finish current declare reduction construct initializer.
8012   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8013   /// \brief Called at the end of '#pragma omp declare reduction'.
8014   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8015       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8016
8017   /// Called on the start of target region i.e. '#pragma omp declare target'.
8018   bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8019   /// Called at the end of target region i.e. '#pragme omp end declare target'.
8020   void ActOnFinishOpenMPDeclareTargetDirective();
8021   /// Called on correct id-expression from the '#pragma omp declare target'.
8022   void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8023                                     const DeclarationNameInfo &Id,
8024                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
8025                                     NamedDeclSetType &SameDirectiveDecls);
8026   /// Check declaration inside target region.
8027   void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8028   /// Return true inside OpenMP target region.
8029   bool isInOpenMPDeclareTargetContext() const {
8030     return IsInOpenMPDeclareTargetContext;
8031   }
8032
8033   /// \brief Initialization of captured region for OpenMP region.
8034   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8035   /// \brief End of OpenMP region.
8036   ///
8037   /// \param S Statement associated with the current OpenMP region.
8038   /// \param Clauses List of clauses for the current OpenMP region.
8039   ///
8040   /// \returns Statement for finished OpenMP region.
8041   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8042   StmtResult ActOnOpenMPExecutableDirective(
8043       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8044       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8045       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8046   /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8047   /// of the  associated statement.
8048   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8049                                           Stmt *AStmt,
8050                                           SourceLocation StartLoc,
8051                                           SourceLocation EndLoc);
8052   /// \brief Called on well-formed '\#pragma omp simd' after parsing
8053   /// of the associated statement.
8054   StmtResult ActOnOpenMPSimdDirective(
8055       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8056       SourceLocation EndLoc,
8057       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8058   /// \brief Called on well-formed '\#pragma omp for' after parsing
8059   /// of the associated statement.
8060   StmtResult ActOnOpenMPForDirective(
8061       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8062       SourceLocation EndLoc,
8063       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8064   /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8065   /// of the associated statement.
8066   StmtResult ActOnOpenMPForSimdDirective(
8067       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8068       SourceLocation EndLoc,
8069       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8070   /// \brief Called on well-formed '\#pragma omp sections' after parsing
8071   /// of the associated statement.
8072   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8073                                           Stmt *AStmt, SourceLocation StartLoc,
8074                                           SourceLocation EndLoc);
8075   /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8076   /// associated statement.
8077   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8078                                          SourceLocation EndLoc);
8079   /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8080   /// associated statement.
8081   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8082                                         Stmt *AStmt, SourceLocation StartLoc,
8083                                         SourceLocation EndLoc);
8084   /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8085   /// associated statement.
8086   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8087                                         SourceLocation EndLoc);
8088   /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8089   /// associated statement.
8090   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8091                                           ArrayRef<OMPClause *> Clauses,
8092                                           Stmt *AStmt, SourceLocation StartLoc,
8093                                           SourceLocation EndLoc);
8094   /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8095   /// of the  associated statement.
8096   StmtResult ActOnOpenMPParallelForDirective(
8097       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8098       SourceLocation EndLoc,
8099       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8100   /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8101   /// parsing of the  associated statement.
8102   StmtResult ActOnOpenMPParallelForSimdDirective(
8103       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8104       SourceLocation EndLoc,
8105       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8106   /// \brief Called on well-formed '\#pragma omp parallel sections' after
8107   /// parsing of the  associated statement.
8108   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8109                                                   Stmt *AStmt,
8110                                                   SourceLocation StartLoc,
8111                                                   SourceLocation EndLoc);
8112   /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8113   /// associated statement.
8114   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8115                                       Stmt *AStmt, SourceLocation StartLoc,
8116                                       SourceLocation EndLoc);
8117   /// \brief Called on well-formed '\#pragma omp taskyield'.
8118   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8119                                            SourceLocation EndLoc);
8120   /// \brief Called on well-formed '\#pragma omp barrier'.
8121   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8122                                          SourceLocation EndLoc);
8123   /// \brief Called on well-formed '\#pragma omp taskwait'.
8124   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8125                                           SourceLocation EndLoc);
8126   /// \brief Called on well-formed '\#pragma omp taskgroup'.
8127   StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8128                                            SourceLocation EndLoc);
8129   /// \brief Called on well-formed '\#pragma omp flush'.
8130   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8131                                        SourceLocation StartLoc,
8132                                        SourceLocation EndLoc);
8133   /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8134   /// associated statement.
8135   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8136                                          Stmt *AStmt, SourceLocation StartLoc,
8137                                          SourceLocation EndLoc);
8138   /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8139   /// associated statement.
8140   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8141                                         Stmt *AStmt, SourceLocation StartLoc,
8142                                         SourceLocation EndLoc);
8143   /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8144   /// associated statement.
8145   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8146                                         Stmt *AStmt, SourceLocation StartLoc,
8147                                         SourceLocation EndLoc);
8148   /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8149   /// the associated statement.
8150   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8151                                             Stmt *AStmt, SourceLocation StartLoc,
8152                                             SourceLocation EndLoc);
8153   /// \brief Called on well-formed '\#pragma omp target enter data' after
8154   /// parsing of the associated statement.
8155   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8156                                                  SourceLocation StartLoc,
8157                                                  SourceLocation EndLoc);
8158   /// \brief Called on well-formed '\#pragma omp target exit data' after
8159   /// parsing of the associated statement.
8160   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8161                                                 SourceLocation StartLoc,
8162                                                 SourceLocation EndLoc);
8163   /// \brief Called on well-formed '\#pragma omp target parallel' after
8164   /// parsing of the associated statement.
8165   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8166                                                 Stmt *AStmt,
8167                                                 SourceLocation StartLoc,
8168                                                 SourceLocation EndLoc);
8169   /// \brief Called on well-formed '\#pragma omp target parallel for' after
8170   /// parsing of the  associated statement.
8171   StmtResult ActOnOpenMPTargetParallelForDirective(
8172       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8173       SourceLocation EndLoc,
8174       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8175   /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8176   /// associated statement.
8177   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8178                                        Stmt *AStmt, SourceLocation StartLoc,
8179                                        SourceLocation EndLoc);
8180   /// \brief Called on well-formed '\#pragma omp cancellation point'.
8181   StmtResult
8182   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8183                                         SourceLocation EndLoc,
8184                                         OpenMPDirectiveKind CancelRegion);
8185   /// \brief Called on well-formed '\#pragma omp cancel'.
8186   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8187                                         SourceLocation StartLoc,
8188                                         SourceLocation EndLoc,
8189                                         OpenMPDirectiveKind CancelRegion);
8190   /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8191   /// associated statement.
8192   StmtResult ActOnOpenMPTaskLoopDirective(
8193       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8194       SourceLocation EndLoc,
8195       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8196   /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8197   /// the associated statement.
8198   StmtResult ActOnOpenMPTaskLoopSimdDirective(
8199       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8200       SourceLocation EndLoc,
8201       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8202   /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8203   /// of the associated statement.
8204   StmtResult ActOnOpenMPDistributeDirective(
8205       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8206       SourceLocation EndLoc,
8207       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8208   /// \brief Called on well-formed '\#pragma omp target update'.
8209   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8210                                               SourceLocation StartLoc,
8211                                               SourceLocation EndLoc);
8212   /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8213   /// parsing of the associated statement.
8214   StmtResult ActOnOpenMPDistributeParallelForDirective(
8215       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8216       SourceLocation EndLoc,
8217       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8218   /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8219   /// after parsing of the associated statement.
8220   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8221       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8222       SourceLocation EndLoc,
8223       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8224   /// \brief Called on well-formed '\#pragma omp distribute simd' after
8225   /// parsing of the associated statement.
8226   StmtResult ActOnOpenMPDistributeSimdDirective(
8227       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8228       SourceLocation EndLoc,
8229       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8230   /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8231   /// parsing of the associated statement.
8232   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8233       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8234       SourceLocation EndLoc,
8235       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8236
8237   /// Checks correctness of linear modifiers.
8238   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8239                                  SourceLocation LinLoc);
8240   /// Checks that the specified declaration matches requirements for the linear
8241   /// decls.
8242   bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8243                              OpenMPLinearClauseKind LinKind, QualType Type);
8244
8245   /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8246   /// the associated method/function.
8247   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8248       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8249       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8250       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8251       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8252
8253   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8254                                          Expr *Expr,
8255                                          SourceLocation StartLoc,
8256                                          SourceLocation LParenLoc,
8257                                          SourceLocation EndLoc);
8258   /// \brief Called on well-formed 'if' clause.
8259   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8260                                  Expr *Condition, SourceLocation StartLoc,
8261                                  SourceLocation LParenLoc,
8262                                  SourceLocation NameModifierLoc,
8263                                  SourceLocation ColonLoc,
8264                                  SourceLocation EndLoc);
8265   /// \brief Called on well-formed 'final' clause.
8266   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8267                                     SourceLocation LParenLoc,
8268                                     SourceLocation EndLoc);
8269   /// \brief Called on well-formed 'num_threads' clause.
8270   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8271                                          SourceLocation StartLoc,
8272                                          SourceLocation LParenLoc,
8273                                          SourceLocation EndLoc);
8274   /// \brief Called on well-formed 'safelen' clause.
8275   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8276                                       SourceLocation StartLoc,
8277                                       SourceLocation LParenLoc,
8278                                       SourceLocation EndLoc);
8279   /// \brief Called on well-formed 'simdlen' clause.
8280   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8281                                       SourceLocation LParenLoc,
8282                                       SourceLocation EndLoc);
8283   /// \brief Called on well-formed 'collapse' clause.
8284   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8285                                        SourceLocation StartLoc,
8286                                        SourceLocation LParenLoc,
8287                                        SourceLocation EndLoc);
8288   /// \brief Called on well-formed 'ordered' clause.
8289   OMPClause *
8290   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8291                            SourceLocation LParenLoc = SourceLocation(),
8292                            Expr *NumForLoops = nullptr);
8293   /// \brief Called on well-formed 'grainsize' clause.
8294   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8295                                         SourceLocation LParenLoc,
8296                                         SourceLocation EndLoc);
8297   /// \brief Called on well-formed 'num_tasks' clause.
8298   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8299                                        SourceLocation LParenLoc,
8300                                        SourceLocation EndLoc);
8301   /// \brief Called on well-formed 'hint' clause.
8302   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8303                                    SourceLocation LParenLoc,
8304                                    SourceLocation EndLoc);
8305
8306   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8307                                      unsigned Argument,
8308                                      SourceLocation ArgumentLoc,
8309                                      SourceLocation StartLoc,
8310                                      SourceLocation LParenLoc,
8311                                      SourceLocation EndLoc);
8312   /// \brief Called on well-formed 'default' clause.
8313   OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8314                                       SourceLocation KindLoc,
8315                                       SourceLocation StartLoc,
8316                                       SourceLocation LParenLoc,
8317                                       SourceLocation EndLoc);
8318   /// \brief Called on well-formed 'proc_bind' clause.
8319   OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8320                                        SourceLocation KindLoc,
8321                                        SourceLocation StartLoc,
8322                                        SourceLocation LParenLoc,
8323                                        SourceLocation EndLoc);
8324
8325   OMPClause *ActOnOpenMPSingleExprWithArgClause(
8326       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8327       SourceLocation StartLoc, SourceLocation LParenLoc,
8328       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8329       SourceLocation EndLoc);
8330   /// \brief Called on well-formed 'schedule' clause.
8331   OMPClause *ActOnOpenMPScheduleClause(
8332       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8333       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8334       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8335       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8336
8337   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8338                                SourceLocation EndLoc);
8339   /// \brief Called on well-formed 'nowait' clause.
8340   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8341                                      SourceLocation EndLoc);
8342   /// \brief Called on well-formed 'untied' clause.
8343   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8344                                      SourceLocation EndLoc);
8345   /// \brief Called on well-formed 'mergeable' clause.
8346   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8347                                         SourceLocation EndLoc);
8348   /// \brief Called on well-formed 'read' clause.
8349   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8350                                    SourceLocation EndLoc);
8351   /// \brief Called on well-formed 'write' clause.
8352   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8353                                     SourceLocation EndLoc);
8354   /// \brief Called on well-formed 'update' clause.
8355   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8356                                      SourceLocation EndLoc);
8357   /// \brief Called on well-formed 'capture' clause.
8358   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8359                                       SourceLocation EndLoc);
8360   /// \brief Called on well-formed 'seq_cst' clause.
8361   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8362                                      SourceLocation EndLoc);
8363   /// \brief Called on well-formed 'threads' clause.
8364   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8365                                       SourceLocation EndLoc);
8366   /// \brief Called on well-formed 'simd' clause.
8367   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8368                                    SourceLocation EndLoc);
8369   /// \brief Called on well-formed 'nogroup' clause.
8370   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8371                                       SourceLocation EndLoc);
8372
8373   OMPClause *ActOnOpenMPVarListClause(
8374       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8375       SourceLocation StartLoc, SourceLocation LParenLoc,
8376       SourceLocation ColonLoc, SourceLocation EndLoc,
8377       CXXScopeSpec &ReductionIdScopeSpec,
8378       const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8379       OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8380       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8381       SourceLocation DepLinMapLoc);
8382   /// \brief Called on well-formed 'private' clause.
8383   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8384                                       SourceLocation StartLoc,
8385                                       SourceLocation LParenLoc,
8386                                       SourceLocation EndLoc);
8387   /// \brief Called on well-formed 'firstprivate' clause.
8388   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8389                                            SourceLocation StartLoc,
8390                                            SourceLocation LParenLoc,
8391                                            SourceLocation EndLoc);
8392   /// \brief Called on well-formed 'lastprivate' clause.
8393   OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8394                                           SourceLocation StartLoc,
8395                                           SourceLocation LParenLoc,
8396                                           SourceLocation EndLoc);
8397   /// \brief Called on well-formed 'shared' clause.
8398   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8399                                      SourceLocation StartLoc,
8400                                      SourceLocation LParenLoc,
8401                                      SourceLocation EndLoc);
8402   /// \brief Called on well-formed 'reduction' clause.
8403   OMPClause *ActOnOpenMPReductionClause(
8404       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8405       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8406       CXXScopeSpec &ReductionIdScopeSpec,
8407       const DeclarationNameInfo &ReductionId,
8408       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8409   /// \brief Called on well-formed 'linear' clause.
8410   OMPClause *
8411   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8412                           SourceLocation StartLoc, SourceLocation LParenLoc,
8413                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8414                           SourceLocation ColonLoc, SourceLocation EndLoc);
8415   /// \brief Called on well-formed 'aligned' clause.
8416   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8417                                       Expr *Alignment,
8418                                       SourceLocation StartLoc,
8419                                       SourceLocation LParenLoc,
8420                                       SourceLocation ColonLoc,
8421                                       SourceLocation EndLoc);
8422   /// \brief Called on well-formed 'copyin' clause.
8423   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8424                                      SourceLocation StartLoc,
8425                                      SourceLocation LParenLoc,
8426                                      SourceLocation EndLoc);
8427   /// \brief Called on well-formed 'copyprivate' clause.
8428   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8429                                           SourceLocation StartLoc,
8430                                           SourceLocation LParenLoc,
8431                                           SourceLocation EndLoc);
8432   /// \brief Called on well-formed 'flush' pseudo clause.
8433   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8434                                     SourceLocation StartLoc,
8435                                     SourceLocation LParenLoc,
8436                                     SourceLocation EndLoc);
8437   /// \brief Called on well-formed 'depend' clause.
8438   OMPClause *
8439   ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8440                           SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8441                           SourceLocation StartLoc, SourceLocation LParenLoc,
8442                           SourceLocation EndLoc);
8443   /// \brief Called on well-formed 'device' clause.
8444   OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8445                                      SourceLocation LParenLoc,
8446                                      SourceLocation EndLoc);
8447   /// \brief Called on well-formed 'map' clause.
8448   OMPClause *
8449   ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8450                        OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8451                        SourceLocation MapLoc, SourceLocation ColonLoc,
8452                        ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8453                        SourceLocation LParenLoc, SourceLocation EndLoc);
8454   /// \brief Called on well-formed 'num_teams' clause.
8455   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8456                                        SourceLocation LParenLoc,
8457                                        SourceLocation EndLoc);
8458   /// \brief Called on well-formed 'thread_limit' clause.
8459   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8460                                           SourceLocation StartLoc,
8461                                           SourceLocation LParenLoc,
8462                                           SourceLocation EndLoc);
8463   /// \brief Called on well-formed 'priority' clause.
8464   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8465                                        SourceLocation LParenLoc,
8466                                        SourceLocation EndLoc);
8467   /// \brief Called on well-formed 'dist_schedule' clause.
8468   OMPClause *ActOnOpenMPDistScheduleClause(
8469       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8470       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8471       SourceLocation CommaLoc, SourceLocation EndLoc);
8472   /// \brief Called on well-formed 'defaultmap' clause.
8473   OMPClause *ActOnOpenMPDefaultmapClause(
8474       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8475       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8476       SourceLocation KindLoc, SourceLocation EndLoc);
8477   /// \brief Called on well-formed 'to' clause.
8478   OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8479                                  SourceLocation StartLoc,
8480                                  SourceLocation LParenLoc,
8481                                  SourceLocation EndLoc);
8482   /// \brief Called on well-formed 'from' clause.
8483   OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8484                                    SourceLocation StartLoc,
8485                                    SourceLocation LParenLoc,
8486                                    SourceLocation EndLoc);
8487   /// Called on well-formed 'use_device_ptr' clause.
8488   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8489                                            SourceLocation StartLoc,
8490                                            SourceLocation LParenLoc,
8491                                            SourceLocation EndLoc);
8492   /// Called on well-formed 'is_device_ptr' clause.
8493   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8494                                           SourceLocation StartLoc,
8495                                           SourceLocation LParenLoc,
8496                                           SourceLocation EndLoc);
8497
8498   /// \brief The kind of conversion being performed.
8499   enum CheckedConversionKind {
8500     /// \brief An implicit conversion.
8501     CCK_ImplicitConversion,
8502     /// \brief A C-style cast.
8503     CCK_CStyleCast,
8504     /// \brief A functional-style cast.
8505     CCK_FunctionalCast,
8506     /// \brief A cast other than a C-style cast.
8507     CCK_OtherCast
8508   };
8509
8510   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8511   /// cast.  If there is already an implicit cast, merge into the existing one.
8512   /// If isLvalue, the result of the cast is an lvalue.
8513   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8514                                ExprValueKind VK = VK_RValue,
8515                                const CXXCastPath *BasePath = nullptr,
8516                                CheckedConversionKind CCK
8517                                   = CCK_ImplicitConversion);
8518
8519   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8520   /// to the conversion from scalar type ScalarTy to the Boolean type.
8521   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8522
8523   /// IgnoredValueConversions - Given that an expression's result is
8524   /// syntactically ignored, perform any conversions that are
8525   /// required.
8526   ExprResult IgnoredValueConversions(Expr *E);
8527
8528   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8529   // functions and arrays to their respective pointers (C99 6.3.2.1).
8530   ExprResult UsualUnaryConversions(Expr *E);
8531
8532   /// CallExprUnaryConversions - a special case of an unary conversion
8533   /// performed on a function designator of a call expression.
8534   ExprResult CallExprUnaryConversions(Expr *E);
8535
8536   // DefaultFunctionArrayConversion - converts functions and arrays
8537   // to their respective pointers (C99 6.3.2.1).
8538   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8539
8540   // DefaultFunctionArrayLvalueConversion - converts functions and
8541   // arrays to their respective pointers and performs the
8542   // lvalue-to-rvalue conversion.
8543   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8544                                                   bool Diagnose = true);
8545
8546   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8547   // the operand.  This is DefaultFunctionArrayLvalueConversion,
8548   // except that it assumes the operand isn't of function or array
8549   // type.
8550   ExprResult DefaultLvalueConversion(Expr *E);
8551
8552   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8553   // do not have a prototype. Integer promotions are performed on each
8554   // argument, and arguments that have type float are promoted to double.
8555   ExprResult DefaultArgumentPromotion(Expr *E);
8556
8557   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8558   enum VariadicCallType {
8559     VariadicFunction,
8560     VariadicBlock,
8561     VariadicMethod,
8562     VariadicConstructor,
8563     VariadicDoesNotApply
8564   };
8565
8566   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8567                                        const FunctionProtoType *Proto,
8568                                        Expr *Fn);
8569
8570   // Used for determining in which context a type is allowed to be passed to a
8571   // vararg function.
8572   enum VarArgKind {
8573     VAK_Valid,
8574     VAK_ValidInCXX11,
8575     VAK_Undefined,
8576     VAK_MSVCUndefined,
8577     VAK_Invalid
8578   };
8579
8580   // Determines which VarArgKind fits an expression.
8581   VarArgKind isValidVarArgType(const QualType &Ty);
8582
8583   /// Check to see if the given expression is a valid argument to a variadic
8584   /// function, issuing a diagnostic if not.
8585   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8586
8587   /// Check to see if a given expression could have '.c_str()' called on it.
8588   bool hasCStrMethod(const Expr *E);
8589
8590   /// GatherArgumentsForCall - Collector argument expressions for various
8591   /// form of call prototypes.
8592   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8593                               const FunctionProtoType *Proto,
8594                               unsigned FirstParam, ArrayRef<Expr *> Args,
8595                               SmallVectorImpl<Expr *> &AllArgs,
8596                               VariadicCallType CallType = VariadicDoesNotApply,
8597                               bool AllowExplicit = false,
8598                               bool IsListInitialization = false);
8599
8600   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8601   // will create a runtime trap if the resulting type is not a POD type.
8602   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8603                                               FunctionDecl *FDecl);
8604
8605   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8606   // operands and then handles various conversions that are common to binary
8607   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8608   // routine returns the first non-arithmetic type found. The client is
8609   // responsible for emitting appropriate error diagnostics.
8610   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8611                                       bool IsCompAssign = false);
8612
8613   /// AssignConvertType - All of the 'assignment' semantic checks return this
8614   /// enum to indicate whether the assignment was allowed.  These checks are
8615   /// done for simple assignments, as well as initialization, return from
8616   /// function, argument passing, etc.  The query is phrased in terms of a
8617   /// source and destination type.
8618   enum AssignConvertType {
8619     /// Compatible - the types are compatible according to the standard.
8620     Compatible,
8621
8622     /// PointerToInt - The assignment converts a pointer to an int, which we
8623     /// accept as an extension.
8624     PointerToInt,
8625
8626     /// IntToPointer - The assignment converts an int to a pointer, which we
8627     /// accept as an extension.
8628     IntToPointer,
8629
8630     /// FunctionVoidPointer - The assignment is between a function pointer and
8631     /// void*, which the standard doesn't allow, but we accept as an extension.
8632     FunctionVoidPointer,
8633
8634     /// IncompatiblePointer - The assignment is between two pointers types that
8635     /// are not compatible, but we accept them as an extension.
8636     IncompatiblePointer,
8637
8638     /// IncompatiblePointer - The assignment is between two pointers types which
8639     /// point to integers which have a different sign, but are otherwise
8640     /// identical. This is a subset of the above, but broken out because it's by
8641     /// far the most common case of incompatible pointers.
8642     IncompatiblePointerSign,
8643
8644     /// CompatiblePointerDiscardsQualifiers - The assignment discards
8645     /// c/v/r qualifiers, which we accept as an extension.
8646     CompatiblePointerDiscardsQualifiers,
8647
8648     /// IncompatiblePointerDiscardsQualifiers - The assignment
8649     /// discards qualifiers that we don't permit to be discarded,
8650     /// like address spaces.
8651     IncompatiblePointerDiscardsQualifiers,
8652
8653     /// IncompatibleNestedPointerQualifiers - The assignment is between two
8654     /// nested pointer types, and the qualifiers other than the first two
8655     /// levels differ e.g. char ** -> const char **, but we accept them as an
8656     /// extension.
8657     IncompatibleNestedPointerQualifiers,
8658
8659     /// IncompatibleVectors - The assignment is between two vector types that
8660     /// have the same size, which we accept as an extension.
8661     IncompatibleVectors,
8662
8663     /// IntToBlockPointer - The assignment converts an int to a block
8664     /// pointer. We disallow this.
8665     IntToBlockPointer,
8666
8667     /// IncompatibleBlockPointer - The assignment is between two block
8668     /// pointers types that are not compatible.
8669     IncompatibleBlockPointer,
8670
8671     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8672     /// id type and something else (that is incompatible with it). For example,
8673     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8674     IncompatibleObjCQualifiedId,
8675
8676     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8677     /// object with __weak qualifier.
8678     IncompatibleObjCWeakRef,
8679
8680     /// Incompatible - We reject this conversion outright, it is invalid to
8681     /// represent it in the AST.
8682     Incompatible
8683   };
8684
8685   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8686   /// assignment conversion type specified by ConvTy.  This returns true if the
8687   /// conversion was invalid or false if the conversion was accepted.
8688   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8689                                 SourceLocation Loc,
8690                                 QualType DstType, QualType SrcType,
8691                                 Expr *SrcExpr, AssignmentAction Action,
8692                                 bool *Complained = nullptr);
8693
8694   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8695   /// enum. If AllowMask is true, then we also allow the complement of a valid
8696   /// value, to be used as a mask.
8697   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8698                          bool AllowMask) const;
8699
8700   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8701   /// integer not in the range of enum values.
8702   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8703                               Expr *SrcExpr);
8704
8705   /// CheckAssignmentConstraints - Perform type checking for assignment,
8706   /// argument passing, variable initialization, and function return values.
8707   /// C99 6.5.16.
8708   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8709                                                QualType LHSType,
8710                                                QualType RHSType);
8711
8712   /// Check assignment constraints and optionally prepare for a conversion of
8713   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8714   /// is true.
8715   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8716                                                ExprResult &RHS,
8717                                                CastKind &Kind,
8718                                                bool ConvertRHS = true);
8719
8720   // CheckSingleAssignmentConstraints - Currently used by
8721   // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
8722   // this routine performs the default function/array converions, if ConvertRHS
8723   // is true.
8724   AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
8725                                                      ExprResult &RHS,
8726                                                      bool Diagnose = true,
8727                                                      bool DiagnoseCFAudited = false,
8728                                                      bool ConvertRHS = true);
8729
8730   // \brief If the lhs type is a transparent union, check whether we
8731   // can initialize the transparent union with the given expression.
8732   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8733                                                              ExprResult &RHS);
8734
8735   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8736
8737   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8738
8739   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8740                                        AssignmentAction Action,
8741                                        bool AllowExplicit = false);
8742   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8743                                        AssignmentAction Action,
8744                                        bool AllowExplicit,
8745                                        ImplicitConversionSequence& ICS);
8746   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8747                                        const ImplicitConversionSequence& ICS,
8748                                        AssignmentAction Action,
8749                                        CheckedConversionKind CCK
8750                                           = CCK_ImplicitConversion);
8751   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8752                                        const StandardConversionSequence& SCS,
8753                                        AssignmentAction Action,
8754                                        CheckedConversionKind CCK);
8755
8756   /// the following "Check" methods will return a valid/converted QualType
8757   /// or a null QualType (indicating an error diagnostic was issued).
8758
8759   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8760   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8761                            ExprResult &RHS);
8762   QualType CheckPointerToMemberOperands( // C++ 5.5
8763     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8764     SourceLocation OpLoc, bool isIndirect);
8765   QualType CheckMultiplyDivideOperands( // C99 6.5.5
8766     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8767     bool IsDivide);
8768   QualType CheckRemainderOperands( // C99 6.5.5
8769     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8770     bool IsCompAssign = false);
8771   QualType CheckAdditionOperands( // C99 6.5.6
8772     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8773     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
8774   QualType CheckSubtractionOperands( // C99 6.5.6
8775     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8776     QualType* CompLHSTy = nullptr);
8777   QualType CheckShiftOperands( // C99 6.5.7
8778     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8779     BinaryOperatorKind Opc, bool IsCompAssign = false);
8780   QualType CheckCompareOperands( // C99 6.5.8/9
8781     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8782     BinaryOperatorKind Opc, bool isRelational);
8783   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8784     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8785     bool IsCompAssign = false);
8786   QualType CheckLogicalOperands( // C99 6.5.[13,14]
8787     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8788     BinaryOperatorKind Opc);
8789   // CheckAssignmentOperands is used for both simple and compound assignment.
8790   // For simple assignment, pass both expressions and a null converted type.
8791   // For compound assignment, pass both expressions and the converted type.
8792   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8793     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8794
8795   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8796                                      UnaryOperatorKind Opcode, Expr *Op);
8797   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8798                                          BinaryOperatorKind Opcode,
8799                                          Expr *LHS, Expr *RHS);
8800   ExprResult checkPseudoObjectRValue(Expr *E);
8801   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8802
8803   QualType CheckConditionalOperands( // C99 6.5.15
8804     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8805     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8806   QualType CXXCheckConditionalOperands( // C++ 5.16
8807     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8808     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8809   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8810                                     bool *NonStandardCompositeType = nullptr);
8811   QualType FindCompositePointerType(SourceLocation Loc,
8812                                     ExprResult &E1, ExprResult &E2,
8813                                     bool *NonStandardCompositeType = nullptr) {
8814     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8815     QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8816                                                   NonStandardCompositeType);
8817     E1 = E1Tmp;
8818     E2 = E2Tmp;
8819     return Composite;
8820   }
8821
8822   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8823                                         SourceLocation QuestionLoc);
8824
8825   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8826                                   SourceLocation QuestionLoc);
8827
8828   void DiagnoseAlwaysNonNullPointer(Expr *E,
8829                                     Expr::NullPointerConstantKind NullType,
8830                                     bool IsEqual, SourceRange Range);
8831
8832   /// type checking for vector binary operators.
8833   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8834                                SourceLocation Loc, bool IsCompAssign,
8835                                bool AllowBothBool, bool AllowBoolConversion);
8836   QualType GetSignedVectorType(QualType V);
8837   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8838                                       SourceLocation Loc, bool isRelational);
8839   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8840                                       SourceLocation Loc);
8841
8842   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8843   bool isLaxVectorConversion(QualType srcType, QualType destType);
8844
8845   /// type checking declaration initializers (C99 6.7.8)
8846   bool CheckForConstantInitializer(Expr *e, QualType t);
8847
8848   // type checking C++ declaration initializers (C++ [dcl.init]).
8849
8850   /// ReferenceCompareResult - Expresses the result of comparing two
8851   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8852   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8853   enum ReferenceCompareResult {
8854     /// Ref_Incompatible - The two types are incompatible, so direct
8855     /// reference binding is not possible.
8856     Ref_Incompatible = 0,
8857     /// Ref_Related - The two types are reference-related, which means
8858     /// that their unqualified forms (T1 and T2) are either the same
8859     /// or T1 is a base class of T2.
8860     Ref_Related,
8861     /// Ref_Compatible_With_Added_Qualification - The two types are
8862     /// reference-compatible with added qualification, meaning that
8863     /// they are reference-compatible and the qualifiers on T1 (cv1)
8864     /// are greater than the qualifiers on T2 (cv2).
8865     Ref_Compatible_With_Added_Qualification,
8866     /// Ref_Compatible - The two types are reference-compatible and
8867     /// have equivalent qualifiers (cv1 == cv2).
8868     Ref_Compatible
8869   };
8870
8871   ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8872                                                       QualType T1, QualType T2,
8873                                                       bool &DerivedToBase,
8874                                                       bool &ObjCConversion,
8875                                                 bool &ObjCLifetimeConversion);
8876
8877   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8878                                  Expr *CastExpr, CastKind &CastKind,
8879                                  ExprValueKind &VK, CXXCastPath &Path);
8880
8881   /// \brief Force an expression with unknown-type to an expression of the
8882   /// given type.
8883   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8884
8885   /// \brief Type-check an expression that's being passed to an
8886   /// __unknown_anytype parameter.
8887   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8888                                 Expr *result, QualType &paramType);
8889
8890   // CheckVectorCast - check type constraints for vectors.
8891   // Since vectors are an extension, there are no C standard reference for this.
8892   // We allow casting between vectors and integer datatypes of the same size.
8893   // returns true if the cast is invalid
8894   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8895                        CastKind &Kind);
8896
8897   /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
8898   /// implicit casts if necessary.
8899   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8900
8901   // CheckExtVectorCast - check type constraints for extended vectors.
8902   // Since vectors are an extension, there are no C standard reference for this.
8903   // We allow casting between vectors and integer datatypes of the same size,
8904   // or vectors and the element type of that vector.
8905   // returns the cast expr
8906   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8907                                 CastKind &Kind);
8908
8909   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8910                                         SourceLocation LParenLoc,
8911                                         Expr *CastExpr,
8912                                         SourceLocation RParenLoc);
8913
8914   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
8915
8916   /// \brief Checks for invalid conversions and casts between
8917   /// retainable pointers and other pointer kinds.
8918   ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8919                                              QualType castType, Expr *&op,
8920                                              CheckedConversionKind CCK,
8921                                              bool Diagnose = true,
8922                                              bool DiagnoseCFAudited = false,
8923                                              BinaryOperatorKind Opc = BO_PtrMemD
8924                                              );
8925
8926   Expr *stripARCUnbridgedCast(Expr *e);
8927   void diagnoseARCUnbridgedCast(Expr *e);
8928
8929   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8930                                              QualType ExprType);
8931
8932   /// checkRetainCycles - Check whether an Objective-C message send
8933   /// might create an obvious retain cycle.
8934   void checkRetainCycles(ObjCMessageExpr *msg);
8935   void checkRetainCycles(Expr *receiver, Expr *argument);
8936   void checkRetainCycles(VarDecl *Var, Expr *Init);
8937
8938   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8939   /// to weak/__unsafe_unretained type.
8940   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8941
8942   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8943   /// to weak/__unsafe_unretained expression.
8944   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8945
8946   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8947   /// \param Method - May be null.
8948   /// \param [out] ReturnType - The return type of the send.
8949   /// \return true iff there were any incompatible types.
8950   bool CheckMessageArgumentTypes(QualType ReceiverType,
8951                                  MultiExprArg Args, Selector Sel,
8952                                  ArrayRef<SourceLocation> SelectorLocs,
8953                                  ObjCMethodDecl *Method, bool isClassMessage,
8954                                  bool isSuperMessage,
8955                                  SourceLocation lbrac, SourceLocation rbrac,
8956                                  SourceRange RecRange,
8957                                  QualType &ReturnType, ExprValueKind &VK);
8958
8959   /// \brief Determine the result of a message send expression based on
8960   /// the type of the receiver, the method expected to receive the message,
8961   /// and the form of the message send.
8962   QualType getMessageSendResultType(QualType ReceiverType,
8963                                     ObjCMethodDecl *Method,
8964                                     bool isClassMessage, bool isSuperMessage);
8965
8966   /// \brief If the given expression involves a message send to a method
8967   /// with a related result type, emit a note describing what happened.
8968   void EmitRelatedResultTypeNote(const Expr *E);
8969
8970   /// \brief Given that we had incompatible pointer types in a return
8971   /// statement, check whether we're in a method with a related result
8972   /// type, and if so, emit a note describing what happened.
8973   void EmitRelatedResultTypeNoteForReturn(QualType destType);
8974
8975   class ConditionResult {
8976     Decl *ConditionVar;
8977     FullExprArg Condition;
8978     bool Invalid;
8979     bool HasKnownValue;
8980     bool KnownValue;
8981
8982     friend class Sema;
8983     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
8984                     bool IsConstexpr)
8985         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
8986           HasKnownValue(IsConstexpr && Condition.get() &&
8987                         !Condition.get()->isValueDependent()),
8988           KnownValue(HasKnownValue &&
8989                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
8990     explicit ConditionResult(bool Invalid)
8991         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
8992           HasKnownValue(false), KnownValue(false) {}
8993
8994   public:
8995     ConditionResult() : ConditionResult(false) {}
8996     bool isInvalid() const { return Invalid; }
8997     std::pair<VarDecl *, Expr *> get() const {
8998       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
8999                             Condition.get());
9000     }
9001     llvm::Optional<bool> getKnownValue() const {
9002       if (!HasKnownValue)
9003         return None;
9004       return KnownValue;
9005     }
9006   };
9007   static ConditionResult ConditionError() { return ConditionResult(true); }
9008
9009   enum class ConditionKind {
9010     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9011     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9012     Switch       ///< An integral condition for a 'switch' statement.
9013   };
9014
9015   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9016                                  Expr *SubExpr, ConditionKind CK);
9017
9018   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9019                                          SourceLocation StmtLoc,
9020                                          ConditionKind CK);
9021
9022   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9023
9024   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9025                                     SourceLocation StmtLoc,
9026                                     ConditionKind CK);
9027   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9028
9029   /// CheckBooleanCondition - Diagnose problems involving the use of
9030   /// the given expression as a boolean condition (e.g. in an if
9031   /// statement).  Also performs the standard function and array
9032   /// decays, possibly changing the input variable.
9033   ///
9034   /// \param Loc - A location associated with the condition, e.g. the
9035   /// 'if' keyword.
9036   /// \return true iff there were any errors
9037   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9038                                    bool IsConstexpr = false);
9039
9040   /// DiagnoseAssignmentAsCondition - Given that an expression is
9041   /// being used as a boolean condition, warn if it's an assignment.
9042   void DiagnoseAssignmentAsCondition(Expr *E);
9043
9044   /// \brief Redundant parentheses over an equality comparison can indicate
9045   /// that the user intended an assignment used as condition.
9046   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9047
9048   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9049   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9050
9051   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9052   /// the specified width and sign.  If an overflow occurs, detect it and emit
9053   /// the specified diagnostic.
9054   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9055                                           unsigned NewWidth, bool NewSign,
9056                                           SourceLocation Loc, unsigned DiagID);
9057
9058   /// Checks that the Objective-C declaration is declared in the global scope.
9059   /// Emits an error and marks the declaration as invalid if it's not declared
9060   /// in the global scope.
9061   bool CheckObjCDeclScope(Decl *D);
9062
9063   /// \brief Abstract base class used for diagnosing integer constant
9064   /// expression violations.
9065   class VerifyICEDiagnoser {
9066   public:
9067     bool Suppress;
9068
9069     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9070
9071     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9072     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9073     virtual ~VerifyICEDiagnoser() { }
9074   };
9075
9076   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9077   /// and reports the appropriate diagnostics. Returns false on success.
9078   /// Can optionally return the value of the expression.
9079   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9080                                              VerifyICEDiagnoser &Diagnoser,
9081                                              bool AllowFold = true);
9082   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9083                                              unsigned DiagID,
9084                                              bool AllowFold = true);
9085   ExprResult VerifyIntegerConstantExpression(Expr *E,
9086                                              llvm::APSInt *Result = nullptr);
9087
9088   /// VerifyBitField - verifies that a bit field expression is an ICE and has
9089   /// the correct width, and that the field type is valid.
9090   /// Returns false on success.
9091   /// Can optionally return whether the bit-field is of width 0
9092   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9093                             QualType FieldTy, bool IsMsStruct,
9094                             Expr *BitWidth, bool *ZeroWidth = nullptr);
9095
9096   enum CUDAFunctionTarget {
9097     CFT_Device,
9098     CFT_Global,
9099     CFT_Host,
9100     CFT_HostDevice,
9101     CFT_InvalidTarget
9102   };
9103
9104   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
9105
9106   // CUDA function call preference. Must be ordered numerically from
9107   // worst to best.
9108   enum CUDAFunctionPreference {
9109     CFP_Never,      // Invalid caller/callee combination.
9110     CFP_WrongSide,  // Calls from host-device to host or device
9111                     // function that do not match current compilation
9112                     // mode. Only in effect if
9113                     // LangOpts.CUDADisableTargetCallChecks is true.
9114     CFP_HostDevice, // Any calls to host/device functions.
9115     CFP_SameSide,   // Calls from host-device to host or device
9116                     // function matching current compilation mode.
9117     CFP_Native,     // host-to-host or device-to-device calls.
9118   };
9119
9120   /// Identifies relative preference of a given Caller/Callee
9121   /// combination, based on their host/device attributes.
9122   /// \param Caller function which needs address of \p Callee.
9123   ///               nullptr in case of global context.
9124   /// \param Callee target function
9125   ///
9126   /// \returns preference value for particular Caller/Callee combination.
9127   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9128                                                 const FunctionDecl *Callee);
9129
9130   /// Determines whether Caller may invoke Callee, based on their CUDA
9131   /// host/device attributes.  Returns true if the call is not allowed.
9132   bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
9133     return IdentifyCUDAPreference(Caller, Callee) == CFP_Never;
9134   }
9135
9136   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9137   /// depending on FD and the current compilation settings.
9138   void maybeAddCUDAHostDeviceAttrs(Scope *S, FunctionDecl *FD,
9139                                    const LookupResult &Previous);
9140
9141   /// Finds a function in \p Matches with highest calling priority
9142   /// from \p Caller context and erases all functions with lower
9143   /// calling priority.
9144   void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
9145                                 SmallVectorImpl<FunctionDecl *> &Matches);
9146   void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
9147                                 SmallVectorImpl<DeclAccessPair> &Matches);
9148   void EraseUnwantedCUDAMatches(
9149       const FunctionDecl *Caller,
9150       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9151
9152   /// Given a implicit special member, infer its CUDA target from the
9153   /// calls it needs to make to underlying base/field special members.
9154   /// \param ClassDecl the class for which the member is being created.
9155   /// \param CSM the kind of special member.
9156   /// \param MemberDecl the special member itself.
9157   /// \param ConstRHS true if this is a copy operation with a const object on
9158   ///        its RHS.
9159   /// \param Diagnose true if this call should emit diagnostics.
9160   /// \return true if there was an error inferring.
9161   /// The result of this call is implicit CUDA target attribute(s) attached to
9162   /// the member declaration.
9163   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9164                                                CXXSpecialMember CSM,
9165                                                CXXMethodDecl *MemberDecl,
9166                                                bool ConstRHS,
9167                                                bool Diagnose);
9168
9169   /// \return true if \p CD can be considered empty according to CUDA
9170   /// (E.2.3.1 in CUDA 7.5 Programming guide).
9171   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9172   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9173
9174   /// \name Code completion
9175   //@{
9176   /// \brief Describes the context in which code completion occurs.
9177   enum ParserCompletionContext {
9178     /// \brief Code completion occurs at top-level or namespace context.
9179     PCC_Namespace,
9180     /// \brief Code completion occurs within a class, struct, or union.
9181     PCC_Class,
9182     /// \brief Code completion occurs within an Objective-C interface, protocol,
9183     /// or category.
9184     PCC_ObjCInterface,
9185     /// \brief Code completion occurs within an Objective-C implementation or
9186     /// category implementation
9187     PCC_ObjCImplementation,
9188     /// \brief Code completion occurs within the list of instance variables
9189     /// in an Objective-C interface, protocol, category, or implementation.
9190     PCC_ObjCInstanceVariableList,
9191     /// \brief Code completion occurs following one or more template
9192     /// headers.
9193     PCC_Template,
9194     /// \brief Code completion occurs following one or more template
9195     /// headers within a class.
9196     PCC_MemberTemplate,
9197     /// \brief Code completion occurs within an expression.
9198     PCC_Expression,
9199     /// \brief Code completion occurs within a statement, which may
9200     /// also be an expression or a declaration.
9201     PCC_Statement,
9202     /// \brief Code completion occurs at the beginning of the
9203     /// initialization statement (or expression) in a for loop.
9204     PCC_ForInit,
9205     /// \brief Code completion occurs within the condition of an if,
9206     /// while, switch, or for statement.
9207     PCC_Condition,
9208     /// \brief Code completion occurs within the body of a function on a
9209     /// recovery path, where we do not have a specific handle on our position
9210     /// in the grammar.
9211     PCC_RecoveryInFunction,
9212     /// \brief Code completion occurs where only a type is permitted.
9213     PCC_Type,
9214     /// \brief Code completion occurs in a parenthesized expression, which
9215     /// might also be a type cast.
9216     PCC_ParenthesizedExpression,
9217     /// \brief Code completion occurs within a sequence of declaration
9218     /// specifiers within a function, method, or block.
9219     PCC_LocalDeclarationSpecifiers
9220   };
9221
9222   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9223   void CodeCompleteOrdinaryName(Scope *S,
9224                                 ParserCompletionContext CompletionContext);
9225   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9226                             bool AllowNonIdentifiers,
9227                             bool AllowNestedNameSpecifiers);
9228
9229   struct CodeCompleteExpressionData;
9230   void CodeCompleteExpression(Scope *S,
9231                               const CodeCompleteExpressionData &Data);
9232   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9233                                        SourceLocation OpLoc,
9234                                        bool IsArrow);
9235   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9236   void CodeCompleteTag(Scope *S, unsigned TagSpec);
9237   void CodeCompleteTypeQualifiers(DeclSpec &DS);
9238   void CodeCompleteBracketDeclarator(Scope *S);
9239   void CodeCompleteCase(Scope *S);
9240   void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9241   void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9242                                ArrayRef<Expr *> Args);
9243   void CodeCompleteInitializer(Scope *S, Decl *D);
9244   void CodeCompleteReturn(Scope *S);
9245   void CodeCompleteAfterIf(Scope *S);
9246   void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9247
9248   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9249                                bool EnteringContext);
9250   void CodeCompleteUsing(Scope *S);
9251   void CodeCompleteUsingDirective(Scope *S);
9252   void CodeCompleteNamespaceDecl(Scope *S);
9253   void CodeCompleteNamespaceAliasDecl(Scope *S);
9254   void CodeCompleteOperatorName(Scope *S);
9255   void CodeCompleteConstructorInitializer(
9256                                 Decl *Constructor,
9257                                 ArrayRef<CXXCtorInitializer *> Initializers);
9258
9259   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9260                                     bool AfterAmpersand);
9261
9262   void CodeCompleteObjCAtDirective(Scope *S);
9263   void CodeCompleteObjCAtVisibility(Scope *S);
9264   void CodeCompleteObjCAtStatement(Scope *S);
9265   void CodeCompleteObjCAtExpression(Scope *S);
9266   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9267   void CodeCompleteObjCPropertyGetter(Scope *S);
9268   void CodeCompleteObjCPropertySetter(Scope *S);
9269   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9270                                    bool IsParameter);
9271   void CodeCompleteObjCMessageReceiver(Scope *S);
9272   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9273                                     ArrayRef<IdentifierInfo *> SelIdents,
9274                                     bool AtArgumentExpression);
9275   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9276                                     ArrayRef<IdentifierInfo *> SelIdents,
9277                                     bool AtArgumentExpression,
9278                                     bool IsSuper = false);
9279   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9280                                        ArrayRef<IdentifierInfo *> SelIdents,
9281                                        bool AtArgumentExpression,
9282                                        ObjCInterfaceDecl *Super = nullptr);
9283   void CodeCompleteObjCForCollection(Scope *S,
9284                                      DeclGroupPtrTy IterationVar);
9285   void CodeCompleteObjCSelector(Scope *S,
9286                                 ArrayRef<IdentifierInfo *> SelIdents);
9287   void CodeCompleteObjCProtocolReferences(
9288                                          ArrayRef<IdentifierLocPair> Protocols);
9289   void CodeCompleteObjCProtocolDecl(Scope *S);
9290   void CodeCompleteObjCInterfaceDecl(Scope *S);
9291   void CodeCompleteObjCSuperclass(Scope *S,
9292                                   IdentifierInfo *ClassName,
9293                                   SourceLocation ClassNameLoc);
9294   void CodeCompleteObjCImplementationDecl(Scope *S);
9295   void CodeCompleteObjCInterfaceCategory(Scope *S,
9296                                          IdentifierInfo *ClassName,
9297                                          SourceLocation ClassNameLoc);
9298   void CodeCompleteObjCImplementationCategory(Scope *S,
9299                                               IdentifierInfo *ClassName,
9300                                               SourceLocation ClassNameLoc);
9301   void CodeCompleteObjCPropertyDefinition(Scope *S);
9302   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9303                                               IdentifierInfo *PropertyName);
9304   void CodeCompleteObjCMethodDecl(Scope *S,
9305                                   bool IsInstanceMethod,
9306                                   ParsedType ReturnType);
9307   void CodeCompleteObjCMethodDeclSelector(Scope *S,
9308                                           bool IsInstanceMethod,
9309                                           bool AtParameterName,
9310                                           ParsedType ReturnType,
9311                                           ArrayRef<IdentifierInfo *> SelIdents);
9312   void CodeCompletePreprocessorDirective(bool InConditional);
9313   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9314   void CodeCompletePreprocessorMacroName(bool IsDefinition);
9315   void CodeCompletePreprocessorExpression();
9316   void CodeCompletePreprocessorMacroArgument(Scope *S,
9317                                              IdentifierInfo *Macro,
9318                                              MacroInfo *MacroInfo,
9319                                              unsigned Argument);
9320   void CodeCompleteNaturalLanguage();
9321   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
9322                                    CodeCompletionTUInfo &CCTUInfo,
9323                   SmallVectorImpl<CodeCompletionResult> &Results);
9324   //@}
9325
9326   //===--------------------------------------------------------------------===//
9327   // Extra semantic analysis beyond the C type system
9328
9329 public:
9330   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
9331                                                 unsigned ByteNo) const;
9332
9333 private:
9334   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9335                         const ArraySubscriptExpr *ASE=nullptr,
9336                         bool AllowOnePastEnd=true, bool IndexNegated=false);
9337   void CheckArrayAccess(const Expr *E);
9338   // Used to grab the relevant information from a FormatAttr and a
9339   // FunctionDeclaration.
9340   struct FormatStringInfo {
9341     unsigned FormatIdx;
9342     unsigned FirstDataArg;
9343     bool HasVAListArg;
9344   };
9345
9346   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
9347                                   FormatStringInfo *FSI);
9348   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
9349                          const FunctionProtoType *Proto);
9350   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
9351                            ArrayRef<const Expr *> Args);
9352   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
9353                         const FunctionProtoType *Proto);
9354   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
9355   void CheckConstructorCall(FunctionDecl *FDecl,
9356                             ArrayRef<const Expr *> Args,
9357                             const FunctionProtoType *Proto,
9358                             SourceLocation Loc);
9359
9360   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
9361                  ArrayRef<const Expr *> Args, bool IsMemberFunction, 
9362                  SourceLocation Loc, SourceRange Range, 
9363                  VariadicCallType CallType);
9364
9365   bool CheckObjCString(Expr *Arg);
9366
9367   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
9368                                       unsigned BuiltinID, CallExpr *TheCall);
9369
9370   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
9371                                     unsigned MaxWidth);
9372   bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9373   bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9374
9375   bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9376   bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9377   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9378   bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9379   bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9380
9381   bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
9382   bool SemaBuiltinVAStart(CallExpr *TheCall);
9383   bool SemaBuiltinMSVAStart(CallExpr *TheCall);
9384   bool SemaBuiltinVAStartARM(CallExpr *Call);
9385   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
9386   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
9387
9388 public:
9389   // Used by C++ template instantiation.
9390   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
9391   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
9392                                    SourceLocation BuiltinLoc,
9393                                    SourceLocation RParenLoc);
9394
9395 private:
9396   bool SemaBuiltinPrefetch(CallExpr *TheCall);
9397   bool SemaBuiltinAssume(CallExpr *TheCall);
9398   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
9399   bool SemaBuiltinLongjmp(CallExpr *TheCall);
9400   bool SemaBuiltinSetjmp(CallExpr *TheCall);
9401   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
9402   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
9403   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
9404                                      AtomicExpr::AtomicOp Op);
9405   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
9406                               llvm::APSInt &Result);
9407   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
9408                                    int Low, int High);
9409   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
9410                                 int ArgNum, unsigned ExpectedFieldNum,
9411                                 bool AllowName);
9412 public:
9413   enum FormatStringType {
9414     FST_Scanf,
9415     FST_Printf,
9416     FST_NSString,
9417     FST_Strftime,
9418     FST_Strfmon,
9419     FST_Kprintf,
9420     FST_FreeBSDKPrintf,
9421     FST_OSTrace,
9422     FST_Unknown
9423   };
9424   static FormatStringType GetFormatStringType(const FormatAttr *Format);
9425
9426   bool FormatStringHasSArg(const StringLiteral *FExpr);
9427   
9428   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
9429
9430 private:
9431   bool CheckFormatArguments(const FormatAttr *Format,
9432                             ArrayRef<const Expr *> Args,
9433                             bool IsCXXMember,
9434                             VariadicCallType CallType,
9435                             SourceLocation Loc, SourceRange Range,
9436                             llvm::SmallBitVector &CheckedVarArgs);
9437   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
9438                             bool HasVAListArg, unsigned format_idx,
9439                             unsigned firstDataArg, FormatStringType Type,
9440                             VariadicCallType CallType,
9441                             SourceLocation Loc, SourceRange range,
9442                             llvm::SmallBitVector &CheckedVarArgs);
9443
9444   void CheckAbsoluteValueFunction(const CallExpr *Call,
9445                                   const FunctionDecl *FDecl,
9446                                   IdentifierInfo *FnInfo);
9447
9448   void CheckMemaccessArguments(const CallExpr *Call,
9449                                unsigned BId,
9450                                IdentifierInfo *FnName);
9451
9452   void CheckStrlcpycatArguments(const CallExpr *Call,
9453                                 IdentifierInfo *FnName);
9454
9455   void CheckStrncatArguments(const CallExpr *Call,
9456                              IdentifierInfo *FnName);
9457
9458   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9459                           SourceLocation ReturnLoc,
9460                           bool isObjCMethod = false,
9461                           const AttrVec *Attrs = nullptr,
9462                           const FunctionDecl *FD = nullptr);
9463
9464   void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
9465   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
9466   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
9467   void CheckForIntOverflow(Expr *E);
9468   void CheckUnsequencedOperations(Expr *E);
9469
9470   /// \brief Perform semantic checks on a completed expression. This will either
9471   /// be a full-expression or a default argument expression.
9472   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
9473                           bool IsConstexpr = false);
9474
9475   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
9476                                    Expr *Init);
9477
9478   /// \brief Check if the given expression contains 'break' or 'continue'
9479   /// statement that produces control flow different from GCC.
9480   void CheckBreakContinueBinding(Expr *E);
9481
9482   /// \brief Check whether receiver is mutable ObjC container which
9483   /// attempts to add itself into the container
9484   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
9485
9486   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9487   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9488                                  bool DeleteWasArrayForm);
9489 public:
9490   /// \brief Register a magic integral constant to be used as a type tag.
9491   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9492                                   uint64_t MagicValue, QualType Type,
9493                                   bool LayoutCompatible, bool MustBeNull);
9494
9495   struct TypeTagData {
9496     TypeTagData() {}
9497
9498     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
9499         Type(Type), LayoutCompatible(LayoutCompatible),
9500         MustBeNull(MustBeNull)
9501     {}
9502
9503     QualType Type;
9504
9505     /// If true, \c Type should be compared with other expression's types for
9506     /// layout-compatibility.
9507     unsigned LayoutCompatible : 1;
9508     unsigned MustBeNull : 1;
9509   };
9510
9511   /// A pair of ArgumentKind identifier and magic value.  This uniquely
9512   /// identifies the magic value.
9513   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
9514
9515 private:
9516   /// \brief A map from magic value to type information.
9517   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
9518       TypeTagForDatatypeMagicValues;
9519
9520   /// \brief Peform checks on a call of a function with argument_with_type_tag
9521   /// or pointer_with_type_tag attributes.
9522   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9523                                 const Expr * const *ExprArgs);
9524
9525   /// \brief The parser's current scope.
9526   ///
9527   /// The parser maintains this state here.
9528   Scope *CurScope;
9529
9530   mutable IdentifierInfo *Ident_super;
9531   mutable IdentifierInfo *Ident___float128;
9532
9533   /// Nullability type specifiers.
9534   IdentifierInfo *Ident__Nonnull = nullptr;
9535   IdentifierInfo *Ident__Nullable = nullptr;
9536   IdentifierInfo *Ident__Null_unspecified = nullptr;
9537
9538   IdentifierInfo *Ident_NSError = nullptr;
9539
9540 protected:
9541   friend class Parser;
9542   friend class InitializationSequence;
9543   friend class ASTReader;
9544   friend class ASTDeclReader;
9545   friend class ASTWriter;
9546
9547 public:
9548   /// Retrieve the keyword associated
9549   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
9550
9551   /// The struct behind the CFErrorRef pointer.
9552   RecordDecl *CFError = nullptr;
9553
9554   /// Retrieve the identifier "NSError".
9555   IdentifierInfo *getNSErrorIdent();
9556
9557   /// \brief Retrieve the parser's current scope.
9558   ///
9559   /// This routine must only be used when it is certain that semantic analysis
9560   /// and the parser are in precisely the same context, which is not the case
9561   /// when, e.g., we are performing any kind of template instantiation.
9562   /// Therefore, the only safe places to use this scope are in the parser
9563   /// itself and in routines directly invoked from the parser and *never* from
9564   /// template substitution or instantiation.
9565   Scope *getCurScope() const { return CurScope; }
9566
9567   void incrementMSManglingNumber() const {
9568     return CurScope->incrementMSManglingNumber();
9569   }
9570
9571   IdentifierInfo *getSuperIdentifier() const;
9572   IdentifierInfo *getFloat128Identifier() const;
9573
9574   Decl *getObjCDeclContext() const;
9575
9576   DeclContext *getCurLexicalContext() const {
9577     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
9578   }
9579
9580   AvailabilityResult getCurContextAvailability() const;
9581   
9582   const DeclContext *getCurObjCLexicalContext() const {
9583     const DeclContext *DC = getCurLexicalContext();
9584     // A category implicitly has the attribute of the interface.
9585     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
9586       DC = CatD->getClassInterface();
9587     return DC;
9588   }
9589
9590   /// \brief To be used for checking whether the arguments being passed to
9591   /// function exceeds the number of parameters expected for it.
9592   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
9593                                bool PartialOverloading = false) {
9594     // We check whether we're just after a comma in code-completion.
9595     if (NumArgs > 0 && PartialOverloading)
9596       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
9597     return NumArgs > NumParams;
9598   }
9599
9600   // Emitting members of dllexported classes is delayed until the class
9601   // (including field initializers) is fully parsed.
9602   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
9603 };
9604
9605 /// \brief RAII object that enters a new expression evaluation context.
9606 class EnterExpressionEvaluationContext {
9607   Sema &Actions;
9608   bool Entered = true;
9609
9610 public:
9611   EnterExpressionEvaluationContext(Sema &Actions,
9612                                    Sema::ExpressionEvaluationContext NewContext,
9613                                    Decl *LambdaContextDecl = nullptr,
9614                                    bool IsDecltype = false,
9615                                    bool ShouldEnter = true)
9616       : Actions(Actions), Entered(ShouldEnter) {
9617     if (Entered)
9618       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
9619                                               IsDecltype);
9620   }
9621   EnterExpressionEvaluationContext(Sema &Actions,
9622                                    Sema::ExpressionEvaluationContext NewContext,
9623                                    Sema::ReuseLambdaContextDecl_t,
9624                                    bool IsDecltype = false)
9625     : Actions(Actions) {
9626     Actions.PushExpressionEvaluationContext(NewContext, 
9627                                             Sema::ReuseLambdaContextDecl,
9628                                             IsDecltype);
9629   }
9630
9631   ~EnterExpressionEvaluationContext() {
9632     if (Entered)
9633       Actions.PopExpressionEvaluationContext();
9634   }
9635 };
9636
9637 DeductionFailureInfo
9638 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
9639                          sema::TemplateDeductionInfo &Info);
9640
9641 /// \brief Contains a late templated function.
9642 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
9643 struct LateParsedTemplate {
9644   CachedTokens Toks;
9645   /// \brief The template function declaration to be late parsed.
9646   Decl *D;
9647 };
9648
9649 } // end namespace clang
9650
9651 #endif