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