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