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