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