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