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