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