clang  10.0.0svn
Sema.h
Go to the documentation of this file.
1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the Sema class, which performs semantic analysis and
10 // builds ASTs.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_SEMA_SEMA_H
15 #define LLVM_CLANG_SEMA_SEMA_H
16 
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Availability.h"
20 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/LocInfoType.h"
28 #include "clang/AST/NSAPI.h"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/TypeOrdering.h"
34 #include "clang/Basic/Module.h"
37 #include "clang/Basic/Specifiers.h"
39 #include "clang/Basic/TypeTraits.h"
41 #include "clang/Sema/CleanupInfo.h"
42 #include "clang/Sema/DeclSpec.h"
46 #include "clang/Sema/Ownership.h"
47 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/Weak.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/SetVector.h"
53 #include "llvm/ADT/SmallBitVector.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  struct 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 ParsedAttr;
79  class BindingDecl;
80  class BlockDecl;
81  class CapturedDecl;
82  class CXXBasePath;
83  class CXXBasePaths;
84  class CXXBindTemporaryExpr;
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;
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;
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 OMPRequiresDecl;
156  class OMPDeclareReductionDecl;
157  class OMPDeclareSimdDecl;
158  class OMPClause;
159  struct OMPVarListLocTy;
160  struct OverloadCandidate;
161  class OverloadCandidateSet;
162  class OverloadExpr;
163  class ParenListExpr;
164  class ParmVarDecl;
165  class Preprocessor;
166  class PseudoDestructorTypeStorage;
167  class PseudoObjectExpr;
168  class QualType;
169  class StandardConversionSequence;
170  class Stmt;
171  class StringLiteral;
172  class SwitchStmt;
173  class TemplateArgument;
174  class TemplateArgumentList;
175  class TemplateArgumentLoc;
176  class TemplateDecl;
177  class TemplateInstantiationCallback;
178  class TemplateParameterList;
179  class TemplatePartialOrderingContext;
180  class TemplateTemplateParmDecl;
181  class Token;
182  class TypeAliasDecl;
183  class TypedefDecl;
184  class TypedefNameDecl;
185  class TypeLoc;
186  class TypoCorrectionConsumer;
187  class UnqualifiedId;
188  class UnresolvedLookupExpr;
189  class UnresolvedMemberExpr;
190  class UnresolvedSetImpl;
191  class UnresolvedSetIterator;
192  class UsingDecl;
193  class UsingShadowDecl;
194  class ValueDecl;
195  class VarDecl;
196  class VarTemplateSpecializationDecl;
197  class VisibilityAttr;
198  class VisibleDeclConsumer;
199  class IndirectFieldDecl;
200  struct DeductionFailureInfo;
201  class TemplateSpecCandidateSet;
202 
203 namespace sema {
204  class AccessedEntity;
205  class BlockScopeInfo;
206  class Capture;
207  class CapturedRegionScopeInfo;
208  class CapturingScopeInfo;
209  class CompoundScopeInfo;
210  class DelayedDiagnostic;
211  class DelayedDiagnosticPool;
212  class FunctionScopeInfo;
213  class LambdaScopeInfo;
214  class PossiblyUnreachableDiag;
215  class SemaPPCallbacks;
216  class TemplateDeductionInfo;
217 }
218 
219 namespace threadSafety {
220  class BeforeSet;
221  void threadSafetyCleanup(BeforeSet* Cache);
222 }
223 
224 // FIXME: No way to easily map from TemplateTypeParmTypes to
225 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
226 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
228 
229 /// Describes whether we've seen any nullability information for the given
230 /// file.
232  /// The first pointer declarator (of any pointer kind) in the file that does
233  /// not have a corresponding nullability annotation.
235 
236  /// The end location for the first pointer declarator in the file. Used for
237  /// placing fix-its.
239 
240  /// Which kind of pointer declarator we saw.
241  uint8_t PointerKind;
242 
243  /// Whether we saw any type nullability annotations in the given file.
244  bool SawTypeNullability = false;
245 };
246 
247 /// A mapping from file IDs to a record of whether we've seen nullability
248 /// information in that file.
250  /// A mapping from file IDs to the nullability information for each file ID.
251  llvm::DenseMap<FileID, FileNullability> Map;
252 
253  /// A single-element cache based on the file ID.
254  struct {
257  } Cache;
258 
259 public:
261  // Check the single-element cache.
262  if (file == Cache.File)
263  return Cache.Nullability;
264 
265  // It's not in the single-element cache; flush the cache if we have one.
266  if (!Cache.File.isInvalid()) {
267  Map[Cache.File] = Cache.Nullability;
268  }
269 
270  // Pull this entry into the cache.
271  Cache.File = file;
272  Cache.Nullability = Map[file];
273  return Cache.Nullability;
274  }
275 };
276 
277 /// Keeps track of expected type during expression parsing. The type is tied to
278 /// a particular token, all functions that update or consume the type take a
279 /// start location of the token they are looking at as a parameter. This allows
280 /// to avoid updating the type on hot paths in the parser.
282 public:
283  PreferredTypeBuilder() = default;
284  explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
285 
286  void enterCondition(Sema &S, SourceLocation Tok);
287  void enterReturn(Sema &S, SourceLocation Tok);
288  void enterVariableInit(SourceLocation Tok, Decl *D);
289  /// Computing a type for the function argument may require running
290  /// overloading, so we postpone its computation until it is actually needed.
291  ///
292  /// Clients should be very careful when using this funciton, as it stores a
293  /// function_ref, clients should make sure all calls to get() with the same
294  /// location happen while function_ref is alive.
295  void enterFunctionArgument(SourceLocation Tok,
296  llvm::function_ref<QualType()> ComputeType);
297 
298  void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
299  void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
300  SourceLocation OpLoc);
301  void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
302  void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
303  void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
304  /// Handles all type casts, including C-style cast, C++ casts, etc.
305  void enterTypeCast(SourceLocation Tok, QualType CastType);
306 
308  if (Tok != ExpectedLoc)
309  return QualType();
310  if (!Type.isNull())
311  return Type;
312  if (ComputeType)
313  return ComputeType();
314  return QualType();
315  }
316 
317 private:
318  /// Start position of a token for which we store expected type.
319  SourceLocation ExpectedLoc;
320  /// Expected type for a token starting at ExpectedLoc.
321  QualType Type;
322  /// A function to compute expected type at ExpectedLoc. It is only considered
323  /// if Type is null.
324  llvm::function_ref<QualType()> ComputeType;
325 };
326 
327 /// Sema - This implements semantic analysis and AST building for C.
328 class Sema {
329  Sema(const Sema &) = delete;
330  void operator=(const Sema &) = delete;
331 
332  ///Source of additional semantic information.
333  ExternalSemaSource *ExternalSource;
334 
335  ///Whether Sema has generated a multiplexer and has to delete it.
336  bool isMultiplexExternalSource;
337 
338  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
339 
340  bool isVisibleSlow(const NamedDecl *D);
341 
342  /// Determine whether two declarations should be linked together, given that
343  /// the old declaration might not be visible and the new declaration might
344  /// not have external linkage.
345  bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
346  const NamedDecl *New) {
347  if (isVisible(Old))
348  return true;
349  // See comment in below overload for why it's safe to compute the linkage
350  // of the new declaration here.
351  if (New->isExternallyDeclarable()) {
352  assert(Old->isExternallyDeclarable() &&
353  "should not have found a non-externally-declarable previous decl");
354  return true;
355  }
356  return false;
357  }
358  bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
359 
360  void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
361  QualType ResultTy,
362  ArrayRef<QualType> Args);
363 
364 public:
368 
371 
378 
379  /// Flag indicating whether or not to collect detailed statistics.
381 
382  /// Code-completion consumer.
384 
385  /// CurContext - This is the current declaration context of parsing.
387 
388  /// Generally null except when we temporarily switch decl contexts,
389  /// like in \see ActOnObjCTemporaryExitContainerContext.
391 
392  /// VAListTagName - The declaration name corresponding to __va_list_tag.
393  /// This is used as part of a hack to omit that class from ADL results.
395 
396  bool MSStructPragmaOn; // True when \#pragma ms_struct on
397 
398  /// Controls member pointer representation format under the MS ABI.
401 
402  /// Stack of active SEH __finally scopes. Can be empty.
404 
405  /// Source location for newly created implicit MSInheritanceAttrs
407 
408  /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
409  /// `TransformTypos` in order to keep track of any TypoExprs that are created
410  /// recursively during typo correction and wipe them away if the correction
411  /// fails.
413 
414  /// pragma clang section kind
416  PCSK_Invalid = 0,
417  PCSK_BSS = 1,
418  PCSK_Data = 2,
419  PCSK_Rodata = 3,
420  PCSK_Text = 4
421  };
422 
424  PCSA_Set = 0,
425  PCSA_Clear = 1
426  };
427 
429  std::string SectionName;
430  bool Valid = false;
432 
433  void Act(SourceLocation PragmaLocation,
435  StringLiteral* Name);
436  };
437 
442 
444  PSK_Reset = 0x0, // #pragma ()
445  PSK_Set = 0x1, // #pragma (value)
446  PSK_Push = 0x2, // #pragma (push[, id])
447  PSK_Pop = 0x4, // #pragma (pop[, id])
448  PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
449  PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
450  PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
451  };
452 
453  template<typename ValueType>
454  struct PragmaStack {
455  struct Slot {
456  llvm::StringRef StackSlotLabel;
457  ValueType Value;
460  Slot(llvm::StringRef StackSlotLabel, ValueType Value,
461  SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
462  : StackSlotLabel(StackSlotLabel), Value(Value),
463  PragmaLocation(PragmaLocation),
464  PragmaPushLocation(PragmaPushLocation) {}
465  };
466  void Act(SourceLocation PragmaLocation,
467  PragmaMsStackAction Action,
468  llvm::StringRef StackSlotLabel,
469  ValueType Value);
470 
471  // MSVC seems to add artificial slots to #pragma stacks on entering a C++
472  // method body to restore the stacks on exit, so it works like this:
473  //
474  // struct S {
475  // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
476  // void Method {}
477  // #pragma <name>(pop, InternalPragmaSlot)
478  // };
479  //
480  // It works even with #pragma vtordisp, although MSVC doesn't support
481  // #pragma vtordisp(push [, id], n)
482  // syntax.
483  //
484  // Push / pop a named sentinel slot.
485  void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
486  assert((Action == PSK_Push || Action == PSK_Pop) &&
487  "Can only push / pop #pragma stack sentinels!");
488  Act(CurrentPragmaLocation, Action, Label, CurrentValue);
489  }
490 
491  // Constructors.
492  explicit PragmaStack(const ValueType &Default)
493  : DefaultValue(Default), CurrentValue(Default) {}
494 
495  bool hasValue() const { return CurrentValue != DefaultValue; }
496 
498  ValueType DefaultValue; // Value used for PSK_Reset action.
499  ValueType CurrentValue;
501  };
502  // FIXME: We should serialize / deserialize these if they occur in a PCH (but
503  // we shouldn't do so if they're in a module).
504 
505  /// Whether to insert vtordisps prior to virtual bases in the Microsoft
506  /// C++ ABI. Possible values are 0, 1, and 2, which mean:
507  ///
508  /// 0: Suppress all vtordisps
509  /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
510  /// structors
511  /// 2: Always insert vtordisps to support RTTI on partially constructed
512  /// objects
514  // #pragma pack.
515  // Sentinel to represent when the stack is set to mac68k alignment.
516  static const unsigned kMac68kAlignmentSentinel = ~0U;
518  // The current #pragma pack values and locations at each #include.
520  unsigned CurrentValue;
522  bool HasNonDefaultValue, ShouldWarnOnInclude;
523  };
525  // Segment #pragmas.
530 
531  // RAII object to push / pop sentinel slots for all MS #pragma stacks.
532  // Actions should be performed only if we enter / exit a C++ method body.
534  public:
535  PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
537 
538  private:
539  Sema &S;
540  StringRef SlotLabel;
541  bool ShouldAct;
542  };
543 
544  /// A mapping that describes the nullability we've seen in each header file.
546 
547  /// Last section used with #pragma init_seg.
550 
551  /// VisContext - Manages the stack for \#pragma GCC visibility.
552  void *VisContext; // Really a "PragmaVisStack*"
553 
554  /// This an attribute introduced by \#pragma clang attribute.
559  bool IsUsed;
560  };
561 
562  /// A push'd group of PragmaAttributeEntries.
564  /// The location of the push attribute.
566  /// The namespace of this push group.
569  };
570 
572 
573  /// The declaration that is currently receiving an attribute from the
574  /// #pragma attribute stack.
576 
577  /// This represents the last location of a "#pragma clang optimize off"
578  /// directive if such a directive has not been closed by an "on" yet. If
579  /// optimizations are currently "on", this is set to an invalid location.
581 
582  /// Flag indicating if Sema is building a recovery call expression.
583  ///
584  /// This flag is used to avoid building recovery call expressions
585  /// if Sema is already doing so, which would cause infinite recursions.
587 
588  /// Used to control the generation of ExprWithCleanups.
590 
591  /// ExprCleanupObjects - This is the stack of objects requiring
592  /// cleanup that are created by the current full expression. The
593  /// element type here is ExprWithCleanups::Object.
595 
596  /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
597  /// to a variable (constant) that may or may not be odr-used in this Expr, and
598  /// we won't know until all lvalue-to-rvalue and discarded value conversions
599  /// have been applied to all subexpressions of the enclosing full expression.
600  /// This is cleared at the end of each full expression.
601  using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
603 
604  std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
605 
606  /// Stack containing information about each of the nested
607  /// function, block, and method scopes that are currently active.
609 
611  &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
613 
614  /// ExtVectorDecls - This is a list all the extended vector types. This allows
615  /// us to associate a raw vector type with one of the ext_vector type names.
616  /// This is only necessary for issuing pretty diagnostics.
618 
619  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
620  std::unique_ptr<CXXFieldCollector> FieldCollector;
621 
623 
624  /// Set containing all declared private fields that are not used.
625  NamedDeclSetType UnusedPrivateFields;
626 
627  /// Set containing all typedefs that are likely unused.
630 
631  /// Delete-expressions to be analyzed at the end of translation unit
632  ///
633  /// This list contains class members, and locations of delete-expressions
634  /// that could not be proven as to whether they mismatch with new-expression
635  /// used in initializer of the field.
636  typedef std::pair<SourceLocation, bool> DeleteExprLoc;
638  llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
639 
640  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
641 
642  /// PureVirtualClassDiagSet - a set of class declarations which we have
643  /// emitted a list of pure virtual functions. Used to prevent emitting the
644  /// same list more than once.
645  std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
646 
647  /// ParsingInitForAutoVars - a set of declarations with auto types for which
648  /// we are currently parsing the initializer.
649  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
650 
651  /// Look for a locally scoped extern "C" declaration by the given name.
652  NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
653 
654  typedef LazyVector<VarDecl *, ExternalSemaSource,
655  &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
657 
658  /// All the tentative definitions encountered in the TU.
660 
661  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
662  &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
664 
665  /// The set of file scoped decls seen so far that have not been used
666  /// and must warn if not used. Only contains the first declaration.
668 
669  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
670  &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
672 
673  /// All the delegating constructors seen so far in the file, used for
674  /// cycle detection at the end of the TU.
676 
677  /// All the overriding functions seen during a class definition
678  /// that had their exception spec checks delayed, plus the overridden
679  /// function.
682 
683  /// All the function redeclarations seen during a class definition that had
684  /// their exception spec checks delayed, plus the prior declaration they
685  /// should be checked against. Except during error recovery, the new decl
686  /// should always be a friend declaration, as that's the only valid way to
687  /// redeclare a special member before its class is complete.
690 
691  typedef llvm::MapVector<const FunctionDecl *,
692  std::unique_ptr<LateParsedTemplate>>
695 
696  /// Callback to the parser to parse templated functions when needed.
697  typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
698  typedef void LateTemplateParserCleanupCB(void *P);
699  LateTemplateParserCB *LateTemplateParser;
700  LateTemplateParserCleanupCB *LateTemplateParserCleanup;
702 
703  void SetLateTemplateParser(LateTemplateParserCB *LTP,
704  LateTemplateParserCleanupCB *LTPCleanup,
705  void *P) {
706  LateTemplateParser = LTP;
707  LateTemplateParserCleanup = LTPCleanup;
708  OpaqueParser = P;
709  }
710 
711  class DelayedDiagnostics;
712 
714  sema::DelayedDiagnosticPool *SavedPool;
716  };
719 
720  /// A class which encapsulates the logic for delaying diagnostics
721  /// during parsing and other processing.
723  /// The current pool of diagnostics into which delayed
724  /// diagnostics should go.
726 
727  public:
728  DelayedDiagnostics() : CurPool(nullptr) {}
729 
730  /// Adds a delayed diagnostic.
731  void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
732 
733  /// Determines whether diagnostics should be delayed.
734  bool shouldDelayDiagnostics() { return CurPool != nullptr; }
735 
736  /// Returns the current delayed-diagnostics pool.
738  return CurPool;
739  }
740 
741  /// Enter a new scope. Access and deprecation diagnostics will be
742  /// collected in this pool.
745  state.SavedPool = CurPool;
746  CurPool = &pool;
747  return state;
748  }
749 
750  /// Leave a delayed-diagnostic state that was previously pushed.
751  /// Do not emit any of the diagnostics. This is performed as part
752  /// of the bookkeeping of popping a pool "properly".
754  CurPool = state.SavedPool;
755  }
756 
757  /// Enter a new scope where access and deprecation diagnostics are
758  /// not delayed.
761  state.SavedPool = CurPool;
762  CurPool = nullptr;
763  return state;
764  }
765 
766  /// Undo a previous pushUndelayed().
768  assert(CurPool == nullptr);
769  CurPool = state.SavedPool;
770  }
772 
773  /// A RAII object to temporarily push a declaration context.
774  class ContextRAII {
775  private:
776  Sema &S;
777  DeclContext *SavedContext;
778  ProcessingContextState SavedContextState;
779  QualType SavedCXXThisTypeOverride;
780 
781  public:
782  ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
783  : S(S), SavedContext(S.CurContext),
784  SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
785  SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
786  {
787  assert(ContextToPush && "pushing null context");
788  S.CurContext = ContextToPush;
789  if (NewThisContext)
791  }
792 
793  void pop() {
794  if (!SavedContext) return;
795  S.CurContext = SavedContext;
796  S.DelayedDiagnostics.popUndelayed(SavedContextState);
797  S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
798  SavedContext = nullptr;
799  }
800 
802  pop();
803  }
804  };
805 
806  /// Used to change context to isConstantEvaluated without pushing a heavy
807  /// ExpressionEvaluationContextRecord object.
809 
811  return ExprEvalContexts.back().isConstantEvaluated() ||
812  isConstantEvaluatedOverride;
813  }
814 
815  /// RAII object to handle the state changes required to synthesize
816  /// a function body.
818  Sema &S;
819  Sema::ContextRAII SavedContext;
820  bool PushedCodeSynthesisContext = false;
821 
822  public:
824  : S(S), SavedContext(S, DC) {
825  S.PushFunctionScope();
827  Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
828  if (auto *FD = dyn_cast<FunctionDecl>(DC))
829  FD->setWillHaveBody(true);
830  else
831  assert(isa<ObjCMethodDecl>(DC));
832  }
833 
835  assert(!PushedCodeSynthesisContext);
836 
838  Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
839  Ctx.PointOfInstantiation = UseLoc;
840  Ctx.Entity = cast<Decl>(S.CurContext);
842 
843  PushedCodeSynthesisContext = true;
844  }
845 
847  if (PushedCodeSynthesisContext)
849  if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
850  FD->setWillHaveBody(false);
853  }
854  };
855 
856  /// WeakUndeclaredIdentifiers - Identifiers contained in
857  /// \#pragma weak before declared. rare. may alias another
858  /// identifier, declared or undeclared
859  llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
860 
861  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
862  /// \#pragma redefine_extname before declared. Used in Solaris system headers
863  /// to define functions that occur in multiple standards to call the version
864  /// in the currently selected standard.
865  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
866 
867 
868  /// Load weak undeclared identifiers from the external source.
869  void LoadExternalWeakUndeclaredIdentifiers();
870 
871  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
872  /// \#pragma weak during processing of other Decls.
873  /// I couldn't figure out a clean way to generate these in-line, so
874  /// we store them here and handle separately -- which is a hack.
875  /// It would be best to refactor this.
877 
879 
880  /// Translation Unit Scope - useful to Objective-C actions that need
881  /// to lookup file scope declarations in the "ordinary" C decl namespace.
882  /// For example, user-defined classes, built-in "id" type, etc.
884 
885  /// The C++ "std" namespace, where the standard library resides.
887 
888  /// The C++ "std::bad_alloc" class, which is defined by the C++
889  /// standard library.
891 
892  /// The C++ "std::align_val_t" enum class, which is defined by the C++
893  /// standard library.
895 
896  /// The C++ "std::experimental" namespace, where the experimental parts
897  /// of the standard library resides.
899 
900  /// The C++ "std::initializer_list" template, which is defined in
901  /// <initializer_list>.
903 
904  /// The C++ "std::coroutine_traits" template, which is defined in
905  /// <coroutine_traits>
907 
908  /// The C++ "type_info" declaration, which is defined in <typeinfo>.
910 
911  /// The MSVC "_GUID" struct, which is defined in MSVC header files.
913 
914  /// Caches identifiers/selectors for NSFoundation APIs.
915  std::unique_ptr<NSAPI> NSAPIObj;
916 
917  /// The declaration of the Objective-C NSNumber class.
919 
920  /// The declaration of the Objective-C NSValue class.
922 
923  /// Pointer to NSNumber type (NSNumber *).
925 
926  /// Pointer to NSValue type (NSValue *).
928 
929  /// The Objective-C NSNumber methods used to create NSNumber literals.
930  ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
931 
932  /// The declaration of the Objective-C NSString class.
934 
935  /// Pointer to NSString type (NSString *).
937 
938  /// The declaration of the stringWithUTF8String: method.
940 
941  /// The declaration of the valueWithBytes:objCType: method.
943 
944  /// The declaration of the Objective-C NSArray class.
946 
947  /// The declaration of the arrayWithObjects:count: method.
949 
950  /// The declaration of the Objective-C NSDictionary class.
952 
953  /// The declaration of the dictionaryWithObjects:forKeys:count: method.
955 
956  /// id<NSCopying> type.
958 
959  /// will hold 'respondsToSelector:'
961 
962  /// A flag to remember whether the implicit forms of operator new and delete
963  /// have been declared.
965 
966  /// A flag to indicate that we're in a context that permits abstract
967  /// references to fields. This is really a
969 
970  /// Describes how the expressions currently being parsed are
971  /// evaluated at run-time, if at all.
973  /// The current expression and its subexpressions occur within an
974  /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
975  /// \c sizeof, where the type of the expression may be significant but
976  /// no code will be generated to evaluate the value of the expression at
977  /// run time.
978  Unevaluated,
979 
980  /// The current expression occurs within a braced-init-list within
981  /// an unevaluated operand. This is mostly like a regular unevaluated
982  /// context, except that we still instantiate constexpr functions that are
983  /// referenced here so that we can perform narrowing checks correctly.
984  UnevaluatedList,
985 
986  /// The current expression occurs within a discarded statement.
987  /// This behaves largely similarly to an unevaluated operand in preventing
988  /// definitions from being required, but not in other ways.
989  DiscardedStatement,
990 
991  /// The current expression occurs within an unevaluated
992  /// operand that unconditionally permits abstract references to
993  /// fields, such as a SIZE operator in MS-style inline assembly.
994  UnevaluatedAbstract,
995 
996  /// The current context is "potentially evaluated" in C++11 terms,
997  /// but the expression is evaluated at compile-time (like the values of
998  /// cases in a switch statement).
999  ConstantEvaluated,
1000 
1001  /// The current expression is potentially evaluated at run time,
1002  /// which means that code may be generated to evaluate the value of the
1003  /// expression at run time.
1004  PotentiallyEvaluated,
1005 
1006  /// The current expression is potentially evaluated, but any
1007  /// declarations referenced inside that expression are only used if
1008  /// in fact the current expression is used.
1009  ///
1010  /// This value is used when parsing default function arguments, for which
1011  /// we would like to provide diagnostics (e.g., passing non-POD arguments
1012  /// through varargs) but do not want to mark declarations as "referenced"
1013  /// until the default argument is used.
1014  PotentiallyEvaluatedIfUsed
1015  };
1016 
1017  /// Data structure used to record current or nested
1018  /// expression evaluation contexts.
1020  /// The expression evaluation context.
1022 
1023  /// Whether the enclosing context needed a cleanup.
1025 
1026  /// Whether we are in a decltype expression.
1028 
1029  /// The number of active cleanup objects when we entered
1030  /// this expression evaluation context.
1032 
1033  /// The number of typos encountered during this expression evaluation
1034  /// context (i.e. the number of TypoExprs created).
1035  unsigned NumTypos;
1036 
1038 
1039  /// The lambdas that are present within this context, if it
1040  /// is indeed an unevaluated context.
1042 
1043  /// The declaration that provides context for lambda expressions
1044  /// and block literals if the normal declaration context does not
1045  /// suffice, e.g., in a default function argument.
1047 
1048  /// The context information used to mangle lambda expressions
1049  /// and block literals within this context.
1050  ///
1051  /// This mangling information is allocated lazily, since most contexts
1052  /// do not have lambda expressions or block literals.
1053  std::unique_ptr<MangleNumberingContext> MangleNumbering;
1054 
1055  /// If we are processing a decltype type, a set of call expressions
1056  /// for which we have deferred checking the completeness of the return type.
1058 
1059  /// If we are processing a decltype type, a set of temporary binding
1060  /// expressions for which we have deferred checking the destructor.
1062 
1063  llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1064 
1065  /// \brief Describes whether we are in an expression constext which we have
1066  /// to handle differently.
1068  EK_Decltype, EK_TemplateArgument, EK_Other
1069  } ExprContext;
1070 
1072  unsigned NumCleanupObjects,
1073  CleanupInfo ParentCleanup,
1074  Decl *ManglingContextDecl,
1075  ExpressionKind ExprContext)
1076  : Context(Context), ParentCleanup(ParentCleanup),
1077  NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1078  ManglingContextDecl(ManglingContextDecl), MangleNumbering(),
1079  ExprContext(ExprContext) {}
1080 
1081  /// Retrieve the mangling numbering context, used to consistently
1082  /// number constructs like lambdas for mangling.
1083  MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
1084 
1085  bool isUnevaluated() const {
1086  return Context == ExpressionEvaluationContext::Unevaluated ||
1087  Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1088  Context == ExpressionEvaluationContext::UnevaluatedList;
1089  }
1090  bool isConstantEvaluated() const {
1091  return Context == ExpressionEvaluationContext::ConstantEvaluated;
1092  }
1093  };
1094 
1095  /// A stack of expression evaluation contexts.
1097 
1098  /// Emit a warning for all pending noderef expressions that we recorded.
1099  void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1100 
1101  /// Compute the mangling number context for a lambda expression or
1102  /// block literal.
1103  ///
1104  /// \param DC - The DeclContext containing the lambda expression or
1105  /// block literal.
1106  /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
1107  /// associated with the context, if relevant.
1108  MangleNumberingContext *getCurrentMangleNumberContext(
1109  const DeclContext *DC,
1110  Decl *&ManglingContextDecl);
1111 
1112 
1113  /// SpecialMemberOverloadResult - The overloading result for a special member
1114  /// function.
1115  ///
1116  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1117  /// integer are used to determine whether overload resolution succeeded.
1119  public:
1120  enum Kind {
1123  Success
1124  };
1125 
1126  private:
1127  llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1128 
1129  public:
1132  : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1133 
1134  CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1135  void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1136 
1137  Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1138  void setKind(Kind K) { Pair.setInt(K); }
1139  };
1140 
1142  : public llvm::FastFoldingSetNode,
1144  public:
1145  SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1146  : FastFoldingSetNode(ID)
1147  {}
1148  };
1149 
1150  /// A cache of special member function overload resolution results
1151  /// for C++ records.
1152  llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1153 
1154  /// A cache of the flags available in enumerations with the flag_bits
1155  /// attribute.
1156  mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1157 
1158  /// The kind of translation unit we are processing.
1159  ///
1160  /// When we're processing a complete translation unit, Sema will perform
1161  /// end-of-translation-unit semantic tasks (such as creating
1162  /// initializers for tentative definitions in C) once parsing has
1163  /// completed. Modules and precompiled headers perform different kinds of
1164  /// checks.
1166 
1167  llvm::BumpPtrAllocator BumpAlloc;
1168 
1169  /// The number of SFINAE diagnostics that have been trapped.
1171 
1172  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1174 
1175  /// A mapping from parameters with unparsed default arguments to the
1176  /// set of instantiations of each parameter.
1177  ///
1178  /// This mapping is a temporary data structure used when parsing
1179  /// nested class templates or nested classes of class templates,
1180  /// where we might end up instantiating an inner class before the
1181  /// default arguments of its methods have been parsed.
1183 
1184  // Contains the locations of the beginning of unparsed default
1185  // argument locations.
1186  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1187 
1188  /// UndefinedInternals - all the used, undefined objects which require a
1189  /// definition in this translation unit.
1190  llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1191 
1192  /// Determine if VD, which must be a variable or function, is an external
1193  /// symbol that nonetheless can't be referenced from outside this translation
1194  /// unit because its type has no linkage and it's not extern "C".
1195  bool isExternalWithNoLinkageType(ValueDecl *VD);
1196 
1197  /// Obtain a sorted list of functions that are undefined but ODR-used.
1198  void getUndefinedButUsed(
1199  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1200 
1201  /// Retrieves list of suspicious delete-expressions that will be checked at
1202  /// the end of translation unit.
1203  const llvm::MapVector<FieldDecl *, DeleteLocs> &
1204  getMismatchingDeleteExpressions() const;
1205 
1206  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1207  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1208 
1209  /// Method Pool - allows efficient lookup when typechecking messages to "id".
1210  /// We need to maintain a list, since selectors can have differing signatures
1211  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1212  /// of selectors are "overloaded").
1213  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1214  /// methods inside categories with a particular selector.
1215  GlobalMethodPool MethodPool;
1216 
1217  /// Method selectors used in a \@selector expression. Used for implementation
1218  /// of -Wselector.
1219  llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1220 
1221  /// List of SourceLocations where 'self' is implicitly retained inside a
1222  /// block.
1225 
1226  /// Kinds of C++ special members.
1234  CXXInvalid
1235  };
1236 
1237  typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1239 
1240  /// The C++ special members which we are currently in the process of
1241  /// declaring. If this process recursively triggers the declaration of the
1242  /// same special member, we should act as if it is not yet declared.
1243  llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1244 
1245  /// The function definitions which were renamed as part of typo-correction
1246  /// to match their respective declarations. We want to keep track of them
1247  /// to ensure that we don't emit a "redefinition" error if we encounter a
1248  /// correctly named definition after the renamed definition.
1249  llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1250 
1251  /// Stack of types that correspond to the parameter entities that are
1252  /// currently being copy-initialized. Can be empty.
1254 
1255  void ReadMethodPool(Selector Sel);
1256  void updateOutOfDateSelector(Selector Sel);
1257 
1258  /// Private Helper predicate to check for 'self'.
1259  bool isSelfExpr(Expr *RExpr);
1260  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1261 
1262  /// Cause the active diagnostic on the DiagosticsEngine to be
1263  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1264  /// should not be used elsewhere.
1265  void EmitCurrentDiagnostic(unsigned DiagID);
1266 
1267  /// Records and restores the FP_CONTRACT state on entry/exit of compound
1268  /// statements.
1270  public:
1271  FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1272  ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1273 
1274  private:
1275  Sema& S;
1276  FPOptions OldFPFeaturesState;
1277  };
1278 
1279  void addImplicitTypedef(StringRef Name, QualType T);
1280 
1281 public:
1282  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1284  CodeCompleteConsumer *CompletionConsumer = nullptr);
1285  ~Sema();
1286 
1287  /// Perform initialization that occurs after the parser has been
1288  /// initialized but before it parses anything.
1289  void Initialize();
1290 
1291  const LangOptions &getLangOpts() const { return LangOpts; }
1292  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1293  FPOptions &getFPOptions() { return FPFeatures; }
1294 
1295  DiagnosticsEngine &getDiagnostics() const { return Diags; }
1296  SourceManager &getSourceManager() const { return SourceMgr; }
1297  Preprocessor &getPreprocessor() const { return PP; }
1298  ASTContext &getASTContext() const { return Context; }
1299  ASTConsumer &getASTConsumer() const { return Consumer; }
1300  ASTMutationListener *getASTMutationListener() const;
1301  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1302 
1303  ///Registers an external source. If an external source already exists,
1304  /// creates a multiplex external source and appends to it.
1305  ///
1306  ///\param[in] E - A non-null external sema source.
1307  ///
1308  void addExternalSource(ExternalSemaSource *E);
1309 
1310  void PrintStats() const;
1311 
1312  /// Helper class that creates diagnostics with optional
1313  /// template instantiation stacks.
1314  ///
1315  /// This class provides a wrapper around the basic DiagnosticBuilder
1316  /// class that emits diagnostics. SemaDiagnosticBuilder is
1317  /// responsible for emitting the diagnostic (as DiagnosticBuilder
1318  /// does) and, if the diagnostic comes from inside a template
1319  /// instantiation, printing the template instantiation stack as
1320  /// well.
1322  Sema &SemaRef;
1323  unsigned DiagID;
1324 
1325  public:
1326  SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1327  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1328 
1329  // This is a cunning lie. DiagnosticBuilder actually performs move
1330  // construction in its copy constructor (but due to varied uses, it's not
1331  // possible to conveniently express this as actual move construction). So
1332  // the default copy ctor here is fine, because the base class disables the
1333  // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1334  // in that case anwyay.
1335  SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1336 
1338  // If we aren't active, there is nothing to do.
1339  if (!isActive()) return;
1340 
1341  // Otherwise, we need to emit the diagnostic. First flush the underlying
1342  // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1343  // won't emit the diagnostic in its own destructor.
1344  //
1345  // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1346  // do its own needless checks to see if the diagnostic needs to be
1347  // emitted. However, because we take care to ensure that the builder
1348  // objects never escape, a sufficiently smart compiler will be able to
1349  // eliminate that code.
1350  FlushCounts();
1351  Clear();
1352 
1353  // Dispatch to Sema to emit the diagnostic.
1354  SemaRef.EmitCurrentDiagnostic(DiagID);
1355  }
1356 
1357  /// Teach operator<< to produce an object of the correct type.
1358  template<typename T>
1360  const SemaDiagnosticBuilder &Diag, const T &Value) {
1361  const DiagnosticBuilder &BaseDiag = Diag;
1362  BaseDiag << Value;
1363  return Diag;
1364  }
1365  };
1366 
1367  /// Emit a diagnostic.
1369  DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1370  return SemaDiagnosticBuilder(DB, *this, DiagID);
1371  }
1372 
1373  /// Emit a partial diagnostic.
1375 
1376  /// Build a partial diagnostic.
1377  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1378 
1379  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1380 
1381  /// Get a string to suggest for zero-initialization of a type.
1382  std::string
1383  getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1384  std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1385 
1386  /// Calls \c Lexer::getLocForEndOfToken()
1387  SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1388 
1389  /// Retrieve the module loader associated with the preprocessor.
1390  ModuleLoader &getModuleLoader() const;
1391 
1392  void emitAndClearUnusedLocalTypedefWarnings();
1393 
1395  /// The global module fragment, between 'module;' and a module-declaration.
1397  /// A normal translation unit fragment. For a non-module unit, this is the
1398  /// entire translation unit. Otherwise, it runs from the module-declaration
1399  /// to the private-module-fragment (if any) or the end of the TU (if not).
1401  /// The private module fragment, between 'module :private;' and the end of
1402  /// the translation unit.
1403  Private
1404  };
1405 
1406  void ActOnStartOfTranslationUnit();
1407  void ActOnEndOfTranslationUnit();
1408  void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1409 
1410  void CheckDelegatingCtorCycles();
1411 
1412  Scope *getScopeForContext(DeclContext *Ctx);
1413 
1414  void PushFunctionScope();
1415  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1416  sema::LambdaScopeInfo *PushLambdaScope();
1417 
1418  /// This is used to inform Sema what the current TemplateParameterDepth
1419  /// is during Parsing. Currently it is used to pass on the depth
1420  /// when parsing generic lambda 'auto' parameters.
1421  void RecordParsingTemplateParameterDepth(unsigned Depth);
1422 
1423  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1424  RecordDecl *RD,
1425  CapturedRegionKind K);
1426 
1427  /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1428  /// time after they've been popped.
1430  Sema *Self;
1431 
1432  public:
1433  explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1434  void operator()(sema::FunctionScopeInfo *Scope) const;
1435  };
1436 
1437  using PoppedFunctionScopePtr =
1438  std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1439 
1441  PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1442  const Decl *D = nullptr,
1443  QualType BlockType = QualType());
1444 
1446  return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1447  }
1448 
1449  sema::FunctionScopeInfo *getEnclosingFunction() const;
1450 
1451  void setFunctionHasBranchIntoScope();
1452  void setFunctionHasBranchProtectedScope();
1453  void setFunctionHasIndirectGoto();
1454 
1455  void PushCompoundScope(bool IsStmtExpr);
1456  void PopCompoundScope();
1457 
1458  sema::CompoundScopeInfo &getCurCompoundScope() const;
1459 
1460  bool hasAnyUnrecoverableErrorsInThisFunction() const;
1461 
1462  /// Retrieve the current block, if any.
1463  sema::BlockScopeInfo *getCurBlock();
1464 
1465  /// Retrieve the current lambda scope info, if any.
1466  /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1467  /// lambda scope info ignoring all inner capturing scopes that are not
1468  /// lambda scopes.
1470  getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1471 
1472  /// Retrieve the current generic lambda info, if any.
1473  sema::LambdaScopeInfo *getCurGenericLambda();
1474 
1475  /// Retrieve the current captured region, if any.
1476  sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1477 
1478  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1479  SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1480 
1481  void ActOnComment(SourceRange Comment);
1482 
1483  //===--------------------------------------------------------------------===//
1484  // Type Analysis / Processing: SemaType.cpp.
1485  //
1486 
1487  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1488  const DeclSpec *DS = nullptr);
1489  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1490  const DeclSpec *DS = nullptr);
1491  QualType BuildPointerType(QualType T,
1492  SourceLocation Loc, DeclarationName Entity);
1493  QualType BuildReferenceType(QualType T, bool LValueRef,
1494  SourceLocation Loc, DeclarationName Entity);
1495  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1496  Expr *ArraySize, unsigned Quals,
1497  SourceRange Brackets, DeclarationName Entity);
1498  QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1499  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1500  SourceLocation AttrLoc);
1501  QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1502  SourceLocation AttrLoc);
1503 
1504  /// Same as above, but constructs the AddressSpace index if not provided.
1505  QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1506  SourceLocation AttrLoc);
1507 
1508  bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1509 
1510  /// Build a function type.
1511  ///
1512  /// This routine checks the function type according to C++ rules and
1513  /// under the assumption that the result type and parameter types have
1514  /// just been instantiated from a template. It therefore duplicates
1515  /// some of the behavior of GetTypeForDeclarator, but in a much
1516  /// simpler form that is only suitable for this narrow use case.
1517  ///
1518  /// \param T The return type of the function.
1519  ///
1520  /// \param ParamTypes The parameter types of the function. This array
1521  /// will be modified to account for adjustments to the types of the
1522  /// function parameters.
1523  ///
1524  /// \param Loc The location of the entity whose type involves this
1525  /// function type or, if there is no such entity, the location of the
1526  /// type that will have function type.
1527  ///
1528  /// \param Entity The name of the entity that involves the function
1529  /// type, if known.
1530  ///
1531  /// \param EPI Extra information about the function type. Usually this will
1532  /// be taken from an existing function with the same prototype.
1533  ///
1534  /// \returns A suitable function type, if there are no errors. The
1535  /// unqualified type will always be a FunctionProtoType.
1536  /// Otherwise, returns a NULL type.
1537  QualType BuildFunctionType(QualType T,
1538  MutableArrayRef<QualType> ParamTypes,
1539  SourceLocation Loc, DeclarationName Entity,
1540  const FunctionProtoType::ExtProtoInfo &EPI);
1541 
1542  QualType BuildMemberPointerType(QualType T, QualType Class,
1543  SourceLocation Loc,
1544  DeclarationName Entity);
1545  QualType BuildBlockPointerType(QualType T,
1546  SourceLocation Loc, DeclarationName Entity);
1547  QualType BuildParenType(QualType T);
1548  QualType BuildAtomicType(QualType T, SourceLocation Loc);
1549  QualType BuildReadPipeType(QualType T,
1550  SourceLocation Loc);
1551  QualType BuildWritePipeType(QualType T,
1552  SourceLocation Loc);
1553 
1554  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1555  TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1556 
1557  /// Package the given type and TSI into a ParsedType.
1558  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1559  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1560  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1561  static QualType GetTypeFromParser(ParsedType Ty,
1562  TypeSourceInfo **TInfo = nullptr);
1563  CanThrowResult canThrow(const Expr *E);
1564  const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1565  const FunctionProtoType *FPT);
1566  void UpdateExceptionSpec(FunctionDecl *FD,
1568  bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1569  bool CheckDistantExceptionSpec(QualType T);
1570  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1571  bool CheckEquivalentExceptionSpec(
1572  const FunctionProtoType *Old, SourceLocation OldLoc,
1573  const FunctionProtoType *New, SourceLocation NewLoc);
1574  bool CheckEquivalentExceptionSpec(
1575  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1576  const FunctionProtoType *Old, SourceLocation OldLoc,
1577  const FunctionProtoType *New, SourceLocation NewLoc);
1578  bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1579  bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1580  const PartialDiagnostic &NestedDiagID,
1581  const PartialDiagnostic &NoteID,
1582  const PartialDiagnostic &NoThrowDiagID,
1583  const FunctionProtoType *Superset,
1584  SourceLocation SuperLoc,
1585  const FunctionProtoType *Subset,
1586  SourceLocation SubLoc);
1587  bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1588  const PartialDiagnostic &NoteID,
1589  const FunctionProtoType *Target,
1590  SourceLocation TargetLoc,
1591  const FunctionProtoType *Source,
1592  SourceLocation SourceLoc);
1593 
1594  TypeResult ActOnTypeName(Scope *S, Declarator &D);
1595 
1596  /// The parser has parsed the context-sensitive type 'instancetype'
1597  /// in an Objective-C message declaration. Return the appropriate type.
1598  ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1599 
1600  /// Abstract class used to diagnose incomplete types.
1601  struct TypeDiagnoser {
1603 
1604  virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1605  virtual ~TypeDiagnoser() {}
1606  };
1607 
1608  static int getPrintable(int I) { return I; }
1609  static unsigned getPrintable(unsigned I) { return I; }
1610  static bool getPrintable(bool B) { return B; }
1611  static const char * getPrintable(const char *S) { return S; }
1612  static StringRef getPrintable(StringRef S) { return S; }
1613  static const std::string &getPrintable(const std::string &S) { return S; }
1614  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1615  return II;
1616  }
1618  static QualType getPrintable(QualType T) { return T; }
1619  static SourceRange getPrintable(SourceRange R) { return R; }
1620  static SourceRange getPrintable(SourceLocation L) { return L; }
1621  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1622  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1623 
1624  template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1625  unsigned DiagID;
1626  std::tuple<const Ts &...> Args;
1627 
1628  template <std::size_t... Is>
1629  void emit(const SemaDiagnosticBuilder &DB,
1630  std::index_sequence<Is...>) const {
1631  // Apply all tuple elements to the builder in order.
1632  bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1633  (void)Dummy;
1634  }
1635 
1636  public:
1637  BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1638  : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1639  assert(DiagID != 0 && "no diagnostic for type diagnoser");
1640  }
1641 
1642  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1643  const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1644  emit(DB, std::index_sequence_for<Ts...>());
1645  DB << T;
1646  }
1647  };
1648 
1649 private:
1650  /// Methods for marking which expressions involve dereferencing a pointer
1651  /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1652  /// they are parsed, meaning that a noderef pointer may not be accessed. For
1653  /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1654  /// `*p`, but need to check that `address of` is called on it. This requires
1655  /// keeping a container of all pending expressions and checking if the address
1656  /// of them are eventually taken.
1657  void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1658  void CheckAddressOfNoDeref(const Expr *E);
1659  void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1660 
1661  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1662  TypeDiagnoser *Diagnoser);
1663 
1664  struct ModuleScope {
1665  SourceLocation BeginLoc;
1666  clang::Module *Module = nullptr;
1667  bool ModuleInterface = false;
1668  bool ImplicitGlobalModuleFragment = false;
1669  VisibleModuleSet OuterVisibleModules;
1670  };
1671  /// The modules we're currently parsing.
1673 
1674  /// Namespace definitions that we will export when they finish.
1675  llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1676 
1677  /// Get the module whose scope we are currently within.
1678  Module *getCurrentModule() const {
1679  return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1680  }
1681 
1682  VisibleModuleSet VisibleModules;
1683 
1684 public:
1685  /// Get the module owning an entity.
1686  Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1687 
1688  /// Make a merged definition of an existing hidden definition \p ND
1689  /// visible at the specified location.
1690  void makeMergedDefinitionVisible(NamedDecl *ND);
1691 
1692  bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1693 
1694  /// Determine whether a declaration is visible to name lookup.
1695  bool isVisible(const NamedDecl *D) {
1696  return !D->isHidden() || isVisibleSlow(D);
1697  }
1698 
1699  /// Determine whether any declaration of an entity is visible.
1700  bool
1702  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1703  return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1704  }
1705  bool hasVisibleDeclarationSlow(const NamedDecl *D,
1707 
1708  bool hasVisibleMergedDefinition(NamedDecl *Def);
1709  bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1710 
1711  /// Determine if \p D and \p Suggested have a structurally compatible
1712  /// layout as described in C11 6.2.7/1.
1713  bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1714 
1715  /// Determine if \p D has a visible definition. If not, suggest a declaration
1716  /// that should be made visible to expose the definition.
1717  bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1718  bool OnlyNeedComplete = false);
1720  NamedDecl *Hidden;
1721  return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1722  }
1723 
1724  /// Determine if the template parameter \p D has a visible default argument.
1725  bool
1727  llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1728 
1729  /// Determine if there is a visible declaration of \p D that is an explicit
1730  /// specialization declaration for a specialization of a template. (For a
1731  /// member specialization, use hasVisibleMemberSpecialization.)
1732  bool hasVisibleExplicitSpecialization(
1733  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1734 
1735  /// Determine if there is a visible declaration of \p D that is a member
1736  /// specialization declaration (as opposed to an instantiated declaration).
1737  bool hasVisibleMemberSpecialization(
1738  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1739 
1740  /// Determine if \p A and \p B are equivalent internal linkage declarations
1741  /// from different modules, and thus an ambiguity error can be downgraded to
1742  /// an extension warning.
1743  bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1744  const NamedDecl *B);
1745  void diagnoseEquivalentInternalLinkageDeclarations(
1746  SourceLocation Loc, const NamedDecl *D,
1748 
1749  bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1750 
1752  return !RequireCompleteTypeImpl(Loc, T, nullptr);
1753  }
1754  bool RequireCompleteType(SourceLocation Loc, QualType T,
1755  TypeDiagnoser &Diagnoser);
1756  bool RequireCompleteType(SourceLocation Loc, QualType T,
1757  unsigned DiagID);
1758 
1759  template <typename... Ts>
1760  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1761  const Ts &...Args) {
1762  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1763  return RequireCompleteType(Loc, T, Diagnoser);
1764  }
1765 
1766  void completeExprArrayBound(Expr *E);
1767  bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1768  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1769 
1770  template <typename... Ts>
1771  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1772  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1773  return RequireCompleteExprType(E, Diagnoser);
1774  }
1775 
1776  bool RequireLiteralType(SourceLocation Loc, QualType T,
1777  TypeDiagnoser &Diagnoser);
1778  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1779 
1780  template <typename... Ts>
1781  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1782  const Ts &...Args) {
1783  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1784  return RequireLiteralType(Loc, T, Diagnoser);
1785  }
1786 
1787  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1788  const CXXScopeSpec &SS, QualType T,
1789  TagDecl *OwnedTagDecl = nullptr);
1790 
1791  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1792  /// If AsUnevaluated is false, E is treated as though it were an evaluated
1793  /// context, such as when building a type for decltype(auto).
1794  QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1795  bool AsUnevaluated = true);
1796  QualType BuildUnaryTransformType(QualType BaseType,
1798  SourceLocation Loc);
1799 
1800  //===--------------------------------------------------------------------===//
1801  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1802  //
1803 
1804  struct SkipBodyInfo {
1806  : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1807  New(nullptr) {}
1812  };
1813 
1814  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1815 
1816  void DiagnoseUseOfUnimplementedSelectors();
1817 
1818  bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1819 
1821  Scope *S, CXXScopeSpec *SS = nullptr,
1822  bool isClassName = false, bool HasTrailingDot = false,
1823  ParsedType ObjectType = nullptr,
1824  bool IsCtorOrDtorName = false,
1825  bool WantNontrivialTypeSourceInfo = false,
1826  bool IsClassTemplateDeductionContext = true,
1827  IdentifierInfo **CorrectedII = nullptr);
1828  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1829  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1830  void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1831  SourceLocation IILoc,
1832  Scope *S,
1833  CXXScopeSpec *SS,
1834  ParsedType &SuggestedType,
1835  bool IsTemplateName = false);
1836 
1837  /// Attempt to behave like MSVC in situations where lookup of an unqualified
1838  /// type name has failed in a dependent context. In these situations, we
1839  /// automatically form a DependentTypeName that will retry lookup in a related
1840  /// scope during instantiation.
1841  ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1842  SourceLocation NameLoc,
1843  bool IsTemplateTypeArg);
1844 
1845  /// Describes the result of the name lookup and resolution performed
1846  /// by \c ClassifyName().
1858  };
1859 
1862  ExprResult Expr;
1863  TemplateName Template;
1864  ParsedType Type;
1865 
1866  explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1867 
1868  public:
1869  NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1870 
1871  NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1872 
1873  NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1874 
1876  return NameClassification(NC_Error);
1877  }
1878 
1880  return NameClassification(NC_Unknown);
1881  }
1882 
1884  return NameClassification(NC_NestedNameSpecifier);
1885  }
1886 
1888  NameClassification Result(NC_TypeTemplate);
1889  Result.Template = Name;
1890  return Result;
1891  }
1892 
1894  NameClassification Result(NC_VarTemplate);
1895  Result.Template = Name;
1896  return Result;
1897  }
1898 
1900  NameClassification Result(NC_FunctionTemplate);
1901  Result.Template = Name;
1902  return Result;
1903  }
1904 
1906  NameClassification Result(NC_UndeclaredTemplate);
1907  Result.Template = Name;
1908  return Result;
1909  }
1910 
1912 
1914  assert(Kind == NC_Type);
1915  return Type;
1916  }
1917 
1919  assert(Kind == NC_Expression);
1920  return Expr;
1921  }
1922 
1924  assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1925  Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate);
1926  return Template;
1927  }
1928 
1930  switch (Kind) {
1931  case NC_TypeTemplate:
1932  return TNK_Type_template;
1933  case NC_FunctionTemplate:
1934  return TNK_Function_template;
1935  case NC_VarTemplate:
1936  return TNK_Var_template;
1937  case NC_UndeclaredTemplate:
1938  return TNK_Undeclared_template;
1939  default:
1940  llvm_unreachable("unsupported name classification.");
1941  }
1942  }
1943  };
1944 
1945  /// Perform name lookup on the given name, classifying it based on
1946  /// the results of name lookup and the following token.
1947  ///
1948  /// This routine is used by the parser to resolve identifiers and help direct
1949  /// parsing. When the identifier cannot be found, this routine will attempt
1950  /// to correct the typo and classify based on the resulting name.
1951  ///
1952  /// \param S The scope in which we're performing name lookup.
1953  ///
1954  /// \param SS The nested-name-specifier that precedes the name.
1955  ///
1956  /// \param Name The identifier. If typo correction finds an alternative name,
1957  /// this pointer parameter will be updated accordingly.
1958  ///
1959  /// \param NameLoc The location of the identifier.
1960  ///
1961  /// \param NextToken The token following the identifier. Used to help
1962  /// disambiguate the name.
1963  ///
1964  /// \param IsAddressOfOperand True if this name is the operand of a unary
1965  /// address of ('&') expression, assuming it is classified as an
1966  /// expression.
1967  ///
1968  /// \param CCC The correction callback, if typo correction is desired.
1969  NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
1970  IdentifierInfo *&Name, SourceLocation NameLoc,
1971  const Token &NextToken,
1972  bool IsAddressOfOperand,
1973  CorrectionCandidateCallback *CCC = nullptr);
1974 
1975  /// Describes the detailed kind of a template name. Used in diagnostics.
1977  ClassTemplate,
1978  FunctionTemplate,
1979  VarTemplate,
1980  AliasTemplate,
1981  TemplateTemplateParam,
1982  Concept,
1983  DependentTemplate
1984  };
1986  getTemplateNameKindForDiagnostics(TemplateName Name);
1987 
1988  /// Determine whether it's plausible that E was intended to be a
1989  /// template-name.
1990  bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
1991  if (!getLangOpts().CPlusPlus || E.isInvalid())
1992  return false;
1993  Dependent = false;
1994  if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1995  return !DRE->hasExplicitTemplateArgs();
1996  if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1997  return !ME->hasExplicitTemplateArgs();
1998  Dependent = true;
1999  if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2000  return !DSDRE->hasExplicitTemplateArgs();
2001  if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2002  return !DSME->hasExplicitTemplateArgs();
2003  // Any additional cases recognized here should also be handled by
2004  // diagnoseExprIntendedAsTemplateName.
2005  return false;
2006  }
2007  void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2010 
2011  Decl *ActOnDeclarator(Scope *S, Declarator &D);
2012 
2013  NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2014  MultiTemplateParamsArg TemplateParameterLists);
2015  void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2016  bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2017  bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2018  DeclarationName Name, SourceLocation Loc,
2019  bool IsTemplateId);
2020  void
2021  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2022  SourceLocation FallbackLoc,
2023  SourceLocation ConstQualLoc = SourceLocation(),
2024  SourceLocation VolatileQualLoc = SourceLocation(),
2025  SourceLocation RestrictQualLoc = SourceLocation(),
2026  SourceLocation AtomicQualLoc = SourceLocation(),
2027  SourceLocation UnalignedQualLoc = SourceLocation());
2028 
2029  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2030  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2031  NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2032  const LookupResult &R);
2033  NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2034  void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2035  const LookupResult &R);
2036  void CheckShadow(Scope *S, VarDecl *D);
2037 
2038  /// Warn if 'E', which is an expression that is about to be modified, refers
2039  /// to a shadowing declaration.
2040  void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2041 
2042  void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2043 
2044 private:
2045  /// Map of current shadowing declarations to shadowed declarations. Warn if
2046  /// it looks like the user is trying to modify the shadowing declaration.
2047  llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2048 
2049 public:
2050  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2051  void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2052  void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2053  TypedefNameDecl *NewTD);
2054  void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2055  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2056  TypeSourceInfo *TInfo,
2058  NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2059  LookupResult &Previous, bool &Redeclaration);
2060  NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2061  TypeSourceInfo *TInfo,
2062  LookupResult &Previous,
2063  MultiTemplateParamsArg TemplateParamLists,
2064  bool &AddToScope,
2065  ArrayRef<BindingDecl *> Bindings = None);
2066  NamedDecl *
2067  ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2068  MultiTemplateParamsArg TemplateParamLists);
2069  // Returns true if the variable declaration is a redeclaration
2070  bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2071  void CheckVariableDeclarationType(VarDecl *NewVD);
2072  bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2073  Expr *Init);
2074  void CheckCompleteVariableDeclaration(VarDecl *VD);
2075  void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2076  void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2077 
2078  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2079  TypeSourceInfo *TInfo,
2080  LookupResult &Previous,
2081  MultiTemplateParamsArg TemplateParamLists,
2082  bool &AddToScope);
2083  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2084 
2085  enum class CheckConstexprKind {
2086  /// Diagnose issues that are non-constant or that are extensions.
2087  Diagnose,
2088  /// Identify whether this function satisfies the formal rules for constexpr
2089  /// functions in the current lanugage mode (with no extensions).
2090  CheckValid
2091  };
2092 
2093  bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2095 
2096  void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2097  void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2098  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2099  void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2100  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2101  // Returns true if the function declaration is a redeclaration
2102  bool CheckFunctionDeclaration(Scope *S,
2103  FunctionDecl *NewFD, LookupResult &Previous,
2104  bool IsMemberSpecialization);
2105  bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2106  bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2107  QualType NewT, QualType OldT);
2108  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2109  void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2110  Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2111  bool IsDefinition);
2112  void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2113  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2114  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2115  SourceLocation Loc,
2116  QualType T);
2117  ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2118  SourceLocation NameLoc, IdentifierInfo *Name,
2119  QualType T, TypeSourceInfo *TSInfo,
2120  StorageClass SC);
2121  void ActOnParamDefaultArgument(Decl *param,
2122  SourceLocation EqualLoc,
2123  Expr *defarg);
2124  void ActOnParamUnparsedDefaultArgument(Decl *param,
2125  SourceLocation EqualLoc,
2126  SourceLocation ArgLoc);
2127  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2128  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2129  SourceLocation EqualLoc);
2130 
2131  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2132  void ActOnUninitializedDecl(Decl *dcl);
2133  void ActOnInitializerError(Decl *Dcl);
2134 
2135  void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2136  void ActOnCXXForRangeDecl(Decl *D);
2137  StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2138  IdentifierInfo *Ident,
2139  ParsedAttributes &Attrs,
2140  SourceLocation AttrEnd);
2141  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2142  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2143  void CheckStaticLocalForDllExport(VarDecl *VD);
2144  void FinalizeDeclaration(Decl *D);
2145  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2146  ArrayRef<Decl *> Group);
2147  DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2148 
2149  /// Should be called on all declarations that might have attached
2150  /// documentation comments.
2151  void ActOnDocumentableDecl(Decl *D);
2152  void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2153 
2154  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2155  SourceLocation LocAfterDecls);
2156  void CheckForFunctionRedefinition(
2157  FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2158  SkipBodyInfo *SkipBody = nullptr);
2159  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2160  MultiTemplateParamsArg TemplateParamLists,
2161  SkipBodyInfo *SkipBody = nullptr);
2162  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2163  SkipBodyInfo *SkipBody = nullptr);
2164  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2166  return D && isa<ObjCMethodDecl>(D);
2167  }
2168 
2169  /// Determine whether we can delay parsing the body of a function or
2170  /// function template until it is used, assuming we don't care about emitting
2171  /// code for that function.
2172  ///
2173  /// This will be \c false if we may need the body of the function in the
2174  /// middle of parsing an expression (where it's impractical to switch to
2175  /// parsing a different function), for instance, if it's constexpr in C++11
2176  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2177  bool canDelayFunctionBody(const Declarator &D);
2178 
2179  /// Determine whether we can skip parsing the body of a function
2180  /// definition, assuming we don't care about analyzing its body or emitting
2181  /// code for that function.
2182  ///
2183  /// This will be \c false only if we may need the body of the function in
2184  /// order to parse the rest of the program (for instance, if it is
2185  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2186  bool canSkipFunctionBody(Decl *D);
2187 
2188  void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2189  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2190  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2191  Decl *ActOnSkippedFunctionBody(Decl *Decl);
2192  void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2193 
2194  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2195  /// attribute for which parsing is delayed.
2196  void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2197 
2198  /// Diagnose any unused parameters in the given sequence of
2199  /// ParmVarDecl pointers.
2200  void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2201 
2202  /// Diagnose whether the size of parameters or return value of a
2203  /// function or obj-c method definition is pass-by-value and larger than a
2204  /// specified threshold.
2205  void
2206  DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2207  QualType ReturnTy, NamedDecl *D);
2208 
2209  void DiagnoseInvalidJumps(Stmt *Body);
2210  Decl *ActOnFileScopeAsmDecl(Expr *expr,
2211  SourceLocation AsmLoc,
2212  SourceLocation RParenLoc);
2213 
2214  /// Handle a C++11 empty-declaration and attribute-declaration.
2215  Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2216  SourceLocation SemiLoc);
2217 
2218  enum class ModuleDeclKind {
2219  Interface, ///< 'export module X;'
2220  Implementation, ///< 'module X;'
2221  };
2222 
2223  /// The parser has processed a module-declaration that begins the definition
2224  /// of a module interface or implementation.
2225  DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2226  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2227  ModuleIdPath Path, bool IsFirstDecl);
2228 
2229  /// The parser has processed a global-module-fragment declaration that begins
2230  /// the definition of the global module fragment of the current module unit.
2231  /// \param ModuleLoc The location of the 'module' keyword.
2232  DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2233 
2234  /// The parser has processed a private-module-fragment declaration that begins
2235  /// the definition of the private module fragment of the current module unit.
2236  /// \param ModuleLoc The location of the 'module' keyword.
2237  /// \param PrivateLoc The location of the 'private' keyword.
2238  DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2239  SourceLocation PrivateLoc);
2240 
2241  /// The parser has processed a module import declaration.
2242  ///
2243  /// \param StartLoc The location of the first token in the declaration. This
2244  /// could be the location of an '@', 'export', or 'import'.
2245  /// \param ExportLoc The location of the 'export' keyword, if any.
2246  /// \param ImportLoc The location of the 'import' keyword.
2247  /// \param Path The module access path.
2248  DeclResult ActOnModuleImport(SourceLocation StartLoc,
2249  SourceLocation ExportLoc,
2250  SourceLocation ImportLoc, ModuleIdPath Path);
2251  DeclResult ActOnModuleImport(SourceLocation StartLoc,
2252  SourceLocation ExportLoc,
2253  SourceLocation ImportLoc, Module *M,
2254  ModuleIdPath Path = {});
2255 
2256  /// The parser has processed a module import translated from a
2257  /// #include or similar preprocessing directive.
2258  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2259  void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2260 
2261  /// The parsed has entered a submodule.
2262  void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2263  /// The parser has left a submodule.
2264  void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2265 
2266  /// Create an implicit import of the given module at the given
2267  /// source location, for error recovery, if possible.
2268  ///
2269  /// This routine is typically used when an entity found by name lookup
2270  /// is actually hidden within a module that we know about but the user
2271  /// has forgotten to import.
2272  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2273  Module *Mod);
2274 
2275  /// Kinds of missing import. Note, the values of these enumerators correspond
2276  /// to %select values in diagnostics.
2277  enum class MissingImportKind {
2278  Declaration,
2279  Definition,
2280  DefaultArgument,
2281  ExplicitSpecialization,
2282  PartialSpecialization
2283  };
2284 
2285  /// Diagnose that the specified declaration needs to be visible but
2286  /// isn't, and suggest a module import that would resolve the problem.
2287  void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2288  MissingImportKind MIK, bool Recover = true);
2289  void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2290  SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2291  MissingImportKind MIK, bool Recover);
2292 
2293  Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2294  SourceLocation LBraceLoc);
2295  Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2296  SourceLocation RBraceLoc);
2297 
2298  /// We've found a use of a templated declaration that would trigger an
2299  /// implicit instantiation. Check that any relevant explicit specializations
2300  /// and partial specializations are visible, and diagnose if not.
2301  void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2302 
2303  /// We've found a use of a template specialization that would select a
2304  /// partial specialization. Check that the partial specialization is visible,
2305  /// and diagnose if not.
2306  void checkPartialSpecializationVisibility(SourceLocation Loc,
2307  NamedDecl *Spec);
2308 
2309  /// Retrieve a suitable printing policy for diagnostics.
2311  return getPrintingPolicy(Context, PP);
2312  }
2313 
2314  /// Retrieve a suitable printing policy for diagnostics.
2315  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2316  const Preprocessor &PP);
2317 
2318  /// Scope actions.
2319  void ActOnPopScope(SourceLocation Loc, Scope *S);
2320  void ActOnTranslationUnitScope(Scope *S);
2321 
2322  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2323  RecordDecl *&AnonRecord);
2324  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2325  MultiTemplateParamsArg TemplateParams,
2326  bool IsExplicitInstantiation,
2327  RecordDecl *&AnonRecord);
2328 
2329  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2330  AccessSpecifier AS,
2331  RecordDecl *Record,
2332  const PrintingPolicy &Policy);
2333 
2334  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2335  RecordDecl *Record);
2336 
2337  /// Common ways to introduce type names without a tag for use in diagnostics.
2338  /// Keep in sync with err_tag_reference_non_tag.
2339  enum NonTagKind {
2349  };
2350 
2351  /// Given a non-tag type declaration, returns an enum useful for indicating
2352  /// what kind of non-tag type this is.
2353  NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2354 
2355  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2356  TagTypeKind NewTag, bool isDefinition,
2357  SourceLocation NewTagLoc,
2358  const IdentifierInfo *Name);
2359 
2360  enum TagUseKind {
2361  TUK_Reference, // Reference to a tag: 'struct foo *X;'
2362  TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2363  TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2364  TUK_Friend // Friend declaration: 'friend struct foo;'
2365  };
2366 
2367  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2368  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2369  SourceLocation NameLoc, const ParsedAttributesView &Attr,
2370  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2371  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2372  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2373  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2374  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2375  SkipBodyInfo *SkipBody = nullptr);
2376 
2377  Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2378  unsigned TagSpec, SourceLocation TagLoc,
2379  CXXScopeSpec &SS, IdentifierInfo *Name,
2380  SourceLocation NameLoc,
2381  const ParsedAttributesView &Attr,
2382  MultiTemplateParamsArg TempParamLists);
2383 
2384  TypeResult ActOnDependentTag(Scope *S,
2385  unsigned TagSpec,
2386  TagUseKind TUK,
2387  const CXXScopeSpec &SS,
2388  IdentifierInfo *Name,
2389  SourceLocation TagLoc,
2390  SourceLocation NameLoc);
2391 
2392  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2393  IdentifierInfo *ClassName,
2394  SmallVectorImpl<Decl *> &Decls);
2395  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2396  Declarator &D, Expr *BitfieldWidth);
2397 
2398  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2399  Declarator &D, Expr *BitfieldWidth,
2400  InClassInitStyle InitStyle,
2401  AccessSpecifier AS);
2402  MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2403  SourceLocation DeclStart, Declarator &D,
2404  Expr *BitfieldWidth,
2405  InClassInitStyle InitStyle,
2406  AccessSpecifier AS,
2407  const ParsedAttr &MSPropertyAttr);
2408 
2409  FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2410  TypeSourceInfo *TInfo,
2411  RecordDecl *Record, SourceLocation Loc,
2412  bool Mutable, Expr *BitfieldWidth,
2413  InClassInitStyle InitStyle,
2414  SourceLocation TSSL,
2415  AccessSpecifier AS, NamedDecl *PrevDecl,
2416  Declarator *D = nullptr);
2417 
2418  bool CheckNontrivialField(FieldDecl *FD);
2419  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2420 
2422  /// The triviality of a method unaffected by "trivial_abi".
2424 
2425  /// The triviality of a method affected by "trivial_abi".
2426  TAH_ConsiderTrivialABI
2427  };
2428 
2429  bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2430  TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2431  bool Diagnose = false);
2432  CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2433  void ActOnLastBitfield(SourceLocation DeclStart,
2434  SmallVectorImpl<Decl *> &AllIvarDecls);
2435  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2436  Declarator &D, Expr *BitfieldWidth,
2437  tok::ObjCKeywordKind visibility);
2438 
2439  // This is used for both record definitions and ObjC interface declarations.
2440  void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2441  ArrayRef<Decl *> Fields, SourceLocation LBrac,
2442  SourceLocation RBrac, const ParsedAttributesView &AttrList);
2443 
2444  /// ActOnTagStartDefinition - Invoked when we have entered the
2445  /// scope of a tag's definition (e.g., for an enumeration, class,
2446  /// struct, or union).
2447  void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2448 
2449  /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2450  /// Differently from C++, actually parse the body and reject / error out
2451  /// in case of a structural mismatch.
2452  bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2453  SkipBodyInfo &SkipBody);
2454 
2456 
2457  /// Invoked when we enter a tag definition that we're skipping.
2458  SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2459 
2460  Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2461 
2462  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2463  /// C++ record definition's base-specifiers clause and are starting its
2464  /// member declarations.
2465  void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2466  SourceLocation FinalLoc,
2467  bool IsFinalSpelledSealed,
2468  SourceLocation LBraceLoc);
2469 
2470  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2471  /// the definition of a tag (enumeration, class, struct, or union).
2472  void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2473  SourceRange BraceRange);
2474 
2475  void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2476 
2477  void ActOnObjCContainerFinishDefinition();
2478 
2479  /// Invoked when we must temporarily exit the objective-c container
2480  /// scope for parsing/looking-up C constructs.
2481  ///
2482  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2483  void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2484  void ActOnObjCReenterContainerContext(DeclContext *DC);
2485 
2486  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2487  /// error parsing the definition of a tag.
2488  void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2489 
2490  EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2491  EnumConstantDecl *LastEnumConst,
2492  SourceLocation IdLoc,
2493  IdentifierInfo *Id,
2494  Expr *val);
2495  bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2496  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2497  QualType EnumUnderlyingTy, bool IsFixed,
2498  const EnumDecl *Prev);
2499 
2500  /// Determine whether the body of an anonymous enumeration should be skipped.
2501  /// \param II The name of the first enumerator.
2502  SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2503  SourceLocation IILoc);
2504 
2505  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2507  const ParsedAttributesView &Attrs,
2508  SourceLocation EqualLoc, Expr *Val);
2509  void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2510  Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2511  const ParsedAttributesView &Attr);
2512 
2513  DeclContext *getContainingDC(DeclContext *DC);
2514 
2515  /// Set the current declaration context until it gets popped.
2516  void PushDeclContext(Scope *S, DeclContext *DC);
2517  void PopDeclContext();
2518 
2519  /// EnterDeclaratorContext - Used when we must lookup names in the context
2520  /// of a declarator's nested name specifier.
2521  void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2522  void ExitDeclaratorContext(Scope *S);
2523 
2524  /// Push the parameters of D, which must be a function, into scope.
2525  void ActOnReenterFunctionContext(Scope* S, Decl* D);
2526  void ActOnExitFunctionContext();
2527 
2528  DeclContext *getFunctionLevelDeclContext();
2529 
2530  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2531  /// to the function decl for the function being parsed. If we're currently
2532  /// in a 'block', this returns the containing context.
2533  FunctionDecl *getCurFunctionDecl();
2534 
2535  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2536  /// the method decl for the method being parsed. If we're currently
2537  /// in a 'block', this returns the containing context.
2538  ObjCMethodDecl *getCurMethodDecl();
2539 
2540  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2541  /// or C function we're in, otherwise return null. If we're currently
2542  /// in a 'block', this returns the containing context.
2543  NamedDecl *getCurFunctionOrMethodDecl();
2544 
2545  /// Add this decl to the scope shadowed decl chains.
2546  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2547 
2548  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2549  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2550  /// true if 'D' belongs to the given declaration context.
2551  ///
2552  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2553  /// enclosing namespace set of the context, rather than contained
2554  /// directly within it.
2555  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2556  bool AllowInlineNamespace = false);
2557 
2558  /// Finds the scope corresponding to the given decl context, if it
2559  /// happens to be an enclosing scope. Otherwise return NULL.
2560  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2561 
2562  /// Subroutines of ActOnDeclarator().
2563  TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2564  TypeSourceInfo *TInfo);
2565  bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2566 
2567  /// Describes the kind of merge to perform for availability
2568  /// attributes (including "deprecated", "unavailable", and "availability").
2570  /// Don't merge availability attributes at all.
2572  /// Merge availability attributes for a redeclaration, which requires
2573  /// an exact match.
2575  /// Merge availability attributes for an override, which requires
2576  /// an exact match or a weakening of constraints.
2578  /// Merge availability attributes for an implementation of
2579  /// a protocol requirement.
2581  };
2582 
2583  /// Describes the kind of priority given to an availability attribute.
2584  ///
2585  /// The sum of priorities deteremines the final priority of the attribute.
2586  /// The final priority determines how the attribute will be merged.
2587  /// An attribute with a lower priority will always remove higher priority
2588  /// attributes for the specified platform when it is being applied. An
2589  /// attribute with a higher priority will not be applied if the declaration
2590  /// already has an availability attribute with a lower priority for the
2591  /// specified platform. The final prirority values are not expected to match
2592  /// the values in this enumeration, but instead should be treated as a plain
2593  /// integer value. This enumeration just names the priority weights that are
2594  /// used to calculate that final vaue.
2596  /// The availability attribute was specified explicitly next to the
2597  /// declaration.
2598  AP_Explicit = 0,
2599 
2600  /// The availability attribute was applied using '#pragma clang attribute'.
2601  AP_PragmaClangAttribute = 1,
2602 
2603  /// The availability attribute for a specific platform was inferred from
2604  /// an availability attribute for another platform.
2605  AP_InferredFromOtherPlatform = 2
2606  };
2607 
2608  /// Attribute merging methods. Return true if a new attribute was added.
2609  AvailabilityAttr *mergeAvailabilityAttr(
2610  NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit,
2611  VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted,
2612  bool IsUnavailable, StringRef Message, bool IsStrict,
2613  StringRef Replacement, AvailabilityMergeKind AMK, int Priority,
2614  unsigned AttrSpellingListIndex);
2615  TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2616  TypeVisibilityAttr::VisibilityType Vis,
2617  unsigned AttrSpellingListIndex);
2618  VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2619  VisibilityAttr::VisibilityType Vis,
2620  unsigned AttrSpellingListIndex);
2621  UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2622  unsigned AttrSpellingListIndex, StringRef Uuid);
2623  DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2624  unsigned AttrSpellingListIndex);
2625  DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2626  unsigned AttrSpellingListIndex);
2627  MSInheritanceAttr *
2628  mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2629  unsigned AttrSpellingListIndex,
2630  MSInheritanceAttr::Spelling SemanticSpelling);
2631  FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2632  IdentifierInfo *Format, int FormatIdx,
2633  int FirstArg, unsigned AttrSpellingListIndex);
2634  SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2635  unsigned AttrSpellingListIndex);
2636  CodeSegAttr *mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name,
2637  unsigned AttrSpellingListIndex);
2638  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2639  IdentifierInfo *Ident,
2640  unsigned AttrSpellingListIndex);
2641  MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2642  unsigned AttrSpellingListIndex);
2643  NoSpeculativeLoadHardeningAttr *
2644  mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2645  const NoSpeculativeLoadHardeningAttr &AL);
2646  SpeculativeLoadHardeningAttr *
2647  mergeSpeculativeLoadHardeningAttr(Decl *D,
2648  const SpeculativeLoadHardeningAttr &AL);
2649  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2650  unsigned AttrSpellingListIndex);
2651  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2652  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2653  const InternalLinkageAttr &AL);
2654  CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2655  CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2656 
2657  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2658  AvailabilityMergeKind AMK = AMK_Redeclaration);
2659  void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2660  LookupResult &OldDecls);
2661  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2662  bool MergeTypeWithOld);
2663  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2664  Scope *S, bool MergeTypeWithOld);
2665  void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2666  void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2667  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2668  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2669  bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2670  void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2671  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2672 
2673  // AssignmentAction - This is used by all the assignment diagnostic functions
2674  // to represent what is actually causing the operation
2683  AA_Passing_CFAudited
2684  };
2685 
2686  /// C++ Overloading.
2688  /// This is a legitimate overload: the existing declarations are
2689  /// functions or function templates with different signatures.
2691 
2692  /// This is not an overload because the signature exactly matches
2693  /// an existing declaration.
2695 
2696  /// This is not an overload because the lookup results contain a
2697  /// non-function.
2698  Ovl_NonFunction
2699  };
2700  OverloadKind CheckOverload(Scope *S,
2701  FunctionDecl *New,
2702  const LookupResult &OldDecls,
2703  NamedDecl *&OldDecl,
2704  bool IsForUsingDecl);
2705  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2706  bool ConsiderCudaAttrs = true);
2707 
2709  TryImplicitConversion(Expr *From, QualType ToType,
2710  bool SuppressUserConversions,
2711  bool AllowExplicit,
2712  bool InOverloadResolution,
2713  bool CStyle,
2714  bool AllowObjCWritebackConversion);
2715 
2716  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2717  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2718  bool IsComplexPromotion(QualType FromType, QualType ToType);
2719  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2720  bool InOverloadResolution,
2721  QualType& ConvertedType, bool &IncompatibleObjC);
2722  bool isObjCPointerConversion(QualType FromType, QualType ToType,
2723  QualType& ConvertedType, bool &IncompatibleObjC);
2724  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2725  QualType &ConvertedType);
2726  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2727  QualType& ConvertedType);
2728  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2729  const FunctionProtoType *NewType,
2730  unsigned *ArgPos = nullptr);
2731  void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2732  QualType FromType, QualType ToType);
2733 
2734  void maybeExtendBlockObject(ExprResult &E);
2735  CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2736  bool CheckPointerConversion(Expr *From, QualType ToType,
2737  CastKind &Kind,
2738  CXXCastPath& BasePath,
2739  bool IgnoreBaseAccess,
2740  bool Diagnose = true);
2741  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2742  bool InOverloadResolution,
2743  QualType &ConvertedType);
2744  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2745  CastKind &Kind,
2746  CXXCastPath &BasePath,
2747  bool IgnoreBaseAccess);
2748  bool IsQualificationConversion(QualType FromType, QualType ToType,
2749  bool CStyle, bool &ObjCLifetimeConversion);
2750  bool IsFunctionConversion(QualType FromType, QualType ToType,
2751  QualType &ResultTy);
2752  bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2753  bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2754 
2755  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2756  const VarDecl *NRVOCandidate,
2757  QualType ResultType,
2758  Expr *Value,
2759  bool AllowNRVO = true);
2760 
2761  bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2762  ExprResult Init);
2763  ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2764  SourceLocation EqualLoc,
2765  ExprResult Init,
2766  bool TopLevelOfInitList = false,
2767  bool AllowExplicit = false);
2768  ExprResult PerformObjectArgumentInitialization(Expr *From,
2769  NestedNameSpecifier *Qualifier,
2770  NamedDecl *FoundDecl,
2771  CXXMethodDecl *Method);
2772 
2773  /// Check that the lifetime of the initializer (and its subobjects) is
2774  /// sufficient for initializing the entity, and perform lifetime extension
2775  /// (when permitted) if not.
2776  void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2777 
2778  ExprResult PerformContextuallyConvertToBool(Expr *From);
2779  ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2780 
2781  /// Contexts in which a converted constant expression is required.
2782  enum CCEKind {
2783  CCEK_CaseValue, ///< Expression in a case label.
2784  CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2785  CCEK_TemplateArg, ///< Value of a non-type template parameter.
2786  CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2787  CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
2788  CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
2789  };
2791  llvm::APSInt &Value, CCEKind CCE);
2793  APValue &Value, CCEKind CCE);
2794 
2795  /// Abstract base class used to perform a contextual implicit
2796  /// conversion from an expression to any type passing a filter.
2798  public:
2799  bool Suppress;
2801 
2802  ContextualImplicitConverter(bool Suppress = false,
2803  bool SuppressConversion = false)
2804  : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2805 
2806  /// Determine whether the specified type is a valid destination type
2807  /// for this conversion.
2808  virtual bool match(QualType T) = 0;
2809 
2810  /// Emits a diagnostic complaining that the expression does not have
2811  /// integral or enumeration type.
2812  virtual SemaDiagnosticBuilder
2813  diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2814 
2815  /// Emits a diagnostic when the expression has incomplete class type.
2816  virtual SemaDiagnosticBuilder
2817  diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2818 
2819  /// Emits a diagnostic when the only matching conversion function
2820  /// is explicit.
2821  virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2822  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2823 
2824  /// Emits a note for the explicit conversion function.
2825  virtual SemaDiagnosticBuilder
2826  noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2827 
2828  /// Emits a diagnostic when there are multiple possible conversion
2829  /// functions.
2830  virtual SemaDiagnosticBuilder
2831  diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2832 
2833  /// Emits a note for one of the candidate conversions.
2834  virtual SemaDiagnosticBuilder
2835  noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2836 
2837  /// Emits a diagnostic when we picked a conversion function
2838  /// (for cases when we are not allowed to pick a conversion function).
2839  virtual SemaDiagnosticBuilder diagnoseConversion(
2840  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2841 
2843  };
2844 
2846  bool AllowScopedEnumerations;
2847 
2848  public:
2849  ICEConvertDiagnoser(bool AllowScopedEnumerations,
2850  bool Suppress, bool SuppressConversion)
2851  : ContextualImplicitConverter(Suppress, SuppressConversion),
2852  AllowScopedEnumerations(AllowScopedEnumerations) {}
2853 
2854  /// Match an integral or (possibly scoped) enumeration type.
2855  bool match(QualType T) override;
2856 
2859  return diagnoseNotInt(S, Loc, T);
2860  }
2861 
2862  /// Emits a diagnostic complaining that the expression does not have
2863  /// integral or enumeration type.
2864  virtual SemaDiagnosticBuilder
2865  diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2866  };
2867 
2868  /// Perform a contextual implicit conversion.
2869  ExprResult PerformContextualImplicitConversion(
2870  SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2871 
2872 
2876  OS_Error
2877  };
2878  ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2879 
2880  // Note that LK_String is intentionally after the other literals, as
2881  // this is used for diagnostics logic.
2889  LK_None
2890  };
2891  ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2892 
2893  ExprResult PerformObjectMemberConversion(Expr *From,
2894  NestedNameSpecifier *Qualifier,
2895  NamedDecl *FoundDecl,
2896  NamedDecl *Member);
2897 
2898  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2899  // TODO: make this is a typesafe union.
2902 
2904 
2905  void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
2906  ArrayRef<Expr *> Args,
2907  OverloadCandidateSet &CandidateSet,
2908  bool SuppressUserConversions = false,
2909  bool PartialOverloading = false,
2910  bool AllowExplicit = true,
2911  bool AllowExplicitConversion = false,
2912  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
2913  ConversionSequenceList EarlyConversions = None);
2914  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2915  ArrayRef<Expr *> Args,
2916  OverloadCandidateSet &CandidateSet,
2917  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2918  bool SuppressUserConversions = false,
2919  bool PartialOverloading = false,
2920  bool FirstArgumentIsBase = false);
2921  void AddMethodCandidate(DeclAccessPair FoundDecl,
2922  QualType ObjectType,
2923  Expr::Classification ObjectClassification,
2924  ArrayRef<Expr *> Args,
2925  OverloadCandidateSet& CandidateSet,
2926  bool SuppressUserConversion = false);
2927  void AddMethodCandidate(CXXMethodDecl *Method,
2928  DeclAccessPair FoundDecl,
2929  CXXRecordDecl *ActingContext, QualType ObjectType,
2930  Expr::Classification ObjectClassification,
2931  ArrayRef<Expr *> Args,
2932  OverloadCandidateSet& CandidateSet,
2933  bool SuppressUserConversions = false,
2934  bool PartialOverloading = false,
2935  ConversionSequenceList EarlyConversions = None);
2936  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2937  DeclAccessPair FoundDecl,
2938  CXXRecordDecl *ActingContext,
2939  TemplateArgumentListInfo *ExplicitTemplateArgs,
2940  QualType ObjectType,
2941  Expr::Classification ObjectClassification,
2942  ArrayRef<Expr *> Args,
2943  OverloadCandidateSet& CandidateSet,
2944  bool SuppressUserConversions = false,
2945  bool PartialOverloading = false);
2946  void AddTemplateOverloadCandidate(
2947  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
2948  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
2949  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
2950  bool PartialOverloading = false, bool AllowExplicit = true,
2951  ADLCallKind IsADLCandidate = ADLCallKind::NotADL);
2952  bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2953  ArrayRef<QualType> ParamTypes,
2954  ArrayRef<Expr *> Args,
2955  OverloadCandidateSet &CandidateSet,
2956  ConversionSequenceList &Conversions,
2957  bool SuppressUserConversions,
2958  CXXRecordDecl *ActingContext = nullptr,
2959  QualType ObjectType = QualType(),
2961  ObjectClassification = {});
2962  void AddConversionCandidate(
2963  CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
2964  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
2965  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
2966  bool AllowExplicit, bool AllowResultConversion = true);
2967  void AddTemplateConversionCandidate(
2968  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
2969  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
2970  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
2971  bool AllowExplicit, bool AllowResultConversion = true);
2972  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2973  DeclAccessPair FoundDecl,
2974  CXXRecordDecl *ActingContext,
2975  const FunctionProtoType *Proto,
2976  Expr *Object, ArrayRef<Expr *> Args,
2977  OverloadCandidateSet& CandidateSet);
2978  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2979  SourceLocation OpLoc, ArrayRef<Expr *> Args,
2980  OverloadCandidateSet& CandidateSet,
2981  SourceRange OpRange = SourceRange());
2982  void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2983  OverloadCandidateSet& CandidateSet,
2984  bool IsAssignmentOperator = false,
2985  unsigned NumContextualBoolArguments = 0);
2986  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2987  SourceLocation OpLoc, ArrayRef<Expr *> Args,
2988  OverloadCandidateSet& CandidateSet);
2989  void AddArgumentDependentLookupCandidates(DeclarationName Name,
2990  SourceLocation Loc,
2991  ArrayRef<Expr *> Args,
2992  TemplateArgumentListInfo *ExplicitTemplateArgs,
2993  OverloadCandidateSet& CandidateSet,
2994  bool PartialOverloading = false);
2995 
2996  // Emit as a 'note' the specific overload candidate
2997  void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2998  QualType DestType = QualType(),
2999  bool TakingAddress = false);
3000 
3001  // Emit as a series of 'note's all template and non-templates identified by
3002  // the expression Expr
3003  void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3004  bool TakingAddress = false);
3005 
3006  /// Check the enable_if expressions on the given function. Returns the first
3007  /// failing attribute, or NULL if they were all successful.
3008  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3009  bool MissingImplicitThis = false);
3010 
3011  /// Find the failed Boolean condition within a given Boolean
3012  /// constant expression, and describe it with a string.
3013  std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3014 
3015  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3016  /// non-ArgDependent DiagnoseIfAttrs.
3017  ///
3018  /// Argument-dependent diagnose_if attributes should be checked each time a
3019  /// function is used as a direct callee of a function call.
3020  ///
3021  /// Returns true if any errors were emitted.
3022  bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3023  const Expr *ThisArg,
3025  SourceLocation Loc);
3026 
3027  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3028  /// ArgDependent DiagnoseIfAttrs.
3029  ///
3030  /// Argument-independent diagnose_if attributes should be checked on every use
3031  /// of a function.
3032  ///
3033  /// Returns true if any errors were emitted.
3034  bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3035  SourceLocation Loc);
3036 
3037  /// Returns whether the given function's address can be taken or not,
3038  /// optionally emitting a diagnostic if the address can't be taken.
3039  ///
3040  /// Returns false if taking the address of the function is illegal.
3041  bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3042  bool Complain = false,
3043  SourceLocation Loc = SourceLocation());
3044 
3045  // [PossiblyAFunctionType] --> [Return]
3046  // NonFunctionType --> NonFunctionType
3047  // R (A) --> R(A)
3048  // R (*)(A) --> R (A)
3049  // R (&)(A) --> R (A)
3050  // R (S::*)(A) --> R (A)
3051  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3052 
3053  FunctionDecl *
3054  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3055  QualType TargetType,
3056  bool Complain,
3057  DeclAccessPair &Found,
3058  bool *pHadMultipleCandidates = nullptr);
3059 
3060  FunctionDecl *
3061  resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
3062  DeclAccessPair &FoundResult);
3063 
3064  bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
3065  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3066 
3067  FunctionDecl *
3068  ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3069  bool Complain = false,
3070  DeclAccessPair *Found = nullptr);
3071 
3072  bool ResolveAndFixSingleFunctionTemplateSpecialization(
3073  ExprResult &SrcExpr,
3074  bool DoFunctionPointerConverion = false,
3075  bool Complain = false,
3076  SourceRange OpRangeForComplaining = SourceRange(),
3077  QualType DestTypeForComplaining = QualType(),
3078  unsigned DiagIDForComplaining = 0);
3079 
3080 
3081  Expr *FixOverloadedFunctionReference(Expr *E,
3082  DeclAccessPair FoundDecl,
3083  FunctionDecl *Fn);
3084  ExprResult FixOverloadedFunctionReference(ExprResult,
3085  DeclAccessPair FoundDecl,
3086  FunctionDecl *Fn);
3087 
3088  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3089  ArrayRef<Expr *> Args,
3090  OverloadCandidateSet &CandidateSet,
3091  bool PartialOverloading = false);
3092 
3093  // An enum used to represent the different possible results of building a
3094  // range-based for loop.
3098  FRS_DiagnosticIssued
3099  };
3100 
3101  ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3102  SourceLocation RangeLoc,
3103  const DeclarationNameInfo &NameInfo,
3104  LookupResult &MemberLookup,
3105  OverloadCandidateSet *CandidateSet,
3106  Expr *Range, ExprResult *CallExpr);
3107 
3108  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3109  UnresolvedLookupExpr *ULE,
3110  SourceLocation LParenLoc,
3111  MultiExprArg Args,
3112  SourceLocation RParenLoc,
3113  Expr *ExecConfig,
3114  bool AllowTypoCorrection=true,
3115  bool CalleesAddressIsTaken=false);
3116 
3117  bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3118  MultiExprArg Args, SourceLocation RParenLoc,
3119  OverloadCandidateSet *CandidateSet,
3120  ExprResult *Result);
3121 
3122  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3123  UnaryOperatorKind Opc,
3124  const UnresolvedSetImpl &Fns,
3125  Expr *input, bool RequiresADL = true);
3126 
3127  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3128  BinaryOperatorKind Opc,
3129  const UnresolvedSetImpl &Fns,
3130  Expr *LHS, Expr *RHS,
3131  bool RequiresADL = true);
3132 
3133  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3134  SourceLocation RLoc,
3135  Expr *Base,Expr *Idx);
3136 
3137  ExprResult
3138  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3139  SourceLocation LParenLoc,
3140  MultiExprArg Args,
3141  SourceLocation RParenLoc);
3142  ExprResult
3143  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3144  MultiExprArg Args,
3145  SourceLocation RParenLoc);
3146 
3147  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3148  SourceLocation OpLoc,
3149  bool *NoArrowOperatorFound = nullptr);
3150 
3151  /// CheckCallReturnType - Checks that a call expression's return type is
3152  /// complete. Returns true on failure. The location passed in is the location
3153  /// that best represents the call.
3154  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3155  CallExpr *CE, FunctionDecl *FD);
3156 
3157  /// Helpers for dealing with blocks and functions.
3158  bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3159  bool CheckParameterNames);
3160  void CheckCXXDefaultArguments(FunctionDecl *FD);
3161  void CheckExtraCXXDefaultArguments(Declarator &D);
3162  Scope *getNonFieldDeclScope(Scope *S);
3163 
3164  /// \name Name lookup
3165  ///
3166  /// These routines provide name lookup that is used during semantic
3167  /// analysis to resolve the various kinds of names (identifiers,
3168  /// overloaded operator names, constructor names, etc.) into zero or
3169  /// more declarations within a particular scope. The major entry
3170  /// points are LookupName, which performs unqualified name lookup,
3171  /// and LookupQualifiedName, which performs qualified name lookup.
3172  ///
3173  /// All name lookup is performed based on some specific criteria,
3174  /// which specify what names will be visible to name lookup and how
3175  /// far name lookup should work. These criteria are important both
3176  /// for capturing language semantics (certain lookups will ignore
3177  /// certain names, for example) and for performance, since name
3178  /// lookup is often a bottleneck in the compilation of C++. Name
3179  /// lookup criteria is specified via the LookupCriteria enumeration.
3180  ///
3181  /// The results of name lookup can vary based on the kind of name
3182  /// lookup performed, the current language, and the translation
3183  /// unit. In C, for example, name lookup will either return nothing
3184  /// (no entity found) or a single declaration. In C++, name lookup
3185  /// can additionally refer to a set of overloaded functions or
3186  /// result in an ambiguity. All of the possible results of name
3187  /// lookup are captured by the LookupResult class, which provides
3188  /// the ability to distinguish among them.
3189  //@{
3190 
3191  /// Describes the kind of name lookup to perform.
3193  /// Ordinary name lookup, which finds ordinary names (functions,
3194  /// variables, typedefs, etc.) in C and most kinds of names
3195  /// (functions, variables, members, types, etc.) in C++.
3196  LookupOrdinaryName = 0,
3197  /// Tag name lookup, which finds the names of enums, classes,
3198  /// structs, and unions.
3200  /// Label name lookup.
3202  /// Member name lookup, which finds the names of
3203  /// class/struct/union members.
3205  /// Look up of an operator name (e.g., operator+) for use with
3206  /// operator overloading. This lookup is similar to ordinary name
3207  /// lookup, but will ignore any declarations that are class members.
3209  /// Look up of a name that precedes the '::' scope resolution
3210  /// operator in C++. This lookup completely ignores operator, object,
3211  /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3213  /// Look up a namespace name within a C++ using directive or
3214  /// namespace alias definition, ignoring non-namespace names (C++
3215  /// [basic.lookup.udir]p1).
3217  /// Look up all declarations in a scope with the given name,
3218  /// including resolved using declarations. This is appropriate
3219  /// for checking redeclarations for a using declaration.
3221  /// Look up an ordinary name that is going to be redeclared as a
3222  /// name with linkage. This lookup ignores any declarations that
3223  /// are outside of the current scope unless they have linkage. See
3224  /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3226  /// Look up a friend of a local class. This lookup does not look
3227  /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3229  /// Look up the name of an Objective-C protocol.
3231  /// Look up implicit 'self' parameter of an objective-c method.
3233  /// Look up the name of an OpenMP user-defined reduction operation.
3235  /// Look up the name of an OpenMP user-defined mapper.
3237  /// Look up any declaration with any name.
3238  LookupAnyName
3239  };
3240 
3241  /// Specifies whether (or how) name lookup is being performed for a
3242  /// redeclaration (vs. a reference).
3244  /// The lookup is a reference to this name that is not for the
3245  /// purpose of redeclaring the name.
3246  NotForRedeclaration = 0,
3247  /// The lookup results will be used for redeclaration of a name,
3248  /// if an entity by that name already exists and is visible.
3250  /// The lookup results will be used for redeclaration of a name
3251  /// with external linkage; non-visible lookup results with external linkage
3252  /// may also be found.
3253  ForExternalRedeclaration
3254  };
3255 
3257  // A declaration with an owning module for linkage can never link against
3258  // anything that is not visible. We don't need to check linkage here; if
3259  // the context has internal linkage, redeclaration lookup won't find things
3260  // from other TUs, and we can't safely compute linkage yet in general.
3261  if (cast<Decl>(CurContext)
3262  ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3263  return ForVisibleRedeclaration;
3264  return ForExternalRedeclaration;
3265  }
3266 
3267  /// The possible outcomes of name lookup for a literal operator.
3269  /// The lookup resulted in an error.
3271  /// The lookup found no match but no diagnostic was issued.
3273  /// The lookup found a single 'cooked' literal operator, which
3274  /// expects a normal literal to be built and passed to it.
3276  /// The lookup found a single 'raw' literal operator, which expects
3277  /// a string literal containing the spelling of the literal token.
3279  /// The lookup found an overload set of literal operator templates,
3280  /// which expect the characters of the spelling of the literal token to be
3281  /// passed as a non-type template argument pack.
3283  /// The lookup found an overload set of literal operator templates,
3284  /// which expect the character type and characters of the spelling of the
3285  /// string literal token to be passed as template arguments.
3286  LOLR_StringTemplate
3287  };
3288 
3289  SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3291  bool ConstArg,
3292  bool VolatileArg,
3293  bool RValueThis,
3294  bool ConstThis,
3295  bool VolatileThis);
3296 
3297  typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3298  typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3300 
3301 private:
3302  bool CppLookupName(LookupResult &R, Scope *S);
3303 
3304  struct TypoExprState {
3305  std::unique_ptr<TypoCorrectionConsumer> Consumer;
3306  TypoDiagnosticGenerator DiagHandler;
3307  TypoRecoveryCallback RecoveryHandler;
3308  TypoExprState();
3309  TypoExprState(TypoExprState &&other) noexcept;
3310  TypoExprState &operator=(TypoExprState &&other) noexcept;
3311  };
3312 
3313  /// The set of unhandled TypoExprs and their associated state.
3314  llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3315 
3316  /// Creates a new TypoExpr AST node.
3317  TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3318  TypoDiagnosticGenerator TDG,
3319  TypoRecoveryCallback TRC);
3320 
3321  // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3322  //
3323  // The boolean value will be true to indicate that the namespace was loaded
3324  // from an AST/PCH file, or false otherwise.
3325  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3326 
3327  /// Whether we have already loaded known namespaces from an extenal
3328  /// source.
3329  bool LoadedExternalKnownNamespaces;
3330 
3331  /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3332  /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3333  /// should be skipped entirely.
3334  std::unique_ptr<TypoCorrectionConsumer>
3335  makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3336  Sema::LookupNameKind LookupKind, Scope *S,
3337  CXXScopeSpec *SS,
3339  DeclContext *MemberContext, bool EnteringContext,
3340  const ObjCObjectPointerType *OPT,
3341  bool ErrorRecovery);
3342 
3343 public:
3344  const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3345 
3346  /// Clears the state of the given TypoExpr.
3347  void clearDelayedTypo(TypoExpr *TE);
3348 
3349  /// Look up a name, looking for a single declaration. Return
3350  /// null if the results were absent, ambiguous, or overloaded.
3351  ///
3352  /// It is preferable to use the elaborated form and explicitly handle
3353  /// ambiguity and overloaded.
3354  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3355  SourceLocation Loc,
3356  LookupNameKind NameKind,
3357  RedeclarationKind Redecl
3358  = NotForRedeclaration);
3359  bool LookupName(LookupResult &R, Scope *S,
3360  bool AllowBuiltinCreation = false);
3361  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3362  bool InUnqualifiedLookup = false);
3363  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3364  CXXScopeSpec &SS);
3365  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3366  bool AllowBuiltinCreation = false,
3367  bool EnteringContext = false);
3368  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3369  RedeclarationKind Redecl
3370  = NotForRedeclaration);
3371  bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3372 
3373  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3374  QualType T1, QualType T2,
3375  UnresolvedSetImpl &Functions);
3376 
3377  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3378  SourceLocation GnuLabelLoc = SourceLocation());
3379 
3380  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3381  CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3382  CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3383  unsigned Quals);
3384  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3385  bool RValueThis, unsigned ThisQuals);
3386  CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3387  unsigned Quals);
3388  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3389  bool RValueThis, unsigned ThisQuals);
3390  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3391 
3392  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3393  LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3394  ArrayRef<QualType> ArgTys,
3395  bool AllowRaw,
3396  bool AllowTemplate,
3397  bool AllowStringTemplate,
3398  bool DiagnoseMissing);
3399  bool isKnownName(StringRef name);
3400 
3401  void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3402  ArrayRef<Expr *> Args, ADLResult &Functions);
3403 
3404  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3405  VisibleDeclConsumer &Consumer,
3406  bool IncludeGlobalScope = true,
3407  bool LoadExternal = true);
3409  VisibleDeclConsumer &Consumer,
3410  bool IncludeGlobalScope = true,
3411  bool IncludeDependentBases = false,
3412  bool LoadExternal = true);
3413 
3415  CTK_NonError, // CorrectTypo used in a non error recovery situation.
3416  CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3417  };
3418 
3419  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3420  Sema::LookupNameKind LookupKind,
3421  Scope *S, CXXScopeSpec *SS,
3423  CorrectTypoKind Mode,
3424  DeclContext *MemberContext = nullptr,
3425  bool EnteringContext = false,
3426  const ObjCObjectPointerType *OPT = nullptr,
3427  bool RecordFailure = true);
3428 
3429  TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3430  Sema::LookupNameKind LookupKind, Scope *S,
3431  CXXScopeSpec *SS,
3433  TypoDiagnosticGenerator TDG,
3435  DeclContext *MemberContext = nullptr,
3436  bool EnteringContext = false,
3437  const ObjCObjectPointerType *OPT = nullptr);
3438 
3439  /// Process any TypoExprs in the given Expr and its children,
3440  /// generating diagnostics as appropriate and returning a new Expr if there
3441  /// were typos that were all successfully corrected and ExprError if one or
3442  /// more typos could not be corrected.
3443  ///
3444  /// \param E The Expr to check for TypoExprs.
3445  ///
3446  /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3447  /// initializer.
3448  ///
3449  /// \param Filter A function applied to a newly rebuilt Expr to determine if
3450  /// it is an acceptable/usable result from a single combination of typo
3451  /// corrections. As long as the filter returns ExprError, different
3452  /// combinations of corrections will be tried until all are exhausted.
3453  ExprResult
3454  CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3455  llvm::function_ref<ExprResult(Expr *)> Filter =
3456  [](Expr *E) -> ExprResult { return E; });
3457 
3458  ExprResult
3460  llvm::function_ref<ExprResult(Expr *)> Filter) {
3461  return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3462  }
3463 
3464  ExprResult
3465  CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3466  llvm::function_ref<ExprResult(Expr *)> Filter =
3467  [](Expr *E) -> ExprResult { return E; }) {
3468  return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3469  }
3470 
3471  ExprResult
3473  llvm::function_ref<ExprResult(Expr *)> Filter) {
3474  return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3475  }
3476 
3477  void diagnoseTypo(const TypoCorrection &Correction,
3478  const PartialDiagnostic &TypoDiag,
3479  bool ErrorRecovery = true);
3480 
3481  void diagnoseTypo(const TypoCorrection &Correction,
3482  const PartialDiagnostic &TypoDiag,
3483  const PartialDiagnostic &PrevNote,
3484  bool ErrorRecovery = true);
3485 
3486  void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3487 
3488  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3489  ArrayRef<Expr *> Args,
3490  AssociatedNamespaceSet &AssociatedNamespaces,
3491  AssociatedClassSet &AssociatedClasses);
3492 
3493  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3494  bool ConsiderLinkage, bool AllowInlineNamespace);
3495 
3496  bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3497 
3498  void DiagnoseAmbiguousLookup(LookupResult &Result);
3499  //@}
3500 
3501  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3502  SourceLocation IdLoc,
3503  bool TypoCorrection = false);
3504  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3505  Scope *S, bool ForRedeclaration,
3506  SourceLocation Loc);
3507  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3508  Scope *S);
3509  void AddKnownFunctionAttributes(FunctionDecl *FD);
3510 
3511  // More parsing and symbol table subroutines.
3512 
3513  void ProcessPragmaWeak(Scope *S, Decl *D);
3514  // Decl attributes - this routine is the top level dispatcher.
3515  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3516  // Helper for delayed processing of attributes.
3517  void ProcessDeclAttributeDelayed(Decl *D,
3518  const ParsedAttributesView &AttrList);
3519  void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3520  bool IncludeCXX11Attributes = true);
3521  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3522  const ParsedAttributesView &AttrList);
3523 
3524  void checkUnusedDeclAttributes(Declarator &D);
3525 
3526  /// Determine if type T is a valid subject for a nonnull and similar
3527  /// attributes. By default, we look through references (the behavior used by
3528  /// nonnull), but if the second parameter is true, then we treat a reference
3529  /// type as valid.
3530  bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3531 
3532  bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3533  bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3534  const FunctionDecl *FD = nullptr);
3535  bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3536  bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3537  bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3538  StringRef &Str,
3539  SourceLocation *ArgLocation = nullptr);
3540  bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3541  bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3542  bool checkMSInheritanceAttrOnDefinition(
3543  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3544  MSInheritanceAttr::Spelling SemanticSpelling);
3545 
3546  void CheckAlignasUnderalignment(Decl *D);
3547 
3548  /// Adjust the calling convention of a method to be the ABI default if it
3549  /// wasn't specified explicitly. This handles method types formed from
3550  /// function type typedefs and typename template arguments.
3551  void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3552  SourceLocation Loc);
3553 
3554  // Check if there is an explicit attribute, but only look through parens.
3555  // The intent is to look for an attribute on the current declarator, but not
3556  // one that came from a typedef.
3557  bool hasExplicitCallingConv(QualType T);
3558 
3559  /// Get the outermost AttributedType node that sets a calling convention.
3560  /// Valid types should not have multiple attributes with different CCs.
3561  const AttributedType *getCallingConvAttributedType(QualType T) const;
3562 
3563  /// Stmt attributes - this routine is the top level dispatcher.
3564  StmtResult ProcessStmtAttributes(Stmt *Stmt,
3565  const ParsedAttributesView &Attrs,
3566  SourceRange Range);
3567 
3568  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3569  ObjCMethodDecl *MethodDecl,
3570  bool IsProtocolMethodDecl);
3571 
3572  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3573  ObjCMethodDecl *Overridden,
3574  bool IsProtocolMethodDecl);
3575 
3576  /// WarnExactTypedMethods - This routine issues a warning if method
3577  /// implementation declaration matches exactly that of its declaration.
3578  void WarnExactTypedMethods(ObjCMethodDecl *Method,
3579  ObjCMethodDecl *MethodDecl,
3580  bool IsProtocolMethodDecl);
3581 
3582  typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3583 
3584  /// CheckImplementationIvars - This routine checks if the instance variables
3585  /// listed in the implelementation match those listed in the interface.
3586  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3587  ObjCIvarDecl **Fields, unsigned nIvars,
3588  SourceLocation Loc);
3589 
3590  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3591  /// remains unimplemented in the class or category \@implementation.
3592  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3593  ObjCContainerDecl* IDecl,
3594  bool IncompleteImpl = false);
3595 
3596  /// DiagnoseUnimplementedProperties - This routine warns on those properties
3597  /// which must be implemented by this implementation.
3598  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3599  ObjCContainerDecl *CDecl,
3600  bool SynthesizeProperties);
3601 
3602  /// Diagnose any null-resettable synthesized setters.
3603  void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3604 
3605  /// DefaultSynthesizeProperties - This routine default synthesizes all
3606  /// properties which must be synthesized in the class's \@implementation.
3607  void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3608  ObjCInterfaceDecl *IDecl,
3609  SourceLocation AtEnd);
3610  void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3611 
3612  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3613  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3614  /// declared in class 'IFace'.
3615  bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3616  ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3617 
3618  /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3619  /// backs the property is not used in the property's accessor.
3620  void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3621  const ObjCImplementationDecl *ImplD);
3622 
3623  /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3624  /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3625  /// It also returns ivar's property on success.
3626  ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3627  const ObjCPropertyDecl *&PDecl) const;
3628 
3629  /// Called by ActOnProperty to handle \@property declarations in
3630  /// class extensions.
3631  ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3632  SourceLocation AtLoc,
3633  SourceLocation LParenLoc,
3634  FieldDeclarator &FD,
3635  Selector GetterSel,
3636  SourceLocation GetterNameLoc,
3637  Selector SetterSel,
3638  SourceLocation SetterNameLoc,
3639  const bool isReadWrite,
3640  unsigned &Attributes,
3641  const unsigned AttributesAsWritten,
3642  QualType T,
3643  TypeSourceInfo *TSI,
3644  tok::ObjCKeywordKind MethodImplKind);
3645 
3646  /// Called by ActOnProperty and HandlePropertyInClassExtension to
3647  /// handle creating the ObjcPropertyDecl for a category or \@interface.
3648  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3649  ObjCContainerDecl *CDecl,
3650  SourceLocation AtLoc,
3651  SourceLocation LParenLoc,
3652  FieldDeclarator &FD,
3653  Selector GetterSel,
3654  SourceLocation GetterNameLoc,
3655  Selector SetterSel,
3656  SourceLocation SetterNameLoc,
3657  const bool isReadWrite,
3658  const unsigned Attributes,
3659  const unsigned AttributesAsWritten,
3660  QualType T,
3661  TypeSourceInfo *TSI,
3662  tok::ObjCKeywordKind MethodImplKind,
3663  DeclContext *lexicalDC = nullptr);
3664 
3665  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3666  /// warning) when atomic property has one but not the other user-declared
3667  /// setter or getter.
3668  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3669  ObjCInterfaceDecl* IDecl);
3670 
3671  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3672 
3673  void DiagnoseMissingDesignatedInitOverrides(
3674  const ObjCImplementationDecl *ImplD,
3675  const ObjCInterfaceDecl *IFD);
3676 
3677  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3678 
3681  MMS_strict
3682  };
3683 
3684  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3685  /// true, or false, accordingly.
3686  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3687  const ObjCMethodDecl *PrevMethod,
3688  MethodMatchStrategy strategy = MMS_strict);
3689 
3690  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3691  /// or protocol against those declared in their implementations.
3692  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3693  const SelectorSet &ClsMap,
3694  SelectorSet &InsMapSeen,
3695  SelectorSet &ClsMapSeen,
3696  ObjCImplDecl* IMPDecl,
3697  ObjCContainerDecl* IDecl,
3698  bool &IncompleteImpl,
3699  bool ImmediateClass,
3700  bool WarnCategoryMethodImpl=false);
3701 
3702  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3703  /// category matches with those implemented in its primary class and
3704  /// warns each time an exact match is found.
3705  void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3706 
3707  /// Add the given method to the list of globally-known methods.
3708  void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3709 
3710 private:
3711  /// AddMethodToGlobalPool - Add an instance or factory method to the global
3712  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3713  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3714 
3715  /// LookupMethodInGlobalPool - Returns the instance or factory method and
3716  /// optionally warns if there are multiple signatures.
3717  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3718  bool receiverIdOrClass,
3719  bool instance);
3720 
3721 public:
3722  /// - Returns instance or factory methods in global method pool for
3723  /// given selector. It checks the desired kind first, if none is found, and
3724  /// parameter checkTheOther is set, it then checks the other kind. If no such
3725  /// method or only one method is found, function returns false; otherwise, it
3726  /// returns true.
3727  bool
3728  CollectMultipleMethodsInGlobalPool(Selector Sel,
3730  bool InstanceFirst, bool CheckTheOther,
3731  const ObjCObjectType *TypeBound = nullptr);
3732 
3733  bool
3734  AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3735  SourceRange R, bool receiverIdOrClass,
3737 
3738  void
3739  DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3740  Selector Sel, SourceRange R,
3741  bool receiverIdOrClass);
3742 
3743 private:
3744  /// - Returns a selector which best matches given argument list or
3745  /// nullptr if none could be found
3746  ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3747  bool IsInstance,
3749 
3750 
3751  /// Record the typo correction failure and return an empty correction.
3752  TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3753  bool RecordFailure = true) {
3754  if (RecordFailure)
3755  TypoCorrectionFailures[Typo].insert(TypoLoc);
3756  return TypoCorrection();
3757  }
3758 
3759 public:
3760  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3761  /// unit are added to a global pool. This allows us to efficiently associate
3762  /// a selector with a method declaraation for purposes of typechecking
3763  /// messages sent to "id" (where the class of the object is unknown).
3764  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3765  AddMethodToGlobalPool(Method, impl, /*instance*/true);
3766  }
3767 
3768  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3769  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3770  AddMethodToGlobalPool(Method, impl, /*instance*/false);
3771  }
3772 
3773  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3774  /// pool.
3775  void AddAnyMethodToGlobalPool(Decl *D);
3776 
3777  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3778  /// there are multiple signatures.
3780  bool receiverIdOrClass=false) {
3781  return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3782  /*instance*/true);
3783  }
3784 
3785  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3786  /// there are multiple signatures.
3788  bool receiverIdOrClass=false) {
3789  return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3790  /*instance*/false);
3791  }
3792 
3793  const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3794  QualType ObjectType=QualType());
3795  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3796  /// implementation.
3797  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3798 
3799  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3800  /// initialization.
3801  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3803 
3804  //===--------------------------------------------------------------------===//
3805  // Statement Parsing Callbacks: SemaStmt.cpp.
3806 public:
3807  class FullExprArg {
3808  public:
3809  FullExprArg() : E(nullptr) { }
3810  FullExprArg(Sema &actions) : E(nullptr) { }
3811 
3813  return E;
3814  }
3815 
3816  Expr *get() const { return E; }
3817 
3819  return E;
3820  }
3821 
3822  private:
3823  // FIXME: No need to make the entire Sema class a friend when it's just
3824  // Sema::MakeFullExpr that needs access to the constructor below.
3825  friend class Sema;
3826 
3827  explicit FullExprArg(Expr *expr) : E(expr) {}
3828 
3829  Expr *E;
3830  };
3831 
3833  return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3834  }
3836  return FullExprArg(
3837  ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
3838  }
3840  ExprResult FE =
3841  ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3842  /*DiscardedValue*/ true);
3843  return FullExprArg(FE.get());
3844  }
3845 
3846  StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
3847  StmtResult ActOnExprStmtError();
3848 
3849  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3850  bool HasLeadingEmptyMacro = false);
3851 
3852  void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3853  void ActOnFinishOfCompoundStmt();
3854  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3855  ArrayRef<Stmt *> Elts, bool isStmtExpr);
3856 
3857  /// A RAII object to enter scope of a compound statement.
3859  public:
3860  CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3861  S.ActOnStartOfCompoundStmt(IsStmtExpr);
3862  }
3863 
3865  S.ActOnFinishOfCompoundStmt();
3866  }
3867 
3868  private:
3869  Sema &S;
3870  };
3871 
3872  /// An RAII helper that pops function a function scope on exit.
3875  bool Active;
3876  FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3878  if (Active)
3880  }
3881  void disable() { Active = false; }
3882  };
3883 
3884  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3885  SourceLocation StartLoc,
3886  SourceLocation EndLoc);
3887  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3888  StmtResult ActOnForEachLValueExpr(Expr *E);
3889  ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
3890  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
3891  SourceLocation DotDotDotLoc, ExprResult RHS,
3893  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3894 
3895  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3896  SourceLocation ColonLoc,
3897  Stmt *SubStmt, Scope *CurScope);
3898  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3899  SourceLocation ColonLoc, Stmt *SubStmt);
3900 
3901  StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3902  ArrayRef<const Attr*> Attrs,
3903  Stmt *SubStmt);
3904 
3905  class ConditionResult;
3906  StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3907  Stmt *InitStmt,
3908  ConditionResult Cond, Stmt *ThenVal,
3909  SourceLocation ElseLoc, Stmt *ElseVal);
3910  StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3911  Stmt *InitStmt,
3912  ConditionResult Cond, Stmt *ThenVal,
3913  SourceLocation ElseLoc, Stmt *ElseVal);
3914  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3915  Stmt *InitStmt,
3916  ConditionResult Cond);
3917  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3918  Stmt *Switch, Stmt *Body);
3919  StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3920  Stmt *Body);
3921  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3922  SourceLocation WhileLoc, SourceLocation CondLParen,
3923  Expr *Cond, SourceLocation CondRParen);
3924 
3925  StmtResult ActOnForStmt(SourceLocation ForLoc,
3926  SourceLocation LParenLoc,
3927  Stmt *First,
3928  ConditionResult Second,
3929  FullExprArg Third,
3930  SourceLocation RParenLoc,
3931  Stmt *Body);
3932  ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3933  Expr *collection);
3934  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3935  Stmt *First, Expr *collection,
3936  SourceLocation RParenLoc);
3937  StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3938 
3940  /// Initial building of a for-range statement.
3942  /// Instantiation or recovery rebuild of a for-range statement. Don't
3943  /// attempt any typo-correction.
3945  /// Determining whether a for-range statement could be built. Avoid any
3946  /// unnecessary or irreversible actions.
3947  BFRK_Check
3948  };
3949 
3950  StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3951  SourceLocation CoawaitLoc,
3952  Stmt *InitStmt,
3953  Stmt *LoopVar,
3954  SourceLocation ColonLoc, Expr *Collection,
3955  SourceLocation RParenLoc,
3956  BuildForRangeKind Kind);
3957  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3958  SourceLocation CoawaitLoc,
3959  Stmt *InitStmt,
3960  SourceLocation ColonLoc,
3961  Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3962  Expr *Cond, Expr *Inc,
3963  Stmt *LoopVarDecl,
3964  SourceLocation RParenLoc,
3965  BuildForRangeKind Kind);
3966  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3967 
3968  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3969  SourceLocation LabelLoc,
3970  LabelDecl *TheDecl);
3971  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3972  SourceLocation StarLoc,
3973  Expr *DestExp);
3974  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3975  StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3976 
3977  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3978  CapturedRegionKind Kind, unsigned NumParams);
3979  typedef std::pair<StringRef, QualType> CapturedParamNameType;
3980  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3981  CapturedRegionKind Kind,
3983  StmtResult ActOnCapturedRegionEnd(Stmt *S);
3984  void ActOnCapturedRegionError();
3985  RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3986  SourceLocation Loc,
3987  unsigned NumParams);
3988 
3990  CES_Strict = 0,
3991  CES_AllowParameters = 1,
3992  CES_AllowDifferentTypes = 2,
3993  CES_AllowExceptionVariables = 4,
3994  CES_FormerDefault = (CES_AllowParameters),
3995  CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
3996  CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
3997  CES_AllowExceptionVariables),
3998  };
3999 
4000  VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4002  bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4004 
4005  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4006  Scope *CurScope);
4007  StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4008  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4009 
4010  StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4011  bool IsVolatile, unsigned NumOutputs,
4012  unsigned NumInputs, IdentifierInfo **Names,
4013  MultiExprArg Constraints, MultiExprArg Exprs,
4014  Expr *AsmString, MultiExprArg Clobbers,
4015  unsigned NumLabels,
4016  SourceLocation RParenLoc);
4017 
4018  void FillInlineAsmIdentifierInfo(Expr *Res,
4019  llvm::InlineAsmIdentifierInfo &Info);
4020  ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4021  SourceLocation TemplateKWLoc,
4022  UnqualifiedId &Id,
4023  bool IsUnevaluatedContext);
4024  bool LookupInlineAsmField(StringRef Base, StringRef Member,
4025  unsigned &Offset, SourceLocation AsmLoc);
4026  ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4027  SourceLocation AsmLoc);
4028  StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4029  ArrayRef<Token> AsmToks,
4030  StringRef AsmString,
4031  unsigned NumOutputs, unsigned NumInputs,
4032  ArrayRef<StringRef> Constraints,
4033  ArrayRef<StringRef> Clobbers,
4034  ArrayRef<Expr*> Exprs,
4035  SourceLocation EndLoc);
4036  LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4037  SourceLocation Location,
4038  bool AlwaysCreate);
4039 
4040  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4041  SourceLocation StartLoc,
4042  SourceLocation IdLoc, IdentifierInfo *Id,
4043  bool Invalid = false);
4044 
4045  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4046 
4047  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4048  Decl *Parm, Stmt *Body);
4049 
4050  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4051 
4052  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4053  MultiStmtArg Catch, Stmt *Finally);
4054 
4055  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4056  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4057  Scope *CurScope);
4058  ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4059  Expr *operand);
4060  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4061  Expr *SynchExpr,
4062  Stmt *SynchBody);
4063 
4064  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4065 
4066  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4067  SourceLocation StartLoc,
4068  SourceLocation IdLoc,
4069  IdentifierInfo *Id);
4070 
4071  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4072 
4073  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4074  Decl *ExDecl, Stmt *HandlerBlock);
4075  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4076  ArrayRef<Stmt *> Handlers);
4077 
4078  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4079  SourceLocation TryLoc, Stmt *TryBlock,
4080  Stmt *Handler);
4081  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4082  Expr *FilterExpr,
4083  Stmt *Block);
4084  void ActOnStartSEHFinallyBlock();
4085  void ActOnAbortSEHFinallyBlock();
4086  StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4087  StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4088 
4089  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4090 
4091  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4092 
4093  /// If it's a file scoped decl that must warn if not used, keep track
4094  /// of it.
4095  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4096 
4097  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4098  /// whose result is unused, warn.
4099  void DiagnoseUnusedExprResult(const Stmt *S);
4100  void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4101  void DiagnoseUnusedDecl(const NamedDecl *ND);
4102 
4103  /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4104  /// statement as a \p Body, and it is located on the same line.
4105  ///
4106  /// This helps prevent bugs due to typos, such as:
4107  /// if (condition);
4108  /// do_stuff();
4109  void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4110  const Stmt *Body,
4111  unsigned DiagID);
4112 
4113  /// Warn if a for/while loop statement \p S, which is followed by
4114  /// \p PossibleBody, has a suspicious null statement as a body.
4115  void DiagnoseEmptyLoopBody(const Stmt *S,
4116  const Stmt *PossibleBody);
4117 
4118  /// Warn if a value is moved to itself.
4119  void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4120  SourceLocation OpLoc);
4121 
4122  /// Warn if we're implicitly casting from a _Nullable pointer type to a
4123  /// _Nonnull one.
4124  void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4125  SourceLocation Loc);
4126 
4127  /// Warn when implicitly casting 0 to nullptr.
4128  void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4129 
4131  return DelayedDiagnostics.push(pool);
4132  }
4133  void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4134 
4135  typedef ProcessingContextState ParsingClassState;
4136  ParsingClassState PushParsingClass() {
4138  }
4139  void PopParsingClass(ParsingClassState state) {
4141  }
4142 
4143  void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4144 
4145  void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4146  const ObjCInterfaceDecl *UnknownObjCClass,
4147  bool ObjCPropertyAccess,
4148  bool AvoidPartialAvailabilityChecks = false,
4149  ObjCInterfaceDecl *ClassReceiver = nullptr);
4150 
4151  bool makeUnavailableInSystemHeader(SourceLocation loc,
4152  UnavailableAttr::ImplicitReason reason);
4153 
4154  /// Issue any -Wunguarded-availability warnings in \c FD
4155  void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4156 
4157  //===--------------------------------------------------------------------===//
4158  // Expression Parsing Callbacks: SemaExpr.cpp.
4159 
4160  bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4161  bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4162  const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4163  bool ObjCPropertyAccess = false,
4164  bool AvoidPartialAvailabilityChecks = false,
4165  ObjCInterfaceDecl *ClassReciever = nullptr);
4166  void NoteDeletedFunction(FunctionDecl *FD);
4167  void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4168  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4169  ObjCMethodDecl *Getter,
4170  SourceLocation Loc);
4171  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4172  ArrayRef<Expr *> Args);
4173 
4174  void PushExpressionEvaluationContext(
4175  ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4177  ExpressionEvaluationContextRecord::EK_Other);
4178  enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4179  void PushExpressionEvaluationContext(
4182  ExpressionEvaluationContextRecord::EK_Other);
4183  void PopExpressionEvaluationContext();
4184 
4185  void DiscardCleanupsInEvaluationContext();
4186 
4187  ExprResult TransformToPotentiallyEvaluated(Expr *E);
4188  ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4189 
4190  ExprResult ActOnConstantExpression(ExprResult Res);
4191 
4192  // Functions for marking a declaration referenced. These functions also
4193  // contain the relevant logic for marking if a reference to a function or
4194  // variable is an odr-use (in the C++11 sense). There are separate variants
4195  // for expressions referring to a decl; these exist because odr-use marking
4196  // needs to be delayed for some constant variables when we build one of the
4197  // named expressions.
4198  //
4199  // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4200  // should usually be true. This only needs to be set to false if the lack of
4201  // odr-use cannot be determined from the current context (for instance,
4202  // because the name denotes a virtual function and was written without an
4203  // explicit nested-name-specifier).
4204  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4205  void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4206  bool MightBeOdrUse = true);
4207  void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4208  void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4209  void MarkMemberReferenced(MemberExpr *E);
4210  void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4211  void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4212  unsigned CapturingScopeIndex);
4213 
4214  ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4215  void CleanupVarDeclMarking();
4216 
4218  TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4219  };
4220 
4221  /// Try to capture the given variable.
4222  ///
4223  /// \param Var The variable to capture.
4224  ///
4225  /// \param Loc The location at which the capture occurs.
4226  ///
4227  /// \param Kind The kind of capture, which may be implicit (for either a
4228  /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4229  ///
4230  /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4231  /// an explicit lambda capture.
4232  ///
4233  /// \param BuildAndDiagnose Whether we are actually supposed to add the
4234  /// captures or diagnose errors. If false, this routine merely check whether
4235  /// the capture can occur without performing the capture itself or complaining
4236  /// if the variable cannot be captured.
4237  ///
4238  /// \param CaptureType Will be set to the type of the field used to capture
4239  /// this variable in the innermost block or lambda. Only valid when the
4240  /// variable can be captured.
4241  ///
4242  /// \param DeclRefType Will be set to the type of a reference to the capture
4243  /// from within the current scope. Only valid when the variable can be
4244  /// captured.
4245  ///
4246  /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4247  /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4248  /// This is useful when enclosing lambdas must speculatively capture
4249  /// variables that may or may not be used in certain specializations of
4250  /// a nested generic lambda.
4251  ///
4252  /// \returns true if an error occurred (i.e., the variable cannot be
4253  /// captured) and false if the capture succeeded.
4254  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4255  SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4256  QualType &CaptureType,
4257  QualType &DeclRefType,
4258  const unsigned *const FunctionScopeIndexToStopAt);
4259 
4260  /// Try to capture the given variable.
4261  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4262  TryCaptureKind Kind = TryCapture_Implicit,
4263  SourceLocation EllipsisLoc = SourceLocation());
4264 
4265  /// Checks if the variable must be captured.
4266  bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4267 
4268  /// Given a variable, determine the type that a reference to that
4269  /// variable will have in the given scope.
4270  QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4271 
4272  /// Mark all of the declarations referenced within a particular AST node as
4273  /// referenced. Used when template instantiation instantiates a non-dependent
4274  /// type -- entities referenced by the type are now referenced.
4275  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4276  void MarkDeclarationsReferencedInExpr(Expr *E,
4277  bool SkipLocalVariables = false);
4278 
4279  /// Try to recover by turning the given expression into a
4280  /// call. Returns true if recovery was attempted or an error was
4281  /// emitted; this may also leave the ExprResult invalid.
4282  bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4283  bool ForceComplain = false,
4284  bool (*IsPlausibleResult)(QualType) = nullptr);
4285 
4286  /// Figure out if an expression could be turned into a call.
4287  bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4288  UnresolvedSetImpl &NonTemplateOverloads);
4289 
4290  /// Conditionally issue a diagnostic based on the current
4291  /// evaluation context.
4292  ///
4293  /// \param Statement If Statement is non-null, delay reporting the
4294  /// diagnostic until the function body is parsed, and then do a basic
4295  /// reachability analysis to determine if the statement is reachable.
4296  /// If it is unreachable, the diagnostic will not be emitted.
4297  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4298  const PartialDiagnostic &PD);
4299  /// Similar, but diagnostic is only produced if all the specified statements
4300  /// are reachable.
4301  bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4302  const PartialDiagnostic &PD);
4303 
4304  // Primary Expressions.
4305  SourceRange getExprRange(Expr *E) const;
4306 
4307  ExprResult ActOnIdExpression(
4308  Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4309  UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4310  CorrectionCandidateCallback *CCC = nullptr,
4311  bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4312 
4313  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4314  TemplateArgumentListInfo &Buffer,
4315  DeclarationNameInfo &NameInfo,
4316  const TemplateArgumentListInfo *&TemplateArgs);
4317 
4318  bool
4319  DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4321  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4322  ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4323 
4324  ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4325  IdentifierInfo *II,
4326  bool AllowBuiltinCreation=false);
4327 
4328  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4329  SourceLocation TemplateKWLoc,
4330  const DeclarationNameInfo &NameInfo,
4331  bool isAddressOfOperand,
4332  const TemplateArgumentListInfo *TemplateArgs);
4333 
4334  /// If \p D cannot be odr-used in the current expression evaluation context,
4335  /// return a reason explaining why. Otherwise, return NOUR_None.
4336  NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4337 
4338  DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4339  SourceLocation Loc,
4340  const CXXScopeSpec *SS = nullptr);
4341  DeclRefExpr *
4342  BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4343  const DeclarationNameInfo &NameInfo,
4344  const CXXScopeSpec *SS = nullptr,
4345  NamedDecl *FoundD = nullptr,
4346  SourceLocation TemplateKWLoc = SourceLocation(),
4347  const TemplateArgumentListInfo *TemplateArgs = nullptr);
4348  DeclRefExpr *
4349  BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4350  const DeclarationNameInfo &NameInfo,
4352  NamedDecl *FoundD = nullptr,
4353  SourceLocation TemplateKWLoc = SourceLocation(),
4354  const TemplateArgumentListInfo *TemplateArgs = nullptr);
4355 
4356  ExprResult
4357  BuildAnonymousStructUnionMemberReference(
4358  const CXXScopeSpec &SS,
4359  SourceLocation nameLoc,
4360  IndirectFieldDecl *indirectField,
4361  DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4362  Expr *baseObjectExpr = nullptr,
4363  SourceLocation opLoc = SourceLocation());
4364 
4365  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4366  SourceLocation TemplateKWLoc,
4367  LookupResult &R,
4368  const TemplateArgumentListInfo *TemplateArgs,
4369  const Scope *S);
4370  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4371  SourceLocation TemplateKWLoc,
4372  LookupResult &R,
4373  const TemplateArgumentListInfo *TemplateArgs,
4374  bool IsDefiniteInstance,
4375  const Scope *S);
4376  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4377  const LookupResult &R,
4378  bool HasTrailingLParen);
4379 
4380  ExprResult
4381  BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4382  const DeclarationNameInfo &NameInfo,
4383  bool IsAddressOfOperand, const Scope *S,
4384  TypeSourceInfo **RecoveryTSI = nullptr);
4385 
4386  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4387  SourceLocation TemplateKWLoc,
4388  const DeclarationNameInfo &NameInfo,
4389  const TemplateArgumentListInfo *TemplateArgs);
4390 
4391  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4392  LookupResult &R,
4393  bool NeedsADL,
4394  bool AcceptInvalidDecl = false);
4395  ExprResult BuildDeclarationNameExpr(
4396  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4397  NamedDecl *FoundD = nullptr,
4398  const TemplateArgumentListInfo *TemplateArgs = nullptr,
4399  bool AcceptInvalidDecl = false);
4400 
4401  ExprResult BuildLiteralOperatorCall(LookupResult &R,
4402  DeclarationNameInfo &SuffixInfo,
4403  ArrayRef<Expr *> Args,
4404  SourceLocation LitEndLoc,
4405  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4406 
4407  ExprResult BuildPredefinedExpr(SourceLocation Loc,
4409  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4410  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4411 
4412  bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4413 
4414  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4415  ExprResult ActOnCharacterConstant(const Token &Tok,
4416  Scope *UDLScope = nullptr);
4417  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4418  ExprResult ActOnParenListExpr(SourceLocation L,
4419  SourceLocation R,
4420  MultiExprArg Val);
4421 
4422  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4423  /// fragments (e.g. "foo" "bar" L"baz").
4424  ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4425  Scope *UDLScope = nullptr);
4426 
4427  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4428  SourceLocation DefaultLoc,
4429  SourceLocation RParenLoc,
4430  Expr *ControllingExpr,
4431  ArrayRef<ParsedType> ArgTypes,
4432  ArrayRef<Expr *> ArgExprs);
4433  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4434  SourceLocation DefaultLoc,
4435  SourceLocation RParenLoc,
4436  Expr *ControllingExpr,
4438  ArrayRef<Expr *> Exprs);
4439 
4440  // Binary/Unary Operators. 'Tok' is the token for the operator.
4441  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4442  Expr *InputExpr);
4443  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4444  UnaryOperatorKind Opc, Expr *Input);
4445  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4446  tok::TokenKind Op, Expr *Input);
4447 
4448  bool isQualifiedMemberAccess(Expr *E);
4449  QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4450 
4451  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4452  SourceLocation OpLoc,
4453  UnaryExprOrTypeTrait ExprKind,
4454  SourceRange R);
4455  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4456  UnaryExprOrTypeTrait ExprKind);
4457  ExprResult
4458  ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4459  UnaryExprOrTypeTrait ExprKind,
4460  bool IsType, void *TyOrEx,
4461  SourceRange ArgRange);
4462 
4463  ExprResult CheckPlaceholderExpr(Expr *E);
4464  bool CheckVecStepExpr(Expr *E);
4465 
4466  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4467  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4468  SourceRange ExprRange,
4469  UnaryExprOrTypeTrait ExprKind);
4470  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4471  SourceLocation OpLoc,
4472  IdentifierInfo &Name,
4473  SourceLocation NameLoc,
4474  SourceLocation RParenLoc);
4475  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4476  tok::TokenKind Kind, Expr *Input);
4477 
4478  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4479  Expr *Idx, SourceLocation RLoc);
4480  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4481  Expr *Idx, SourceLocation RLoc);
4482  ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4483  Expr *LowerBound, SourceLocation ColonLoc,
4484  Expr *Length, SourceLocation RBLoc);
4485 
4486  // This struct is for use by ActOnMemberAccess to allow
4487  // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4488  // changing the access operator from a '.' to a '->' (to see if that is the
4489  // change needed to fix an error about an unknown member, e.g. when the class
4490  // defines a custom operator->).
4492  Scope *S;
4495  };
4496 
4497  ExprResult BuildMemberReferenceExpr(
4498  Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4499  CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4500  NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4501  const TemplateArgumentListInfo *TemplateArgs,
4502  const Scope *S,
4503  ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4504 
4505  ExprResult
4506  BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4507  bool IsArrow, const CXXScopeSpec &SS,
4508  SourceLocation TemplateKWLoc,
4509  NamedDecl *FirstQualifierInScope, LookupResult &R,
4510  const TemplateArgumentListInfo *TemplateArgs,
4511  const Scope *S,
4512  bool SuppressQualifierCheck = false,
4513  ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4514 
4515  ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4516  SourceLocation OpLoc,
4517  const CXXScopeSpec &SS, FieldDecl *Field,
4518  DeclAccessPair FoundDecl,
4519  const DeclarationNameInfo &MemberNameInfo);
4520 
4521  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4522 
4523  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4524  const CXXScopeSpec &SS,
4525  const LookupResult &R);
4526 
4527  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4528  bool IsArrow, SourceLocation OpLoc,
4529  const CXXScopeSpec &SS,
4530  SourceLocation TemplateKWLoc,
4531  NamedDecl *FirstQualifierInScope,
4532  const DeclarationNameInfo &NameInfo,
4533  const TemplateArgumentListInfo *TemplateArgs);
4534 
4535  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4536  SourceLocation OpLoc,
4537  tok::TokenKind OpKind,
4538  CXXScopeSpec &SS,
4539  SourceLocation TemplateKWLoc,
4540  UnqualifiedId &Member,
4541  Decl *ObjCImpDecl);
4542 
4543  MemberExpr *
4544  BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4545  const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4546  ValueDecl *Member, DeclAccessPair FoundDecl,
4547  bool HadMultipleCandidates,
4548  const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4550  const TemplateArgumentListInfo *TemplateArgs = nullptr);
4551  MemberExpr *
4552  BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4553  NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4554  ValueDecl *Member, DeclAccessPair FoundDecl,
4555  bool HadMultipleCandidates,
4556  const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4558  const TemplateArgumentListInfo *TemplateArgs = nullptr);
4559 
4560  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4561  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4562  FunctionDecl *FDecl,
4563  const FunctionProtoType *Proto,
4564  ArrayRef<Expr *> Args,
4565  SourceLocation RParenLoc,
4566  bool ExecConfig = false);
4567  void CheckStaticArrayArgument(SourceLocation CallLoc,
4568  ParmVarDecl *Param,
4569  const Expr *ArgExpr);
4570 
4571  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4572  /// This provides the location of the left/right parens and a list of comma
4573  /// locations.
4574  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4575  MultiExprArg ArgExprs, SourceLocation RParenLoc,
4576  Expr *ExecConfig = nullptr);
4577  ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4578  MultiExprArg ArgExprs, SourceLocation RParenLoc,
4579  Expr *ExecConfig = nullptr,
4580  bool IsExecConfig = false);
4581  ExprResult
4582  BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4583  ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4584  Expr *Config = nullptr, bool IsExecConfig = false,
4585  ADLCallKind UsesADL = ADLCallKind::NotADL);
4586 
4587  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4588  MultiExprArg ExecConfig,
4589  SourceLocation GGGLoc);
4590 
4591  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4592  Declarator &D, ParsedType &Ty,
4593  SourceLocation RParenLoc, Expr *CastExpr);
4594  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4595  TypeSourceInfo *Ty,
4596  SourceLocation RParenLoc,
4597  Expr *Op);
4598  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4599 
4600  /// Build an altivec or OpenCL literal.
4601  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4602  SourceLocation RParenLoc, Expr *E,
4603  TypeSourceInfo *TInfo);
4604 
4605  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4606 
4607  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4608  ParsedType Ty,
4609  SourceLocation RParenLoc,
4610  Expr *InitExpr);
4611 
4612  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4613  TypeSourceInfo *TInfo,
4614  SourceLocation RParenLoc,
4615  Expr *LiteralExpr);
4616 
4617  ExprResult ActOnInitList(SourceLocation LBraceLoc,
4618  MultiExprArg InitArgList,
4619  SourceLocation RBraceLoc);
4620 
4621  ExprResult ActOnDesignatedInitializer(Designation &Desig,
4622  SourceLocation Loc,
4623  bool GNUSyntax,
4624  ExprResult Init);
4625 
4626 private:
4627  static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4628 
4629 public:
4630  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4631  tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4632  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4633  BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4634  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4635  Expr *LHSExpr, Expr *RHSExpr);
4636 
4637  void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4638 
4639  /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4640  /// in the case of a the GNU conditional expr extension.
4641  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4642  SourceLocation ColonLoc,
4643  Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4644 
4645  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4646  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4647  LabelDecl *TheDecl);
4648 
4649  void ActOnStartStmtExpr();
4650  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4651  SourceLocation RPLoc); // "({..})"
4652  // Handle the final expression in a statement expression.
4653  ExprResult ActOnStmtExprResult(ExprResult E);
4654  void ActOnStmtExprError();
4655 
4656  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4659  bool isBrackets; // true if [expr], false if .ident
4660  union {
4663  } U;
4664  };
4665 
4666  /// __builtin_offsetof(type, a.b[123][456].c)
4667  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4668  TypeSourceInfo *TInfo,
4669  ArrayRef<OffsetOfComponent> Components,
4670  SourceLocation RParenLoc);
4671  ExprResult ActOnBuiltinOffsetOf(Scope *S,
4672  SourceLocation BuiltinLoc,
4674  ParsedType ParsedArgTy,
4675  ArrayRef<OffsetOfComponent> Components,
4676  SourceLocation RParenLoc);
4677 
4678  // __builtin_choose_expr(constExpr, expr1, expr2)
4679  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4680  Expr *CondExpr, Expr *LHSExpr,
4681  Expr *RHSExpr, SourceLocation RPLoc);
4682 
4683  // __builtin_va_arg(expr, type)
4684  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4685  SourceLocation RPLoc);
4686  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4687  TypeSourceInfo *TInfo, SourceLocation RPLoc);
4688 
4689  // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
4690  // __builtin_COLUMN()
4691  ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
4692  SourceLocation BuiltinLoc,
4693  SourceLocation RPLoc);
4694 
4695  // Build a potentially resolved SourceLocExpr.
4696  ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
4697  SourceLocation BuiltinLoc, SourceLocation RPLoc,
4698  DeclContext *ParentContext);
4699 
4700  // __null
4701  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4702 
4703  bool CheckCaseExpression(Expr *E);
4704 
4705  /// Describes the result of an "if-exists" condition check.
4707  /// The symbol exists.
4709 
4710  /// The symbol does not exist.
4712 
4713  /// The name is a dependent name, so the results will differ
4714  /// from one instantiation to the next.
4716 
4717  /// An error occurred.
4718  IER_Error
4719  };
4720 
4722  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4723  const DeclarationNameInfo &TargetNameInfo);
4724 
4726  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4727  bool IsIfExists, CXXScopeSpec &SS,
4728  UnqualifiedId &Name);
4729 
4730  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4731  bool IsIfExists,
4732  NestedNameSpecifierLoc QualifierLoc,
4733  DeclarationNameInfo NameInfo,
4734  Stmt *Nested);
4735  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4736  bool IsIfExists,
4737  CXXScopeSpec &SS, UnqualifiedId &Name,
4738  Stmt *Nested);
4739 
4740  //===------------------------- "Block" Extension ------------------------===//
4741 
4742  /// ActOnBlockStart - This callback is invoked when a block literal is
4743  /// started.
4744  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4745 
4746  /// ActOnBlockArguments - This callback allows processing of block arguments.
4747  /// If there are no arguments, this is still invoked.
4748  void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4749  Scope *CurScope);
4750 
4751  /// ActOnBlockError - If there is an error parsing a block, this callback
4752  /// is invoked to pop the information about the block from the action impl.
4753  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4754 
4755  /// ActOnBlockStmtExpr - This is called when the body of a block statement
4756  /// literal was successfully completed. ^(int x){...}
4757  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4758  Scope *CurScope);
4759 
4760  //===---------------------------- Clang Extensions ----------------------===//
4761 
4762  /// __builtin_convertvector(...)
4763  ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4764  SourceLocation BuiltinLoc,
4765  SourceLocation RParenLoc);
4766 
4767  //===---------------------------- OpenCL Features -----------------------===//
4768 
4769  /// __builtin_astype(...)
4770  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4771  SourceLocation BuiltinLoc,
4772  SourceLocation RParenLoc);
4773 
4774  //===---------------------------- C++ Features --------------------------===//
4775 
4776  // Act on C++ namespaces
4777  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4778  SourceLocation NamespaceLoc,
4779  SourceLocation IdentLoc, IdentifierInfo *Ident,
4780  SourceLocation LBrace,
4781  const ParsedAttributesView &AttrList,
4783  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4784 
4785  NamespaceDecl *getStdNamespace() const;
4786  NamespaceDecl *getOrCreateStdNamespace();
4787 
4788  NamespaceDecl *lookupStdExperimentalNamespace();
4789 
4790  CXXRecordDecl *getStdBadAlloc() const;
4791  EnumDecl *getStdAlignValT() const;
4792 
4793 private:
4794  // A cache representing if we've fully checked the various comparison category
4795  // types stored in ASTContext. The bit-index corresponds to the integer value
4796  // of a ComparisonCategoryType enumerator.
4797  llvm::SmallBitVector FullyCheckedComparisonCategories;
4798 
4799  ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4800  CXXScopeSpec &SS,
4801  ParsedType TemplateTypeTy,
4802  IdentifierInfo *MemberOrBase);
4803 
4804 public:
4805  /// Lookup the specified comparison category types in the standard
4806  /// library, an check the VarDecls possibly returned by the operator<=>
4807  /// builtins for that type.
4808  ///
4809  /// \return The type of the comparison category type corresponding to the
4810  /// specified Kind, or a null type if an error occurs
4811  QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
4812  SourceLocation Loc);
4813 
4814  /// Tests whether Ty is an instance of std::initializer_list and, if
4815  /// it is and Element is not NULL, assigns the element type to Element.
4816  bool isStdInitializerList(QualType Ty, QualType *Element);
4817 
4818  /// Looks for the std::initializer_list template and instantiates it
4819  /// with Element, or emits an error if it's not found.
4820  ///
4821  /// \returns The instantiated template, or null on error.
4822  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4823 
4824  /// Determine whether Ctor is an initializer-list constructor, as
4825  /// defined in [dcl.init.list]p2.
4826  bool isInitListConstructor(const FunctionDecl *Ctor);
4827 
4828  Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
4829  SourceLocation NamespcLoc, CXXScopeSpec &SS,
4830  SourceLocation IdentLoc,
4831  IdentifierInfo *NamespcName,
4832  const ParsedAttributesView &AttrList);
4833 
4834  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4835 
4836  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4837  SourceLocation NamespaceLoc,
4838  SourceLocation AliasLoc,
4839  IdentifierInfo *Alias,
4840  CXXScopeSpec &SS,
4841  SourceLocation IdentLoc,
4842  IdentifierInfo *Ident);
4843 
4844  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4845  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4846  const LookupResult &PreviousDecls,
4847  UsingShadowDecl *&PrevShadow);
4848  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4849  NamedDecl *Target,
4850  UsingShadowDecl *PrevDecl);
4851 
4852  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4853  bool HasTypenameKeyword,
4854  const CXXScopeSpec &SS,
4855  SourceLocation NameLoc,
4856  const LookupResult &Previous);
4857  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4858  bool HasTypename,
4859  const CXXScopeSpec &SS,
4860  const DeclarationNameInfo &NameInfo,
4861  SourceLocation NameLoc);
4862 
4863  NamedDecl *BuildUsingDeclaration(
4864  Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
4865  bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
4866  DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
4867  const ParsedAttributesView &AttrList, bool IsInstantiation);
4868  NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4869  ArrayRef<NamedDecl *> Expansions);
4870 
4871  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4872 
4873  /// Given a derived-class using shadow declaration for a constructor and the
4874  /// correspnding base class constructor, find or create the implicit
4875  /// synthesized derived class constructor to use for this initialization.
4876  CXXConstructorDecl *
4877  findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4878  ConstructorUsingShadowDecl *DerivedShadow);
4879 
4880  Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
4881  SourceLocation UsingLoc,
4882  SourceLocation TypenameLoc, CXXScopeSpec &SS,
4883  UnqualifiedId &Name, SourceLocation EllipsisLoc,
4884  const ParsedAttributesView &AttrList);
4885  Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
4886  MultiTemplateParamsArg TemplateParams,
4887  SourceLocation UsingLoc, UnqualifiedId &Name,
4888  const ParsedAttributesView &AttrList,
4889  TypeResult Type, Decl *DeclFromDeclSpec);
4890 
4891  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4892  /// including handling of its default argument expressions.
4893  ///
4894  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4895  ExprResult
4896  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4897  NamedDecl *FoundDecl,
4898  CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4899  bool HadMultipleCandidates, bool IsListInitialization,
4900  bool IsStdInitListInitialization,
4901  bool RequiresZeroInit, unsigned ConstructKind,
4902  SourceRange ParenRange);
4903 
4904  /// Build a CXXConstructExpr whose constructor has already been resolved if
4905  /// it denotes an inherited constructor.
4906  ExprResult
4907  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4908  CXXConstructorDecl *Constructor, bool Elidable,
4909  MultiExprArg Exprs,
4910  bool HadMultipleCandidates, bool IsListInitialization,
4911  bool IsStdInitListInitialization,
4912  bool RequiresZeroInit, unsigned ConstructKind,
4913  SourceRange ParenRange);
4914 
4915  // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4916  // the constructor can be elidable?
4917  ExprResult
4918  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4919  NamedDecl *FoundDecl,
4920  CXXConstructorDecl *Constructor, bool Elidable,
4921  MultiExprArg Exprs, bool HadMultipleCandidates,
4922  bool IsListInitialization,
4923  bool IsStdInitListInitialization, bool RequiresZeroInit,
4924  unsigned ConstructKind, SourceRange ParenRange);
4925 
4926  ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4927 
4928 
4929  /// Instantiate or parse a C++ default argument expression as necessary.
4930  /// Return true on error.
4931  bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4932  ParmVarDecl *Param);
4933 
4934  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4935  /// the default expr if needed.
4936  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4937  FunctionDecl *FD,
4938  ParmVarDecl *Param);
4939 
4940  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4941  /// constructed variable.
4942  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4943 
4944  /// Helper class that collects exception specifications for
4945  /// implicitly-declared special member functions.
4947  // Pointer to allow copying
4948  Sema *Self;
4949  // We order exception specifications thus:
4950  // noexcept is the most restrictive, but is only used in C++11.
4951  // throw() comes next.
4952  // Then a throw(collected exceptions)
4953  // Finally no specification, which is expressed as noexcept(false).
4954  // throw(...) is used instead if any called function uses it.
4955  ExceptionSpecificationType ComputedEST;
4956  llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4957  SmallVector<QualType, 4> Exceptions;
4958 
4959  void ClearExceptions() {
4960  ExceptionsSeen.clear();
4961  Exceptions.clear();
4962  }
4963 
4964  public:
4966  : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4967  if (!Self.getLangOpts().CPlusPlus11)
4968  ComputedEST = EST_DynamicNone;
4969  }
4970 
4971  /// Get the computed exception specification type.
4973  assert(!isComputedNoexcept(ComputedEST) &&
4974  "noexcept(expr) should not be a possible result");
4975  return ComputedEST;
4976  }
4977 
4978  /// The number of exceptions in the exception specification.
4979  unsigned size() const { return Exceptions.size(); }
4980 
4981  /// The set of exceptions in the exception specification.
4982  const QualType *data() const { return Exceptions.data(); }
4983 
4984  /// Integrate another called method into the collected data.
4985  void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4986 
4987  /// Integrate an invoked expression into the collected data.
4988  void CalledExpr(Expr *E);
4989 
4990  /// Overwrite an EPI's exception specification with this
4991  /// computed exception specification.
4994  ESI.Type = getExceptionSpecType();
4995  if (ESI.Type == EST_Dynamic) {
4996  ESI.Exceptions = Exceptions;
4997  } else if (ESI.Type == EST_None) {
4998  /// C++11 [except.spec]p14:
4999  /// The exception-specification is noexcept(false) if the set of
5000  /// potential exceptions of the special member function contains "any"
5001  ESI.Type = EST_NoexceptFalse;
5003  tok::kw_false).get();
5004  }
5005  return ESI;
5006  }
5007  };
5008 
5009  /// Determine what sort of exception specification a defaulted
5010  /// copy constructor of a class will have.
5012  ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5013  CXXMethodDecl *MD);
5014 
5015  /// Determine what sort of exception specification a defaulted
5016  /// default constructor of a class will have, and whether the parameter
5017  /// will be const.
5019  ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5020 
5021  /// Determine what sort of exception specification a defaulted
5022  /// copy assignment operator of a class will have, and whether the
5023  /// parameter will be const.
5025  ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5026 
5027  /// Determine what sort of exception specification a defaulted move
5028  /// constructor of a class will have.
5030  ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5031 
5032  /// Determine what sort of exception specification a defaulted move
5033  /// assignment operator of a class will have.
5035  ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5036 
5037  /// Determine what sort of exception specification a defaulted
5038  /// destructor of a class will have.
5040  ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5041 
5042  /// Determine what sort of exception specification an inheriting
5043  /// constructor of a class will have.
5045  ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5046  CXXConstructorDecl *CD);
5047 
5048  /// Evaluate the implicit exception specification for a defaulted
5049  /// special member function.
5050  void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
5051 
5052  /// Check the given noexcept-specifier, convert its expression, and compute
5053  /// the appropriate ExceptionSpecificationType.
5054  ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5056 
5057  /// Check the given exception-specification and update the
5058  /// exception specification information with the results.
5059  void checkExceptionSpecification(bool IsTopLevel,
5061  ArrayRef<ParsedType> DynamicExceptions,
5062  ArrayRef<SourceRange> DynamicExceptionRanges,
5063  Expr *NoexceptExpr,
5064  SmallVectorImpl<QualType> &Exceptions,
5066 
5067  /// Determine if we're in a case where we need to (incorrectly) eagerly
5068  /// parse an exception specification to work around a libstdc++ bug.
5069  bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5070 
5071  /// Add an exception-specification to the given member function
5072  /// (or member function template). The exception-specification was parsed
5073  /// after the method itself was declared.
5074  void actOnDelayedExceptionSpecification(Decl *Method,
5076  SourceRange SpecificationRange,
5077  ArrayRef<ParsedType> DynamicExceptions,
5078  ArrayRef<SourceRange> DynamicExceptionRanges,
5079  Expr *NoexceptExpr);
5080 
5082 
5083  /// Determine if a special member function should have a deleted
5084  /// definition when it is defaulted.
5085  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5086  InheritedConstructorInfo *ICI = nullptr,
5087  bool Diagnose = false);
5088 
5089  /// Declare the implicit default constructor for the given class.
5090  ///
5091  /// \param ClassDecl The class declaration into which the implicit
5092  /// default constructor will be added.
5093  ///
5094  /// \returns The implicitly-declared default constructor.
5095  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5096  CXXRecordDecl *ClassDecl);
5097 
5098  /// DefineImplicitDefaultConstructor - Checks for feasibility of
5099  /// defining this constructor as the default constructor.
5100  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5101  CXXConstructorDecl *Constructor);
5102 
5103  /// Declare the implicit destructor for the given class.
5104  ///
5105  /// \param ClassDecl The class declaration into which the implicit
5106  /// destructor will be added.
5107  ///
5108  /// \returns The implicitly-declared destructor.
5109  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5110 
5111  /// DefineImplicitDestructor - Checks for feasibility of
5112  /// defining this destructor as the default destructor.
5113  void DefineImplicitDestructor(SourceLocation CurrentLocation,
5114  CXXDestructorDecl *Destructor);
5115 
5116  /// Build an exception spec for destructors that don't have one.
5117  ///
5118  /// C++11 says that user-defined destructors with no exception spec get one
5119  /// that looks as if the destructor was implicitly declared.
5120  void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5121 
5122  /// Define the specified inheriting constructor.
5123  void DefineInheritingConstructor(SourceLocation UseLoc,
5124  CXXConstructorDecl *Constructor);
5125 
5126  /// Declare the implicit copy constructor for the given class.
5127  ///
5128  /// \param ClassDecl The class declaration into which the implicit
5129  /// copy constructor will be added.
5130  ///
5131  /// \returns The implicitly-declared copy constructor.
5132  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5133 
5134  /// DefineImplicitCopyConstructor - Checks for feasibility of
5135  /// defining this constructor as the copy constructor.
5136  void DefineImplicitCopyConstructor(