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