Sema.h revision 58ee425b11e178c652fa6ff4c1c924fe9b98801e
15976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// 25976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// 35976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// The LLVM Compiler Infrastructure 45976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// 55976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// This file is distributed under the University of Illinois Open Source 65976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// License. See LICENSE.TXT for details. 75976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// 85976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org//===----------------------------------------------------------------------===// 95976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// 105976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// This file defines the Sema class, which performs semantic analysis and 115976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// builds ASTs. 125976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org// 135976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org//===----------------------------------------------------------------------===// 145976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org 155976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#ifndef LLVM_CLANG_SEMA_SEMA_H 165976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#define LLVM_CLANG_SEMA_SEMA_H 175976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org 185976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/Attr.h" 195976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/DeclarationName.h" 205976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/Expr.h" 215976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/ExprObjC.h" 225976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/ExternalASTSource.h" 235976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/MangleNumberingContext.h" 245976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/NSAPI.h" 255976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/PrettyPrinter.h" 265976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/AST/TypeLoc.h" 275976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Basic/ExpressionTraits.h" 285976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Basic/LangOptions.h" 295976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Basic/OpenMPKinds.h" 305976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Basic/Specifiers.h" 315976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Basic/TemplateKinds.h" 325976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Basic/TypeTraits.h" 335976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Lex/ModuleLoader.h" 345976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Sema/AnalysisBasedWarnings.h" 355976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Sema/DeclSpec.h" 365976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Sema/ExternalSemaSource.h" 375976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Sema/IdentifierResolver.h" 385976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Sema/LocInfoType.h" 395976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Sema/ObjCMethodList.h" 405976650443d68ccfadf1dea24999ee459dd2819mflodman@webrtc.org#include "clang/Sema/Ownership.h" 41#include "clang/Sema/ScopeInfo.h" 42#include "clang/Sema/TypoCorrection.h" 43#include "clang/Sema/Weak.h" 44#include "llvm/ADT/ArrayRef.h" 45#include "llvm/ADT/Optional.h" 46#include "llvm/ADT/OwningPtr.h" 47#include "llvm/ADT/SetVector.h" 48#include "llvm/ADT/SmallPtrSet.h" 49#include "llvm/ADT/SmallVector.h" 50#include "llvm/MC/MCParser/MCAsmParser.h" 51#include <deque> 52#include <string> 53#include <vector> 54 55namespace llvm { 56 class APSInt; 57 template <typename ValueT> struct DenseMapInfo; 58 template <typename ValueT, typename ValueInfoT> class DenseSet; 59 class SmallBitVector; 60} 61 62namespace clang { 63 class ADLResult; 64 class ASTConsumer; 65 class ASTContext; 66 class ASTMutationListener; 67 class ASTReader; 68 class ASTWriter; 69 class ArrayType; 70 class AttributeList; 71 class BlockDecl; 72 class CapturedDecl; 73 class CXXBasePath; 74 class CXXBasePaths; 75 class CXXBindTemporaryExpr; 76 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 77 class CXXConstructorDecl; 78 class CXXConversionDecl; 79 class CXXDestructorDecl; 80 class CXXFieldCollector; 81 class CXXMemberCallExpr; 82 class CXXMethodDecl; 83 class CXXScopeSpec; 84 class CXXTemporary; 85 class CXXTryStmt; 86 class CallExpr; 87 class ClassTemplateDecl; 88 class ClassTemplatePartialSpecializationDecl; 89 class ClassTemplateSpecializationDecl; 90 class VarTemplatePartialSpecializationDecl; 91 class CodeCompleteConsumer; 92 class CodeCompletionAllocator; 93 class CodeCompletionTUInfo; 94 class CodeCompletionResult; 95 class Decl; 96 class DeclAccessPair; 97 class DeclContext; 98 class DeclRefExpr; 99 class DeclaratorDecl; 100 class DeducedTemplateArgument; 101 class DependentDiagnostic; 102 class DesignatedInitExpr; 103 class Designation; 104 class EnumConstantDecl; 105 class Expr; 106 class ExtVectorType; 107 class ExternalSemaSource; 108 class FormatAttr; 109 class FriendDecl; 110 class FunctionDecl; 111 class FunctionProtoType; 112 class FunctionTemplateDecl; 113 class ImplicitConversionSequence; 114 class InitListExpr; 115 class InitializationKind; 116 class InitializationSequence; 117 class InitializedEntity; 118 class IntegerLiteral; 119 class LabelStmt; 120 class LambdaExpr; 121 class LangOptions; 122 class LocalInstantiationScope; 123 class LookupResult; 124 class MacroInfo; 125 class MultiLevelTemplateArgumentList; 126 class NamedDecl; 127 class NonNullAttr; 128 class ObjCCategoryDecl; 129 class ObjCCategoryImplDecl; 130 class ObjCCompatibleAliasDecl; 131 class ObjCContainerDecl; 132 class ObjCImplDecl; 133 class ObjCImplementationDecl; 134 class ObjCInterfaceDecl; 135 class ObjCIvarDecl; 136 template <class T> class ObjCList; 137 class ObjCMessageExpr; 138 class ObjCMethodDecl; 139 class ObjCPropertyDecl; 140 class ObjCProtocolDecl; 141 class OMPThreadPrivateDecl; 142 class OMPClause; 143 class OverloadCandidateSet; 144 class OverloadExpr; 145 class ParenListExpr; 146 class ParmVarDecl; 147 class Preprocessor; 148 class PseudoDestructorTypeStorage; 149 class PseudoObjectExpr; 150 class QualType; 151 class StandardConversionSequence; 152 class Stmt; 153 class StringLiteral; 154 class SwitchStmt; 155 class TargetAttributesSema; 156 class TemplateArgument; 157 class TemplateArgumentList; 158 class TemplateArgumentLoc; 159 class TemplateDecl; 160 class TemplateParameterList; 161 class TemplatePartialOrderingContext; 162 class TemplateTemplateParmDecl; 163 class Token; 164 class TypeAliasDecl; 165 class TypedefDecl; 166 class TypedefNameDecl; 167 class TypeLoc; 168 class UnqualifiedId; 169 class UnresolvedLookupExpr; 170 class UnresolvedMemberExpr; 171 class UnresolvedSetImpl; 172 class UnresolvedSetIterator; 173 class UsingDecl; 174 class UsingShadowDecl; 175 class ValueDecl; 176 class VarDecl; 177 class VarTemplateSpecializationDecl; 178 class VisibilityAttr; 179 class VisibleDeclConsumer; 180 class IndirectFieldDecl; 181 struct DeductionFailureInfo; 182 class TemplateSpecCandidateSet; 183 184namespace sema { 185 class AccessedEntity; 186 class BlockScopeInfo; 187 class CapturedRegionScopeInfo; 188 class CapturingScopeInfo; 189 class CompoundScopeInfo; 190 class DelayedDiagnostic; 191 class DelayedDiagnosticPool; 192 class FunctionScopeInfo; 193 class LambdaScopeInfo; 194 class PossiblyUnreachableDiag; 195 class TemplateDeductionInfo; 196} 197 198// FIXME: No way to easily map from TemplateTypeParmTypes to 199// TemplateTypeParmDecls, so we have this horrible PointerUnion. 200typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 201 SourceLocation> UnexpandedParameterPack; 202 203/// Sema - This implements semantic analysis and AST building for C. 204class Sema { 205 Sema(const Sema &) LLVM_DELETED_FUNCTION; 206 void operator=(const Sema &) LLVM_DELETED_FUNCTION; 207 mutable const TargetAttributesSema* TheTargetAttributesSema; 208 209 ///\brief Source of additional semantic information. 210 ExternalSemaSource *ExternalSource; 211 212 ///\brief Whether Sema has generated a multiplexer and has to delete it. 213 bool isMultiplexExternalSource; 214 215 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); 216 217 static bool 218 shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { 219 // We are about to link these. It is now safe to compute the linkage of 220 // the new decl. If the new decl has external linkage, we will 221 // link it with the hidden decl (which also has external linkage) and 222 // it will keep having external linkage. If it has internal linkage, we 223 // will not link it. Since it has no previous decls, it will remain 224 // with internal linkage. 225 return !Old->isHidden() || New->isExternallyVisible(); 226 } 227 228public: 229 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 230 typedef OpaquePtr<TemplateName> TemplateTy; 231 typedef OpaquePtr<QualType> TypeTy; 232 233 OpenCLOptions OpenCLFeatures; 234 FPOptions FPFeatures; 235 236 const LangOptions &LangOpts; 237 Preprocessor &PP; 238 ASTContext &Context; 239 ASTConsumer &Consumer; 240 DiagnosticsEngine &Diags; 241 SourceManager &SourceMgr; 242 243 /// \brief Flag indicating whether or not to collect detailed statistics. 244 bool CollectStats; 245 246 /// \brief Code-completion consumer. 247 CodeCompleteConsumer *CodeCompleter; 248 249 /// CurContext - This is the current declaration context of parsing. 250 DeclContext *CurContext; 251 252 /// \brief Generally null except when we temporarily switch decl contexts, 253 /// like in \see ActOnObjCTemporaryExitContainerContext. 254 DeclContext *OriginalLexicalContext; 255 256 /// VAListTagName - The declaration name corresponding to __va_list_tag. 257 /// This is used as part of a hack to omit that class from ADL results. 258 DeclarationName VAListTagName; 259 260 /// PackContext - Manages the stack for \#pragma pack. An alignment 261 /// of 0 indicates default alignment. 262 void *PackContext; // Really a "PragmaPackStack*" 263 264 bool MSStructPragmaOn; // True when \#pragma ms_struct on 265 266 /// VisContext - Manages the stack for \#pragma GCC visibility. 267 void *VisContext; // Really a "PragmaVisStack*" 268 269 /// \brief Flag indicating if Sema is building a recovery call expression. 270 /// 271 /// This flag is used to avoid building recovery call expressions 272 /// if Sema is already doing so, which would cause infinite recursions. 273 bool IsBuildingRecoveryCallExpr; 274 275 /// ExprNeedsCleanups - True if the current evaluation context 276 /// requires cleanups to be run at its conclusion. 277 bool ExprNeedsCleanups; 278 279 /// ExprCleanupObjects - This is the stack of objects requiring 280 /// cleanup that are created by the current full expression. The 281 /// element type here is ExprWithCleanups::Object. 282 SmallVector<BlockDecl*, 8> ExprCleanupObjects; 283 284 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs; 285 286 /// \brief Stack containing information about each of the nested 287 /// function, block, and method scopes that are currently active. 288 /// 289 /// This array is never empty. Clients should ignore the first 290 /// element, which is used to cache a single FunctionScopeInfo 291 /// that's used to parse every top-level function. 292 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 293 294 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 295 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 296 ExtVectorDeclsType; 297 298 /// ExtVectorDecls - This is a list all the extended vector types. This allows 299 /// us to associate a raw vector type with one of the ext_vector type names. 300 /// This is only necessary for issuing pretty diagnostics. 301 ExtVectorDeclsType ExtVectorDecls; 302 303 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 304 OwningPtr<CXXFieldCollector> FieldCollector; 305 306 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType; 307 308 /// \brief Set containing all declared private fields that are not used. 309 NamedDeclSetType UnusedPrivateFields; 310 311 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 312 313 /// PureVirtualClassDiagSet - a set of class declarations which we have 314 /// emitted a list of pure virtual functions. Used to prevent emitting the 315 /// same list more than once. 316 OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet; 317 318 /// ParsingInitForAutoVars - a set of declarations with auto types for which 319 /// we are currently parsing the initializer. 320 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 321 322 /// \brief A mapping from external names to the most recent 323 /// locally-scoped extern "C" declaration with that name. 324 /// 325 /// This map contains external declarations introduced in local 326 /// scopes, e.g., 327 /// 328 /// \code 329 /// extern "C" void f() { 330 /// void foo(int, int); 331 /// } 332 /// \endcode 333 /// 334 /// Here, the name "foo" will be associated with the declaration of 335 /// "foo" within f. This name is not visible outside of 336 /// "f". However, we still find it in two cases: 337 /// 338 /// - If we are declaring another global or extern "C" entity with 339 /// the name "foo", we can find "foo" as a previous declaration, 340 /// so that the types of this external declaration can be checked 341 /// for compatibility. 342 /// 343 /// - If we would implicitly declare "foo" (e.g., due to a call to 344 /// "foo" in C when no prototype or definition is visible), then 345 /// we find this declaration of "foo" and complain that it is 346 /// not visible. 347 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls; 348 349 /// \brief Look for a locally scoped extern "C" declaration by the given name. 350 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 351 352 typedef LazyVector<VarDecl *, ExternalSemaSource, 353 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 354 TentativeDefinitionsType; 355 356 /// \brief All the tentative definitions encountered in the TU. 357 TentativeDefinitionsType TentativeDefinitions; 358 359 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 360 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 361 UnusedFileScopedDeclsType; 362 363 /// \brief The set of file scoped decls seen so far that have not been used 364 /// and must warn if not used. Only contains the first declaration. 365 UnusedFileScopedDeclsType UnusedFileScopedDecls; 366 367 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 368 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 369 DelegatingCtorDeclsType; 370 371 /// \brief All the delegating constructors seen so far in the file, used for 372 /// cycle detection at the end of the TU. 373 DelegatingCtorDeclsType DelegatingCtorDecls; 374 375 /// \brief All the destructors seen during a class definition that had their 376 /// exception spec computation delayed because it depended on an unparsed 377 /// exception spec. 378 SmallVector<CXXDestructorDecl*, 2> DelayedDestructorExceptionSpecs; 379 380 /// \brief All the overriding destructors seen during a class definition 381 /// (there could be multiple due to nested classes) that had their exception 382 /// spec checks delayed, plus the overridden destructor. 383 SmallVector<std::pair<const CXXDestructorDecl*, 384 const CXXDestructorDecl*>, 2> 385 DelayedDestructorExceptionSpecChecks; 386 387 /// \brief All the members seen during a class definition which were both 388 /// explicitly defaulted and had explicitly-specified exception 389 /// specifications, along with the function type containing their 390 /// user-specified exception specification. Those exception specifications 391 /// were overridden with the default specifications, but we still need to 392 /// check whether they are compatible with the default specification, and 393 /// we can't do that until the nesting set of class definitions is complete. 394 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2> 395 DelayedDefaultedMemberExceptionSpecs; 396 397 typedef llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> 398 LateParsedTemplateMapT; 399 LateParsedTemplateMapT LateParsedTemplateMap; 400 401 /// \brief Callback to the parser to parse templated functions when needed. 402 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 403 LateTemplateParserCB *LateTemplateParser; 404 void *OpaqueParser; 405 406 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) { 407 LateTemplateParser = LTP; 408 OpaqueParser = P; 409 } 410 411 class DelayedDiagnostics; 412 413 class DelayedDiagnosticsState { 414 sema::DelayedDiagnosticPool *SavedPool; 415 friend class Sema::DelayedDiagnostics; 416 }; 417 typedef DelayedDiagnosticsState ParsingDeclState; 418 typedef DelayedDiagnosticsState ProcessingContextState; 419 420 /// A class which encapsulates the logic for delaying diagnostics 421 /// during parsing and other processing. 422 class DelayedDiagnostics { 423 /// \brief The current pool of diagnostics into which delayed 424 /// diagnostics should go. 425 sema::DelayedDiagnosticPool *CurPool; 426 427 public: 428 DelayedDiagnostics() : CurPool(0) {} 429 430 /// Adds a delayed diagnostic. 431 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 432 433 /// Determines whether diagnostics should be delayed. 434 bool shouldDelayDiagnostics() { return CurPool != 0; } 435 436 /// Returns the current delayed-diagnostics pool. 437 sema::DelayedDiagnosticPool *getCurrentPool() const { 438 return CurPool; 439 } 440 441 /// Enter a new scope. Access and deprecation diagnostics will be 442 /// collected in this pool. 443 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 444 DelayedDiagnosticsState state; 445 state.SavedPool = CurPool; 446 CurPool = &pool; 447 return state; 448 } 449 450 /// Leave a delayed-diagnostic state that was previously pushed. 451 /// Do not emit any of the diagnostics. This is performed as part 452 /// of the bookkeeping of popping a pool "properly". 453 void popWithoutEmitting(DelayedDiagnosticsState state) { 454 CurPool = state.SavedPool; 455 } 456 457 /// Enter a new scope where access and deprecation diagnostics are 458 /// not delayed. 459 DelayedDiagnosticsState pushUndelayed() { 460 DelayedDiagnosticsState state; 461 state.SavedPool = CurPool; 462 CurPool = 0; 463 return state; 464 } 465 466 /// Undo a previous pushUndelayed(). 467 void popUndelayed(DelayedDiagnosticsState state) { 468 assert(CurPool == NULL); 469 CurPool = state.SavedPool; 470 } 471 } DelayedDiagnostics; 472 473 /// A RAII object to temporarily push a declaration context. 474 class ContextRAII { 475 private: 476 Sema &S; 477 DeclContext *SavedContext; 478 ProcessingContextState SavedContextState; 479 QualType SavedCXXThisTypeOverride; 480 481 public: 482 ContextRAII(Sema &S, DeclContext *ContextToPush) 483 : S(S), SavedContext(S.CurContext), 484 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 485 SavedCXXThisTypeOverride(S.CXXThisTypeOverride) 486 { 487 assert(ContextToPush && "pushing null context"); 488 S.CurContext = ContextToPush; 489 } 490 491 void pop() { 492 if (!SavedContext) return; 493 S.CurContext = SavedContext; 494 S.DelayedDiagnostics.popUndelayed(SavedContextState); 495 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 496 SavedContext = 0; 497 } 498 499 ~ContextRAII() { 500 pop(); 501 } 502 }; 503 504 /// \brief RAII object to handle the state changes required to synthesize 505 /// a function body. 506 class SynthesizedFunctionScope { 507 Sema &S; 508 Sema::ContextRAII SavedContext; 509 510 public: 511 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 512 : S(S), SavedContext(S, DC) 513 { 514 S.PushFunctionScope(); 515 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 516 } 517 518 ~SynthesizedFunctionScope() { 519 S.PopExpressionEvaluationContext(); 520 S.PopFunctionScopeInfo(); 521 } 522 }; 523 524 /// WeakUndeclaredIdentifiers - Identifiers contained in 525 /// \#pragma weak before declared. rare. may alias another 526 /// identifier, declared or undeclared 527 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers; 528 529 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 530 /// \#pragma redefine_extname before declared. Used in Solaris system headers 531 /// to define functions that occur in multiple standards to call the version 532 /// in the currently selected standard. 533 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 534 535 536 /// \brief Load weak undeclared identifiers from the external source. 537 void LoadExternalWeakUndeclaredIdentifiers(); 538 539 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 540 /// \#pragma weak during processing of other Decls. 541 /// I couldn't figure out a clean way to generate these in-line, so 542 /// we store them here and handle separately -- which is a hack. 543 /// It would be best to refactor this. 544 SmallVector<Decl*,2> WeakTopLevelDecl; 545 546 IdentifierResolver IdResolver; 547 548 /// Translation Unit Scope - useful to Objective-C actions that need 549 /// to lookup file scope declarations in the "ordinary" C decl namespace. 550 /// For example, user-defined classes, built-in "id" type, etc. 551 Scope *TUScope; 552 553 /// \brief The C++ "std" namespace, where the standard library resides. 554 LazyDeclPtr StdNamespace; 555 556 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ 557 /// standard library. 558 LazyDeclPtr StdBadAlloc; 559 560 /// \brief The C++ "std::initializer_list" template, which is defined in 561 /// \<initializer_list>. 562 ClassTemplateDecl *StdInitializerList; 563 564 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>. 565 RecordDecl *CXXTypeInfoDecl; 566 567 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. 568 RecordDecl *MSVCGuidDecl; 569 570 /// \brief Caches identifiers/selectors for NSFoundation APIs. 571 OwningPtr<NSAPI> NSAPIObj; 572 573 /// \brief The declaration of the Objective-C NSNumber class. 574 ObjCInterfaceDecl *NSNumberDecl; 575 576 /// \brief Pointer to NSNumber type (NSNumber *). 577 QualType NSNumberPointer; 578 579 /// \brief The Objective-C NSNumber methods used to create NSNumber literals. 580 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 581 582 /// \brief The declaration of the Objective-C NSString class. 583 ObjCInterfaceDecl *NSStringDecl; 584 585 /// \brief Pointer to NSString type (NSString *). 586 QualType NSStringPointer; 587 588 /// \brief The declaration of the stringWithUTF8String: method. 589 ObjCMethodDecl *StringWithUTF8StringMethod; 590 591 /// \brief The declaration of the Objective-C NSArray class. 592 ObjCInterfaceDecl *NSArrayDecl; 593 594 /// \brief The declaration of the arrayWithObjects:count: method. 595 ObjCMethodDecl *ArrayWithObjectsMethod; 596 597 /// \brief The declaration of the Objective-C NSDictionary class. 598 ObjCInterfaceDecl *NSDictionaryDecl; 599 600 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method. 601 ObjCMethodDecl *DictionaryWithObjectsMethod; 602 603 /// \brief id<NSCopying> type. 604 QualType QIDNSCopying; 605 606 /// \brief will hold 'respondsToSelector:' 607 Selector RespondsToSelectorSel; 608 609 /// A flag to remember whether the implicit forms of operator new and delete 610 /// have been declared. 611 bool GlobalNewDeleteDeclared; 612 613 /// A flag to indicate that we're in a context that permits abstract 614 /// references to fields. This is really a 615 bool AllowAbstractFieldReference; 616 617 /// \brief Describes how the expressions currently being parsed are 618 /// evaluated at run-time, if at all. 619 enum ExpressionEvaluationContext { 620 /// \brief The current expression and its subexpressions occur within an 621 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 622 /// \c sizeof, where the type of the expression may be significant but 623 /// no code will be generated to evaluate the value of the expression at 624 /// run time. 625 Unevaluated, 626 627 /// \brief The current expression occurs within an unevaluated 628 /// operand that unconditionally permits abstract references to 629 /// fields, such as a SIZE operator in MS-style inline assembly. 630 UnevaluatedAbstract, 631 632 /// \brief The current context is "potentially evaluated" in C++11 terms, 633 /// but the expression is evaluated at compile-time (like the values of 634 /// cases in a switch statment). 635 ConstantEvaluated, 636 637 /// \brief The current expression is potentially evaluated at run time, 638 /// which means that code may be generated to evaluate the value of the 639 /// expression at run time. 640 PotentiallyEvaluated, 641 642 /// \brief The current expression is potentially evaluated, but any 643 /// declarations referenced inside that expression are only used if 644 /// in fact the current expression is used. 645 /// 646 /// This value is used when parsing default function arguments, for which 647 /// we would like to provide diagnostics (e.g., passing non-POD arguments 648 /// through varargs) but do not want to mark declarations as "referenced" 649 /// until the default argument is used. 650 PotentiallyEvaluatedIfUsed 651 }; 652 653 /// \brief Data structure used to record current or nested 654 /// expression evaluation contexts. 655 struct ExpressionEvaluationContextRecord { 656 /// \brief The expression evaluation context. 657 ExpressionEvaluationContext Context; 658 659 /// \brief Whether the enclosing context needed a cleanup. 660 bool ParentNeedsCleanups; 661 662 /// \brief Whether we are in a decltype expression. 663 bool IsDecltype; 664 665 /// \brief The number of active cleanup objects when we entered 666 /// this expression evaluation context. 667 unsigned NumCleanupObjects; 668 669 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs; 670 671 /// \brief The lambdas that are present within this context, if it 672 /// is indeed an unevaluated context. 673 SmallVector<LambdaExpr *, 2> Lambdas; 674 675 /// \brief The declaration that provides context for lambda expressions 676 /// and block literals if the normal declaration context does not 677 /// suffice, e.g., in a default function argument. 678 Decl *ManglingContextDecl; 679 680 /// \brief The context information used to mangle lambda expressions 681 /// and block literals within this context. 682 /// 683 /// This mangling information is allocated lazily, since most contexts 684 /// do not have lambda expressions or block literals. 685 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering; 686 687 /// \brief If we are processing a decltype type, a set of call expressions 688 /// for which we have deferred checking the completeness of the return type. 689 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 690 691 /// \brief If we are processing a decltype type, a set of temporary binding 692 /// expressions for which we have deferred checking the destructor. 693 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 694 695 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 696 unsigned NumCleanupObjects, 697 bool ParentNeedsCleanups, 698 Decl *ManglingContextDecl, 699 bool IsDecltype) 700 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups), 701 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects), 702 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { } 703 704 /// \brief Retrieve the mangling numbering context, used to consistently 705 /// number constructs like lambdas for mangling. 706 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); 707 708 bool isUnevaluated() const { 709 return Context == Unevaluated || Context == UnevaluatedAbstract; 710 } 711 }; 712 713 /// A stack of expression evaluation contexts. 714 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 715 716 /// \brief Compute the mangling number context for a lambda expression or 717 /// block literal. 718 /// 719 /// \param DC - The DeclContext containing the lambda expression or 720 /// block literal. 721 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl 722 /// associated with the context, if relevant. 723 MangleNumberingContext *getCurrentMangleNumberContext( 724 const DeclContext *DC, 725 Decl *&ManglingContextDecl); 726 727 728 /// SpecialMemberOverloadResult - The overloading result for a special member 729 /// function. 730 /// 731 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 732 /// integer are used to determine whether overload resolution succeeded. 733 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode { 734 public: 735 enum Kind { 736 NoMemberOrDeleted, 737 Ambiguous, 738 Success 739 }; 740 741 private: 742 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 743 744 public: 745 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID) 746 : FastFoldingSetNode(ID) 747 {} 748 749 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } 750 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 751 752 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } 753 void setKind(Kind K) { Pair.setInt(K); } 754 }; 755 756 /// \brief A cache of special member function overload resolution results 757 /// for C++ records. 758 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache; 759 760 /// \brief The kind of translation unit we are processing. 761 /// 762 /// When we're processing a complete translation unit, Sema will perform 763 /// end-of-translation-unit semantic tasks (such as creating 764 /// initializers for tentative definitions in C) once parsing has 765 /// completed. Modules and precompiled headers perform different kinds of 766 /// checks. 767 TranslationUnitKind TUKind; 768 769 llvm::BumpPtrAllocator BumpAlloc; 770 771 /// \brief The number of SFINAE diagnostics that have been trapped. 772 unsigned NumSFINAEErrors; 773 774 typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> > 775 UnparsedDefaultArgInstantiationsMap; 776 777 /// \brief A mapping from parameters with unparsed default arguments to the 778 /// set of instantiations of each parameter. 779 /// 780 /// This mapping is a temporary data structure used when parsing 781 /// nested class templates or nested classes of class templates, 782 /// where we might end up instantiating an inner class before the 783 /// default arguments of its methods have been parsed. 784 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 785 786 // Contains the locations of the beginning of unparsed default 787 // argument locations. 788 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 789 790 /// UndefinedInternals - all the used, undefined objects which require a 791 /// definition in this translation unit. 792 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed; 793 794 /// Obtain a sorted list of functions that are undefined but ODR-used. 795 void getUndefinedButUsed( 796 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 797 798 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 799 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 800 801 /// Method Pool - allows efficient lookup when typechecking messages to "id". 802 /// We need to maintain a list, since selectors can have differing signatures 803 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 804 /// of selectors are "overloaded"). 805 /// At the head of the list it is recorded whether there were 0, 1, or >= 2 806 /// methods inside categories with a particular selector. 807 GlobalMethodPool MethodPool; 808 809 /// Method selectors used in a \@selector expression. Used for implementation 810 /// of -Wselector. 811 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors; 812 813 /// Kinds of C++ special members. 814 enum CXXSpecialMember { 815 CXXDefaultConstructor, 816 CXXCopyConstructor, 817 CXXMoveConstructor, 818 CXXCopyAssignment, 819 CXXMoveAssignment, 820 CXXDestructor, 821 CXXInvalid 822 }; 823 824 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl; 825 826 /// The C++ special members which we are currently in the process of 827 /// declaring. If this process recursively triggers the declaration of the 828 /// same special member, we should act as if it is not yet declared. 829 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 830 831 void ReadMethodPool(Selector Sel); 832 833 /// Private Helper predicate to check for 'self'. 834 bool isSelfExpr(Expr *RExpr); 835 836 /// \brief Cause the active diagnostic on the DiagosticsEngine to be 837 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 838 /// should not be used elsewhere. 839 void EmitCurrentDiagnostic(unsigned DiagID); 840 841 /// Records and restores the FP_CONTRACT state on entry/exit of compound 842 /// statements. 843 class FPContractStateRAII { 844 public: 845 FPContractStateRAII(Sema& S) 846 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {} 847 ~FPContractStateRAII() { 848 S.FPFeatures.fp_contract = OldFPContractState; 849 } 850 private: 851 Sema& S; 852 bool OldFPContractState : 1; 853 }; 854 855 typedef llvm::MCAsmParserSemaCallback::InlineAsmIdentifierInfo 856 InlineAsmIdentifierInfo; 857 858public: 859 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 860 TranslationUnitKind TUKind = TU_Complete, 861 CodeCompleteConsumer *CompletionConsumer = 0); 862 ~Sema(); 863 864 /// \brief Perform initialization that occurs after the parser has been 865 /// initialized but before it parses anything. 866 void Initialize(); 867 868 const LangOptions &getLangOpts() const { return LangOpts; } 869 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } 870 FPOptions &getFPOptions() { return FPFeatures; } 871 872 DiagnosticsEngine &getDiagnostics() const { return Diags; } 873 SourceManager &getSourceManager() const { return SourceMgr; } 874 const TargetAttributesSema &getTargetAttributesSema() const; 875 Preprocessor &getPreprocessor() const { return PP; } 876 ASTContext &getASTContext() const { return Context; } 877 ASTConsumer &getASTConsumer() const { return Consumer; } 878 ASTMutationListener *getASTMutationListener() const; 879 ExternalSemaSource* getExternalSource() const { return ExternalSource; } 880 881 ///\brief Registers an external source. If an external source already exists, 882 /// creates a multiplex external source and appends to it. 883 /// 884 ///\param[in] E - A non-null external sema source. 885 /// 886 void addExternalSource(ExternalSemaSource *E); 887 888 void PrintStats() const; 889 890 /// \brief Helper class that creates diagnostics with optional 891 /// template instantiation stacks. 892 /// 893 /// This class provides a wrapper around the basic DiagnosticBuilder 894 /// class that emits diagnostics. SemaDiagnosticBuilder is 895 /// responsible for emitting the diagnostic (as DiagnosticBuilder 896 /// does) and, if the diagnostic comes from inside a template 897 /// instantiation, printing the template instantiation stack as 898 /// well. 899 class SemaDiagnosticBuilder : public DiagnosticBuilder { 900 Sema &SemaRef; 901 unsigned DiagID; 902 903 public: 904 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 905 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 906 907 ~SemaDiagnosticBuilder() { 908 // If we aren't active, there is nothing to do. 909 if (!isActive()) return; 910 911 // Otherwise, we need to emit the diagnostic. First flush the underlying 912 // DiagnosticBuilder data, and clear the diagnostic builder itself so it 913 // won't emit the diagnostic in its own destructor. 914 // 915 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 916 // do its own needless checks to see if the diagnostic needs to be 917 // emitted. However, because we take care to ensure that the builder 918 // objects never escape, a sufficiently smart compiler will be able to 919 // eliminate that code. 920 FlushCounts(); 921 Clear(); 922 923 // Dispatch to Sema to emit the diagnostic. 924 SemaRef.EmitCurrentDiagnostic(DiagID); 925 } 926 927 /// Teach operator<< to produce an object of the correct type. 928 template<typename T> 929 friend const SemaDiagnosticBuilder &operator<<( 930 const SemaDiagnosticBuilder &Diag, const T &Value) { 931 const DiagnosticBuilder &BaseDiag = Diag; 932 BaseDiag << Value; 933 return Diag; 934 } 935 }; 936 937 /// \brief Emit a diagnostic. 938 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { 939 DiagnosticBuilder DB = Diags.Report(Loc, DiagID); 940 return SemaDiagnosticBuilder(DB, *this, DiagID); 941 } 942 943 /// \brief Emit a partial diagnostic. 944 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 945 946 /// \brief Build a partial diagnostic. 947 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 948 949 bool findMacroSpelling(SourceLocation &loc, StringRef name); 950 951 /// \brief Get a string to suggest for zero-initialization of a type. 952 std::string getFixItZeroInitializerForType(QualType T) const; 953 std::string getFixItZeroLiteralForType(QualType T) const; 954 955 ExprResult Owned(Expr* E) { return E; } 956 ExprResult Owned(ExprResult R) { return R; } 957 StmtResult Owned(Stmt* S) { return S; } 958 959 void ActOnEndOfTranslationUnit(); 960 961 void CheckDelegatingCtorCycles(); 962 963 Scope *getScopeForContext(DeclContext *Ctx); 964 965 void PushFunctionScope(); 966 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 967 void PushLambdaScope(CXXRecordDecl *Lambda, CXXMethodDecl *CallOperator); 968 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 969 RecordDecl *RD, 970 CapturedRegionKind K); 971 void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP =0, 972 const Decl *D = 0, const BlockExpr *blkExpr = 0); 973 974 sema::FunctionScopeInfo *getCurFunction() const { 975 return FunctionScopes.back(); 976 } 977 978 template <typename ExprT> 979 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) { 980 if (!isUnevaluatedContext()) 981 getCurFunction()->recordUseOfWeak(E, IsRead); 982 } 983 984 void PushCompoundScope(); 985 void PopCompoundScope(); 986 987 sema::CompoundScopeInfo &getCurCompoundScope() const; 988 989 bool hasAnyUnrecoverableErrorsInThisFunction() const; 990 991 /// \brief Retrieve the current block, if any. 992 sema::BlockScopeInfo *getCurBlock(); 993 994 /// \brief Retrieve the current lambda expression, if any. 995 sema::LambdaScopeInfo *getCurLambda(); 996 997 /// \brief Retrieve the current captured region, if any. 998 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 999 1000 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls 1001 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 1002 1003 void ActOnComment(SourceRange Comment); 1004 1005 //===--------------------------------------------------------------------===// 1006 // Type Analysis / Processing: SemaType.cpp. 1007 // 1008 1009 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 1010 const DeclSpec *DS = 0); 1011 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 1012 const DeclSpec *DS = 0); 1013 QualType BuildPointerType(QualType T, 1014 SourceLocation Loc, DeclarationName Entity); 1015 QualType BuildReferenceType(QualType T, bool LValueRef, 1016 SourceLocation Loc, DeclarationName Entity); 1017 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1018 Expr *ArraySize, unsigned Quals, 1019 SourceRange Brackets, DeclarationName Entity); 1020 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 1021 SourceLocation AttrLoc); 1022 1023 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 1024 1025 /// \brief Build a function type. 1026 /// 1027 /// This routine checks the function type according to C++ rules and 1028 /// under the assumption that the result type and parameter types have 1029 /// just been instantiated from a template. It therefore duplicates 1030 /// some of the behavior of GetTypeForDeclarator, but in a much 1031 /// simpler form that is only suitable for this narrow use case. 1032 /// 1033 /// \param T The return type of the function. 1034 /// 1035 /// \param ParamTypes The parameter types of the function. This array 1036 /// will be modified to account for adjustments to the types of the 1037 /// function parameters. 1038 /// 1039 /// \param Loc The location of the entity whose type involves this 1040 /// function type or, if there is no such entity, the location of the 1041 /// type that will have function type. 1042 /// 1043 /// \param Entity The name of the entity that involves the function 1044 /// type, if known. 1045 /// 1046 /// \param EPI Extra information about the function type. Usually this will 1047 /// be taken from an existing function with the same prototype. 1048 /// 1049 /// \returns A suitable function type, if there are no errors. The 1050 /// unqualified type will always be a FunctionProtoType. 1051 /// Otherwise, returns a NULL type. 1052 QualType BuildFunctionType(QualType T, 1053 llvm::MutableArrayRef<QualType> ParamTypes, 1054 SourceLocation Loc, DeclarationName Entity, 1055 const FunctionProtoType::ExtProtoInfo &EPI); 1056 1057 QualType BuildMemberPointerType(QualType T, QualType Class, 1058 SourceLocation Loc, 1059 DeclarationName Entity); 1060 QualType BuildBlockPointerType(QualType T, 1061 SourceLocation Loc, DeclarationName Entity); 1062 QualType BuildParenType(QualType T); 1063 QualType BuildAtomicType(QualType T, SourceLocation Loc); 1064 1065 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 1066 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 1067 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 1068 TypeSourceInfo *ReturnTypeInfo); 1069 1070 /// \brief Package the given type and TSI into a ParsedType. 1071 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 1072 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 1073 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 1074 static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0); 1075 CanThrowResult canThrow(const Expr *E); 1076 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 1077 const FunctionProtoType *FPT); 1078 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range); 1079 bool CheckDistantExceptionSpec(QualType T); 1080 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 1081 bool CheckEquivalentExceptionSpec( 1082 const FunctionProtoType *Old, SourceLocation OldLoc, 1083 const FunctionProtoType *New, SourceLocation NewLoc); 1084 bool CheckEquivalentExceptionSpec( 1085 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1086 const FunctionProtoType *Old, SourceLocation OldLoc, 1087 const FunctionProtoType *New, SourceLocation NewLoc, 1088 bool *MissingExceptionSpecification = 0, 1089 bool *MissingEmptyExceptionSpecification = 0, 1090 bool AllowNoexceptAllMatchWithNoSpec = false, 1091 bool IsOperatorNew = false); 1092 bool CheckExceptionSpecSubset( 1093 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1094 const FunctionProtoType *Superset, SourceLocation SuperLoc, 1095 const FunctionProtoType *Subset, SourceLocation SubLoc); 1096 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID, 1097 const FunctionProtoType *Target, SourceLocation TargetLoc, 1098 const FunctionProtoType *Source, SourceLocation SourceLoc); 1099 1100 TypeResult ActOnTypeName(Scope *S, Declarator &D); 1101 1102 /// \brief The parser has parsed the context-sensitive type 'instancetype' 1103 /// in an Objective-C message declaration. Return the appropriate type. 1104 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 1105 1106 /// \brief Abstract class used to diagnose incomplete types. 1107 struct TypeDiagnoser { 1108 bool Suppressed; 1109 1110 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { } 1111 1112 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; 1113 virtual ~TypeDiagnoser() {} 1114 }; 1115 1116 static int getPrintable(int I) { return I; } 1117 static unsigned getPrintable(unsigned I) { return I; } 1118 static bool getPrintable(bool B) { return B; } 1119 static const char * getPrintable(const char *S) { return S; } 1120 static StringRef getPrintable(StringRef S) { return S; } 1121 static const std::string &getPrintable(const std::string &S) { return S; } 1122 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 1123 return II; 1124 } 1125 static DeclarationName getPrintable(DeclarationName N) { return N; } 1126 static QualType getPrintable(QualType T) { return T; } 1127 static SourceRange getPrintable(SourceRange R) { return R; } 1128 static SourceRange getPrintable(SourceLocation L) { return L; } 1129 static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); } 1130 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 1131 1132 template<typename T1> 1133 class BoundTypeDiagnoser1 : public TypeDiagnoser { 1134 unsigned DiagID; 1135 const T1 &Arg1; 1136 1137 public: 1138 BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1) 1139 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { } 1140 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 1141 if (Suppressed) return; 1142 S.Diag(Loc, DiagID) << getPrintable(Arg1) << T; 1143 } 1144 1145 virtual ~BoundTypeDiagnoser1() { } 1146 }; 1147 1148 template<typename T1, typename T2> 1149 class BoundTypeDiagnoser2 : public TypeDiagnoser { 1150 unsigned DiagID; 1151 const T1 &Arg1; 1152 const T2 &Arg2; 1153 1154 public: 1155 BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1, 1156 const T2 &Arg2) 1157 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1), 1158 Arg2(Arg2) { } 1159 1160 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 1161 if (Suppressed) return; 1162 S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T; 1163 } 1164 1165 virtual ~BoundTypeDiagnoser2() { } 1166 }; 1167 1168 template<typename T1, typename T2, typename T3> 1169 class BoundTypeDiagnoser3 : public TypeDiagnoser { 1170 unsigned DiagID; 1171 const T1 &Arg1; 1172 const T2 &Arg2; 1173 const T3 &Arg3; 1174 1175 public: 1176 BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1, 1177 const T2 &Arg2, const T3 &Arg3) 1178 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1), 1179 Arg2(Arg2), Arg3(Arg3) { } 1180 1181 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 1182 if (Suppressed) return; 1183 S.Diag(Loc, DiagID) 1184 << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T; 1185 } 1186 1187 virtual ~BoundTypeDiagnoser3() { } 1188 }; 1189 1190private: 1191 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 1192 TypeDiagnoser &Diagnoser); 1193public: 1194 bool RequireCompleteType(SourceLocation Loc, QualType T, 1195 TypeDiagnoser &Diagnoser); 1196 bool RequireCompleteType(SourceLocation Loc, QualType T, 1197 unsigned DiagID); 1198 1199 template<typename T1> 1200 bool RequireCompleteType(SourceLocation Loc, QualType T, 1201 unsigned DiagID, const T1 &Arg1) { 1202 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1203 return RequireCompleteType(Loc, T, Diagnoser); 1204 } 1205 1206 template<typename T1, typename T2> 1207 bool RequireCompleteType(SourceLocation Loc, QualType T, 1208 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { 1209 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1210 return RequireCompleteType(Loc, T, Diagnoser); 1211 } 1212 1213 template<typename T1, typename T2, typename T3> 1214 bool RequireCompleteType(SourceLocation Loc, QualType T, 1215 unsigned DiagID, const T1 &Arg1, const T2 &Arg2, 1216 const T3 &Arg3) { 1217 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1218 Arg3); 1219 return RequireCompleteType(Loc, T, Diagnoser); 1220 } 1221 1222 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); 1223 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 1224 1225 template<typename T1> 1226 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) { 1227 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1228 return RequireCompleteExprType(E, Diagnoser); 1229 } 1230 1231 template<typename T1, typename T2> 1232 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1, 1233 const T2 &Arg2) { 1234 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1235 return RequireCompleteExprType(E, Diagnoser); 1236 } 1237 1238 template<typename T1, typename T2, typename T3> 1239 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1, 1240 const T2 &Arg2, const T3 &Arg3) { 1241 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1242 Arg3); 1243 return RequireCompleteExprType(E, Diagnoser); 1244 } 1245 1246 bool RequireLiteralType(SourceLocation Loc, QualType T, 1247 TypeDiagnoser &Diagnoser); 1248 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 1249 1250 template<typename T1> 1251 bool RequireLiteralType(SourceLocation Loc, QualType T, 1252 unsigned DiagID, const T1 &Arg1) { 1253 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1254 return RequireLiteralType(Loc, T, Diagnoser); 1255 } 1256 1257 template<typename T1, typename T2> 1258 bool RequireLiteralType(SourceLocation Loc, QualType T, 1259 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { 1260 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1261 return RequireLiteralType(Loc, T, Diagnoser); 1262 } 1263 1264 template<typename T1, typename T2, typename T3> 1265 bool RequireLiteralType(SourceLocation Loc, QualType T, 1266 unsigned DiagID, const T1 &Arg1, const T2 &Arg2, 1267 const T3 &Arg3) { 1268 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1269 Arg3); 1270 return RequireLiteralType(Loc, T, Diagnoser); 1271 } 1272 1273 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 1274 const CXXScopeSpec &SS, QualType T); 1275 1276 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 1277 QualType BuildDecltypeType(Expr *E, SourceLocation Loc); 1278 QualType BuildUnaryTransformType(QualType BaseType, 1279 UnaryTransformType::UTTKind UKind, 1280 SourceLocation Loc); 1281 1282 //===--------------------------------------------------------------------===// 1283 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 1284 // 1285 1286 /// List of decls defined in a function prototype. This contains EnumConstants 1287 /// that incorrectly end up in translation unit scope because there is no 1288 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches 1289 /// them into the FunctionDecl. 1290 std::vector<NamedDecl*> DeclsInPrototypeScope; 1291 /// Nonzero if we are currently parsing a function declarator. This is a counter 1292 /// as opposed to a boolean so we can deal with nested function declarators 1293 /// such as: 1294 /// void f(void (*g)(), ...) 1295 unsigned InFunctionDeclarator; 1296 1297 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0); 1298 1299 void DiagnoseUseOfUnimplementedSelectors(); 1300 1301 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; 1302 1303 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 1304 Scope *S, CXXScopeSpec *SS = 0, 1305 bool isClassName = false, 1306 bool HasTrailingDot = false, 1307 ParsedType ObjectType = ParsedType(), 1308 bool IsCtorOrDtorName = false, 1309 bool WantNontrivialTypeSourceInfo = false, 1310 IdentifierInfo **CorrectedII = 0); 1311 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 1312 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 1313 bool DiagnoseUnknownTypeName(IdentifierInfo *&II, 1314 SourceLocation IILoc, 1315 Scope *S, 1316 CXXScopeSpec *SS, 1317 ParsedType &SuggestedType); 1318 1319 /// \brief Describes the result of the name lookup and resolution performed 1320 /// by \c ClassifyName(). 1321 enum NameClassificationKind { 1322 NC_Unknown, 1323 NC_Error, 1324 NC_Keyword, 1325 NC_Type, 1326 NC_Expression, 1327 NC_NestedNameSpecifier, 1328 NC_TypeTemplate, 1329 NC_VarTemplate, 1330 NC_FunctionTemplate 1331 }; 1332 1333 class NameClassification { 1334 NameClassificationKind Kind; 1335 ExprResult Expr; 1336 TemplateName Template; 1337 ParsedType Type; 1338 const IdentifierInfo *Keyword; 1339 1340 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 1341 1342 public: 1343 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} 1344 1345 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 1346 1347 NameClassification(const IdentifierInfo *Keyword) 1348 : Kind(NC_Keyword), Keyword(Keyword) { } 1349 1350 static NameClassification Error() { 1351 return NameClassification(NC_Error); 1352 } 1353 1354 static NameClassification Unknown() { 1355 return NameClassification(NC_Unknown); 1356 } 1357 1358 static NameClassification NestedNameSpecifier() { 1359 return NameClassification(NC_NestedNameSpecifier); 1360 } 1361 1362 static NameClassification TypeTemplate(TemplateName Name) { 1363 NameClassification Result(NC_TypeTemplate); 1364 Result.Template = Name; 1365 return Result; 1366 } 1367 1368 static NameClassification VarTemplate(TemplateName Name) { 1369 NameClassification Result(NC_VarTemplate); 1370 Result.Template = Name; 1371 return Result; 1372 } 1373 1374 static NameClassification FunctionTemplate(TemplateName Name) { 1375 NameClassification Result(NC_FunctionTemplate); 1376 Result.Template = Name; 1377 return Result; 1378 } 1379 1380 NameClassificationKind getKind() const { return Kind; } 1381 1382 ParsedType getType() const { 1383 assert(Kind == NC_Type); 1384 return Type; 1385 } 1386 1387 ExprResult getExpression() const { 1388 assert(Kind == NC_Expression); 1389 return Expr; 1390 } 1391 1392 TemplateName getTemplateName() const { 1393 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 1394 Kind == NC_VarTemplate); 1395 return Template; 1396 } 1397 1398 TemplateNameKind getTemplateNameKind() const { 1399 switch (Kind) { 1400 case NC_TypeTemplate: 1401 return TNK_Type_template; 1402 case NC_FunctionTemplate: 1403 return TNK_Function_template; 1404 case NC_VarTemplate: 1405 return TNK_Var_template; 1406 default: 1407 llvm_unreachable("unsupported name classification."); 1408 } 1409 } 1410 }; 1411 1412 /// \brief Perform name lookup on the given name, classifying it based on 1413 /// the results of name lookup and the following token. 1414 /// 1415 /// This routine is used by the parser to resolve identifiers and help direct 1416 /// parsing. When the identifier cannot be found, this routine will attempt 1417 /// to correct the typo and classify based on the resulting name. 1418 /// 1419 /// \param S The scope in which we're performing name lookup. 1420 /// 1421 /// \param SS The nested-name-specifier that precedes the name. 1422 /// 1423 /// \param Name The identifier. If typo correction finds an alternative name, 1424 /// this pointer parameter will be updated accordingly. 1425 /// 1426 /// \param NameLoc The location of the identifier. 1427 /// 1428 /// \param NextToken The token following the identifier. Used to help 1429 /// disambiguate the name. 1430 /// 1431 /// \param IsAddressOfOperand True if this name is the operand of a unary 1432 /// address of ('&') expression, assuming it is classified as an 1433 /// expression. 1434 /// 1435 /// \param CCC The correction callback, if typo correction is desired. 1436 NameClassification ClassifyName(Scope *S, 1437 CXXScopeSpec &SS, 1438 IdentifierInfo *&Name, 1439 SourceLocation NameLoc, 1440 const Token &NextToken, 1441 bool IsAddressOfOperand, 1442 CorrectionCandidateCallback *CCC = 0); 1443 1444 Decl *ActOnDeclarator(Scope *S, Declarator &D); 1445 1446 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 1447 MultiTemplateParamsArg TemplateParameterLists); 1448 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 1449 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 1450 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 1451 DeclarationName Name, 1452 SourceLocation Loc); 1453 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 1454 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R); 1455 void CheckShadow(Scope *S, VarDecl *D); 1456 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 1457 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 1458 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1459 TypeSourceInfo *TInfo, 1460 LookupResult &Previous); 1461 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 1462 LookupResult &Previous, bool &Redeclaration); 1463 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 1464 TypeSourceInfo *TInfo, 1465 LookupResult &Previous, 1466 MultiTemplateParamsArg TemplateParamLists, 1467 bool &AddToScope); 1468 // Returns true if the variable declaration is a redeclaration 1469 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 1470 void CheckVariableDeclarationType(VarDecl *NewVD); 1471 void CheckCompleteVariableDeclaration(VarDecl *var); 1472 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 1473 void ActOnStartFunctionDeclarator(); 1474 void ActOnEndFunctionDeclarator(); 1475 1476 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1477 TypeSourceInfo *TInfo, 1478 LookupResult &Previous, 1479 MultiTemplateParamsArg TemplateParamLists, 1480 bool &AddToScope); 1481 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1482 void checkVoidParamDecl(ParmVarDecl *Param); 1483 1484 bool CheckConstexprFunctionDecl(const FunctionDecl *FD); 1485 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); 1486 1487 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 1488 void FindHiddenVirtualMethods(CXXMethodDecl *MD, 1489 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 1490 void NoteHiddenVirtualMethods(CXXMethodDecl *MD, 1491 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 1492 // Returns true if the function declaration is a redeclaration 1493 bool CheckFunctionDeclaration(Scope *S, 1494 FunctionDecl *NewFD, LookupResult &Previous, 1495 bool IsExplicitSpecialization); 1496 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 1497 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 1498 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 1499 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 1500 SourceLocation Loc, 1501 QualType T); 1502 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 1503 SourceLocation NameLoc, IdentifierInfo *Name, 1504 QualType T, TypeSourceInfo *TSInfo, 1505 StorageClass SC); 1506 void ActOnParamDefaultArgument(Decl *param, 1507 SourceLocation EqualLoc, 1508 Expr *defarg); 1509 void ActOnParamUnparsedDefaultArgument(Decl *param, 1510 SourceLocation EqualLoc, 1511 SourceLocation ArgLoc); 1512 void ActOnParamDefaultArgumentError(Decl *param); 1513 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 1514 SourceLocation EqualLoc); 1515 1516 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, 1517 bool TypeMayContainAuto); 1518 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto); 1519 void ActOnInitializerError(Decl *Dcl); 1520 void ActOnCXXForRangeDecl(Decl *D); 1521 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 1522 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 1523 void FinalizeDeclaration(Decl *D); 1524 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 1525 ArrayRef<Decl *> Group); 1526 DeclGroupPtrTy BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 1527 bool TypeMayContainAuto = true); 1528 1529 /// Should be called on all declarations that might have attached 1530 /// documentation comments. 1531 void ActOnDocumentableDecl(Decl *D); 1532 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 1533 1534 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 1535 SourceLocation LocAfterDecls); 1536 void CheckForFunctionRedefinition(FunctionDecl *FD); 1537 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D); 1538 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D); 1539 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); 1540 bool isObjCMethodDecl(Decl *D) { 1541 return D && isa<ObjCMethodDecl>(D); 1542 } 1543 1544 /// \brief Determine whether we can skip parsing the body of a function 1545 /// definition, assuming we don't care about analyzing its body or emitting 1546 /// code for that function. 1547 /// 1548 /// This will be \c false only if we may need the body of the function in 1549 /// order to parse the rest of the program (for instance, if it is 1550 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 1551 bool canSkipFunctionBody(Decl *D); 1552 1553 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 1554 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 1555 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 1556 Decl *ActOnSkippedFunctionBody(Decl *Decl); 1557 1558 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 1559 /// attribute for which parsing is delayed. 1560 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 1561 1562 /// \brief Diagnose any unused parameters in the given sequence of 1563 /// ParmVarDecl pointers. 1564 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin, 1565 ParmVarDecl * const *End); 1566 1567 /// \brief Diagnose whether the size of parameters or return value of a 1568 /// function or obj-c method definition is pass-by-value and larger than a 1569 /// specified threshold. 1570 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin, 1571 ParmVarDecl * const *End, 1572 QualType ReturnTy, 1573 NamedDecl *D); 1574 1575 void DiagnoseInvalidJumps(Stmt *Body); 1576 Decl *ActOnFileScopeAsmDecl(Expr *expr, 1577 SourceLocation AsmLoc, 1578 SourceLocation RParenLoc); 1579 1580 /// \brief Handle a C++11 empty-declaration and attribute-declaration. 1581 Decl *ActOnEmptyDeclaration(Scope *S, 1582 AttributeList *AttrList, 1583 SourceLocation SemiLoc); 1584 1585 /// \brief The parser has processed a module import declaration. 1586 /// 1587 /// \param AtLoc The location of the '@' symbol, if any. 1588 /// 1589 /// \param ImportLoc The location of the 'import' keyword. 1590 /// 1591 /// \param Path The module access path. 1592 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, 1593 ModuleIdPath Path); 1594 1595 /// \brief Create an implicit import of the given module at the given 1596 /// source location. 1597 /// 1598 /// This routine is typically used for error recovery, when the entity found 1599 /// by name lookup is actually hidden within a module that we know about but 1600 /// the user has forgotten to import. 1601 void createImplicitModuleImport(SourceLocation Loc, Module *Mod); 1602 1603 /// \brief Retrieve a suitable printing policy. 1604 PrintingPolicy getPrintingPolicy() const { 1605 return getPrintingPolicy(Context, PP); 1606 } 1607 1608 /// \brief Retrieve a suitable printing policy. 1609 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 1610 const Preprocessor &PP); 1611 1612 /// Scope actions. 1613 void ActOnPopScope(SourceLocation Loc, Scope *S); 1614 void ActOnTranslationUnitScope(Scope *S); 1615 1616 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1617 DeclSpec &DS); 1618 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1619 DeclSpec &DS, 1620 MultiTemplateParamsArg TemplateParams, 1621 bool IsExplicitInstantiation = false); 1622 1623 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1624 AccessSpecifier AS, 1625 RecordDecl *Record); 1626 1627 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 1628 RecordDecl *Record); 1629 1630 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 1631 TagTypeKind NewTag, bool isDefinition, 1632 SourceLocation NewTagLoc, 1633 const IdentifierInfo &Name); 1634 1635 enum TagUseKind { 1636 TUK_Reference, // Reference to a tag: 'struct foo *X;' 1637 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 1638 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 1639 TUK_Friend // Friend declaration: 'friend struct foo;' 1640 }; 1641 1642 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 1643 SourceLocation KWLoc, CXXScopeSpec &SS, 1644 IdentifierInfo *Name, SourceLocation NameLoc, 1645 AttributeList *Attr, AccessSpecifier AS, 1646 SourceLocation ModulePrivateLoc, 1647 MultiTemplateParamsArg TemplateParameterLists, 1648 bool &OwnedDecl, bool &IsDependent, 1649 SourceLocation ScopedEnumKWLoc, 1650 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType); 1651 1652 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 1653 unsigned TagSpec, SourceLocation TagLoc, 1654 CXXScopeSpec &SS, 1655 IdentifierInfo *Name, SourceLocation NameLoc, 1656 AttributeList *Attr, 1657 MultiTemplateParamsArg TempParamLists); 1658 1659 TypeResult ActOnDependentTag(Scope *S, 1660 unsigned TagSpec, 1661 TagUseKind TUK, 1662 const CXXScopeSpec &SS, 1663 IdentifierInfo *Name, 1664 SourceLocation TagLoc, 1665 SourceLocation NameLoc); 1666 1667 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 1668 IdentifierInfo *ClassName, 1669 SmallVectorImpl<Decl *> &Decls); 1670 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 1671 Declarator &D, Expr *BitfieldWidth); 1672 1673 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 1674 Declarator &D, Expr *BitfieldWidth, 1675 InClassInitStyle InitStyle, 1676 AccessSpecifier AS); 1677 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 1678 SourceLocation DeclStart, 1679 Declarator &D, Expr *BitfieldWidth, 1680 InClassInitStyle InitStyle, 1681 AccessSpecifier AS, 1682 AttributeList *MSPropertyAttr); 1683 1684 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 1685 TypeSourceInfo *TInfo, 1686 RecordDecl *Record, SourceLocation Loc, 1687 bool Mutable, Expr *BitfieldWidth, 1688 InClassInitStyle InitStyle, 1689 SourceLocation TSSL, 1690 AccessSpecifier AS, NamedDecl *PrevDecl, 1691 Declarator *D = 0); 1692 1693 bool CheckNontrivialField(FieldDecl *FD); 1694 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); 1695 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 1696 bool Diagnose = false); 1697 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); 1698 void ActOnLastBitfield(SourceLocation DeclStart, 1699 SmallVectorImpl<Decl *> &AllIvarDecls); 1700 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 1701 Declarator &D, Expr *BitfieldWidth, 1702 tok::ObjCKeywordKind visibility); 1703 1704 // This is used for both record definitions and ObjC interface declarations. 1705 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl, 1706 ArrayRef<Decl *> Fields, 1707 SourceLocation LBrac, SourceLocation RBrac, 1708 AttributeList *AttrList); 1709 1710 /// ActOnTagStartDefinition - Invoked when we have entered the 1711 /// scope of a tag's definition (e.g., for an enumeration, class, 1712 /// struct, or union). 1713 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 1714 1715 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 1716 1717 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 1718 /// C++ record definition's base-specifiers clause and are starting its 1719 /// member declarations. 1720 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 1721 SourceLocation FinalLoc, 1722 SourceLocation LBraceLoc); 1723 1724 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 1725 /// the definition of a tag (enumeration, class, struct, or union). 1726 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 1727 SourceLocation RBraceLoc); 1728 1729 void ActOnObjCContainerFinishDefinition(); 1730 1731 /// \brief Invoked when we must temporarily exit the objective-c container 1732 /// scope for parsing/looking-up C constructs. 1733 /// 1734 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 1735 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); 1736 void ActOnObjCReenterContainerContext(DeclContext *DC); 1737 1738 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 1739 /// error parsing the definition of a tag. 1740 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 1741 1742 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 1743 EnumConstantDecl *LastEnumConst, 1744 SourceLocation IdLoc, 1745 IdentifierInfo *Id, 1746 Expr *val); 1747 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 1748 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 1749 QualType EnumUnderlyingTy, const EnumDecl *Prev); 1750 1751 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 1752 SourceLocation IdLoc, IdentifierInfo *Id, 1753 AttributeList *Attrs, 1754 SourceLocation EqualLoc, Expr *Val); 1755 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 1756 SourceLocation RBraceLoc, Decl *EnumDecl, 1757 ArrayRef<Decl *> Elements, 1758 Scope *S, AttributeList *Attr); 1759 1760 DeclContext *getContainingDC(DeclContext *DC); 1761 1762 /// Set the current declaration context until it gets popped. 1763 void PushDeclContext(Scope *S, DeclContext *DC); 1764 void PopDeclContext(); 1765 1766 /// EnterDeclaratorContext - Used when we must lookup names in the context 1767 /// of a declarator's nested name specifier. 1768 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 1769 void ExitDeclaratorContext(Scope *S); 1770 1771 /// Push the parameters of D, which must be a function, into scope. 1772 void ActOnReenterFunctionContext(Scope* S, Decl* D); 1773 void ActOnExitFunctionContext(); 1774 1775 DeclContext *getFunctionLevelDeclContext(); 1776 1777 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1778 /// to the function decl for the function being parsed. If we're currently 1779 /// in a 'block', this returns the containing context. 1780 FunctionDecl *getCurFunctionDecl(); 1781 1782 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 1783 /// the method decl for the method being parsed. If we're currently 1784 /// in a 'block', this returns the containing context. 1785 ObjCMethodDecl *getCurMethodDecl(); 1786 1787 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 1788 /// or C function we're in, otherwise return null. If we're currently 1789 /// in a 'block', this returns the containing context. 1790 NamedDecl *getCurFunctionOrMethodDecl(); 1791 1792 /// Add this decl to the scope shadowed decl chains. 1793 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 1794 1795 /// \brief Make the given externally-produced declaration visible at the 1796 /// top level scope. 1797 /// 1798 /// \param D The externally-produced declaration to push. 1799 /// 1800 /// \param Name The name of the externally-produced declaration. 1801 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); 1802 1803 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 1804 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 1805 /// true if 'D' belongs to the given declaration context. 1806 /// 1807 /// \param ExplicitInstantiationOrSpecialization When true, we are checking 1808 /// whether the declaration is in scope for the purposes of explicit template 1809 /// instantiation or specialization. The default is false. 1810 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = 0, 1811 bool ExplicitInstantiationOrSpecialization = false); 1812 1813 /// Finds the scope corresponding to the given decl context, if it 1814 /// happens to be an enclosing scope. Otherwise return NULL. 1815 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 1816 1817 /// Subroutines of ActOnDeclarator(). 1818 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1819 TypeSourceInfo *TInfo); 1820 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 1821 1822 /// Attribute merging methods. Return true if a new attribute was added. 1823 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 1824 IdentifierInfo *Platform, 1825 VersionTuple Introduced, 1826 VersionTuple Deprecated, 1827 VersionTuple Obsoleted, 1828 bool IsUnavailable, 1829 StringRef Message, 1830 bool Override, 1831 unsigned AttrSpellingListIndex); 1832 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 1833 TypeVisibilityAttr::VisibilityType Vis, 1834 unsigned AttrSpellingListIndex); 1835 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, 1836 VisibilityAttr::VisibilityType Vis, 1837 unsigned AttrSpellingListIndex); 1838 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, 1839 unsigned AttrSpellingListIndex); 1840 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, 1841 unsigned AttrSpellingListIndex); 1842 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, 1843 IdentifierInfo *Format, int FormatIdx, 1844 int FirstArg, unsigned AttrSpellingListIndex); 1845 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, 1846 unsigned AttrSpellingListIndex); 1847 1848 /// \brief Describes the kind of merge to perform for availability 1849 /// attributes (including "deprecated", "unavailable", and "availability"). 1850 enum AvailabilityMergeKind { 1851 /// \brief Don't merge availability attributes at all. 1852 AMK_None, 1853 /// \brief Merge availability attributes for a redeclaration, which requires 1854 /// an exact match. 1855 AMK_Redeclaration, 1856 /// \brief Merge availability attributes for an override, which requires 1857 /// an exact match or a weakening of constraints. 1858 AMK_Override 1859 }; 1860 1861 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 1862 AvailabilityMergeKind AMK = AMK_Redeclaration); 1863 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 1864 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S, 1865 bool MergeTypeWithOld); 1866 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 1867 Scope *S, bool MergeTypeWithOld); 1868 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 1869 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 1870 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 1871 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 1872 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 1873 1874 // AssignmentAction - This is used by all the assignment diagnostic functions 1875 // to represent what is actually causing the operation 1876 enum AssignmentAction { 1877 AA_Assigning, 1878 AA_Passing, 1879 AA_Returning, 1880 AA_Converting, 1881 AA_Initializing, 1882 AA_Sending, 1883 AA_Casting, 1884 AA_Passing_CFAudited 1885 }; 1886 1887 /// C++ Overloading. 1888 enum OverloadKind { 1889 /// This is a legitimate overload: the existing declarations are 1890 /// functions or function templates with different signatures. 1891 Ovl_Overload, 1892 1893 /// This is not an overload because the signature exactly matches 1894 /// an existing declaration. 1895 Ovl_Match, 1896 1897 /// This is not an overload because the lookup results contain a 1898 /// non-function. 1899 Ovl_NonFunction 1900 }; 1901 OverloadKind CheckOverload(Scope *S, 1902 FunctionDecl *New, 1903 const LookupResult &OldDecls, 1904 NamedDecl *&OldDecl, 1905 bool IsForUsingDecl); 1906 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 1907 1908 /// \brief Checks availability of the function depending on the current 1909 /// function context.Inside an unavailable function,unavailability is ignored. 1910 /// 1911 /// \returns true if \p FD is unavailable and current context is inside 1912 /// an available function, false otherwise. 1913 bool isFunctionConsideredUnavailable(FunctionDecl *FD); 1914 1915 ImplicitConversionSequence 1916 TryImplicitConversion(Expr *From, QualType ToType, 1917 bool SuppressUserConversions, 1918 bool AllowExplicit, 1919 bool InOverloadResolution, 1920 bool CStyle, 1921 bool AllowObjCWritebackConversion); 1922 1923 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 1924 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 1925 bool IsComplexPromotion(QualType FromType, QualType ToType); 1926 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1927 bool InOverloadResolution, 1928 QualType& ConvertedType, bool &IncompatibleObjC); 1929 bool isObjCPointerConversion(QualType FromType, QualType ToType, 1930 QualType& ConvertedType, bool &IncompatibleObjC); 1931 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 1932 QualType &ConvertedType); 1933 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 1934 QualType& ConvertedType); 1935 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 1936 const FunctionProtoType *NewType, 1937 unsigned *ArgPos = 0); 1938 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 1939 QualType FromType, QualType ToType); 1940 1941 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 1942 bool CheckPointerConversion(Expr *From, QualType ToType, 1943 CastKind &Kind, 1944 CXXCastPath& BasePath, 1945 bool IgnoreBaseAccess); 1946 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 1947 bool InOverloadResolution, 1948 QualType &ConvertedType); 1949 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 1950 CastKind &Kind, 1951 CXXCastPath &BasePath, 1952 bool IgnoreBaseAccess); 1953 bool IsQualificationConversion(QualType FromType, QualType ToType, 1954 bool CStyle, bool &ObjCLifetimeConversion); 1955 bool IsNoReturnConversion(QualType FromType, QualType ToType, 1956 QualType &ResultTy); 1957 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 1958 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); 1959 1960 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1961 const VarDecl *NRVOCandidate, 1962 QualType ResultType, 1963 Expr *Value, 1964 bool AllowNRVO = true); 1965 1966 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 1967 ExprResult Init); 1968 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 1969 SourceLocation EqualLoc, 1970 ExprResult Init, 1971 bool TopLevelOfInitList = false, 1972 bool AllowExplicit = false); 1973 ExprResult PerformObjectArgumentInitialization(Expr *From, 1974 NestedNameSpecifier *Qualifier, 1975 NamedDecl *FoundDecl, 1976 CXXMethodDecl *Method); 1977 1978 ExprResult PerformContextuallyConvertToBool(Expr *From); 1979 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 1980 1981 /// Contexts in which a converted constant expression is required. 1982 enum CCEKind { 1983 CCEK_CaseValue, ///< Expression in a case label. 1984 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 1985 CCEK_TemplateArg, ///< Value of a non-type template parameter. 1986 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator. 1987 }; 1988 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 1989 llvm::APSInt &Value, CCEKind CCE); 1990 1991 /// \brief Abstract base class used to perform a contextual implicit 1992 /// conversion from an expression to any type passing a filter. 1993 class ContextualImplicitConverter { 1994 public: 1995 bool Suppress; 1996 bool SuppressConversion; 1997 1998 ContextualImplicitConverter(bool Suppress = false, 1999 bool SuppressConversion = false) 2000 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 2001 2002 /// \brief Determine whether the specified type is a valid destination type 2003 /// for this conversion. 2004 virtual bool match(QualType T) = 0; 2005 2006 /// \brief Emits a diagnostic complaining that the expression does not have 2007 /// integral or enumeration type. 2008 virtual SemaDiagnosticBuilder 2009 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; 2010 2011 /// \brief Emits a diagnostic when the expression has incomplete class type. 2012 virtual SemaDiagnosticBuilder 2013 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 2014 2015 /// \brief Emits a diagnostic when the only matching conversion function 2016 /// is explicit. 2017 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 2018 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 2019 2020 /// \brief Emits a note for the explicit conversion function. 2021 virtual SemaDiagnosticBuilder 2022 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 2023 2024 /// \brief Emits a diagnostic when there are multiple possible conversion 2025 /// functions. 2026 virtual SemaDiagnosticBuilder 2027 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; 2028 2029 /// \brief Emits a note for one of the candidate conversions. 2030 virtual SemaDiagnosticBuilder 2031 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 2032 2033 /// \brief Emits a diagnostic when we picked a conversion function 2034 /// (for cases when we are not allowed to pick a conversion function). 2035 virtual SemaDiagnosticBuilder diagnoseConversion( 2036 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 2037 2038 virtual ~ContextualImplicitConverter() {} 2039 }; 2040 2041 class ICEConvertDiagnoser : public ContextualImplicitConverter { 2042 bool AllowScopedEnumerations; 2043 2044 public: 2045 ICEConvertDiagnoser(bool AllowScopedEnumerations, 2046 bool Suppress, bool SuppressConversion) 2047 : ContextualImplicitConverter(Suppress, SuppressConversion), 2048 AllowScopedEnumerations(AllowScopedEnumerations) {} 2049 2050 /// Match an integral or (possibly scoped) enumeration type. 2051 bool match(QualType T); 2052 2053 SemaDiagnosticBuilder 2054 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) { 2055 return diagnoseNotInt(S, Loc, T); 2056 } 2057 2058 /// \brief Emits a diagnostic complaining that the expression does not have 2059 /// integral or enumeration type. 2060 virtual SemaDiagnosticBuilder 2061 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; 2062 }; 2063 2064 /// Perform a contextual implicit conversion. 2065 ExprResult PerformContextualImplicitConversion( 2066 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); 2067 2068 2069 enum ObjCSubscriptKind { 2070 OS_Array, 2071 OS_Dictionary, 2072 OS_Error 2073 }; 2074 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 2075 2076 // Note that LK_String is intentionally after the other literals, as 2077 // this is used for diagnostics logic. 2078 enum ObjCLiteralKind { 2079 LK_Array, 2080 LK_Dictionary, 2081 LK_Numeric, 2082 LK_Boxed, 2083 LK_String, 2084 LK_Block, 2085 LK_None 2086 }; 2087 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 2088 2089 ExprResult PerformObjectMemberConversion(Expr *From, 2090 NestedNameSpecifier *Qualifier, 2091 NamedDecl *FoundDecl, 2092 NamedDecl *Member); 2093 2094 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 2095 // TODO: make this is a typesafe union. 2096 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 2097 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 2098 2099 void AddOverloadCandidate(FunctionDecl *Function, 2100 DeclAccessPair FoundDecl, 2101 ArrayRef<Expr *> Args, 2102 OverloadCandidateSet& CandidateSet, 2103 bool SuppressUserConversions = false, 2104 bool PartialOverloading = false, 2105 bool AllowExplicit = false); 2106 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 2107 ArrayRef<Expr *> Args, 2108 OverloadCandidateSet& CandidateSet, 2109 bool SuppressUserConversions = false, 2110 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 2111 void AddMethodCandidate(DeclAccessPair FoundDecl, 2112 QualType ObjectType, 2113 Expr::Classification ObjectClassification, 2114 ArrayRef<Expr *> Args, 2115 OverloadCandidateSet& CandidateSet, 2116 bool SuppressUserConversion = false); 2117 void AddMethodCandidate(CXXMethodDecl *Method, 2118 DeclAccessPair FoundDecl, 2119 CXXRecordDecl *ActingContext, QualType ObjectType, 2120 Expr::Classification ObjectClassification, 2121 ArrayRef<Expr *> Args, 2122 OverloadCandidateSet& CandidateSet, 2123 bool SuppressUserConversions = false); 2124 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 2125 DeclAccessPair FoundDecl, 2126 CXXRecordDecl *ActingContext, 2127 TemplateArgumentListInfo *ExplicitTemplateArgs, 2128 QualType ObjectType, 2129 Expr::Classification ObjectClassification, 2130 ArrayRef<Expr *> Args, 2131 OverloadCandidateSet& CandidateSet, 2132 bool SuppressUserConversions = false); 2133 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 2134 DeclAccessPair FoundDecl, 2135 TemplateArgumentListInfo *ExplicitTemplateArgs, 2136 ArrayRef<Expr *> Args, 2137 OverloadCandidateSet& CandidateSet, 2138 bool SuppressUserConversions = false); 2139 void AddConversionCandidate(CXXConversionDecl *Conversion, 2140 DeclAccessPair FoundDecl, 2141 CXXRecordDecl *ActingContext, 2142 Expr *From, QualType ToType, 2143 OverloadCandidateSet& CandidateSet); 2144 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 2145 DeclAccessPair FoundDecl, 2146 CXXRecordDecl *ActingContext, 2147 Expr *From, QualType ToType, 2148 OverloadCandidateSet &CandidateSet); 2149 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 2150 DeclAccessPair FoundDecl, 2151 CXXRecordDecl *ActingContext, 2152 const FunctionProtoType *Proto, 2153 Expr *Object, ArrayRef<Expr *> Args, 2154 OverloadCandidateSet& CandidateSet); 2155 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 2156 SourceLocation OpLoc, ArrayRef<Expr *> Args, 2157 OverloadCandidateSet& CandidateSet, 2158 SourceRange OpRange = SourceRange()); 2159 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 2160 ArrayRef<Expr *> Args, 2161 OverloadCandidateSet& CandidateSet, 2162 bool IsAssignmentOperator = false, 2163 unsigned NumContextualBoolArguments = 0); 2164 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 2165 SourceLocation OpLoc, ArrayRef<Expr *> Args, 2166 OverloadCandidateSet& CandidateSet); 2167 void AddArgumentDependentLookupCandidates(DeclarationName Name, 2168 bool Operator, SourceLocation Loc, 2169 ArrayRef<Expr *> Args, 2170 TemplateArgumentListInfo *ExplicitTemplateArgs, 2171 OverloadCandidateSet& CandidateSet, 2172 bool PartialOverloading = false); 2173 2174 // Emit as a 'note' the specific overload candidate 2175 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType()); 2176 2177 // Emit as a series of 'note's all template and non-templates 2178 // identified by the expression Expr 2179 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType()); 2180 2181 // [PossiblyAFunctionType] --> [Return] 2182 // NonFunctionType --> NonFunctionType 2183 // R (A) --> R(A) 2184 // R (*)(A) --> R (A) 2185 // R (&)(A) --> R (A) 2186 // R (S::*)(A) --> R (A) 2187 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 2188 2189 FunctionDecl * 2190 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 2191 QualType TargetType, 2192 bool Complain, 2193 DeclAccessPair &Found, 2194 bool *pHadMultipleCandidates = 0); 2195 2196 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 2197 bool Complain = false, 2198 DeclAccessPair* Found = 0); 2199 2200 bool ResolveAndFixSingleFunctionTemplateSpecialization( 2201 ExprResult &SrcExpr, 2202 bool DoFunctionPointerConverion = false, 2203 bool Complain = false, 2204 const SourceRange& OpRangeForComplaining = SourceRange(), 2205 QualType DestTypeForComplaining = QualType(), 2206 unsigned DiagIDForComplaining = 0); 2207 2208 2209 Expr *FixOverloadedFunctionReference(Expr *E, 2210 DeclAccessPair FoundDecl, 2211 FunctionDecl *Fn); 2212 ExprResult FixOverloadedFunctionReference(ExprResult, 2213 DeclAccessPair FoundDecl, 2214 FunctionDecl *Fn); 2215 2216 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 2217 ArrayRef<Expr *> Args, 2218 OverloadCandidateSet &CandidateSet, 2219 bool PartialOverloading = false); 2220 2221 // An enum used to represent the different possible results of building a 2222 // range-based for loop. 2223 enum ForRangeStatus { 2224 FRS_Success, 2225 FRS_NoViableFunction, 2226 FRS_DiagnosticIssued 2227 }; 2228 2229 // An enum to represent whether something is dealing with a call to begin() 2230 // or a call to end() in a range-based for loop. 2231 enum BeginEndFunction { 2232 BEF_begin, 2233 BEF_end 2234 }; 2235 2236 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 2237 SourceLocation RangeLoc, 2238 VarDecl *Decl, 2239 BeginEndFunction BEF, 2240 const DeclarationNameInfo &NameInfo, 2241 LookupResult &MemberLookup, 2242 OverloadCandidateSet *CandidateSet, 2243 Expr *Range, ExprResult *CallExpr); 2244 2245 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 2246 UnresolvedLookupExpr *ULE, 2247 SourceLocation LParenLoc, 2248 MultiExprArg Args, 2249 SourceLocation RParenLoc, 2250 Expr *ExecConfig, 2251 bool AllowTypoCorrection=true); 2252 2253 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 2254 MultiExprArg Args, SourceLocation RParenLoc, 2255 OverloadCandidateSet *CandidateSet, 2256 ExprResult *Result); 2257 2258 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 2259 unsigned Opc, 2260 const UnresolvedSetImpl &Fns, 2261 Expr *input); 2262 2263 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 2264 unsigned Opc, 2265 const UnresolvedSetImpl &Fns, 2266 Expr *LHS, Expr *RHS); 2267 2268 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 2269 SourceLocation RLoc, 2270 Expr *Base,Expr *Idx); 2271 2272 ExprResult 2273 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 2274 SourceLocation LParenLoc, 2275 MultiExprArg Args, 2276 SourceLocation RParenLoc); 2277 ExprResult 2278 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 2279 MultiExprArg Args, 2280 SourceLocation RParenLoc); 2281 2282 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 2283 SourceLocation OpLoc, 2284 bool *NoArrowOperatorFound = 0); 2285 2286 /// CheckCallReturnType - Checks that a call expression's return type is 2287 /// complete. Returns true on failure. The location passed in is the location 2288 /// that best represents the call. 2289 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 2290 CallExpr *CE, FunctionDecl *FD); 2291 2292 /// Helpers for dealing with blocks and functions. 2293 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param, 2294 ParmVarDecl *const *ParamEnd, 2295 bool CheckParameterNames); 2296 void CheckCXXDefaultArguments(FunctionDecl *FD); 2297 void CheckExtraCXXDefaultArguments(Declarator &D); 2298 Scope *getNonFieldDeclScope(Scope *S); 2299 2300 /// \name Name lookup 2301 /// 2302 /// These routines provide name lookup that is used during semantic 2303 /// analysis to resolve the various kinds of names (identifiers, 2304 /// overloaded operator names, constructor names, etc.) into zero or 2305 /// more declarations within a particular scope. The major entry 2306 /// points are LookupName, which performs unqualified name lookup, 2307 /// and LookupQualifiedName, which performs qualified name lookup. 2308 /// 2309 /// All name lookup is performed based on some specific criteria, 2310 /// which specify what names will be visible to name lookup and how 2311 /// far name lookup should work. These criteria are important both 2312 /// for capturing language semantics (certain lookups will ignore 2313 /// certain names, for example) and for performance, since name 2314 /// lookup is often a bottleneck in the compilation of C++. Name 2315 /// lookup criteria is specified via the LookupCriteria enumeration. 2316 /// 2317 /// The results of name lookup can vary based on the kind of name 2318 /// lookup performed, the current language, and the translation 2319 /// unit. In C, for example, name lookup will either return nothing 2320 /// (no entity found) or a single declaration. In C++, name lookup 2321 /// can additionally refer to a set of overloaded functions or 2322 /// result in an ambiguity. All of the possible results of name 2323 /// lookup are captured by the LookupResult class, which provides 2324 /// the ability to distinguish among them. 2325 //@{ 2326 2327 /// @brief Describes the kind of name lookup to perform. 2328 enum LookupNameKind { 2329 /// Ordinary name lookup, which finds ordinary names (functions, 2330 /// variables, typedefs, etc.) in C and most kinds of names 2331 /// (functions, variables, members, types, etc.) in C++. 2332 LookupOrdinaryName = 0, 2333 /// Tag name lookup, which finds the names of enums, classes, 2334 /// structs, and unions. 2335 LookupTagName, 2336 /// Label name lookup. 2337 LookupLabel, 2338 /// Member name lookup, which finds the names of 2339 /// class/struct/union members. 2340 LookupMemberName, 2341 /// Look up of an operator name (e.g., operator+) for use with 2342 /// operator overloading. This lookup is similar to ordinary name 2343 /// lookup, but will ignore any declarations that are class members. 2344 LookupOperatorName, 2345 /// Look up of a name that precedes the '::' scope resolution 2346 /// operator in C++. This lookup completely ignores operator, object, 2347 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 2348 LookupNestedNameSpecifierName, 2349 /// Look up a namespace name within a C++ using directive or 2350 /// namespace alias definition, ignoring non-namespace names (C++ 2351 /// [basic.lookup.udir]p1). 2352 LookupNamespaceName, 2353 /// Look up all declarations in a scope with the given name, 2354 /// including resolved using declarations. This is appropriate 2355 /// for checking redeclarations for a using declaration. 2356 LookupUsingDeclName, 2357 /// Look up an ordinary name that is going to be redeclared as a 2358 /// name with linkage. This lookup ignores any declarations that 2359 /// are outside of the current scope unless they have linkage. See 2360 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 2361 LookupRedeclarationWithLinkage, 2362 /// Look up a friend of a local class. This lookup does not look 2363 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 2364 LookupLocalFriendName, 2365 /// Look up the name of an Objective-C protocol. 2366 LookupObjCProtocolName, 2367 /// Look up implicit 'self' parameter of an objective-c method. 2368 LookupObjCImplicitSelfParam, 2369 /// \brief Look up any declaration with any name. 2370 LookupAnyName 2371 }; 2372 2373 /// \brief Specifies whether (or how) name lookup is being performed for a 2374 /// redeclaration (vs. a reference). 2375 enum RedeclarationKind { 2376 /// \brief The lookup is a reference to this name that is not for the 2377 /// purpose of redeclaring the name. 2378 NotForRedeclaration = 0, 2379 /// \brief The lookup results will be used for redeclaration of a name, 2380 /// if an entity by that name already exists. 2381 ForRedeclaration 2382 }; 2383 2384 /// \brief The possible outcomes of name lookup for a literal operator. 2385 enum LiteralOperatorLookupResult { 2386 /// \brief The lookup resulted in an error. 2387 LOLR_Error, 2388 /// \brief The lookup found a single 'cooked' literal operator, which 2389 /// expects a normal literal to be built and passed to it. 2390 LOLR_Cooked, 2391 /// \brief The lookup found a single 'raw' literal operator, which expects 2392 /// a string literal containing the spelling of the literal token. 2393 LOLR_Raw, 2394 /// \brief The lookup found an overload set of literal operator templates, 2395 /// which expect the characters of the spelling of the literal token to be 2396 /// passed as a non-type template argument pack. 2397 LOLR_Template 2398 }; 2399 2400 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D, 2401 CXXSpecialMember SM, 2402 bool ConstArg, 2403 bool VolatileArg, 2404 bool RValueThis, 2405 bool ConstThis, 2406 bool VolatileThis); 2407 2408private: 2409 bool CppLookupName(LookupResult &R, Scope *S); 2410 2411 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. 2412 // 2413 // The boolean value will be true to indicate that the namespace was loaded 2414 // from an AST/PCH file, or false otherwise. 2415 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 2416 2417 /// \brief Whether we have already loaded known namespaces from an extenal 2418 /// source. 2419 bool LoadedExternalKnownNamespaces; 2420 2421public: 2422 /// \brief Look up a name, looking for a single declaration. Return 2423 /// null if the results were absent, ambiguous, or overloaded. 2424 /// 2425 /// It is preferable to use the elaborated form and explicitly handle 2426 /// ambiguity and overloaded. 2427 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 2428 SourceLocation Loc, 2429 LookupNameKind NameKind, 2430 RedeclarationKind Redecl 2431 = NotForRedeclaration); 2432 bool LookupName(LookupResult &R, Scope *S, 2433 bool AllowBuiltinCreation = false); 2434 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2435 bool InUnqualifiedLookup = false); 2436 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 2437 bool AllowBuiltinCreation = false, 2438 bool EnteringContext = false); 2439 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 2440 RedeclarationKind Redecl 2441 = NotForRedeclaration); 2442 2443 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2444 QualType T1, QualType T2, 2445 UnresolvedSetImpl &Functions); 2446 2447 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 2448 SourceLocation GnuLabelLoc = SourceLocation()); 2449 2450 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 2451 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 2452 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 2453 unsigned Quals); 2454 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 2455 bool RValueThis, unsigned ThisQuals); 2456 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 2457 unsigned Quals); 2458 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 2459 bool RValueThis, unsigned ThisQuals); 2460 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 2461 2462 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, 2463 ArrayRef<QualType> ArgTys, 2464 bool AllowRawAndTemplate); 2465 bool isKnownName(StringRef name); 2466 2467 void ArgumentDependentLookup(DeclarationName Name, bool Operator, 2468 SourceLocation Loc, 2469 ArrayRef<Expr *> Args, 2470 ADLResult &Functions); 2471 2472 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 2473 VisibleDeclConsumer &Consumer, 2474 bool IncludeGlobalScope = true); 2475 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 2476 VisibleDeclConsumer &Consumer, 2477 bool IncludeGlobalScope = true); 2478 2479 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 2480 Sema::LookupNameKind LookupKind, 2481 Scope *S, CXXScopeSpec *SS, 2482 CorrectionCandidateCallback &CCC, 2483 DeclContext *MemberContext = 0, 2484 bool EnteringContext = false, 2485 const ObjCObjectPointerType *OPT = 0); 2486 2487 void diagnoseTypo(const TypoCorrection &Correction, 2488 const PartialDiagnostic &TypoDiag, 2489 bool ErrorRecovery = true); 2490 2491 void diagnoseTypo(const TypoCorrection &Correction, 2492 const PartialDiagnostic &TypoDiag, 2493 const PartialDiagnostic &PrevNote, 2494 bool ErrorRecovery = true); 2495 2496 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 2497 ArrayRef<Expr *> Args, 2498 AssociatedNamespaceSet &AssociatedNamespaces, 2499 AssociatedClassSet &AssociatedClasses); 2500 2501 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 2502 bool ConsiderLinkage, 2503 bool ExplicitInstantiationOrSpecialization); 2504 2505 void DiagnoseAmbiguousLookup(LookupResult &Result); 2506 //@} 2507 2508 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 2509 SourceLocation IdLoc, 2510 bool TypoCorrection = false); 2511 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2512 Scope *S, bool ForRedeclaration, 2513 SourceLocation Loc); 2514 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 2515 Scope *S); 2516 void AddKnownFunctionAttributes(FunctionDecl *FD); 2517 2518 // More parsing and symbol table subroutines. 2519 2520 void ProcessPragmaWeak(Scope *S, Decl *D); 2521 // Decl attributes - this routine is the top level dispatcher. 2522 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 2523 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 2524 bool IncludeCXX11Attributes = true); 2525 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 2526 const AttributeList *AttrList); 2527 2528 void checkUnusedDeclAttributes(Declarator &D); 2529 2530 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 2531 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 2532 const FunctionDecl *FD = 0); 2533 bool CheckNoReturnAttr(const AttributeList &attr); 2534 void CheckAlignasUnderalignment(Decl *D); 2535 2536 /// Adjust the calling convention of a method to be the ABI default if it 2537 /// wasn't specified explicitly. This handles method types formed from 2538 /// function type typedefs and typename template arguments. 2539 void adjustMemberFunctionCC(QualType &T); 2540 2541 /// Get the outermost AttributedType node that sets a calling convention. 2542 /// Valid types should not have multiple attributes with different CCs. 2543 const AttributedType *getCallingConvAttributedType(QualType T) const; 2544 2545 /// \brief Stmt attributes - this routine is the top level dispatcher. 2546 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs, 2547 SourceRange Range); 2548 2549 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 2550 bool &IncompleteImpl, unsigned DiagID); 2551 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 2552 ObjCMethodDecl *MethodDecl, 2553 bool IsProtocolMethodDecl); 2554 2555 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2556 ObjCMethodDecl *Overridden, 2557 bool IsProtocolMethodDecl); 2558 2559 /// WarnExactTypedMethods - This routine issues a warning if method 2560 /// implementation declaration matches exactly that of its declaration. 2561 void WarnExactTypedMethods(ObjCMethodDecl *Method, 2562 ObjCMethodDecl *MethodDecl, 2563 bool IsProtocolMethodDecl); 2564 2565 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 2566 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; 2567 2568 /// CheckProtocolMethodDefs - This routine checks unimplemented 2569 /// methods declared in protocol, and those referenced by it. 2570 void CheckProtocolMethodDefs(SourceLocation ImpLoc, 2571 ObjCProtocolDecl *PDecl, 2572 bool& IncompleteImpl, 2573 const SelectorSet &InsMap, 2574 const SelectorSet &ClsMap, 2575 ObjCContainerDecl *CDecl); 2576 2577 /// CheckImplementationIvars - This routine checks if the instance variables 2578 /// listed in the implelementation match those listed in the interface. 2579 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 2580 ObjCIvarDecl **Fields, unsigned nIvars, 2581 SourceLocation Loc); 2582 2583 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 2584 /// remains unimplemented in the class or category \@implementation. 2585 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2586 ObjCContainerDecl* IDecl, 2587 bool IncompleteImpl = false); 2588 2589 /// DiagnoseUnimplementedProperties - This routine warns on those properties 2590 /// which must be implemented by this implementation. 2591 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 2592 ObjCContainerDecl *CDecl); 2593 2594 /// DefaultSynthesizeProperties - This routine default synthesizes all 2595 /// properties which must be synthesized in the class's \@implementation. 2596 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 2597 ObjCInterfaceDecl *IDecl); 2598 void DefaultSynthesizeProperties(Scope *S, Decl *D); 2599 2600 /// CollectImmediateProperties - This routine collects all properties in 2601 /// the class and its conforming protocols; but not those it its super class. 2602 void CollectImmediateProperties(ObjCContainerDecl *CDecl, 2603 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap, 2604 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap); 2605 2606 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 2607 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 2608 /// declared in class 'IFace'. 2609 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 2610 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 2611 2612 /// Called by ActOnProperty to handle \@property declarations in 2613 /// class extensions. 2614 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 2615 SourceLocation AtLoc, 2616 SourceLocation LParenLoc, 2617 FieldDeclarator &FD, 2618 Selector GetterSel, 2619 Selector SetterSel, 2620 const bool isAssign, 2621 const bool isReadWrite, 2622 const unsigned Attributes, 2623 const unsigned AttributesAsWritten, 2624 bool *isOverridingProperty, 2625 TypeSourceInfo *T, 2626 tok::ObjCKeywordKind MethodImplKind); 2627 2628 /// Called by ActOnProperty and HandlePropertyInClassExtension to 2629 /// handle creating the ObjcPropertyDecl for a category or \@interface. 2630 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 2631 ObjCContainerDecl *CDecl, 2632 SourceLocation AtLoc, 2633 SourceLocation LParenLoc, 2634 FieldDeclarator &FD, 2635 Selector GetterSel, 2636 Selector SetterSel, 2637 const bool isAssign, 2638 const bool isReadWrite, 2639 const unsigned Attributes, 2640 const unsigned AttributesAsWritten, 2641 TypeSourceInfo *T, 2642 tok::ObjCKeywordKind MethodImplKind, 2643 DeclContext *lexicalDC = 0); 2644 2645 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 2646 /// warning) when atomic property has one but not the other user-declared 2647 /// setter or getter. 2648 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 2649 ObjCContainerDecl* IDecl); 2650 2651 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 2652 2653 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 2654 2655 enum MethodMatchStrategy { 2656 MMS_loose, 2657 MMS_strict 2658 }; 2659 2660 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 2661 /// true, or false, accordingly. 2662 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 2663 const ObjCMethodDecl *PrevMethod, 2664 MethodMatchStrategy strategy = MMS_strict); 2665 2666 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 2667 /// or protocol against those declared in their implementations. 2668 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 2669 const SelectorSet &ClsMap, 2670 SelectorSet &InsMapSeen, 2671 SelectorSet &ClsMapSeen, 2672 ObjCImplDecl* IMPDecl, 2673 ObjCContainerDecl* IDecl, 2674 bool &IncompleteImpl, 2675 bool ImmediateClass, 2676 bool WarnCategoryMethodImpl=false); 2677 2678 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2679 /// category matches with those implemented in its primary class and 2680 /// warns each time an exact match is found. 2681 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 2682 2683 /// \brief Add the given method to the list of globally-known methods. 2684 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 2685 2686private: 2687 /// AddMethodToGlobalPool - Add an instance or factory method to the global 2688 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 2689 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 2690 2691 /// LookupMethodInGlobalPool - Returns the instance or factory method and 2692 /// optionally warns if there are multiple signatures. 2693 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2694 bool receiverIdOrClass, 2695 bool warn, bool instance); 2696 2697public: 2698 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 2699 /// unit are added to a global pool. This allows us to efficiently associate 2700 /// a selector with a method declaraation for purposes of typechecking 2701 /// messages sent to "id" (where the class of the object is unknown). 2702 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2703 AddMethodToGlobalPool(Method, impl, /*instance*/true); 2704 } 2705 2706 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 2707 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2708 AddMethodToGlobalPool(Method, impl, /*instance*/false); 2709 } 2710 2711 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 2712 /// pool. 2713 void AddAnyMethodToGlobalPool(Decl *D); 2714 2715 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 2716 /// there are multiple signatures. 2717 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 2718 bool receiverIdOrClass=false, 2719 bool warn=true) { 2720 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2721 warn, /*instance*/true); 2722 } 2723 2724 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 2725 /// there are multiple signatures. 2726 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 2727 bool receiverIdOrClass=false, 2728 bool warn=true) { 2729 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2730 warn, /*instance*/false); 2731 } 2732 2733 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, 2734 QualType ObjectType=QualType()); 2735 2736 /// DiagnoseMismatchedMethodsInGlobalPool - This routine goes through list of 2737 /// methods in global pool and issues diagnostic on identical selectors which 2738 /// have mismathched types. 2739 void DiagnoseMismatchedMethodsInGlobalPool(); 2740 2741 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 2742 /// implementation. 2743 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 2744 2745 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 2746 /// initialization. 2747 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 2748 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 2749 2750 //===--------------------------------------------------------------------===// 2751 // Statement Parsing Callbacks: SemaStmt.cpp. 2752public: 2753 class FullExprArg { 2754 public: 2755 FullExprArg(Sema &actions) : E(0) { } 2756 2757 // FIXME: The const_cast here is ugly. RValue references would make this 2758 // much nicer (or we could duplicate a bunch of the move semantics 2759 // emulation code from Ownership.h). 2760 FullExprArg(const FullExprArg& Other) : E(Other.E) {} 2761 2762 ExprResult release() { 2763 return E; 2764 } 2765 2766 Expr *get() const { return E; } 2767 2768 Expr *operator->() { 2769 return E; 2770 } 2771 2772 private: 2773 // FIXME: No need to make the entire Sema class a friend when it's just 2774 // Sema::MakeFullExpr that needs access to the constructor below. 2775 friend class Sema; 2776 2777 explicit FullExprArg(Expr *expr) : E(expr) {} 2778 2779 Expr *E; 2780 }; 2781 2782 FullExprArg MakeFullExpr(Expr *Arg) { 2783 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 2784 } 2785 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 2786 return FullExprArg(ActOnFinishFullExpr(Arg, CC).release()); 2787 } 2788 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 2789 ExprResult FE = 2790 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 2791 /*DiscardedValue*/ true); 2792 return FullExprArg(FE.release()); 2793 } 2794 2795 StmtResult ActOnExprStmt(ExprResult Arg); 2796 StmtResult ActOnExprStmtError(); 2797 2798 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 2799 bool HasLeadingEmptyMacro = false); 2800 2801 void ActOnStartOfCompoundStmt(); 2802 void ActOnFinishOfCompoundStmt(); 2803 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 2804 ArrayRef<Stmt *> Elts, bool isStmtExpr); 2805 2806 /// \brief A RAII object to enter scope of a compound statement. 2807 class CompoundScopeRAII { 2808 public: 2809 CompoundScopeRAII(Sema &S): S(S) { 2810 S.ActOnStartOfCompoundStmt(); 2811 } 2812 2813 ~CompoundScopeRAII() { 2814 S.ActOnFinishOfCompoundStmt(); 2815 } 2816 2817 private: 2818 Sema &S; 2819 }; 2820 2821 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 2822 SourceLocation StartLoc, 2823 SourceLocation EndLoc); 2824 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 2825 StmtResult ActOnForEachLValueExpr(Expr *E); 2826 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 2827 SourceLocation DotDotDotLoc, Expr *RHSVal, 2828 SourceLocation ColonLoc); 2829 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 2830 2831 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 2832 SourceLocation ColonLoc, 2833 Stmt *SubStmt, Scope *CurScope); 2834 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 2835 SourceLocation ColonLoc, Stmt *SubStmt); 2836 2837 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, 2838 ArrayRef<const Attr*> Attrs, 2839 Stmt *SubStmt); 2840 2841 StmtResult ActOnIfStmt(SourceLocation IfLoc, 2842 FullExprArg CondVal, Decl *CondVar, 2843 Stmt *ThenVal, 2844 SourceLocation ElseLoc, Stmt *ElseVal); 2845 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 2846 Expr *Cond, 2847 Decl *CondVar); 2848 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 2849 Stmt *Switch, Stmt *Body); 2850 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 2851 FullExprArg Cond, 2852 Decl *CondVar, Stmt *Body); 2853 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 2854 SourceLocation WhileLoc, 2855 SourceLocation CondLParen, Expr *Cond, 2856 SourceLocation CondRParen); 2857 2858 StmtResult ActOnForStmt(SourceLocation ForLoc, 2859 SourceLocation LParenLoc, 2860 Stmt *First, FullExprArg Second, 2861 Decl *SecondVar, 2862 FullExprArg Third, 2863 SourceLocation RParenLoc, 2864 Stmt *Body); 2865 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 2866 Expr *collection); 2867 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 2868 Stmt *First, Expr *collection, 2869 SourceLocation RParenLoc); 2870 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 2871 2872 enum BuildForRangeKind { 2873 /// Initial building of a for-range statement. 2874 BFRK_Build, 2875 /// Instantiation or recovery rebuild of a for-range statement. Don't 2876 /// attempt any typo-correction. 2877 BFRK_Rebuild, 2878 /// Determining whether a for-range statement could be built. Avoid any 2879 /// unnecessary or irreversible actions. 2880 BFRK_Check 2881 }; 2882 2883 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar, 2884 SourceLocation ColonLoc, Expr *Collection, 2885 SourceLocation RParenLoc, 2886 BuildForRangeKind Kind); 2887 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 2888 SourceLocation ColonLoc, 2889 Stmt *RangeDecl, Stmt *BeginEndDecl, 2890 Expr *Cond, Expr *Inc, 2891 Stmt *LoopVarDecl, 2892 SourceLocation RParenLoc, 2893 BuildForRangeKind Kind); 2894 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 2895 2896 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 2897 SourceLocation LabelLoc, 2898 LabelDecl *TheDecl); 2899 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 2900 SourceLocation StarLoc, 2901 Expr *DestExp); 2902 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 2903 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 2904 2905 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 2906 CapturedRegionKind Kind, unsigned NumParams); 2907 StmtResult ActOnCapturedRegionEnd(Stmt *S); 2908 void ActOnCapturedRegionError(); 2909 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 2910 SourceLocation Loc, 2911 unsigned NumParams); 2912 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 2913 bool AllowFunctionParameters); 2914 2915 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2916 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2917 2918 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 2919 bool IsVolatile, unsigned NumOutputs, 2920 unsigned NumInputs, IdentifierInfo **Names, 2921 MultiExprArg Constraints, MultiExprArg Exprs, 2922 Expr *AsmString, MultiExprArg Clobbers, 2923 SourceLocation RParenLoc); 2924 2925 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 2926 SourceLocation TemplateKWLoc, 2927 UnqualifiedId &Id, 2928 InlineAsmIdentifierInfo &Info, 2929 bool IsUnevaluatedContext); 2930 bool LookupInlineAsmField(StringRef Base, StringRef Member, 2931 unsigned &Offset, SourceLocation AsmLoc); 2932 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 2933 ArrayRef<Token> AsmToks, 2934 StringRef AsmString, 2935 unsigned NumOutputs, unsigned NumInputs, 2936 ArrayRef<StringRef> Constraints, 2937 ArrayRef<StringRef> Clobbers, 2938 ArrayRef<Expr*> Exprs, 2939 SourceLocation EndLoc); 2940 2941 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 2942 SourceLocation StartLoc, 2943 SourceLocation IdLoc, IdentifierInfo *Id, 2944 bool Invalid = false); 2945 2946 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 2947 2948 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 2949 Decl *Parm, Stmt *Body); 2950 2951 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 2952 2953 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2954 MultiStmtArg Catch, Stmt *Finally); 2955 2956 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 2957 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2958 Scope *CurScope); 2959 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 2960 Expr *operand); 2961 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 2962 Expr *SynchExpr, 2963 Stmt *SynchBody); 2964 2965 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 2966 2967 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 2968 SourceLocation StartLoc, 2969 SourceLocation IdLoc, 2970 IdentifierInfo *Id); 2971 2972 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 2973 2974 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 2975 Decl *ExDecl, Stmt *HandlerBlock); 2976 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2977 ArrayRef<Stmt *> Handlers); 2978 2979 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 2980 SourceLocation TryLoc, Stmt *TryBlock, 2981 Stmt *Handler); 2982 2983 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 2984 Expr *FilterExpr, 2985 Stmt *Block); 2986 2987 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, 2988 Stmt *Block); 2989 2990 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 2991 2992 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 2993 2994 /// \brief If it's a file scoped decl that must warn if not used, keep track 2995 /// of it. 2996 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 2997 2998 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 2999 /// whose result is unused, warn. 3000 void DiagnoseUnusedExprResult(const Stmt *S); 3001 void DiagnoseUnusedDecl(const NamedDecl *ND); 3002 3003 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 3004 /// statement as a \p Body, and it is located on the same line. 3005 /// 3006 /// This helps prevent bugs due to typos, such as: 3007 /// if (condition); 3008 /// do_stuff(); 3009 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 3010 const Stmt *Body, 3011 unsigned DiagID); 3012 3013 /// Warn if a for/while loop statement \p S, which is followed by 3014 /// \p PossibleBody, has a suspicious null statement as a body. 3015 void DiagnoseEmptyLoopBody(const Stmt *S, 3016 const Stmt *PossibleBody); 3017 3018 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 3019 return DelayedDiagnostics.push(pool); 3020 } 3021 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 3022 3023 typedef ProcessingContextState ParsingClassState; 3024 ParsingClassState PushParsingClass() { 3025 return DelayedDiagnostics.pushUndelayed(); 3026 } 3027 void PopParsingClass(ParsingClassState state) { 3028 DelayedDiagnostics.popUndelayed(state); 3029 } 3030 3031 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 3032 3033 void EmitDeprecationWarning(NamedDecl *D, StringRef Message, 3034 SourceLocation Loc, 3035 const ObjCInterfaceDecl *UnknownObjCClass, 3036 const ObjCPropertyDecl *ObjCProperty); 3037 3038 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 3039 3040 bool makeUnavailableInSystemHeader(SourceLocation loc, 3041 StringRef message); 3042 3043 //===--------------------------------------------------------------------===// 3044 // Expression Parsing Callbacks: SemaExpr.cpp. 3045 3046 bool CanUseDecl(NamedDecl *D); 3047 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 3048 const ObjCInterfaceDecl *UnknownObjCClass=0); 3049 void NoteDeletedFunction(FunctionDecl *FD); 3050 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 3051 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 3052 ObjCMethodDecl *Getter, 3053 SourceLocation Loc); 3054 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 3055 ArrayRef<Expr *> Args); 3056 3057 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 3058 Decl *LambdaContextDecl = 0, 3059 bool IsDecltype = false); 3060 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 3061 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 3062 ReuseLambdaContextDecl_t, 3063 bool IsDecltype = false); 3064 void PopExpressionEvaluationContext(); 3065 3066 void DiscardCleanupsInEvaluationContext(); 3067 3068 ExprResult TransformToPotentiallyEvaluated(Expr *E); 3069 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 3070 3071 ExprResult ActOnConstantExpression(ExprResult Res); 3072 3073 // Functions for marking a declaration referenced. These functions also 3074 // contain the relevant logic for marking if a reference to a function or 3075 // variable is an odr-use (in the C++11 sense). There are separate variants 3076 // for expressions referring to a decl; these exist because odr-use marking 3077 // needs to be delayed for some constant variables when we build one of the 3078 // named expressions. 3079 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse); 3080 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func); 3081 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 3082 void MarkDeclRefReferenced(DeclRefExpr *E); 3083 void MarkMemberReferenced(MemberExpr *E); 3084 3085 void UpdateMarkingForLValueToRValue(Expr *E); 3086 void CleanupVarDeclMarking(); 3087 3088 enum TryCaptureKind { 3089 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 3090 }; 3091 3092 /// \brief Try to capture the given variable. 3093 /// 3094 /// \param Var The variable to capture. 3095 /// 3096 /// \param Loc The location at which the capture occurs. 3097 /// 3098 /// \param Kind The kind of capture, which may be implicit (for either a 3099 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 3100 /// 3101 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 3102 /// an explicit lambda capture. 3103 /// 3104 /// \param BuildAndDiagnose Whether we are actually supposed to add the 3105 /// captures or diagnose errors. If false, this routine merely check whether 3106 /// the capture can occur without performing the capture itself or complaining 3107 /// if the variable cannot be captured. 3108 /// 3109 /// \param CaptureType Will be set to the type of the field used to capture 3110 /// this variable in the innermost block or lambda. Only valid when the 3111 /// variable can be captured. 3112 /// 3113 /// \param DeclRefType Will be set to the type of a reference to the capture 3114 /// from within the current scope. Only valid when the variable can be 3115 /// captured. 3116 /// 3117 /// \returns true if an error occurred (i.e., the variable cannot be 3118 /// captured) and false if the capture succeeded. 3119 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 3120 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 3121 QualType &CaptureType, 3122 QualType &DeclRefType); 3123 3124 /// \brief Try to capture the given variable. 3125 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 3126 TryCaptureKind Kind = TryCapture_Implicit, 3127 SourceLocation EllipsisLoc = SourceLocation()); 3128 3129 /// \brief Given a variable, determine the type that a reference to that 3130 /// variable will have in the given scope. 3131 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 3132 3133 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 3134 void MarkDeclarationsReferencedInExpr(Expr *E, 3135 bool SkipLocalVariables = false); 3136 3137 /// \brief Try to recover by turning the given expression into a 3138 /// call. Returns true if recovery was attempted or an error was 3139 /// emitted; this may also leave the ExprResult invalid. 3140 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 3141 bool ForceComplain = false, 3142 bool (*IsPlausibleResult)(QualType) = 0); 3143 3144 /// \brief Figure out if an expression could be turned into a call. 3145 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 3146 UnresolvedSetImpl &NonTemplateOverloads); 3147 3148 /// \brief Conditionally issue a diagnostic based on the current 3149 /// evaluation context. 3150 /// 3151 /// \param Statement If Statement is non-null, delay reporting the 3152 /// diagnostic until the function body is parsed, and then do a basic 3153 /// reachability analysis to determine if the statement is reachable. 3154 /// If it is unreachable, the diagnostic will not be emitted. 3155 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 3156 const PartialDiagnostic &PD); 3157 3158 // Primary Expressions. 3159 SourceRange getExprRange(Expr *E) const; 3160 3161 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 3162 SourceLocation TemplateKWLoc, 3163 UnqualifiedId &Id, 3164 bool HasTrailingLParen, bool IsAddressOfOperand, 3165 CorrectionCandidateCallback *CCC = 0, 3166 bool IsInlineAsmIdentifier = false); 3167 3168 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 3169 TemplateArgumentListInfo &Buffer, 3170 DeclarationNameInfo &NameInfo, 3171 const TemplateArgumentListInfo *&TemplateArgs); 3172 3173 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 3174 CorrectionCandidateCallback &CCC, 3175 TemplateArgumentListInfo *ExplicitTemplateArgs = 0, 3176 ArrayRef<Expr *> Args = None); 3177 3178 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 3179 IdentifierInfo *II, 3180 bool AllowBuiltinCreation=false); 3181 3182 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 3183 SourceLocation TemplateKWLoc, 3184 const DeclarationNameInfo &NameInfo, 3185 bool isAddressOfOperand, 3186 const TemplateArgumentListInfo *TemplateArgs); 3187 3188 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 3189 ExprValueKind VK, 3190 SourceLocation Loc, 3191 const CXXScopeSpec *SS = 0); 3192 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 3193 const DeclarationNameInfo &NameInfo, 3194 const CXXScopeSpec *SS = 0, NamedDecl *FoundD = 0, 3195 const TemplateArgumentListInfo *TemplateArgs = 0); 3196 ExprResult 3197 BuildAnonymousStructUnionMemberReference( 3198 const CXXScopeSpec &SS, 3199 SourceLocation nameLoc, 3200 IndirectFieldDecl *indirectField, 3201 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_none), 3202 Expr *baseObjectExpr = 0, 3203 SourceLocation opLoc = SourceLocation()); 3204 3205 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 3206 SourceLocation TemplateKWLoc, 3207 LookupResult &R, 3208 const TemplateArgumentListInfo *TemplateArgs); 3209 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 3210 SourceLocation TemplateKWLoc, 3211 LookupResult &R, 3212 const TemplateArgumentListInfo *TemplateArgs, 3213 bool IsDefiniteInstance); 3214 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 3215 const LookupResult &R, 3216 bool HasTrailingLParen); 3217 3218 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 3219 const DeclarationNameInfo &NameInfo, 3220 bool IsAddressOfOperand); 3221 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 3222 SourceLocation TemplateKWLoc, 3223 const DeclarationNameInfo &NameInfo, 3224 const TemplateArgumentListInfo *TemplateArgs); 3225 3226 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3227 LookupResult &R, 3228 bool NeedsADL); 3229 ExprResult BuildDeclarationNameExpr( 3230 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3231 NamedDecl *FoundD = 0, const TemplateArgumentListInfo *TemplateArgs = 0); 3232 3233 ExprResult BuildLiteralOperatorCall(LookupResult &R, 3234 DeclarationNameInfo &SuffixInfo, 3235 ArrayRef<Expr*> Args, 3236 SourceLocation LitEndLoc, 3237 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 3238 3239 ExprResult BuildPredefinedExpr(SourceLocation Loc, 3240 PredefinedExpr::IdentType IT); 3241 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 3242 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 3243 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0); 3244 ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0); 3245 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 3246 ExprResult ActOnParenListExpr(SourceLocation L, 3247 SourceLocation R, 3248 MultiExprArg Val); 3249 3250 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 3251 /// fragments (e.g. "foo" "bar" L"baz"). 3252 ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 3253 Scope *UDLScope = 0); 3254 3255 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 3256 SourceLocation DefaultLoc, 3257 SourceLocation RParenLoc, 3258 Expr *ControllingExpr, 3259 ArrayRef<ParsedType> ArgTypes, 3260 ArrayRef<Expr *> ArgExprs); 3261 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 3262 SourceLocation DefaultLoc, 3263 SourceLocation RParenLoc, 3264 Expr *ControllingExpr, 3265 ArrayRef<TypeSourceInfo *> Types, 3266 ArrayRef<Expr *> Exprs); 3267 3268 // Binary/Unary Operators. 'Tok' is the token for the operator. 3269 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 3270 Expr *InputExpr); 3271 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 3272 UnaryOperatorKind Opc, Expr *Input); 3273 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 3274 tok::TokenKind Op, Expr *Input); 3275 3276 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 3277 3278 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3279 SourceLocation OpLoc, 3280 UnaryExprOrTypeTrait ExprKind, 3281 SourceRange R); 3282 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3283 UnaryExprOrTypeTrait ExprKind); 3284 ExprResult 3285 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3286 UnaryExprOrTypeTrait ExprKind, 3287 bool IsType, void *TyOrEx, 3288 const SourceRange &ArgRange); 3289 3290 ExprResult CheckPlaceholderExpr(Expr *E); 3291 bool CheckVecStepExpr(Expr *E); 3292 3293 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 3294 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 3295 SourceRange ExprRange, 3296 UnaryExprOrTypeTrait ExprKind); 3297 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 3298 SourceLocation OpLoc, 3299 IdentifierInfo &Name, 3300 SourceLocation NameLoc, 3301 SourceLocation RParenLoc); 3302 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3303 tok::TokenKind Kind, Expr *Input); 3304 3305 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3306 Expr *Idx, SourceLocation RLoc); 3307 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3308 Expr *Idx, SourceLocation RLoc); 3309 3310 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 3311 SourceLocation OpLoc, bool IsArrow, 3312 CXXScopeSpec &SS, 3313 SourceLocation TemplateKWLoc, 3314 NamedDecl *FirstQualifierInScope, 3315 const DeclarationNameInfo &NameInfo, 3316 const TemplateArgumentListInfo *TemplateArgs); 3317 3318 // This struct is for use by ActOnMemberAccess to allow 3319 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 3320 // changing the access operator from a '.' to a '->' (to see if that is the 3321 // change needed to fix an error about an unknown member, e.g. when the class 3322 // defines a custom operator->). 3323 struct ActOnMemberAccessExtraArgs { 3324 Scope *S; 3325 UnqualifiedId &Id; 3326 Decl *ObjCImpDecl; 3327 bool HasTrailingLParen; 3328 }; 3329 3330 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 3331 SourceLocation OpLoc, bool IsArrow, 3332 const CXXScopeSpec &SS, 3333 SourceLocation TemplateKWLoc, 3334 NamedDecl *FirstQualifierInScope, 3335 LookupResult &R, 3336 const TemplateArgumentListInfo *TemplateArgs, 3337 bool SuppressQualifierCheck = false, 3338 ActOnMemberAccessExtraArgs *ExtraArgs = 0); 3339 3340 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 3341 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base, 3342 bool &IsArrow, SourceLocation OpLoc, 3343 CXXScopeSpec &SS, 3344 Decl *ObjCImpDecl, 3345 bool HasTemplateArgs); 3346 3347 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 3348 const CXXScopeSpec &SS, 3349 const LookupResult &R); 3350 3351 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 3352 bool IsArrow, SourceLocation OpLoc, 3353 const CXXScopeSpec &SS, 3354 SourceLocation TemplateKWLoc, 3355 NamedDecl *FirstQualifierInScope, 3356 const DeclarationNameInfo &NameInfo, 3357 const TemplateArgumentListInfo *TemplateArgs); 3358 3359 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 3360 SourceLocation OpLoc, 3361 tok::TokenKind OpKind, 3362 CXXScopeSpec &SS, 3363 SourceLocation TemplateKWLoc, 3364 UnqualifiedId &Member, 3365 Decl *ObjCImpDecl, 3366 bool HasTrailingLParen); 3367 3368 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 3369 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3370 FunctionDecl *FDecl, 3371 const FunctionProtoType *Proto, 3372 ArrayRef<Expr *> Args, 3373 SourceLocation RParenLoc, 3374 bool ExecConfig = false); 3375 void CheckStaticArrayArgument(SourceLocation CallLoc, 3376 ParmVarDecl *Param, 3377 const Expr *ArgExpr); 3378 3379 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3380 /// This provides the location of the left/right parens and a list of comma 3381 /// locations. 3382 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3383 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3384 Expr *ExecConfig = 0, bool IsExecConfig = false); 3385 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3386 SourceLocation LParenLoc, 3387 ArrayRef<Expr *> Arg, 3388 SourceLocation RParenLoc, 3389 Expr *Config = 0, 3390 bool IsExecConfig = false); 3391 3392 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3393 MultiExprArg ExecConfig, 3394 SourceLocation GGGLoc); 3395 3396 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 3397 Declarator &D, ParsedType &Ty, 3398 SourceLocation RParenLoc, Expr *CastExpr); 3399 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 3400 TypeSourceInfo *Ty, 3401 SourceLocation RParenLoc, 3402 Expr *Op); 3403 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 3404 3405 /// \brief Build an altivec or OpenCL literal. 3406 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 3407 SourceLocation RParenLoc, Expr *E, 3408 TypeSourceInfo *TInfo); 3409 3410 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 3411 3412 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 3413 ParsedType Ty, 3414 SourceLocation RParenLoc, 3415 Expr *InitExpr); 3416 3417 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 3418 TypeSourceInfo *TInfo, 3419 SourceLocation RParenLoc, 3420 Expr *LiteralExpr); 3421 3422 ExprResult ActOnInitList(SourceLocation LBraceLoc, 3423 MultiExprArg InitArgList, 3424 SourceLocation RBraceLoc); 3425 3426 ExprResult ActOnDesignatedInitializer(Designation &Desig, 3427 SourceLocation Loc, 3428 bool GNUSyntax, 3429 ExprResult Init); 3430 3431 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 3432 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 3433 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 3434 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 3435 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 3436 Expr *LHSExpr, Expr *RHSExpr); 3437 3438 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3439 /// in the case of a the GNU conditional expr extension. 3440 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 3441 SourceLocation ColonLoc, 3442 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 3443 3444 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3445 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 3446 LabelDecl *TheDecl); 3447 3448 void ActOnStartStmtExpr(); 3449 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 3450 SourceLocation RPLoc); // "({..})" 3451 void ActOnStmtExprError(); 3452 3453 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 3454 struct OffsetOfComponent { 3455 SourceLocation LocStart, LocEnd; 3456 bool isBrackets; // true if [expr], false if .ident 3457 union { 3458 IdentifierInfo *IdentInfo; 3459 Expr *E; 3460 } U; 3461 }; 3462 3463 /// __builtin_offsetof(type, a.b[123][456].c) 3464 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 3465 TypeSourceInfo *TInfo, 3466 OffsetOfComponent *CompPtr, 3467 unsigned NumComponents, 3468 SourceLocation RParenLoc); 3469 ExprResult ActOnBuiltinOffsetOf(Scope *S, 3470 SourceLocation BuiltinLoc, 3471 SourceLocation TypeLoc, 3472 ParsedType ParsedArgTy, 3473 OffsetOfComponent *CompPtr, 3474 unsigned NumComponents, 3475 SourceLocation RParenLoc); 3476 3477 // __builtin_choose_expr(constExpr, expr1, expr2) 3478 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 3479 Expr *CondExpr, Expr *LHSExpr, 3480 Expr *RHSExpr, SourceLocation RPLoc); 3481 3482 // __builtin_va_arg(expr, type) 3483 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 3484 SourceLocation RPLoc); 3485 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 3486 TypeSourceInfo *TInfo, SourceLocation RPLoc); 3487 3488 // __null 3489 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 3490 3491 bool CheckCaseExpression(Expr *E); 3492 3493 /// \brief Describes the result of an "if-exists" condition check. 3494 enum IfExistsResult { 3495 /// \brief The symbol exists. 3496 IER_Exists, 3497 3498 /// \brief The symbol does not exist. 3499 IER_DoesNotExist, 3500 3501 /// \brief The name is a dependent name, so the results will differ 3502 /// from one instantiation to the next. 3503 IER_Dependent, 3504 3505 /// \brief An error occurred. 3506 IER_Error 3507 }; 3508 3509 IfExistsResult 3510 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 3511 const DeclarationNameInfo &TargetNameInfo); 3512 3513 IfExistsResult 3514 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 3515 bool IsIfExists, CXXScopeSpec &SS, 3516 UnqualifiedId &Name); 3517 3518 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 3519 bool IsIfExists, 3520 NestedNameSpecifierLoc QualifierLoc, 3521 DeclarationNameInfo NameInfo, 3522 Stmt *Nested); 3523 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 3524 bool IsIfExists, 3525 CXXScopeSpec &SS, UnqualifiedId &Name, 3526 Stmt *Nested); 3527 3528 //===------------------------- "Block" Extension ------------------------===// 3529 3530 /// ActOnBlockStart - This callback is invoked when a block literal is 3531 /// started. 3532 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 3533 3534 /// ActOnBlockArguments - This callback allows processing of block arguments. 3535 /// If there are no arguments, this is still invoked. 3536 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 3537 Scope *CurScope); 3538 3539 /// ActOnBlockError - If there is an error parsing a block, this callback 3540 /// is invoked to pop the information about the block from the action impl. 3541 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 3542 3543 /// ActOnBlockStmtExpr - This is called when the body of a block statement 3544 /// literal was successfully completed. ^(int x){...} 3545 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 3546 Scope *CurScope); 3547 3548 //===---------------------------- Clang Extensions ----------------------===// 3549 3550 /// __builtin_convertvector(...) 3551 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 3552 SourceLocation BuiltinLoc, 3553 SourceLocation RParenLoc); 3554 3555 //===---------------------------- OpenCL Features -----------------------===// 3556 3557 /// __builtin_astype(...) 3558 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3559 SourceLocation BuiltinLoc, 3560 SourceLocation RParenLoc); 3561 3562 //===---------------------------- C++ Features --------------------------===// 3563 3564 // Act on C++ namespaces 3565 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 3566 SourceLocation NamespaceLoc, 3567 SourceLocation IdentLoc, 3568 IdentifierInfo *Ident, 3569 SourceLocation LBrace, 3570 AttributeList *AttrList); 3571 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 3572 3573 NamespaceDecl *getStdNamespace() const; 3574 NamespaceDecl *getOrCreateStdNamespace(); 3575 3576 CXXRecordDecl *getStdBadAlloc() const; 3577 3578 /// \brief Tests whether Ty is an instance of std::initializer_list and, if 3579 /// it is and Element is not NULL, assigns the element type to Element. 3580 bool isStdInitializerList(QualType Ty, QualType *Element); 3581 3582 /// \brief Looks for the std::initializer_list template and instantiates it 3583 /// with Element, or emits an error if it's not found. 3584 /// 3585 /// \returns The instantiated template, or null on error. 3586 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 3587 3588 /// \brief Determine whether Ctor is an initializer-list constructor, as 3589 /// defined in [dcl.init.list]p2. 3590 bool isInitListConstructor(const CXXConstructorDecl *Ctor); 3591 3592 Decl *ActOnUsingDirective(Scope *CurScope, 3593 SourceLocation UsingLoc, 3594 SourceLocation NamespcLoc, 3595 CXXScopeSpec &SS, 3596 SourceLocation IdentLoc, 3597 IdentifierInfo *NamespcName, 3598 AttributeList *AttrList); 3599 3600 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 3601 3602 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 3603 SourceLocation NamespaceLoc, 3604 SourceLocation AliasLoc, 3605 IdentifierInfo *Alias, 3606 CXXScopeSpec &SS, 3607 SourceLocation IdentLoc, 3608 IdentifierInfo *Ident); 3609 3610 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 3611 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 3612 const LookupResult &PreviousDecls); 3613 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 3614 NamedDecl *Target); 3615 3616 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3617 bool HasTypenameKeyword, 3618 const CXXScopeSpec &SS, 3619 SourceLocation NameLoc, 3620 const LookupResult &Previous); 3621 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 3622 const CXXScopeSpec &SS, 3623 SourceLocation NameLoc); 3624 3625 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3626 SourceLocation UsingLoc, 3627 CXXScopeSpec &SS, 3628 const DeclarationNameInfo &NameInfo, 3629 AttributeList *AttrList, 3630 bool IsInstantiation, 3631 bool HasTypenameKeyword, 3632 SourceLocation TypenameLoc); 3633 3634 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 3635 3636 Decl *ActOnUsingDeclaration(Scope *CurScope, 3637 AccessSpecifier AS, 3638 bool HasUsingKeyword, 3639 SourceLocation UsingLoc, 3640 CXXScopeSpec &SS, 3641 UnqualifiedId &Name, 3642 AttributeList *AttrList, 3643 bool HasTypenameKeyword, 3644 SourceLocation TypenameLoc); 3645 Decl *ActOnAliasDeclaration(Scope *CurScope, 3646 AccessSpecifier AS, 3647 MultiTemplateParamsArg TemplateParams, 3648 SourceLocation UsingLoc, 3649 UnqualifiedId &Name, 3650 AttributeList *AttrList, 3651 TypeResult Type); 3652 3653 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 3654 /// including handling of its default argument expressions. 3655 /// 3656 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 3657 ExprResult 3658 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3659 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 3660 bool HadMultipleCandidates, bool IsListInitialization, 3661 bool RequiresZeroInit, unsigned ConstructKind, 3662 SourceRange ParenRange); 3663 3664 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if 3665 // the constructor can be elidable? 3666 ExprResult 3667 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3668 CXXConstructorDecl *Constructor, bool Elidable, 3669 MultiExprArg Exprs, bool HadMultipleCandidates, 3670 bool IsListInitialization, bool RequiresZeroInit, 3671 unsigned ConstructKind, SourceRange ParenRange); 3672 3673 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 3674 /// the default expr if needed. 3675 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3676 FunctionDecl *FD, 3677 ParmVarDecl *Param); 3678 3679 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 3680 /// constructed variable. 3681 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 3682 3683 /// \brief Helper class that collects exception specifications for 3684 /// implicitly-declared special member functions. 3685 class ImplicitExceptionSpecification { 3686 // Pointer to allow copying 3687 Sema *Self; 3688 // We order exception specifications thus: 3689 // noexcept is the most restrictive, but is only used in C++11. 3690 // throw() comes next. 3691 // Then a throw(collected exceptions) 3692 // Finally no specification, which is expressed as noexcept(false). 3693 // throw(...) is used instead if any called function uses it. 3694 ExceptionSpecificationType ComputedEST; 3695 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3696 SmallVector<QualType, 4> Exceptions; 3697 3698 void ClearExceptions() { 3699 ExceptionsSeen.clear(); 3700 Exceptions.clear(); 3701 } 3702 3703 public: 3704 explicit ImplicitExceptionSpecification(Sema &Self) 3705 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 3706 if (!Self.getLangOpts().CPlusPlus11) 3707 ComputedEST = EST_DynamicNone; 3708 } 3709 3710 /// \brief Get the computed exception specification type. 3711 ExceptionSpecificationType getExceptionSpecType() const { 3712 assert(ComputedEST != EST_ComputedNoexcept && 3713 "noexcept(expr) should not be a possible result"); 3714 return ComputedEST; 3715 } 3716 3717 /// \brief The number of exceptions in the exception specification. 3718 unsigned size() const { return Exceptions.size(); } 3719 3720 /// \brief The set of exceptions in the exception specification. 3721 const QualType *data() const { return Exceptions.data(); } 3722 3723 /// \brief Integrate another called method into the collected data. 3724 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 3725 3726 /// \brief Integrate an invoked expression into the collected data. 3727 void CalledExpr(Expr *E); 3728 3729 /// \brief Overwrite an EPI's exception specification with this 3730 /// computed exception specification. 3731 void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const { 3732 EPI.ExceptionSpecType = getExceptionSpecType(); 3733 if (EPI.ExceptionSpecType == EST_Dynamic) { 3734 EPI.NumExceptions = size(); 3735 EPI.Exceptions = data(); 3736 } else if (EPI.ExceptionSpecType == EST_None) { 3737 /// C++11 [except.spec]p14: 3738 /// The exception-specification is noexcept(false) if the set of 3739 /// potential exceptions of the special member function contains "any" 3740 EPI.ExceptionSpecType = EST_ComputedNoexcept; 3741 EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 3742 tok::kw_false).take(); 3743 } 3744 } 3745 FunctionProtoType::ExtProtoInfo getEPI() const { 3746 FunctionProtoType::ExtProtoInfo EPI; 3747 getEPI(EPI); 3748 return EPI; 3749 } 3750 }; 3751 3752 /// \brief Determine what sort of exception specification a defaulted 3753 /// copy constructor of a class will have. 3754 ImplicitExceptionSpecification 3755 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 3756 CXXMethodDecl *MD); 3757 3758 /// \brief Determine what sort of exception specification a defaulted 3759 /// default constructor of a class will have, and whether the parameter 3760 /// will be const. 3761 ImplicitExceptionSpecification 3762 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); 3763 3764 /// \brief Determine what sort of exception specification a defautled 3765 /// copy assignment operator of a class will have, and whether the 3766 /// parameter will be const. 3767 ImplicitExceptionSpecification 3768 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); 3769 3770 /// \brief Determine what sort of exception specification a defaulted move 3771 /// constructor of a class will have. 3772 ImplicitExceptionSpecification 3773 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); 3774 3775 /// \brief Determine what sort of exception specification a defaulted move 3776 /// assignment operator of a class will have. 3777 ImplicitExceptionSpecification 3778 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); 3779 3780 /// \brief Determine what sort of exception specification a defaulted 3781 /// destructor of a class will have. 3782 ImplicitExceptionSpecification 3783 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); 3784 3785 /// \brief Determine what sort of exception specification an inheriting 3786 /// constructor of a class will have. 3787 ImplicitExceptionSpecification 3788 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD); 3789 3790 /// \brief Evaluate the implicit exception specification for a defaulted 3791 /// special member function. 3792 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); 3793 3794 /// \brief Check the given exception-specification and update the 3795 /// extended prototype information with the results. 3796 void checkExceptionSpecification(ExceptionSpecificationType EST, 3797 ArrayRef<ParsedType> DynamicExceptions, 3798 ArrayRef<SourceRange> DynamicExceptionRanges, 3799 Expr *NoexceptExpr, 3800 SmallVectorImpl<QualType> &Exceptions, 3801 FunctionProtoType::ExtProtoInfo &EPI); 3802 3803 /// \brief Determine if a special member function should have a deleted 3804 /// definition when it is defaulted. 3805 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 3806 bool Diagnose = false); 3807 3808 /// \brief Declare the implicit default constructor for the given class. 3809 /// 3810 /// \param ClassDecl The class declaration into which the implicit 3811 /// default constructor will be added. 3812 /// 3813 /// \returns The implicitly-declared default constructor. 3814 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 3815 CXXRecordDecl *ClassDecl); 3816 3817 /// DefineImplicitDefaultConstructor - Checks for feasibility of 3818 /// defining this constructor as the default constructor. 3819 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 3820 CXXConstructorDecl *Constructor); 3821 3822 /// \brief Declare the implicit destructor for the given class. 3823 /// 3824 /// \param ClassDecl The class declaration into which the implicit 3825 /// destructor will be added. 3826 /// 3827 /// \returns The implicitly-declared destructor. 3828 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 3829 3830 /// DefineImplicitDestructor - Checks for feasibility of 3831 /// defining this destructor as the default destructor. 3832 void DefineImplicitDestructor(SourceLocation CurrentLocation, 3833 CXXDestructorDecl *Destructor); 3834 3835 /// \brief Build an exception spec for destructors that don't have one. 3836 /// 3837 /// C++11 says that user-defined destructors with no exception spec get one 3838 /// that looks as if the destructor was implicitly declared. 3839 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 3840 CXXDestructorDecl *Destructor); 3841 3842 /// \brief Declare all inheriting constructors for the given class. 3843 /// 3844 /// \param ClassDecl The class declaration into which the inheriting 3845 /// constructors will be added. 3846 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl); 3847 3848 /// \brief Define the specified inheriting constructor. 3849 void DefineInheritingConstructor(SourceLocation UseLoc, 3850 CXXConstructorDecl *Constructor); 3851 3852 /// \brief Declare the implicit copy constructor for the given class. 3853 /// 3854 /// \param ClassDecl The class declaration into which the implicit 3855 /// copy constructor will be added. 3856 /// 3857 /// \returns The implicitly-declared copy constructor. 3858 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 3859 3860 /// DefineImplicitCopyConstructor - Checks for feasibility of 3861 /// defining this constructor as the copy constructor. 3862 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3863 CXXConstructorDecl *Constructor); 3864 3865 /// \brief Declare the implicit move constructor for the given class. 3866 /// 3867 /// \param ClassDecl The Class declaration into which the implicit 3868 /// move constructor will be added. 3869 /// 3870 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 3871 /// declared. 3872 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 3873 3874 /// DefineImplicitMoveConstructor - Checks for feasibility of 3875 /// defining this constructor as the move constructor. 3876 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 3877 CXXConstructorDecl *Constructor); 3878 3879 /// \brief Declare the implicit copy assignment operator for the given class. 3880 /// 3881 /// \param ClassDecl The class declaration into which the implicit 3882 /// copy assignment operator will be added. 3883 /// 3884 /// \returns The implicitly-declared copy assignment operator. 3885 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 3886 3887 /// \brief Defines an implicitly-declared copy assignment operator. 3888 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 3889 CXXMethodDecl *MethodDecl); 3890 3891 /// \brief Declare the implicit move assignment operator for the given class. 3892 /// 3893 /// \param ClassDecl The Class declaration into which the implicit 3894 /// move assignment operator will be added. 3895 /// 3896 /// \returns The implicitly-declared move assignment operator, or NULL if it 3897 /// wasn't declared. 3898 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 3899 3900 /// \brief Defines an implicitly-declared move assignment operator. 3901 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 3902 CXXMethodDecl *MethodDecl); 3903 3904 /// \brief Force the declaration of any implicitly-declared members of this 3905 /// class. 3906 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 3907 3908 /// \brief Determine whether the given function is an implicitly-deleted 3909 /// special member function. 3910 bool isImplicitlyDeleted(FunctionDecl *FD); 3911 3912 /// \brief Check whether 'this' shows up in the type of a static member 3913 /// function after the (naturally empty) cv-qualifier-seq would be. 3914 /// 3915 /// \returns true if an error occurred. 3916 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 3917 3918 /// \brief Whether this' shows up in the exception specification of a static 3919 /// member function. 3920 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 3921 3922 /// \brief Check whether 'this' shows up in the attributes of the given 3923 /// static member function. 3924 /// 3925 /// \returns true if an error occurred. 3926 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 3927 3928 /// MaybeBindToTemporary - If the passed in expression has a record type with 3929 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 3930 /// it simply returns the passed in expression. 3931 ExprResult MaybeBindToTemporary(Expr *E); 3932 3933 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 3934 MultiExprArg ArgsPtr, 3935 SourceLocation Loc, 3936 SmallVectorImpl<Expr*> &ConvertedArgs, 3937 bool AllowExplicit = false, 3938 bool IsListInitialization = false); 3939 3940 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 3941 SourceLocation NameLoc, 3942 IdentifierInfo &Name); 3943 3944 ParsedType getDestructorName(SourceLocation TildeLoc, 3945 IdentifierInfo &II, SourceLocation NameLoc, 3946 Scope *S, CXXScopeSpec &SS, 3947 ParsedType ObjectType, 3948 bool EnteringContext); 3949 3950 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType); 3951 3952 // Checks that reinterpret casts don't have undefined behavior. 3953 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 3954 bool IsDereference, SourceRange Range); 3955 3956 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 3957 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 3958 tok::TokenKind Kind, 3959 SourceLocation LAngleBracketLoc, 3960 Declarator &D, 3961 SourceLocation RAngleBracketLoc, 3962 SourceLocation LParenLoc, 3963 Expr *E, 3964 SourceLocation RParenLoc); 3965 3966 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 3967 tok::TokenKind Kind, 3968 TypeSourceInfo *Ty, 3969 Expr *E, 3970 SourceRange AngleBrackets, 3971 SourceRange Parens); 3972 3973 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3974 SourceLocation TypeidLoc, 3975 TypeSourceInfo *Operand, 3976 SourceLocation RParenLoc); 3977 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3978 SourceLocation TypeidLoc, 3979 Expr *Operand, 3980 SourceLocation RParenLoc); 3981 3982 /// ActOnCXXTypeid - Parse typeid( something ). 3983 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 3984 SourceLocation LParenLoc, bool isType, 3985 void *TyOrExpr, 3986 SourceLocation RParenLoc); 3987 3988 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3989 SourceLocation TypeidLoc, 3990 TypeSourceInfo *Operand, 3991 SourceLocation RParenLoc); 3992 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3993 SourceLocation TypeidLoc, 3994 Expr *Operand, 3995 SourceLocation RParenLoc); 3996 3997 /// ActOnCXXUuidof - Parse __uuidof( something ). 3998 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 3999 SourceLocation LParenLoc, bool isType, 4000 void *TyOrExpr, 4001 SourceLocation RParenLoc); 4002 4003 4004 //// ActOnCXXThis - Parse 'this' pointer. 4005 ExprResult ActOnCXXThis(SourceLocation loc); 4006 4007 /// \brief Try to retrieve the type of the 'this' pointer. 4008 /// 4009 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 4010 QualType getCurrentThisType(); 4011 4012 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the 4013 /// current context not being a non-static member function. In such cases, 4014 /// this provides the type used for 'this'. 4015 QualType CXXThisTypeOverride; 4016 4017 /// \brief RAII object used to temporarily allow the C++ 'this' expression 4018 /// to be used, with the given qualifiers on the current class type. 4019 class CXXThisScopeRAII { 4020 Sema &S; 4021 QualType OldCXXThisTypeOverride; 4022 bool Enabled; 4023 4024 public: 4025 /// \brief Introduce a new scope where 'this' may be allowed (when enabled), 4026 /// using the given declaration (which is either a class template or a 4027 /// class) along with the given qualifiers. 4028 /// along with the qualifiers placed on '*this'. 4029 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals, 4030 bool Enabled = true); 4031 4032 ~CXXThisScopeRAII(); 4033 }; 4034 4035 /// \brief Make sure the value of 'this' is actually available in the current 4036 /// context, if it is a potentially evaluated context. 4037 /// 4038 /// \param Loc The location at which the capture of 'this' occurs. 4039 /// 4040 /// \param Explicit Whether 'this' is explicitly captured in a lambda 4041 /// capture list. 4042 void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false); 4043 4044 /// \brief Determine whether the given type is the type of *this that is used 4045 /// outside of the body of a member function for a type that is currently 4046 /// being defined. 4047 bool isThisOutsideMemberFunctionBody(QualType BaseType); 4048 4049 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 4050 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 4051 4052 4053 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 4054 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 4055 4056 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 4057 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 4058 4059 //// ActOnCXXThrow - Parse throw expressions. 4060 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 4061 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 4062 bool IsThrownVarInScope); 4063 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 4064 bool IsThrownVarInScope); 4065 4066 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 4067 /// Can be interpreted either as function-style casting ("int(x)") 4068 /// or class type construction ("ClassType(x,y,z)") 4069 /// or creation of a value-initialized type ("int()"). 4070 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 4071 SourceLocation LParenLoc, 4072 MultiExprArg Exprs, 4073 SourceLocation RParenLoc); 4074 4075 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 4076 SourceLocation LParenLoc, 4077 MultiExprArg Exprs, 4078 SourceLocation RParenLoc); 4079 4080 /// ActOnCXXNew - Parsed a C++ 'new' expression. 4081 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 4082 SourceLocation PlacementLParen, 4083 MultiExprArg PlacementArgs, 4084 SourceLocation PlacementRParen, 4085 SourceRange TypeIdParens, Declarator &D, 4086 Expr *Initializer); 4087 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, 4088 SourceLocation PlacementLParen, 4089 MultiExprArg PlacementArgs, 4090 SourceLocation PlacementRParen, 4091 SourceRange TypeIdParens, 4092 QualType AllocType, 4093 TypeSourceInfo *AllocTypeInfo, 4094 Expr *ArraySize, 4095 SourceRange DirectInitRange, 4096 Expr *Initializer, 4097 bool TypeMayContainAuto = true); 4098 4099 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 4100 SourceRange R); 4101 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 4102 bool UseGlobal, QualType AllocType, bool IsArray, 4103 MultiExprArg PlaceArgs, 4104 FunctionDecl *&OperatorNew, 4105 FunctionDecl *&OperatorDelete); 4106 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 4107 DeclarationName Name, MultiExprArg Args, 4108 DeclContext *Ctx, 4109 bool AllowMissing, FunctionDecl *&Operator, 4110 bool Diagnose = true); 4111 void DeclareGlobalNewDelete(); 4112 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 4113 QualType Argument, 4114 bool addMallocAttr = false); 4115 4116 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 4117 DeclarationName Name, FunctionDecl* &Operator, 4118 bool Diagnose = true); 4119 4120 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 4121 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 4122 bool UseGlobal, bool ArrayForm, 4123 Expr *Operand); 4124 4125 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 4126 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 4127 SourceLocation StmtLoc, 4128 bool ConvertToBoolean); 4129 4130 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 4131 Expr *Operand, SourceLocation RParen); 4132 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 4133 SourceLocation RParen); 4134 4135 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support 4136 /// pseudo-functions. 4137 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 4138 SourceLocation KWLoc, 4139 ParsedType Ty, 4140 SourceLocation RParen); 4141 4142 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT, 4143 SourceLocation KWLoc, 4144 TypeSourceInfo *T, 4145 SourceLocation RParen); 4146 4147 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support 4148 /// pseudo-functions. 4149 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT, 4150 SourceLocation KWLoc, 4151 ParsedType LhsTy, 4152 ParsedType RhsTy, 4153 SourceLocation RParen); 4154 4155 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT, 4156 SourceLocation KWLoc, 4157 TypeSourceInfo *LhsT, 4158 TypeSourceInfo *RhsT, 4159 SourceLocation RParen); 4160 4161 /// \brief Parsed one of the type trait support pseudo-functions. 4162 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 4163 ArrayRef<ParsedType> Args, 4164 SourceLocation RParenLoc); 4165 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 4166 ArrayRef<TypeSourceInfo *> Args, 4167 SourceLocation RParenLoc); 4168 4169 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 4170 /// pseudo-functions. 4171 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 4172 SourceLocation KWLoc, 4173 ParsedType LhsTy, 4174 Expr *DimExpr, 4175 SourceLocation RParen); 4176 4177 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 4178 SourceLocation KWLoc, 4179 TypeSourceInfo *TSInfo, 4180 Expr *DimExpr, 4181 SourceLocation RParen); 4182 4183 /// ActOnExpressionTrait - Parsed one of the unary type trait support 4184 /// pseudo-functions. 4185 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 4186 SourceLocation KWLoc, 4187 Expr *Queried, 4188 SourceLocation RParen); 4189 4190 ExprResult BuildExpressionTrait(ExpressionTrait OET, 4191 SourceLocation KWLoc, 4192 Expr *Queried, 4193 SourceLocation RParen); 4194 4195 ExprResult ActOnStartCXXMemberReference(Scope *S, 4196 Expr *Base, 4197 SourceLocation OpLoc, 4198 tok::TokenKind OpKind, 4199 ParsedType &ObjectType, 4200 bool &MayBePseudoDestructor); 4201 4202 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 4203 4204 ExprResult BuildPseudoDestructorExpr(Expr *Base, 4205 SourceLocation OpLoc, 4206 tok::TokenKind OpKind, 4207 const CXXScopeSpec &SS, 4208 TypeSourceInfo *ScopeType, 4209 SourceLocation CCLoc, 4210 SourceLocation TildeLoc, 4211 PseudoDestructorTypeStorage DestroyedType, 4212 bool HasTrailingLParen); 4213 4214 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 4215 SourceLocation OpLoc, 4216 tok::TokenKind OpKind, 4217 CXXScopeSpec &SS, 4218 UnqualifiedId &FirstTypeName, 4219 SourceLocation CCLoc, 4220 SourceLocation TildeLoc, 4221 UnqualifiedId &SecondTypeName, 4222 bool HasTrailingLParen); 4223 4224 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 4225 SourceLocation OpLoc, 4226 tok::TokenKind OpKind, 4227 SourceLocation TildeLoc, 4228 const DeclSpec& DS, 4229 bool HasTrailingLParen); 4230 4231 /// MaybeCreateExprWithCleanups - If the current full-expression 4232 /// requires any cleanups, surround it with a ExprWithCleanups node. 4233 /// Otherwise, just returns the passed-in expression. 4234 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 4235 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 4236 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 4237 4238 ExprResult ActOnFinishFullExpr(Expr *Expr) { 4239 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc() 4240 : SourceLocation()); 4241 } 4242 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 4243 bool DiscardedValue = false, 4244 bool IsConstexpr = false); 4245 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 4246 4247 // Marks SS invalid if it represents an incomplete type. 4248 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 4249 4250 DeclContext *computeDeclContext(QualType T); 4251 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 4252 bool EnteringContext = false); 4253 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 4254 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 4255 4256 /// \brief The parser has parsed a global nested-name-specifier '::'. 4257 /// 4258 /// \param S The scope in which this nested-name-specifier occurs. 4259 /// 4260 /// \param CCLoc The location of the '::'. 4261 /// 4262 /// \param SS The nested-name-specifier, which will be updated in-place 4263 /// to reflect the parsed nested-name-specifier. 4264 /// 4265 /// \returns true if an error occurred, false otherwise. 4266 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 4267 CXXScopeSpec &SS); 4268 4269 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD); 4270 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 4271 4272 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 4273 SourceLocation IdLoc, 4274 IdentifierInfo &II, 4275 ParsedType ObjectType); 4276 4277 bool BuildCXXNestedNameSpecifier(Scope *S, 4278 IdentifierInfo &Identifier, 4279 SourceLocation IdentifierLoc, 4280 SourceLocation CCLoc, 4281 QualType ObjectType, 4282 bool EnteringContext, 4283 CXXScopeSpec &SS, 4284 NamedDecl *ScopeLookupResult, 4285 bool ErrorRecoveryLookup); 4286 4287 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 4288 /// 4289 /// \param S The scope in which this nested-name-specifier occurs. 4290 /// 4291 /// \param Identifier The identifier preceding the '::'. 4292 /// 4293 /// \param IdentifierLoc The location of the identifier. 4294 /// 4295 /// \param CCLoc The location of the '::'. 4296 /// 4297 /// \param ObjectType The type of the object, if we're parsing 4298 /// nested-name-specifier in a member access expression. 4299 /// 4300 /// \param EnteringContext Whether we're entering the context nominated by 4301 /// this nested-name-specifier. 4302 /// 4303 /// \param SS The nested-name-specifier, which is both an input 4304 /// parameter (the nested-name-specifier before this type) and an 4305 /// output parameter (containing the full nested-name-specifier, 4306 /// including this new type). 4307 /// 4308 /// \returns true if an error occurred, false otherwise. 4309 bool ActOnCXXNestedNameSpecifier(Scope *S, 4310 IdentifierInfo &Identifier, 4311 SourceLocation IdentifierLoc, 4312 SourceLocation CCLoc, 4313 ParsedType ObjectType, 4314 bool EnteringContext, 4315 CXXScopeSpec &SS); 4316 4317 ExprResult ActOnDecltypeExpression(Expr *E); 4318 4319 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 4320 const DeclSpec &DS, 4321 SourceLocation ColonColonLoc); 4322 4323 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 4324 IdentifierInfo &Identifier, 4325 SourceLocation IdentifierLoc, 4326 SourceLocation ColonLoc, 4327 ParsedType ObjectType, 4328 bool EnteringContext); 4329 4330 /// \brief The parser has parsed a nested-name-specifier 4331 /// 'template[opt] template-name < template-args >::'. 4332 /// 4333 /// \param S The scope in which this nested-name-specifier occurs. 4334 /// 4335 /// \param SS The nested-name-specifier, which is both an input 4336 /// parameter (the nested-name-specifier before this type) and an 4337 /// output parameter (containing the full nested-name-specifier, 4338 /// including this new type). 4339 /// 4340 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 4341 /// \param TemplateName the template name. 4342 /// \param TemplateNameLoc The location of the template name. 4343 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4344 /// \param TemplateArgs The template arguments. 4345 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4346 /// \param CCLoc The location of the '::'. 4347 /// 4348 /// \param EnteringContext Whether we're entering the context of the 4349 /// nested-name-specifier. 4350 /// 4351 /// 4352 /// \returns true if an error occurred, false otherwise. 4353 bool ActOnCXXNestedNameSpecifier(Scope *S, 4354 CXXScopeSpec &SS, 4355 SourceLocation TemplateKWLoc, 4356 TemplateTy TemplateName, 4357 SourceLocation TemplateNameLoc, 4358 SourceLocation LAngleLoc, 4359 ASTTemplateArgsPtr TemplateArgs, 4360 SourceLocation RAngleLoc, 4361 SourceLocation CCLoc, 4362 bool EnteringContext); 4363 4364 /// \brief Given a C++ nested-name-specifier, produce an annotation value 4365 /// that the parser can use later to reconstruct the given 4366 /// nested-name-specifier. 4367 /// 4368 /// \param SS A nested-name-specifier. 4369 /// 4370 /// \returns A pointer containing all of the information in the 4371 /// nested-name-specifier \p SS. 4372 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 4373 4374 /// \brief Given an annotation pointer for a nested-name-specifier, restore 4375 /// the nested-name-specifier structure. 4376 /// 4377 /// \param Annotation The annotation pointer, produced by 4378 /// \c SaveNestedNameSpecifierAnnotation(). 4379 /// 4380 /// \param AnnotationRange The source range corresponding to the annotation. 4381 /// 4382 /// \param SS The nested-name-specifier that will be updated with the contents 4383 /// of the annotation pointer. 4384 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 4385 SourceRange AnnotationRange, 4386 CXXScopeSpec &SS); 4387 4388 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4389 4390 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 4391 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 4392 /// After this method is called, according to [C++ 3.4.3p3], names should be 4393 /// looked up in the declarator-id's scope, until the declarator is parsed and 4394 /// ActOnCXXExitDeclaratorScope is called. 4395 /// The 'SS' should be a non-empty valid CXXScopeSpec. 4396 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 4397 4398 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 4399 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 4400 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 4401 /// Used to indicate that names should revert to being looked up in the 4402 /// defining scope. 4403 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4404 4405 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4406 /// initializer for the declaration 'Dcl'. 4407 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4408 /// static data member of class X, names should be looked up in the scope of 4409 /// class X. 4410 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 4411 4412 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4413 /// initializer for the declaration 'Dcl'. 4414 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 4415 4416 /// \brief Create a new lambda closure type. 4417 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 4418 TypeSourceInfo *Info, 4419 bool KnownDependent); 4420 4421 /// \brief Start the definition of a lambda expression. 4422 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 4423 SourceRange IntroducerRange, 4424 TypeSourceInfo *MethodType, 4425 SourceLocation EndLoc, 4426 ArrayRef<ParmVarDecl *> Params); 4427 4428 /// \brief Introduce the scope for a lambda expression. 4429 sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator, 4430 SourceRange IntroducerRange, 4431 LambdaCaptureDefault CaptureDefault, 4432 SourceLocation CaptureDefaultLoc, 4433 bool ExplicitParams, 4434 bool ExplicitResultType, 4435 bool Mutable); 4436 4437 /// \brief Check and build an init-capture with the specified name and 4438 /// initializer. 4439 FieldDecl *checkInitCapture(SourceLocation Loc, bool ByRef, 4440 IdentifierInfo *Id, Expr *Init); 4441 4442 /// \brief Note that we have finished the explicit captures for the 4443 /// given lambda. 4444 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 4445 4446 /// \brief Introduce the lambda parameters into scope. 4447 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); 4448 4449 /// \brief Deduce a block or lambda's return type based on the return 4450 /// statements present in the body. 4451 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 4452 4453 /// ActOnStartOfLambdaDefinition - This is called just before we start 4454 /// parsing the body of a lambda; it analyzes the explicit captures and 4455 /// arguments, and sets up various data-structures for the body of the 4456 /// lambda. 4457 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 4458 Declarator &ParamInfo, Scope *CurScope); 4459 4460 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 4461 /// is invoked to pop the information about the lambda. 4462 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 4463 bool IsInstantiation = false); 4464 4465 /// ActOnLambdaExpr - This is called when the body of a lambda expression 4466 /// was successfully completed. 4467 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 4468 Scope *CurScope, 4469 bool IsInstantiation = false); 4470 4471 /// \brief Define the "body" of the conversion from a lambda object to a 4472 /// function pointer. 4473 /// 4474 /// This routine doesn't actually define a sensible body; rather, it fills 4475 /// in the initialization expression needed to copy the lambda object into 4476 /// the block, and IR generation actually generates the real body of the 4477 /// block pointer conversion. 4478 void DefineImplicitLambdaToFunctionPointerConversion( 4479 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 4480 4481 /// \brief Define the "body" of the conversion from a lambda object to a 4482 /// block pointer. 4483 /// 4484 /// This routine doesn't actually define a sensible body; rather, it fills 4485 /// in the initialization expression needed to copy the lambda object into 4486 /// the block, and IR generation actually generates the real body of the 4487 /// block pointer conversion. 4488 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 4489 CXXConversionDecl *Conv); 4490 4491 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 4492 SourceLocation ConvLocation, 4493 CXXConversionDecl *Conv, 4494 Expr *Src); 4495 4496 // ParseObjCStringLiteral - Parse Objective-C string literals. 4497 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 4498 Expr **Strings, 4499 unsigned NumStrings); 4500 4501 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 4502 4503 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 4504 /// numeric literal expression. Type of the expression will be "NSNumber *" 4505 /// or "id" if NSNumber is unavailable. 4506 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 4507 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 4508 bool Value); 4509 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 4510 4511 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 4512 /// '@' prefixed parenthesized expression. The type of the expression will 4513 /// either be "NSNumber *" or "NSString *" depending on the type of 4514 /// ValueType, which is allowed to be a built-in numeric type or 4515 /// "char *" or "const char *". 4516 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 4517 4518 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 4519 Expr *IndexExpr, 4520 ObjCMethodDecl *getterMethod, 4521 ObjCMethodDecl *setterMethod); 4522 4523 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 4524 ObjCDictionaryElement *Elements, 4525 unsigned NumElements); 4526 4527 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 4528 TypeSourceInfo *EncodedTypeInfo, 4529 SourceLocation RParenLoc); 4530 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 4531 CXXConversionDecl *Method, 4532 bool HadMultipleCandidates); 4533 4534 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 4535 SourceLocation EncodeLoc, 4536 SourceLocation LParenLoc, 4537 ParsedType Ty, 4538 SourceLocation RParenLoc); 4539 4540 /// ParseObjCSelectorExpression - Build selector expression for \@selector 4541 ExprResult ParseObjCSelectorExpression(Selector Sel, 4542 SourceLocation AtLoc, 4543 SourceLocation SelLoc, 4544 SourceLocation LParenLoc, 4545 SourceLocation RParenLoc); 4546 4547 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 4548 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 4549 SourceLocation AtLoc, 4550 SourceLocation ProtoLoc, 4551 SourceLocation LParenLoc, 4552 SourceLocation ProtoIdLoc, 4553 SourceLocation RParenLoc); 4554 4555 //===--------------------------------------------------------------------===// 4556 // C++ Declarations 4557 // 4558 Decl *ActOnStartLinkageSpecification(Scope *S, 4559 SourceLocation ExternLoc, 4560 SourceLocation LangLoc, 4561 StringRef Lang, 4562 SourceLocation LBraceLoc); 4563 Decl *ActOnFinishLinkageSpecification(Scope *S, 4564 Decl *LinkageSpec, 4565 SourceLocation RBraceLoc); 4566 4567 4568 //===--------------------------------------------------------------------===// 4569 // C++ Classes 4570 // 4571 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 4572 const CXXScopeSpec *SS = 0); 4573 4574 bool ActOnAccessSpecifier(AccessSpecifier Access, 4575 SourceLocation ASLoc, 4576 SourceLocation ColonLoc, 4577 AttributeList *Attrs = 0); 4578 4579 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 4580 Declarator &D, 4581 MultiTemplateParamsArg TemplateParameterLists, 4582 Expr *BitfieldWidth, const VirtSpecifiers &VS, 4583 InClassInitStyle InitStyle); 4584 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, 4585 Expr *Init); 4586 4587 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4588 Scope *S, 4589 CXXScopeSpec &SS, 4590 IdentifierInfo *MemberOrBase, 4591 ParsedType TemplateTypeTy, 4592 const DeclSpec &DS, 4593 SourceLocation IdLoc, 4594 SourceLocation LParenLoc, 4595 ArrayRef<Expr *> Args, 4596 SourceLocation RParenLoc, 4597 SourceLocation EllipsisLoc); 4598 4599 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4600 Scope *S, 4601 CXXScopeSpec &SS, 4602 IdentifierInfo *MemberOrBase, 4603 ParsedType TemplateTypeTy, 4604 const DeclSpec &DS, 4605 SourceLocation IdLoc, 4606 Expr *InitList, 4607 SourceLocation EllipsisLoc); 4608 4609 MemInitResult BuildMemInitializer(Decl *ConstructorD, 4610 Scope *S, 4611 CXXScopeSpec &SS, 4612 IdentifierInfo *MemberOrBase, 4613 ParsedType TemplateTypeTy, 4614 const DeclSpec &DS, 4615 SourceLocation IdLoc, 4616 Expr *Init, 4617 SourceLocation EllipsisLoc); 4618 4619 MemInitResult BuildMemberInitializer(ValueDecl *Member, 4620 Expr *Init, 4621 SourceLocation IdLoc); 4622 4623 MemInitResult BuildBaseInitializer(QualType BaseType, 4624 TypeSourceInfo *BaseTInfo, 4625 Expr *Init, 4626 CXXRecordDecl *ClassDecl, 4627 SourceLocation EllipsisLoc); 4628 4629 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 4630 Expr *Init, 4631 CXXRecordDecl *ClassDecl); 4632 4633 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4634 CXXCtorInitializer *Initializer); 4635 4636 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4637 ArrayRef<CXXCtorInitializer *> Initializers = None); 4638 4639 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 4640 4641 4642 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 4643 /// mark all the non-trivial destructors of its members and bases as 4644 /// referenced. 4645 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 4646 CXXRecordDecl *Record); 4647 4648 /// \brief The list of classes whose vtables have been used within 4649 /// this translation unit, and the source locations at which the 4650 /// first use occurred. 4651 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 4652 4653 /// \brief The list of vtables that are required but have not yet been 4654 /// materialized. 4655 SmallVector<VTableUse, 16> VTableUses; 4656 4657 /// \brief The set of classes whose vtables have been used within 4658 /// this translation unit, and a bit that will be true if the vtable is 4659 /// required to be emitted (otherwise, it should be emitted only if needed 4660 /// by code generation). 4661 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 4662 4663 /// \brief Load any externally-stored vtable uses. 4664 void LoadExternalVTableUses(); 4665 4666 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, 4667 &ExternalSemaSource::ReadDynamicClasses, 2, 2> 4668 DynamicClassesType; 4669 4670 /// \brief A list of all of the dynamic classes in this translation 4671 /// unit. 4672 DynamicClassesType DynamicClasses; 4673 4674 /// \brief Note that the vtable for the given class was used at the 4675 /// given location. 4676 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 4677 bool DefinitionRequired = false); 4678 4679 /// \brief Mark the exception specifications of all virtual member functions 4680 /// in the given class as needed. 4681 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 4682 const CXXRecordDecl *RD); 4683 4684 /// MarkVirtualMembersReferenced - Will mark all members of the given 4685 /// CXXRecordDecl referenced. 4686 void MarkVirtualMembersReferenced(SourceLocation Loc, 4687 const CXXRecordDecl *RD); 4688 4689 /// \brief Define all of the vtables that have been used in this 4690 /// translation unit and reference any virtual members used by those 4691 /// vtables. 4692 /// 4693 /// \returns true if any work was done, false otherwise. 4694 bool DefineUsedVTables(); 4695 4696 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 4697 4698 void ActOnMemInitializers(Decl *ConstructorDecl, 4699 SourceLocation ColonLoc, 4700 ArrayRef<CXXCtorInitializer*> MemInits, 4701 bool AnyErrors); 4702 4703 void CheckCompletedCXXClass(CXXRecordDecl *Record); 4704 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4705 Decl *TagDecl, 4706 SourceLocation LBrac, 4707 SourceLocation RBrac, 4708 AttributeList *AttrList); 4709 void ActOnFinishCXXMemberDecls(); 4710 4711 void ActOnReenterTemplateScope(Scope *S, Decl *Template); 4712 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D); 4713 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 4714 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4715 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 4716 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 4717 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4718 void ActOnFinishDelayedMemberInitializers(Decl *Record); 4719 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 4720 CachedTokens &Toks); 4721 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 4722 bool IsInsideALocalClassWithinATemplateFunction(); 4723 4724 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 4725 Expr *AssertExpr, 4726 Expr *AssertMessageExpr, 4727 SourceLocation RParenLoc); 4728 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 4729 Expr *AssertExpr, 4730 StringLiteral *AssertMessageExpr, 4731 SourceLocation RParenLoc, 4732 bool Failed); 4733 4734 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 4735 SourceLocation FriendLoc, 4736 TypeSourceInfo *TSInfo); 4737 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 4738 MultiTemplateParamsArg TemplateParams); 4739 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 4740 MultiTemplateParamsArg TemplateParams); 4741 4742 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 4743 StorageClass& SC); 4744 void CheckConstructor(CXXConstructorDecl *Constructor); 4745 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 4746 StorageClass& SC); 4747 bool CheckDestructor(CXXDestructorDecl *Destructor); 4748 void CheckConversionDeclarator(Declarator &D, QualType &R, 4749 StorageClass& SC); 4750 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 4751 4752 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); 4753 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, 4754 const FunctionProtoType *T); 4755 void CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 4756 4757 //===--------------------------------------------------------------------===// 4758 // C++ Derived Classes 4759 // 4760 4761 /// ActOnBaseSpecifier - Parsed a base specifier 4762 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 4763 SourceRange SpecifierRange, 4764 bool Virtual, AccessSpecifier Access, 4765 TypeSourceInfo *TInfo, 4766 SourceLocation EllipsisLoc); 4767 4768 BaseResult ActOnBaseSpecifier(Decl *classdecl, 4769 SourceRange SpecifierRange, 4770 ParsedAttributes &Attrs, 4771 bool Virtual, AccessSpecifier Access, 4772 ParsedType basetype, 4773 SourceLocation BaseLoc, 4774 SourceLocation EllipsisLoc); 4775 4776 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 4777 unsigned NumBases); 4778 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 4779 unsigned NumBases); 4780 4781 bool IsDerivedFrom(QualType Derived, QualType Base); 4782 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 4783 4784 // FIXME: I don't like this name. 4785 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 4786 4787 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 4788 4789 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4790 SourceLocation Loc, SourceRange Range, 4791 CXXCastPath *BasePath = 0, 4792 bool IgnoreAccess = false); 4793 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4794 unsigned InaccessibleBaseID, 4795 unsigned AmbigiousBaseConvID, 4796 SourceLocation Loc, SourceRange Range, 4797 DeclarationName Name, 4798 CXXCastPath *BasePath); 4799 4800 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 4801 4802 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 4803 const CXXMethodDecl *Old); 4804 4805 /// CheckOverridingFunctionReturnType - Checks whether the return types are 4806 /// covariant, according to C++ [class.virtual]p5. 4807 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4808 const CXXMethodDecl *Old); 4809 4810 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 4811 /// spec is a subset of base spec. 4812 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 4813 const CXXMethodDecl *Old); 4814 4815 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 4816 4817 /// CheckOverrideControl - Check C++11 override control semantics. 4818 void CheckOverrideControl(NamedDecl *D); 4819 4820 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 4821 /// overrides a virtual member function marked 'final', according to 4822 /// C++11 [class.virtual]p4. 4823 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 4824 const CXXMethodDecl *Old); 4825 4826 4827 //===--------------------------------------------------------------------===// 4828 // C++ Access Control 4829 // 4830 4831 enum AccessResult { 4832 AR_accessible, 4833 AR_inaccessible, 4834 AR_dependent, 4835 AR_delayed 4836 }; 4837 4838 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 4839 NamedDecl *PrevMemberDecl, 4840 AccessSpecifier LexicalAS); 4841 4842 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 4843 DeclAccessPair FoundDecl); 4844 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 4845 DeclAccessPair FoundDecl); 4846 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 4847 SourceRange PlacementRange, 4848 CXXRecordDecl *NamingClass, 4849 DeclAccessPair FoundDecl, 4850 bool Diagnose = true); 4851 AccessResult CheckConstructorAccess(SourceLocation Loc, 4852 CXXConstructorDecl *D, 4853 const InitializedEntity &Entity, 4854 AccessSpecifier Access, 4855 bool IsCopyBindingRefToTemp = false); 4856 AccessResult CheckConstructorAccess(SourceLocation Loc, 4857 CXXConstructorDecl *D, 4858 const InitializedEntity &Entity, 4859 AccessSpecifier Access, 4860 const PartialDiagnostic &PDiag); 4861 AccessResult CheckDestructorAccess(SourceLocation Loc, 4862 CXXDestructorDecl *Dtor, 4863 const PartialDiagnostic &PDiag, 4864 QualType objectType = QualType()); 4865 AccessResult CheckFriendAccess(NamedDecl *D); 4866 AccessResult CheckMemberAccess(SourceLocation UseLoc, 4867 CXXRecordDecl *NamingClass, 4868 NamedDecl *D); 4869 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 4870 Expr *ObjectExpr, 4871 Expr *ArgExpr, 4872 DeclAccessPair FoundDecl); 4873 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 4874 DeclAccessPair FoundDecl); 4875 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 4876 QualType Base, QualType Derived, 4877 const CXXBasePath &Path, 4878 unsigned DiagID, 4879 bool ForceCheck = false, 4880 bool ForceUnprivileged = false); 4881 void CheckLookupAccess(const LookupResult &R); 4882 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx); 4883 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, 4884 AccessSpecifier access, 4885 QualType objectType); 4886 4887 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 4888 const MultiLevelTemplateArgumentList &TemplateArgs); 4889 void PerformDependentDiagnostics(const DeclContext *Pattern, 4890 const MultiLevelTemplateArgumentList &TemplateArgs); 4891 4892 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4893 4894 /// \brief When true, access checking violations are treated as SFINAE 4895 /// failures rather than hard errors. 4896 bool AccessCheckingSFINAE; 4897 4898 enum AbstractDiagSelID { 4899 AbstractNone = -1, 4900 AbstractReturnType, 4901 AbstractParamType, 4902 AbstractVariableType, 4903 AbstractFieldType, 4904 AbstractIvarType, 4905 AbstractSynthesizedIvarType, 4906 AbstractArrayType 4907 }; 4908 4909 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4910 TypeDiagnoser &Diagnoser); 4911 template<typename T1> 4912 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4913 unsigned DiagID, 4914 const T1 &Arg1) { 4915 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 4916 return RequireNonAbstractType(Loc, T, Diagnoser); 4917 } 4918 4919 template<typename T1, typename T2> 4920 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4921 unsigned DiagID, 4922 const T1 &Arg1, const T2 &Arg2) { 4923 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 4924 return RequireNonAbstractType(Loc, T, Diagnoser); 4925 } 4926 4927 template<typename T1, typename T2, typename T3> 4928 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4929 unsigned DiagID, 4930 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { 4931 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); 4932 return RequireNonAbstractType(Loc, T, Diagnoser); 4933 } 4934 4935 void DiagnoseAbstractType(const CXXRecordDecl *RD); 4936 4937 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 4938 AbstractDiagSelID SelID = AbstractNone); 4939 4940 //===--------------------------------------------------------------------===// 4941 // C++ Overloaded Operators [C++ 13.5] 4942 // 4943 4944 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 4945 4946 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 4947 4948 //===--------------------------------------------------------------------===// 4949 // C++ Templates [C++ 14] 4950 // 4951 void FilterAcceptableTemplateNames(LookupResult &R, 4952 bool AllowFunctionTemplates = true); 4953 bool hasAnyAcceptableTemplateNames(LookupResult &R, 4954 bool AllowFunctionTemplates = true); 4955 4956 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 4957 QualType ObjectType, bool EnteringContext, 4958 bool &MemberOfUnknownSpecialization); 4959 4960 TemplateNameKind isTemplateName(Scope *S, 4961 CXXScopeSpec &SS, 4962 bool hasTemplateKeyword, 4963 UnqualifiedId &Name, 4964 ParsedType ObjectType, 4965 bool EnteringContext, 4966 TemplateTy &Template, 4967 bool &MemberOfUnknownSpecialization); 4968 4969 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 4970 SourceLocation IILoc, 4971 Scope *S, 4972 const CXXScopeSpec *SS, 4973 TemplateTy &SuggestedTemplate, 4974 TemplateNameKind &SuggestedKind); 4975 4976 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 4977 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 4978 4979 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 4980 SourceLocation EllipsisLoc, 4981 SourceLocation KeyLoc, 4982 IdentifierInfo *ParamName, 4983 SourceLocation ParamNameLoc, 4984 unsigned Depth, unsigned Position, 4985 SourceLocation EqualLoc, 4986 ParsedType DefaultArg); 4987 4988 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 4989 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 4990 unsigned Depth, 4991 unsigned Position, 4992 SourceLocation EqualLoc, 4993 Expr *DefaultArg); 4994 Decl *ActOnTemplateTemplateParameter(Scope *S, 4995 SourceLocation TmpLoc, 4996 TemplateParameterList *Params, 4997 SourceLocation EllipsisLoc, 4998 IdentifierInfo *ParamName, 4999 SourceLocation ParamNameLoc, 5000 unsigned Depth, 5001 unsigned Position, 5002 SourceLocation EqualLoc, 5003 ParsedTemplateArgument DefaultArg); 5004 5005 TemplateParameterList * 5006 ActOnTemplateParameterList(unsigned Depth, 5007 SourceLocation ExportLoc, 5008 SourceLocation TemplateLoc, 5009 SourceLocation LAngleLoc, 5010 Decl **Params, unsigned NumParams, 5011 SourceLocation RAngleLoc); 5012 5013 /// \brief The context in which we are checking a template parameter list. 5014 enum TemplateParamListContext { 5015 TPC_ClassTemplate, 5016 TPC_VarTemplate, 5017 TPC_FunctionTemplate, 5018 TPC_ClassTemplateMember, 5019 TPC_FriendClassTemplate, 5020 TPC_FriendFunctionTemplate, 5021 TPC_FriendFunctionTemplateDefinition, 5022 TPC_TypeAliasTemplate 5023 }; 5024 5025 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 5026 TemplateParameterList *OldParams, 5027 TemplateParamListContext TPC); 5028 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 5029 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 5030 const CXXScopeSpec &SS, ArrayRef<TemplateParameterList *> ParamLists, 5031 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid); 5032 5033 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 5034 SourceLocation KWLoc, CXXScopeSpec &SS, 5035 IdentifierInfo *Name, SourceLocation NameLoc, 5036 AttributeList *Attr, 5037 TemplateParameterList *TemplateParams, 5038 AccessSpecifier AS, 5039 SourceLocation ModulePrivateLoc, 5040 unsigned NumOuterTemplateParamLists, 5041 TemplateParameterList **OuterTemplateParamLists); 5042 5043 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 5044 TemplateArgumentListInfo &Out); 5045 5046 void NoteAllFoundTemplates(TemplateName Name); 5047 5048 QualType CheckTemplateIdType(TemplateName Template, 5049 SourceLocation TemplateLoc, 5050 TemplateArgumentListInfo &TemplateArgs); 5051 5052 TypeResult 5053 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5054 TemplateTy Template, SourceLocation TemplateLoc, 5055 SourceLocation LAngleLoc, 5056 ASTTemplateArgsPtr TemplateArgs, 5057 SourceLocation RAngleLoc, 5058 bool IsCtorOrDtorName = false); 5059 5060 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 5061 /// such as \c class T::template apply<U>. 5062 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 5063 TypeSpecifierType TagSpec, 5064 SourceLocation TagLoc, 5065 CXXScopeSpec &SS, 5066 SourceLocation TemplateKWLoc, 5067 TemplateTy TemplateD, 5068 SourceLocation TemplateLoc, 5069 SourceLocation LAngleLoc, 5070 ASTTemplateArgsPtr TemplateArgsIn, 5071 SourceLocation RAngleLoc); 5072 5073 DeclResult ActOnVarTemplateSpecialization( 5074 Scope *S, VarTemplateDecl *VarTemplate, Declarator &D, TypeSourceInfo *DI, 5075 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 5076 StorageClass SC, bool IsPartialSpecialization); 5077 5078 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 5079 SourceLocation TemplateLoc, 5080 SourceLocation TemplateNameLoc, 5081 const TemplateArgumentListInfo &TemplateArgs); 5082 5083 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 5084 const DeclarationNameInfo &NameInfo, 5085 VarTemplateDecl *Template, 5086 SourceLocation TemplateLoc, 5087 const TemplateArgumentListInfo *TemplateArgs); 5088 5089 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 5090 SourceLocation TemplateKWLoc, 5091 LookupResult &R, 5092 bool RequiresADL, 5093 const TemplateArgumentListInfo *TemplateArgs); 5094 5095 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 5096 SourceLocation TemplateKWLoc, 5097 const DeclarationNameInfo &NameInfo, 5098 const TemplateArgumentListInfo *TemplateArgs); 5099 5100 TemplateNameKind ActOnDependentTemplateName(Scope *S, 5101 CXXScopeSpec &SS, 5102 SourceLocation TemplateKWLoc, 5103 UnqualifiedId &Name, 5104 ParsedType ObjectType, 5105 bool EnteringContext, 5106 TemplateTy &Template); 5107 5108 DeclResult 5109 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 5110 SourceLocation KWLoc, 5111 SourceLocation ModulePrivateLoc, 5112 CXXScopeSpec &SS, 5113 TemplateTy Template, 5114 SourceLocation TemplateNameLoc, 5115 SourceLocation LAngleLoc, 5116 ASTTemplateArgsPtr TemplateArgs, 5117 SourceLocation RAngleLoc, 5118 AttributeList *Attr, 5119 MultiTemplateParamsArg TemplateParameterLists); 5120 5121 Decl *ActOnTemplateDeclarator(Scope *S, 5122 MultiTemplateParamsArg TemplateParameterLists, 5123 Declarator &D); 5124 5125 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 5126 MultiTemplateParamsArg TemplateParameterLists, 5127 Declarator &D); 5128 5129 bool 5130 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 5131 TemplateSpecializationKind NewTSK, 5132 NamedDecl *PrevDecl, 5133 TemplateSpecializationKind PrevTSK, 5134 SourceLocation PrevPtOfInstantiation, 5135 bool &SuppressNew); 5136 5137 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 5138 const TemplateArgumentListInfo &ExplicitTemplateArgs, 5139 LookupResult &Previous); 5140 5141 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 5142 TemplateArgumentListInfo *ExplicitTemplateArgs, 5143 LookupResult &Previous); 5144 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 5145 5146 DeclResult 5147 ActOnExplicitInstantiation(Scope *S, 5148 SourceLocation ExternLoc, 5149 SourceLocation TemplateLoc, 5150 unsigned TagSpec, 5151 SourceLocation KWLoc, 5152 const CXXScopeSpec &SS, 5153 TemplateTy Template, 5154 SourceLocation TemplateNameLoc, 5155 SourceLocation LAngleLoc, 5156 ASTTemplateArgsPtr TemplateArgs, 5157 SourceLocation RAngleLoc, 5158 AttributeList *Attr); 5159 5160 DeclResult 5161 ActOnExplicitInstantiation(Scope *S, 5162 SourceLocation ExternLoc, 5163 SourceLocation TemplateLoc, 5164 unsigned TagSpec, 5165 SourceLocation KWLoc, 5166 CXXScopeSpec &SS, 5167 IdentifierInfo *Name, 5168 SourceLocation NameLoc, 5169 AttributeList *Attr); 5170 5171 DeclResult ActOnExplicitInstantiation(Scope *S, 5172 SourceLocation ExternLoc, 5173 SourceLocation TemplateLoc, 5174 Declarator &D); 5175 5176 TemplateArgumentLoc 5177 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 5178 SourceLocation TemplateLoc, 5179 SourceLocation RAngleLoc, 5180 Decl *Param, 5181 SmallVectorImpl<TemplateArgument> 5182 &Converted, 5183 bool &HasDefaultArg); 5184 5185 /// \brief Specifies the context in which a particular template 5186 /// argument is being checked. 5187 enum CheckTemplateArgumentKind { 5188 /// \brief The template argument was specified in the code or was 5189 /// instantiated with some deduced template arguments. 5190 CTAK_Specified, 5191 5192 /// \brief The template argument was deduced via template argument 5193 /// deduction. 5194 CTAK_Deduced, 5195 5196 /// \brief The template argument was deduced from an array bound 5197 /// via template argument deduction. 5198 CTAK_DeducedFromArrayBound 5199 }; 5200 5201 bool CheckTemplateArgument(NamedDecl *Param, 5202 const TemplateArgumentLoc &Arg, 5203 NamedDecl *Template, 5204 SourceLocation TemplateLoc, 5205 SourceLocation RAngleLoc, 5206 unsigned ArgumentPackIndex, 5207 SmallVectorImpl<TemplateArgument> &Converted, 5208 CheckTemplateArgumentKind CTAK = CTAK_Specified); 5209 5210 /// \brief Check that the given template arguments can be be provided to 5211 /// the given template, converting the arguments along the way. 5212 /// 5213 /// \param Template The template to which the template arguments are being 5214 /// provided. 5215 /// 5216 /// \param TemplateLoc The location of the template name in the source. 5217 /// 5218 /// \param TemplateArgs The list of template arguments. If the template is 5219 /// a template template parameter, this function may extend the set of 5220 /// template arguments to also include substituted, defaulted template 5221 /// arguments. 5222 /// 5223 /// \param PartialTemplateArgs True if the list of template arguments is 5224 /// intentionally partial, e.g., because we're checking just the initial 5225 /// set of template arguments. 5226 /// 5227 /// \param Converted Will receive the converted, canonicalized template 5228 /// arguments. 5229 /// 5230 /// 5231 /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate 5232 /// when the template arguments contain a pack expansion that is being 5233 /// expanded into a fixed parameter list. 5234 /// 5235 /// \returns True if an error occurred, false otherwise. 5236 bool CheckTemplateArgumentList(TemplateDecl *Template, 5237 SourceLocation TemplateLoc, 5238 TemplateArgumentListInfo &TemplateArgs, 5239 bool PartialTemplateArgs, 5240 SmallVectorImpl<TemplateArgument> &Converted, 5241 bool *ExpansionIntoFixedList = 0); 5242 5243 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 5244 const TemplateArgumentLoc &Arg, 5245 SmallVectorImpl<TemplateArgument> &Converted); 5246 5247 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 5248 TypeSourceInfo *Arg); 5249 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 5250 QualType InstantiatedParamType, Expr *Arg, 5251 TemplateArgument &Converted, 5252 CheckTemplateArgumentKind CTAK = CTAK_Specified); 5253 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 5254 const TemplateArgumentLoc &Arg, 5255 unsigned ArgumentPackIndex); 5256 5257 ExprResult 5258 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 5259 QualType ParamType, 5260 SourceLocation Loc); 5261 ExprResult 5262 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 5263 SourceLocation Loc); 5264 5265 /// \brief Enumeration describing how template parameter lists are compared 5266 /// for equality. 5267 enum TemplateParameterListEqualKind { 5268 /// \brief We are matching the template parameter lists of two templates 5269 /// that might be redeclarations. 5270 /// 5271 /// \code 5272 /// template<typename T> struct X; 5273 /// template<typename T> struct X; 5274 /// \endcode 5275 TPL_TemplateMatch, 5276 5277 /// \brief We are matching the template parameter lists of two template 5278 /// template parameters as part of matching the template parameter lists 5279 /// of two templates that might be redeclarations. 5280 /// 5281 /// \code 5282 /// template<template<int I> class TT> struct X; 5283 /// template<template<int Value> class Other> struct X; 5284 /// \endcode 5285 TPL_TemplateTemplateParmMatch, 5286 5287 /// \brief We are matching the template parameter lists of a template 5288 /// template argument against the template parameter lists of a template 5289 /// template parameter. 5290 /// 5291 /// \code 5292 /// template<template<int Value> class Metafun> struct X; 5293 /// template<int Value> struct integer_c; 5294 /// X<integer_c> xic; 5295 /// \endcode 5296 TPL_TemplateTemplateArgumentMatch 5297 }; 5298 5299 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 5300 TemplateParameterList *Old, 5301 bool Complain, 5302 TemplateParameterListEqualKind Kind, 5303 SourceLocation TemplateArgLoc 5304 = SourceLocation()); 5305 5306 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 5307 5308 /// \brief Called when the parser has parsed a C++ typename 5309 /// specifier, e.g., "typename T::type". 5310 /// 5311 /// \param S The scope in which this typename type occurs. 5312 /// \param TypenameLoc the location of the 'typename' keyword 5313 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 5314 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 5315 /// \param IdLoc the location of the identifier. 5316 TypeResult 5317 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5318 const CXXScopeSpec &SS, const IdentifierInfo &II, 5319 SourceLocation IdLoc); 5320 5321 /// \brief Called when the parser has parsed a C++ typename 5322 /// specifier that ends in a template-id, e.g., 5323 /// "typename MetaFun::template apply<T1, T2>". 5324 /// 5325 /// \param S The scope in which this typename type occurs. 5326 /// \param TypenameLoc the location of the 'typename' keyword 5327 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 5328 /// \param TemplateLoc the location of the 'template' keyword, if any. 5329 /// \param TemplateName The template name. 5330 /// \param TemplateNameLoc The location of the template name. 5331 /// \param LAngleLoc The location of the opening angle bracket ('<'). 5332 /// \param TemplateArgs The template arguments. 5333 /// \param RAngleLoc The location of the closing angle bracket ('>'). 5334 TypeResult 5335 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5336 const CXXScopeSpec &SS, 5337 SourceLocation TemplateLoc, 5338 TemplateTy TemplateName, 5339 SourceLocation TemplateNameLoc, 5340 SourceLocation LAngleLoc, 5341 ASTTemplateArgsPtr TemplateArgs, 5342 SourceLocation RAngleLoc); 5343 5344 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 5345 SourceLocation KeywordLoc, 5346 NestedNameSpecifierLoc QualifierLoc, 5347 const IdentifierInfo &II, 5348 SourceLocation IILoc); 5349 5350 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 5351 SourceLocation Loc, 5352 DeclarationName Name); 5353 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 5354 5355 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 5356 bool RebuildTemplateParamsInCurrentInstantiation( 5357 TemplateParameterList *Params); 5358 5359 std::string 5360 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5361 const TemplateArgumentList &Args); 5362 5363 std::string 5364 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5365 const TemplateArgument *Args, 5366 unsigned NumArgs); 5367 5368 //===--------------------------------------------------------------------===// 5369 // C++ Variadic Templates (C++0x [temp.variadic]) 5370 //===--------------------------------------------------------------------===// 5371 5372 /// \brief The context in which an unexpanded parameter pack is 5373 /// being diagnosed. 5374 /// 5375 /// Note that the values of this enumeration line up with the first 5376 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 5377 enum UnexpandedParameterPackContext { 5378 /// \brief An arbitrary expression. 5379 UPPC_Expression = 0, 5380 5381 /// \brief The base type of a class type. 5382 UPPC_BaseType, 5383 5384 /// \brief The type of an arbitrary declaration. 5385 UPPC_DeclarationType, 5386 5387 /// \brief The type of a data member. 5388 UPPC_DataMemberType, 5389 5390 /// \brief The size of a bit-field. 5391 UPPC_BitFieldWidth, 5392 5393 /// \brief The expression in a static assertion. 5394 UPPC_StaticAssertExpression, 5395 5396 /// \brief The fixed underlying type of an enumeration. 5397 UPPC_FixedUnderlyingType, 5398 5399 /// \brief The enumerator value. 5400 UPPC_EnumeratorValue, 5401 5402 /// \brief A using declaration. 5403 UPPC_UsingDeclaration, 5404 5405 /// \brief A friend declaration. 5406 UPPC_FriendDeclaration, 5407 5408 /// \brief A declaration qualifier. 5409 UPPC_DeclarationQualifier, 5410 5411 /// \brief An initializer. 5412 UPPC_Initializer, 5413 5414 /// \brief A default argument. 5415 UPPC_DefaultArgument, 5416 5417 /// \brief The type of a non-type template parameter. 5418 UPPC_NonTypeTemplateParameterType, 5419 5420 /// \brief The type of an exception. 5421 UPPC_ExceptionType, 5422 5423 /// \brief Partial specialization. 5424 UPPC_PartialSpecialization, 5425 5426 /// \brief Microsoft __if_exists. 5427 UPPC_IfExists, 5428 5429 /// \brief Microsoft __if_not_exists. 5430 UPPC_IfNotExists, 5431 5432 /// \brief Lambda expression. 5433 UPPC_Lambda, 5434 5435 /// \brief Block expression, 5436 UPPC_Block 5437 }; 5438 5439 /// \brief Diagnose unexpanded parameter packs. 5440 /// 5441 /// \param Loc The location at which we should emit the diagnostic. 5442 /// 5443 /// \param UPPC The context in which we are diagnosing unexpanded 5444 /// parameter packs. 5445 /// 5446 /// \param Unexpanded the set of unexpanded parameter packs. 5447 /// 5448 /// \returns true if an error occurred, false otherwise. 5449 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 5450 UnexpandedParameterPackContext UPPC, 5451 ArrayRef<UnexpandedParameterPack> Unexpanded); 5452 5453 /// \brief If the given type contains an unexpanded parameter pack, 5454 /// diagnose the error. 5455 /// 5456 /// \param Loc The source location where a diagnostc should be emitted. 5457 /// 5458 /// \param T The type that is being checked for unexpanded parameter 5459 /// packs. 5460 /// 5461 /// \returns true if an error occurred, false otherwise. 5462 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 5463 UnexpandedParameterPackContext UPPC); 5464 5465 /// \brief If the given expression contains an unexpanded parameter 5466 /// pack, diagnose the error. 5467 /// 5468 /// \param E The expression that is being checked for unexpanded 5469 /// parameter packs. 5470 /// 5471 /// \returns true if an error occurred, false otherwise. 5472 bool DiagnoseUnexpandedParameterPack(Expr *E, 5473 UnexpandedParameterPackContext UPPC = UPPC_Expression); 5474 5475 /// \brief If the given nested-name-specifier contains an unexpanded 5476 /// parameter pack, diagnose the error. 5477 /// 5478 /// \param SS The nested-name-specifier that is being checked for 5479 /// unexpanded parameter packs. 5480 /// 5481 /// \returns true if an error occurred, false otherwise. 5482 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 5483 UnexpandedParameterPackContext UPPC); 5484 5485 /// \brief If the given name contains an unexpanded parameter pack, 5486 /// diagnose the error. 5487 /// 5488 /// \param NameInfo The name (with source location information) that 5489 /// is being checked for unexpanded parameter packs. 5490 /// 5491 /// \returns true if an error occurred, false otherwise. 5492 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 5493 UnexpandedParameterPackContext UPPC); 5494 5495 /// \brief If the given template name contains an unexpanded parameter pack, 5496 /// diagnose the error. 5497 /// 5498 /// \param Loc The location of the template name. 5499 /// 5500 /// \param Template The template name that is being checked for unexpanded 5501 /// parameter packs. 5502 /// 5503 /// \returns true if an error occurred, false otherwise. 5504 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 5505 TemplateName Template, 5506 UnexpandedParameterPackContext UPPC); 5507 5508 /// \brief If the given template argument contains an unexpanded parameter 5509 /// pack, diagnose the error. 5510 /// 5511 /// \param Arg The template argument that is being checked for unexpanded 5512 /// parameter packs. 5513 /// 5514 /// \returns true if an error occurred, false otherwise. 5515 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 5516 UnexpandedParameterPackContext UPPC); 5517 5518 /// \brief Collect the set of unexpanded parameter packs within the given 5519 /// template argument. 5520 /// 5521 /// \param Arg The template argument that will be traversed to find 5522 /// unexpanded parameter packs. 5523 void collectUnexpandedParameterPacks(TemplateArgument Arg, 5524 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5525 5526 /// \brief Collect the set of unexpanded parameter packs within the given 5527 /// template argument. 5528 /// 5529 /// \param Arg The template argument that will be traversed to find 5530 /// unexpanded parameter packs. 5531 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 5532 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5533 5534 /// \brief Collect the set of unexpanded parameter packs within the given 5535 /// type. 5536 /// 5537 /// \param T The type that will be traversed to find 5538 /// unexpanded parameter packs. 5539 void collectUnexpandedParameterPacks(QualType T, 5540 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5541 5542 /// \brief Collect the set of unexpanded parameter packs within the given 5543 /// type. 5544 /// 5545 /// \param TL The type that will be traversed to find 5546 /// unexpanded parameter packs. 5547 void collectUnexpandedParameterPacks(TypeLoc TL, 5548 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5549 5550 /// \brief Collect the set of unexpanded parameter packs within the given 5551 /// nested-name-specifier. 5552 /// 5553 /// \param SS The nested-name-specifier that will be traversed to find 5554 /// unexpanded parameter packs. 5555 void collectUnexpandedParameterPacks(CXXScopeSpec &SS, 5556 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5557 5558 /// \brief Collect the set of unexpanded parameter packs within the given 5559 /// name. 5560 /// 5561 /// \param NameInfo The name that will be traversed to find 5562 /// unexpanded parameter packs. 5563 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 5564 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5565 5566 /// \brief Invoked when parsing a template argument followed by an 5567 /// ellipsis, which creates a pack expansion. 5568 /// 5569 /// \param Arg The template argument preceding the ellipsis, which 5570 /// may already be invalid. 5571 /// 5572 /// \param EllipsisLoc The location of the ellipsis. 5573 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 5574 SourceLocation EllipsisLoc); 5575 5576 /// \brief Invoked when parsing a type followed by an ellipsis, which 5577 /// creates a pack expansion. 5578 /// 5579 /// \param Type The type preceding the ellipsis, which will become 5580 /// the pattern of the pack expansion. 5581 /// 5582 /// \param EllipsisLoc The location of the ellipsis. 5583 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 5584 5585 /// \brief Construct a pack expansion type from the pattern of the pack 5586 /// expansion. 5587 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 5588 SourceLocation EllipsisLoc, 5589 Optional<unsigned> NumExpansions); 5590 5591 /// \brief Construct a pack expansion type from the pattern of the pack 5592 /// expansion. 5593 QualType CheckPackExpansion(QualType Pattern, 5594 SourceRange PatternRange, 5595 SourceLocation EllipsisLoc, 5596 Optional<unsigned> NumExpansions); 5597 5598 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5599 /// creates a pack expansion. 5600 /// 5601 /// \param Pattern The expression preceding the ellipsis, which will become 5602 /// the pattern of the pack expansion. 5603 /// 5604 /// \param EllipsisLoc The location of the ellipsis. 5605 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 5606 5607 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5608 /// creates a pack expansion. 5609 /// 5610 /// \param Pattern The expression preceding the ellipsis, which will become 5611 /// the pattern of the pack expansion. 5612 /// 5613 /// \param EllipsisLoc The location of the ellipsis. 5614 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 5615 Optional<unsigned> NumExpansions); 5616 5617 /// \brief Determine whether we could expand a pack expansion with the 5618 /// given set of parameter packs into separate arguments by repeatedly 5619 /// transforming the pattern. 5620 /// 5621 /// \param EllipsisLoc The location of the ellipsis that identifies the 5622 /// pack expansion. 5623 /// 5624 /// \param PatternRange The source range that covers the entire pattern of 5625 /// the pack expansion. 5626 /// 5627 /// \param Unexpanded The set of unexpanded parameter packs within the 5628 /// pattern. 5629 /// 5630 /// \param ShouldExpand Will be set to \c true if the transformer should 5631 /// expand the corresponding pack expansions into separate arguments. When 5632 /// set, \c NumExpansions must also be set. 5633 /// 5634 /// \param RetainExpansion Whether the caller should add an unexpanded 5635 /// pack expansion after all of the expanded arguments. This is used 5636 /// when extending explicitly-specified template argument packs per 5637 /// C++0x [temp.arg.explicit]p9. 5638 /// 5639 /// \param NumExpansions The number of separate arguments that will be in 5640 /// the expanded form of the corresponding pack expansion. This is both an 5641 /// input and an output parameter, which can be set by the caller if the 5642 /// number of expansions is known a priori (e.g., due to a prior substitution) 5643 /// and will be set by the callee when the number of expansions is known. 5644 /// The callee must set this value when \c ShouldExpand is \c true; it may 5645 /// set this value in other cases. 5646 /// 5647 /// \returns true if an error occurred (e.g., because the parameter packs 5648 /// are to be instantiated with arguments of different lengths), false 5649 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 5650 /// must be set. 5651 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 5652 SourceRange PatternRange, 5653 ArrayRef<UnexpandedParameterPack> Unexpanded, 5654 const MultiLevelTemplateArgumentList &TemplateArgs, 5655 bool &ShouldExpand, 5656 bool &RetainExpansion, 5657 Optional<unsigned> &NumExpansions); 5658 5659 /// \brief Determine the number of arguments in the given pack expansion 5660 /// type. 5661 /// 5662 /// This routine assumes that the number of arguments in the expansion is 5663 /// consistent across all of the unexpanded parameter packs in its pattern. 5664 /// 5665 /// Returns an empty Optional if the type can't be expanded. 5666 Optional<unsigned> getNumArgumentsInExpansion(QualType T, 5667 const MultiLevelTemplateArgumentList &TemplateArgs); 5668 5669 /// \brief Determine whether the given declarator contains any unexpanded 5670 /// parameter packs. 5671 /// 5672 /// This routine is used by the parser to disambiguate function declarators 5673 /// with an ellipsis prior to the ')', e.g., 5674 /// 5675 /// \code 5676 /// void f(T...); 5677 /// \endcode 5678 /// 5679 /// To determine whether we have an (unnamed) function parameter pack or 5680 /// a variadic function. 5681 /// 5682 /// \returns true if the declarator contains any unexpanded parameter packs, 5683 /// false otherwise. 5684 bool containsUnexpandedParameterPacks(Declarator &D); 5685 5686 /// \brief Returns the pattern of the pack expansion for a template argument. 5687 /// 5688 /// \param OrigLoc The template argument to expand. 5689 /// 5690 /// \param Ellipsis Will be set to the location of the ellipsis. 5691 /// 5692 /// \param NumExpansions Will be set to the number of expansions that will 5693 /// be generated from this pack expansion, if known a priori. 5694 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 5695 TemplateArgumentLoc OrigLoc, 5696 SourceLocation &Ellipsis, 5697 Optional<unsigned> &NumExpansions) const; 5698 5699 //===--------------------------------------------------------------------===// 5700 // C++ Template Argument Deduction (C++ [temp.deduct]) 5701 //===--------------------------------------------------------------------===// 5702 5703 /// \brief Describes the result of template argument deduction. 5704 /// 5705 /// The TemplateDeductionResult enumeration describes the result of 5706 /// template argument deduction, as returned from 5707 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 5708 /// structure provides additional information about the results of 5709 /// template argument deduction, e.g., the deduced template argument 5710 /// list (if successful) or the specific template parameters or 5711 /// deduced arguments that were involved in the failure. 5712 enum TemplateDeductionResult { 5713 /// \brief Template argument deduction was successful. 5714 TDK_Success = 0, 5715 /// \brief The declaration was invalid; do nothing. 5716 TDK_Invalid, 5717 /// \brief Template argument deduction exceeded the maximum template 5718 /// instantiation depth (which has already been diagnosed). 5719 TDK_InstantiationDepth, 5720 /// \brief Template argument deduction did not deduce a value 5721 /// for every template parameter. 5722 TDK_Incomplete, 5723 /// \brief Template argument deduction produced inconsistent 5724 /// deduced values for the given template parameter. 5725 TDK_Inconsistent, 5726 /// \brief Template argument deduction failed due to inconsistent 5727 /// cv-qualifiers on a template parameter type that would 5728 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 5729 /// but were given a non-const "X". 5730 TDK_Underqualified, 5731 /// \brief Substitution of the deduced template argument values 5732 /// resulted in an error. 5733 TDK_SubstitutionFailure, 5734 /// \brief A non-depnedent component of the parameter did not match the 5735 /// corresponding component of the argument. 5736 TDK_NonDeducedMismatch, 5737 /// \brief When performing template argument deduction for a function 5738 /// template, there were too many call arguments. 5739 TDK_TooManyArguments, 5740 /// \brief When performing template argument deduction for a function 5741 /// template, there were too few call arguments. 5742 TDK_TooFewArguments, 5743 /// \brief The explicitly-specified template arguments were not valid 5744 /// template arguments for the given template. 5745 TDK_InvalidExplicitArguments, 5746 /// \brief The arguments included an overloaded function name that could 5747 /// not be resolved to a suitable function. 5748 TDK_FailedOverloadResolution, 5749 /// \brief Deduction failed; that's all we know. 5750 TDK_MiscellaneousDeductionFailure 5751 }; 5752 5753 TemplateDeductionResult 5754 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 5755 const TemplateArgumentList &TemplateArgs, 5756 sema::TemplateDeductionInfo &Info); 5757 5758 TemplateDeductionResult 5759 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 5760 const TemplateArgumentList &TemplateArgs, 5761 sema::TemplateDeductionInfo &Info); 5762 5763 TemplateDeductionResult SubstituteExplicitTemplateArguments( 5764 FunctionTemplateDecl *FunctionTemplate, 5765 TemplateArgumentListInfo &ExplicitTemplateArgs, 5766 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5767 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 5768 sema::TemplateDeductionInfo &Info); 5769 5770 /// brief A function argument from which we performed template argument 5771 // deduction for a call. 5772 struct OriginalCallArg { 5773 OriginalCallArg(QualType OriginalParamType, 5774 unsigned ArgIdx, 5775 QualType OriginalArgType) 5776 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 5777 OriginalArgType(OriginalArgType) { } 5778 5779 QualType OriginalParamType; 5780 unsigned ArgIdx; 5781 QualType OriginalArgType; 5782 }; 5783 5784 TemplateDeductionResult 5785 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 5786 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5787 unsigned NumExplicitlySpecified, 5788 FunctionDecl *&Specialization, 5789 sema::TemplateDeductionInfo &Info, 5790 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0); 5791 5792 TemplateDeductionResult 5793 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5794 TemplateArgumentListInfo *ExplicitTemplateArgs, 5795 ArrayRef<Expr *> Args, 5796 FunctionDecl *&Specialization, 5797 sema::TemplateDeductionInfo &Info); 5798 5799 TemplateDeductionResult 5800 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5801 TemplateArgumentListInfo *ExplicitTemplateArgs, 5802 QualType ArgFunctionType, 5803 FunctionDecl *&Specialization, 5804 sema::TemplateDeductionInfo &Info, 5805 bool InOverloadResolution = false); 5806 5807 TemplateDeductionResult 5808 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5809 QualType ToType, 5810 CXXConversionDecl *&Specialization, 5811 sema::TemplateDeductionInfo &Info); 5812 5813 TemplateDeductionResult 5814 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5815 TemplateArgumentListInfo *ExplicitTemplateArgs, 5816 FunctionDecl *&Specialization, 5817 sema::TemplateDeductionInfo &Info, 5818 bool InOverloadResolution = false); 5819 5820 /// \brief Result type of DeduceAutoType. 5821 enum DeduceAutoResult { 5822 DAR_Succeeded, 5823 DAR_Failed, 5824 DAR_FailedAlreadyDiagnosed 5825 }; 5826 5827 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, 5828 QualType &Result); 5829 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, 5830 QualType &Result); 5831 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 5832 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 5833 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 5834 bool Diagnose = true); 5835 5836 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 5837 SourceLocation ReturnLoc, 5838 Expr *&RetExpr, AutoType *AT); 5839 5840 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 5841 FunctionTemplateDecl *FT2, 5842 SourceLocation Loc, 5843 TemplatePartialOrderingContext TPOC, 5844 unsigned NumCallArguments1, 5845 unsigned NumCallArguments2); 5846 UnresolvedSetIterator 5847 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 5848 TemplateSpecCandidateSet &FailedCandidates, 5849 SourceLocation Loc, 5850 const PartialDiagnostic &NoneDiag, 5851 const PartialDiagnostic &AmbigDiag, 5852 const PartialDiagnostic &CandidateDiag, 5853 bool Complain = true, QualType TargetType = QualType()); 5854 5855 ClassTemplatePartialSpecializationDecl * 5856 getMoreSpecializedPartialSpecialization( 5857 ClassTemplatePartialSpecializationDecl *PS1, 5858 ClassTemplatePartialSpecializationDecl *PS2, 5859 SourceLocation Loc); 5860 5861 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 5862 VarTemplatePartialSpecializationDecl *PS1, 5863 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 5864 5865 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 5866 bool OnlyDeduced, 5867 unsigned Depth, 5868 llvm::SmallBitVector &Used); 5869 void MarkDeducedTemplateParameters( 5870 const FunctionTemplateDecl *FunctionTemplate, 5871 llvm::SmallBitVector &Deduced) { 5872 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 5873 } 5874 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 5875 const FunctionTemplateDecl *FunctionTemplate, 5876 llvm::SmallBitVector &Deduced); 5877 5878 //===--------------------------------------------------------------------===// 5879 // C++ Template Instantiation 5880 // 5881 5882 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, 5883 const TemplateArgumentList *Innermost = 0, 5884 bool RelativeToPrimary = false, 5885 const FunctionDecl *Pattern = 0); 5886 5887 /// \brief A template instantiation that is currently in progress. 5888 struct ActiveTemplateInstantiation { 5889 /// \brief The kind of template instantiation we are performing 5890 enum InstantiationKind { 5891 /// We are instantiating a template declaration. The entity is 5892 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 5893 TemplateInstantiation, 5894 5895 /// We are instantiating a default argument for a template 5896 /// parameter. The Entity is the template, and 5897 /// TemplateArgs/NumTemplateArguments provides the template 5898 /// arguments as specified. 5899 /// FIXME: Use a TemplateArgumentList 5900 DefaultTemplateArgumentInstantiation, 5901 5902 /// We are instantiating a default argument for a function. 5903 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 5904 /// provides the template arguments as specified. 5905 DefaultFunctionArgumentInstantiation, 5906 5907 /// We are substituting explicit template arguments provided for 5908 /// a function template. The entity is a FunctionTemplateDecl. 5909 ExplicitTemplateArgumentSubstitution, 5910 5911 /// We are substituting template argument determined as part of 5912 /// template argument deduction for either a class template 5913 /// partial specialization or a function template. The 5914 /// Entity is either a ClassTemplatePartialSpecializationDecl or 5915 /// a FunctionTemplateDecl. 5916 DeducedTemplateArgumentSubstitution, 5917 5918 /// We are substituting prior template arguments into a new 5919 /// template parameter. The template parameter itself is either a 5920 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 5921 PriorTemplateArgumentSubstitution, 5922 5923 /// We are checking the validity of a default template argument that 5924 /// has been used when naming a template-id. 5925 DefaultTemplateArgumentChecking, 5926 5927 /// We are instantiating the exception specification for a function 5928 /// template which was deferred until it was needed. 5929 ExceptionSpecInstantiation 5930 } Kind; 5931 5932 /// \brief The point of instantiation within the source code. 5933 SourceLocation PointOfInstantiation; 5934 5935 /// \brief The template (or partial specialization) in which we are 5936 /// performing the instantiation, for substitutions of prior template 5937 /// arguments. 5938 NamedDecl *Template; 5939 5940 /// \brief The entity that is being instantiated. 5941 Decl *Entity; 5942 5943 /// \brief The list of template arguments we are substituting, if they 5944 /// are not part of the entity. 5945 const TemplateArgument *TemplateArgs; 5946 5947 /// \brief The number of template arguments in TemplateArgs. 5948 unsigned NumTemplateArgs; 5949 5950 /// \brief The template deduction info object associated with the 5951 /// substitution or checking of explicit or deduced template arguments. 5952 sema::TemplateDeductionInfo *DeductionInfo; 5953 5954 /// \brief The source range that covers the construct that cause 5955 /// the instantiation, e.g., the template-id that causes a class 5956 /// template instantiation. 5957 SourceRange InstantiationRange; 5958 5959 ActiveTemplateInstantiation() 5960 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0), 5961 NumTemplateArgs(0), DeductionInfo(0) {} 5962 5963 /// \brief Determines whether this template is an actual instantiation 5964 /// that should be counted toward the maximum instantiation depth. 5965 bool isInstantiationRecord() const; 5966 5967 friend bool operator==(const ActiveTemplateInstantiation &X, 5968 const ActiveTemplateInstantiation &Y) { 5969 if (X.Kind != Y.Kind) 5970 return false; 5971 5972 if (X.Entity != Y.Entity) 5973 return false; 5974 5975 switch (X.Kind) { 5976 case TemplateInstantiation: 5977 case ExceptionSpecInstantiation: 5978 return true; 5979 5980 case PriorTemplateArgumentSubstitution: 5981 case DefaultTemplateArgumentChecking: 5982 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs; 5983 5984 case DefaultTemplateArgumentInstantiation: 5985 case ExplicitTemplateArgumentSubstitution: 5986 case DeducedTemplateArgumentSubstitution: 5987 case DefaultFunctionArgumentInstantiation: 5988 return X.TemplateArgs == Y.TemplateArgs; 5989 5990 } 5991 5992 llvm_unreachable("Invalid InstantiationKind!"); 5993 } 5994 5995 friend bool operator!=(const ActiveTemplateInstantiation &X, 5996 const ActiveTemplateInstantiation &Y) { 5997 return !(X == Y); 5998 } 5999 }; 6000 6001 /// \brief List of active template instantiations. 6002 /// 6003 /// This vector is treated as a stack. As one template instantiation 6004 /// requires another template instantiation, additional 6005 /// instantiations are pushed onto the stack up to a 6006 /// user-configurable limit LangOptions::InstantiationDepth. 6007 SmallVector<ActiveTemplateInstantiation, 16> 6008 ActiveTemplateInstantiations; 6009 6010 /// \brief Extra modules inspected when performing a lookup during a template 6011 /// instantiation. Computed lazily. 6012 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules; 6013 6014 /// \brief Cache of additional modules that should be used for name lookup 6015 /// within the current template instantiation. Computed lazily; use 6016 /// getLookupModules() to get a complete set. 6017 llvm::DenseSet<Module*> LookupModulesCache; 6018 6019 /// \brief Get the set of additional modules that should be checked during 6020 /// name lookup. A module and its imports become visible when instanting a 6021 /// template defined within it. 6022 llvm::DenseSet<Module*> &getLookupModules(); 6023 6024 /// \brief Whether we are in a SFINAE context that is not associated with 6025 /// template instantiation. 6026 /// 6027 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 6028 /// of a template instantiation or template argument deduction. 6029 bool InNonInstantiationSFINAEContext; 6030 6031 /// \brief The number of ActiveTemplateInstantiation entries in 6032 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 6033 /// therefore, should not be counted as part of the instantiation depth. 6034 unsigned NonInstantiationEntries; 6035 6036 /// \brief The last template from which a template instantiation 6037 /// error or warning was produced. 6038 /// 6039 /// This value is used to suppress printing of redundant template 6040 /// instantiation backtraces when there are multiple errors in the 6041 /// same instantiation. FIXME: Does this belong in Sema? It's tough 6042 /// to implement it anywhere else. 6043 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 6044 6045 /// \brief The current index into pack expansion arguments that will be 6046 /// used for substitution of parameter packs. 6047 /// 6048 /// The pack expansion index will be -1 to indicate that parameter packs 6049 /// should be instantiated as themselves. Otherwise, the index specifies 6050 /// which argument within the parameter pack will be used for substitution. 6051 int ArgumentPackSubstitutionIndex; 6052 6053 /// \brief RAII object used to change the argument pack substitution index 6054 /// within a \c Sema object. 6055 /// 6056 /// See \c ArgumentPackSubstitutionIndex for more information. 6057 class ArgumentPackSubstitutionIndexRAII { 6058 Sema &Self; 6059 int OldSubstitutionIndex; 6060 6061 public: 6062 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 6063 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 6064 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 6065 } 6066 6067 ~ArgumentPackSubstitutionIndexRAII() { 6068 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 6069 } 6070 }; 6071 6072 friend class ArgumentPackSubstitutionRAII; 6073 6074 /// \brief The stack of calls expression undergoing template instantiation. 6075 /// 6076 /// The top of this stack is used by a fixit instantiating unresolved 6077 /// function calls to fix the AST to match the textual change it prints. 6078 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 6079 6080 /// \brief For each declaration that involved template argument deduction, the 6081 /// set of diagnostics that were suppressed during that template argument 6082 /// deduction. 6083 /// 6084 /// FIXME: Serialize this structure to the AST file. 6085 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 6086 SuppressedDiagnosticsMap; 6087 SuppressedDiagnosticsMap SuppressedDiagnostics; 6088 6089 /// \brief A stack object to be created when performing template 6090 /// instantiation. 6091 /// 6092 /// Construction of an object of type \c InstantiatingTemplate 6093 /// pushes the current instantiation onto the stack of active 6094 /// instantiations. If the size of this stack exceeds the maximum 6095 /// number of recursive template instantiations, construction 6096 /// produces an error and evaluates true. 6097 /// 6098 /// Destruction of this object will pop the named instantiation off 6099 /// the stack. 6100 struct InstantiatingTemplate { 6101 /// \brief Note that we are instantiating a class template, 6102 /// function template, or a member thereof. 6103 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6104 Decl *Entity, 6105 SourceRange InstantiationRange = SourceRange()); 6106 6107 struct ExceptionSpecification {}; 6108 /// \brief Note that we are instantiating an exception specification 6109 /// of a function template. 6110 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6111 FunctionDecl *Entity, ExceptionSpecification, 6112 SourceRange InstantiationRange = SourceRange()); 6113 6114 /// \brief Note that we are instantiating a default argument in a 6115 /// template-id. 6116 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6117 TemplateDecl *Template, 6118 ArrayRef<TemplateArgument> TemplateArgs, 6119 SourceRange InstantiationRange = SourceRange()); 6120 6121 /// \brief Note that we are instantiating a default argument in a 6122 /// template-id. 6123 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6124 FunctionTemplateDecl *FunctionTemplate, 6125 ArrayRef<TemplateArgument> TemplateArgs, 6126 ActiveTemplateInstantiation::InstantiationKind Kind, 6127 sema::TemplateDeductionInfo &DeductionInfo, 6128 SourceRange InstantiationRange = SourceRange()); 6129 6130 /// \brief Note that we are instantiating as part of template 6131 /// argument deduction for a class template partial 6132 /// specialization. 6133 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6134 ClassTemplatePartialSpecializationDecl *PartialSpec, 6135 ArrayRef<TemplateArgument> TemplateArgs, 6136 sema::TemplateDeductionInfo &DeductionInfo, 6137 SourceRange InstantiationRange = SourceRange()); 6138 6139 /// \brief Note that we are instantiating as part of template 6140 /// argument deduction for a variable template partial 6141 /// specialization. 6142 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6143 VarTemplatePartialSpecializationDecl *PartialSpec, 6144 ArrayRef<TemplateArgument> TemplateArgs, 6145 sema::TemplateDeductionInfo &DeductionInfo, 6146 SourceRange InstantiationRange = SourceRange()); 6147 6148 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6149 ParmVarDecl *Param, 6150 ArrayRef<TemplateArgument> TemplateArgs, 6151 SourceRange InstantiationRange = SourceRange()); 6152 6153 /// \brief Note that we are substituting prior template arguments into a 6154 /// non-type or template template parameter. 6155 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6156 NamedDecl *Template, 6157 NonTypeTemplateParmDecl *Param, 6158 ArrayRef<TemplateArgument> TemplateArgs, 6159 SourceRange InstantiationRange); 6160 6161 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6162 NamedDecl *Template, 6163 TemplateTemplateParmDecl *Param, 6164 ArrayRef<TemplateArgument> TemplateArgs, 6165 SourceRange InstantiationRange); 6166 6167 /// \brief Note that we are checking the default template argument 6168 /// against the template parameter for a given template-id. 6169 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6170 TemplateDecl *Template, 6171 NamedDecl *Param, 6172 ArrayRef<TemplateArgument> TemplateArgs, 6173 SourceRange InstantiationRange); 6174 6175 6176 /// \brief Note that we have finished instantiating this template. 6177 void Clear(); 6178 6179 ~InstantiatingTemplate() { Clear(); } 6180 6181 /// \brief Determines whether we have exceeded the maximum 6182 /// recursive template instantiations. 6183 LLVM_EXPLICIT operator bool() const { return Invalid; } 6184 6185 private: 6186 Sema &SemaRef; 6187 bool Invalid; 6188 bool SavedInNonInstantiationSFINAEContext; 6189 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 6190 SourceRange InstantiationRange); 6191 6192 InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; 6193 6194 InstantiatingTemplate& 6195 operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; 6196 }; 6197 6198 void PrintInstantiationStack(); 6199 6200 /// \brief Determines whether we are currently in a context where 6201 /// template argument substitution failures are not considered 6202 /// errors. 6203 /// 6204 /// \returns An empty \c Optional if we're not in a SFINAE context. 6205 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 6206 /// template-deduction context object, which can be used to capture 6207 /// diagnostics that will be suppressed. 6208 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 6209 6210 /// \brief Determines whether we are currently in a context that 6211 /// is not evaluated as per C++ [expr] p5. 6212 bool isUnevaluatedContext() const { 6213 assert(!ExprEvalContexts.empty() && 6214 "Must be in an expression evaluation context"); 6215 return ExprEvalContexts.back().isUnevaluated(); 6216 } 6217 6218 /// \brief RAII class used to determine whether SFINAE has 6219 /// trapped any errors that occur during template argument 6220 /// deduction. 6221 class SFINAETrap { 6222 Sema &SemaRef; 6223 unsigned PrevSFINAEErrors; 6224 bool PrevInNonInstantiationSFINAEContext; 6225 bool PrevAccessCheckingSFINAE; 6226 6227 public: 6228 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 6229 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 6230 PrevInNonInstantiationSFINAEContext( 6231 SemaRef.InNonInstantiationSFINAEContext), 6232 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 6233 { 6234 if (!SemaRef.isSFINAEContext()) 6235 SemaRef.InNonInstantiationSFINAEContext = true; 6236 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 6237 } 6238 6239 ~SFINAETrap() { 6240 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 6241 SemaRef.InNonInstantiationSFINAEContext 6242 = PrevInNonInstantiationSFINAEContext; 6243 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 6244 } 6245 6246 /// \brief Determine whether any SFINAE errors have been trapped. 6247 bool hasErrorOccurred() const { 6248 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 6249 } 6250 }; 6251 6252 /// \brief RAII class used to indicate that we are performing provisional 6253 /// semantic analysis to determine the validity of a construct, so 6254 /// typo-correction and diagnostics in the immediate context (not within 6255 /// implicitly-instantiated templates) should be suppressed. 6256 class TentativeAnalysisScope { 6257 Sema &SemaRef; 6258 // FIXME: Using a SFINAETrap for this is a hack. 6259 SFINAETrap Trap; 6260 bool PrevDisableTypoCorrection; 6261 public: 6262 explicit TentativeAnalysisScope(Sema &SemaRef) 6263 : SemaRef(SemaRef), Trap(SemaRef, true), 6264 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 6265 SemaRef.DisableTypoCorrection = true; 6266 } 6267 ~TentativeAnalysisScope() { 6268 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 6269 } 6270 }; 6271 6272 /// \brief The current instantiation scope used to store local 6273 /// variables. 6274 LocalInstantiationScope *CurrentInstantiationScope; 6275 6276 /// \brief Tracks whether we are in a context where typo correction is 6277 /// disabled. 6278 bool DisableTypoCorrection; 6279 6280 /// \brief The number of typos corrected by CorrectTypo. 6281 unsigned TyposCorrected; 6282 6283 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection> 6284 UnqualifiedTyposCorrectedMap; 6285 6286 /// \brief A cache containing the results of typo correction for unqualified 6287 /// name lookup. 6288 /// 6289 /// The string is the string that we corrected to (which may be empty, if 6290 /// there was no correction), while the boolean will be true when the 6291 /// string represents a keyword. 6292 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; 6293 6294 /// \brief Worker object for performing CFG-based warnings. 6295 sema::AnalysisBasedWarnings AnalysisWarnings; 6296 6297 /// \brief An entity for which implicit template instantiation is required. 6298 /// 6299 /// The source location associated with the declaration is the first place in 6300 /// the source code where the declaration was "used". It is not necessarily 6301 /// the point of instantiation (which will be either before or after the 6302 /// namespace-scope declaration that triggered this implicit instantiation), 6303 /// However, it is the location that diagnostics should generally refer to, 6304 /// because users will need to know what code triggered the instantiation. 6305 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 6306 6307 /// \brief The queue of implicit template instantiations that are required 6308 /// but have not yet been performed. 6309 std::deque<PendingImplicitInstantiation> PendingInstantiations; 6310 6311 /// \brief The queue of implicit template instantiations that are required 6312 /// and must be performed within the current local scope. 6313 /// 6314 /// This queue is only used for member functions of local classes in 6315 /// templates, which must be instantiated in the same scope as their 6316 /// enclosing function, so that they can reference function-local 6317 /// types, static variables, enumerators, etc. 6318 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 6319 6320 void PerformPendingInstantiations(bool LocalOnly = false); 6321 6322 TypeSourceInfo *SubstType(TypeSourceInfo *T, 6323 const MultiLevelTemplateArgumentList &TemplateArgs, 6324 SourceLocation Loc, DeclarationName Entity); 6325 6326 QualType SubstType(QualType T, 6327 const MultiLevelTemplateArgumentList &TemplateArgs, 6328 SourceLocation Loc, DeclarationName Entity); 6329 6330 TypeSourceInfo *SubstType(TypeLoc TL, 6331 const MultiLevelTemplateArgumentList &TemplateArgs, 6332 SourceLocation Loc, DeclarationName Entity); 6333 6334 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 6335 const MultiLevelTemplateArgumentList &TemplateArgs, 6336 SourceLocation Loc, 6337 DeclarationName Entity, 6338 CXXRecordDecl *ThisContext, 6339 unsigned ThisTypeQuals); 6340 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 6341 const MultiLevelTemplateArgumentList &TemplateArgs, 6342 int indexAdjustment, 6343 Optional<unsigned> NumExpansions, 6344 bool ExpectParameterPack); 6345 bool SubstParmTypes(SourceLocation Loc, 6346 ParmVarDecl **Params, unsigned NumParams, 6347 const MultiLevelTemplateArgumentList &TemplateArgs, 6348 SmallVectorImpl<QualType> &ParamTypes, 6349 SmallVectorImpl<ParmVarDecl *> *OutParams = 0); 6350 ExprResult SubstExpr(Expr *E, 6351 const MultiLevelTemplateArgumentList &TemplateArgs); 6352 6353 /// \brief Substitute the given template arguments into a list of 6354 /// expressions, expanding pack expansions if required. 6355 /// 6356 /// \param Exprs The list of expressions to substitute into. 6357 /// 6358 /// \param NumExprs The number of expressions in \p Exprs. 6359 /// 6360 /// \param IsCall Whether this is some form of call, in which case 6361 /// default arguments will be dropped. 6362 /// 6363 /// \param TemplateArgs The set of template arguments to substitute. 6364 /// 6365 /// \param Outputs Will receive all of the substituted arguments. 6366 /// 6367 /// \returns true if an error occurred, false otherwise. 6368 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 6369 const MultiLevelTemplateArgumentList &TemplateArgs, 6370 SmallVectorImpl<Expr *> &Outputs); 6371 6372 StmtResult SubstStmt(Stmt *S, 6373 const MultiLevelTemplateArgumentList &TemplateArgs); 6374 6375 Decl *SubstDecl(Decl *D, DeclContext *Owner, 6376 const MultiLevelTemplateArgumentList &TemplateArgs); 6377 6378 ExprResult SubstInitializer(Expr *E, 6379 const MultiLevelTemplateArgumentList &TemplateArgs, 6380 bool CXXDirectInit); 6381 6382 bool 6383 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 6384 CXXRecordDecl *Pattern, 6385 const MultiLevelTemplateArgumentList &TemplateArgs); 6386 6387 bool 6388 InstantiateClass(SourceLocation PointOfInstantiation, 6389 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 6390 const MultiLevelTemplateArgumentList &TemplateArgs, 6391 TemplateSpecializationKind TSK, 6392 bool Complain = true); 6393 6394 bool InstantiateEnum(SourceLocation PointOfInstantiation, 6395 EnumDecl *Instantiation, EnumDecl *Pattern, 6396 const MultiLevelTemplateArgumentList &TemplateArgs, 6397 TemplateSpecializationKind TSK); 6398 6399 struct LateInstantiatedAttribute { 6400 const Attr *TmplAttr; 6401 LocalInstantiationScope *Scope; 6402 Decl *NewDecl; 6403 6404 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 6405 Decl *D) 6406 : TmplAttr(A), Scope(S), NewDecl(D) 6407 { } 6408 }; 6409 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 6410 6411 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 6412 const Decl *Pattern, Decl *Inst, 6413 LateInstantiatedAttrVec *LateAttrs = 0, 6414 LocalInstantiationScope *OuterMostScope = 0); 6415 6416 bool 6417 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 6418 ClassTemplateSpecializationDecl *ClassTemplateSpec, 6419 TemplateSpecializationKind TSK, 6420 bool Complain = true); 6421 6422 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 6423 CXXRecordDecl *Instantiation, 6424 const MultiLevelTemplateArgumentList &TemplateArgs, 6425 TemplateSpecializationKind TSK); 6426 6427 void InstantiateClassTemplateSpecializationMembers( 6428 SourceLocation PointOfInstantiation, 6429 ClassTemplateSpecializationDecl *ClassTemplateSpec, 6430 TemplateSpecializationKind TSK); 6431 6432 NestedNameSpecifierLoc 6433 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 6434 const MultiLevelTemplateArgumentList &TemplateArgs); 6435 6436 DeclarationNameInfo 6437 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 6438 const MultiLevelTemplateArgumentList &TemplateArgs); 6439 TemplateName 6440 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 6441 SourceLocation Loc, 6442 const MultiLevelTemplateArgumentList &TemplateArgs); 6443 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 6444 TemplateArgumentListInfo &Result, 6445 const MultiLevelTemplateArgumentList &TemplateArgs); 6446 6447 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 6448 FunctionDecl *Function); 6449 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 6450 FunctionDecl *Function, 6451 bool Recursive = false, 6452 bool DefinitionRequired = false); 6453 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 6454 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 6455 const TemplateArgumentList &TemplateArgList, 6456 const TemplateArgumentListInfo &TemplateArgsInfo, 6457 SmallVectorImpl<TemplateArgument> &Converted, 6458 SourceLocation PointOfInstantiation, void *InsertPos, 6459 LateInstantiatedAttrVec *LateAttrs = 0, 6460 LocalInstantiationScope *StartingScope = 0); 6461 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 6462 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 6463 const MultiLevelTemplateArgumentList &TemplateArgs); 6464 void 6465 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 6466 const MultiLevelTemplateArgumentList &TemplateArgs, 6467 LateInstantiatedAttrVec *LateAttrs = 0, 6468 LocalInstantiationScope *StartingScope = 0, 6469 bool InstantiatingVarTemplate = false); 6470 void InstantiateVariableInitializer( 6471 VarDecl *Var, VarDecl *OldVar, 6472 const MultiLevelTemplateArgumentList &TemplateArgs); 6473 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 6474 VarDecl *Var, bool Recursive = false, 6475 bool DefinitionRequired = false); 6476 void InstantiateStaticDataMemberDefinition( 6477 SourceLocation PointOfInstantiation, 6478 VarDecl *Var, 6479 bool Recursive = false, 6480 bool DefinitionRequired = false); 6481 6482 void InstantiateMemInitializers(CXXConstructorDecl *New, 6483 const CXXConstructorDecl *Tmpl, 6484 const MultiLevelTemplateArgumentList &TemplateArgs); 6485 6486 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 6487 const MultiLevelTemplateArgumentList &TemplateArgs); 6488 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 6489 const MultiLevelTemplateArgumentList &TemplateArgs); 6490 6491 // Objective-C declarations. 6492 enum ObjCContainerKind { 6493 OCK_None = -1, 6494 OCK_Interface = 0, 6495 OCK_Protocol, 6496 OCK_Category, 6497 OCK_ClassExtension, 6498 OCK_Implementation, 6499 OCK_CategoryImplementation 6500 }; 6501 ObjCContainerKind getObjCContainerKind() const; 6502 6503 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 6504 IdentifierInfo *ClassName, 6505 SourceLocation ClassLoc, 6506 IdentifierInfo *SuperName, 6507 SourceLocation SuperLoc, 6508 Decl * const *ProtoRefs, 6509 unsigned NumProtoRefs, 6510 const SourceLocation *ProtoLocs, 6511 SourceLocation EndProtoLoc, 6512 AttributeList *AttrList); 6513 6514 Decl *ActOnCompatibilityAlias( 6515 SourceLocation AtCompatibilityAliasLoc, 6516 IdentifierInfo *AliasName, SourceLocation AliasLocation, 6517 IdentifierInfo *ClassName, SourceLocation ClassLocation); 6518 6519 bool CheckForwardProtocolDeclarationForCircularDependency( 6520 IdentifierInfo *PName, 6521 SourceLocation &PLoc, SourceLocation PrevLoc, 6522 const ObjCList<ObjCProtocolDecl> &PList); 6523 6524 Decl *ActOnStartProtocolInterface( 6525 SourceLocation AtProtoInterfaceLoc, 6526 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 6527 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 6528 const SourceLocation *ProtoLocs, 6529 SourceLocation EndProtoLoc, 6530 AttributeList *AttrList); 6531 6532 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 6533 IdentifierInfo *ClassName, 6534 SourceLocation ClassLoc, 6535 IdentifierInfo *CategoryName, 6536 SourceLocation CategoryLoc, 6537 Decl * const *ProtoRefs, 6538 unsigned NumProtoRefs, 6539 const SourceLocation *ProtoLocs, 6540 SourceLocation EndProtoLoc); 6541 6542 Decl *ActOnStartClassImplementation( 6543 SourceLocation AtClassImplLoc, 6544 IdentifierInfo *ClassName, SourceLocation ClassLoc, 6545 IdentifierInfo *SuperClassname, 6546 SourceLocation SuperClassLoc); 6547 6548 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 6549 IdentifierInfo *ClassName, 6550 SourceLocation ClassLoc, 6551 IdentifierInfo *CatName, 6552 SourceLocation CatLoc); 6553 6554 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 6555 ArrayRef<Decl *> Decls); 6556 6557 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 6558 IdentifierInfo **IdentList, 6559 SourceLocation *IdentLocs, 6560 unsigned NumElts); 6561 6562 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 6563 const IdentifierLocPair *IdentList, 6564 unsigned NumElts, 6565 AttributeList *attrList); 6566 6567 void FindProtocolDeclaration(bool WarnOnDeclarations, 6568 const IdentifierLocPair *ProtocolId, 6569 unsigned NumProtocols, 6570 SmallVectorImpl<Decl *> &Protocols); 6571 6572 /// Ensure attributes are consistent with type. 6573 /// \param [in, out] Attributes The attributes to check; they will 6574 /// be modified to be consistent with \p PropertyTy. 6575 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 6576 SourceLocation Loc, 6577 unsigned &Attributes, 6578 bool propertyInPrimaryClass); 6579 6580 /// Process the specified property declaration and create decls for the 6581 /// setters and getters as needed. 6582 /// \param property The property declaration being processed 6583 /// \param CD The semantic container for the property 6584 /// \param redeclaredProperty Declaration for property if redeclared 6585 /// in class extension. 6586 /// \param lexicalDC Container for redeclaredProperty. 6587 void ProcessPropertyDecl(ObjCPropertyDecl *property, 6588 ObjCContainerDecl *CD, 6589 ObjCPropertyDecl *redeclaredProperty = 0, 6590 ObjCContainerDecl *lexicalDC = 0); 6591 6592 6593 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 6594 ObjCPropertyDecl *SuperProperty, 6595 const IdentifierInfo *Name); 6596 6597 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 6598 ObjCInterfaceDecl *ID); 6599 6600 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 6601 ArrayRef<Decl *> allMethods = None, 6602 ArrayRef<DeclGroupPtrTy> allTUVars = None); 6603 6604 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 6605 SourceLocation LParenLoc, 6606 FieldDeclarator &FD, ObjCDeclSpec &ODS, 6607 Selector GetterSel, Selector SetterSel, 6608 bool *OverridingProperty, 6609 tok::ObjCKeywordKind MethodImplKind, 6610 DeclContext *lexicalDC = 0); 6611 6612 Decl *ActOnPropertyImplDecl(Scope *S, 6613 SourceLocation AtLoc, 6614 SourceLocation PropertyLoc, 6615 bool ImplKind, 6616 IdentifierInfo *PropertyId, 6617 IdentifierInfo *PropertyIvar, 6618 SourceLocation PropertyIvarLoc); 6619 6620 enum ObjCSpecialMethodKind { 6621 OSMK_None, 6622 OSMK_Alloc, 6623 OSMK_New, 6624 OSMK_Copy, 6625 OSMK_RetainingInit, 6626 OSMK_NonRetainingInit 6627 }; 6628 6629 struct ObjCArgInfo { 6630 IdentifierInfo *Name; 6631 SourceLocation NameLoc; 6632 // The Type is null if no type was specified, and the DeclSpec is invalid 6633 // in this case. 6634 ParsedType Type; 6635 ObjCDeclSpec DeclSpec; 6636 6637 /// ArgAttrs - Attribute list for this argument. 6638 AttributeList *ArgAttrs; 6639 }; 6640 6641 Decl *ActOnMethodDeclaration( 6642 Scope *S, 6643 SourceLocation BeginLoc, // location of the + or -. 6644 SourceLocation EndLoc, // location of the ; or {. 6645 tok::TokenKind MethodType, 6646 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 6647 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 6648 // optional arguments. The number of types/arguments is obtained 6649 // from the Sel.getNumArgs(). 6650 ObjCArgInfo *ArgInfo, 6651 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 6652 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 6653 bool isVariadic, bool MethodDefinition); 6654 6655 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 6656 const ObjCObjectPointerType *OPT, 6657 bool IsInstance); 6658 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 6659 bool IsInstance); 6660 6661 bool CheckARCMethodDecl(ObjCMethodDecl *method); 6662 bool inferObjCARCLifetime(ValueDecl *decl); 6663 6664 ExprResult 6665 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 6666 Expr *BaseExpr, 6667 SourceLocation OpLoc, 6668 DeclarationName MemberName, 6669 SourceLocation MemberLoc, 6670 SourceLocation SuperLoc, QualType SuperType, 6671 bool Super); 6672 6673 ExprResult 6674 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 6675 IdentifierInfo &propertyName, 6676 SourceLocation receiverNameLoc, 6677 SourceLocation propertyNameLoc); 6678 6679 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 6680 6681 /// \brief Describes the kind of message expression indicated by a message 6682 /// send that starts with an identifier. 6683 enum ObjCMessageKind { 6684 /// \brief The message is sent to 'super'. 6685 ObjCSuperMessage, 6686 /// \brief The message is an instance message. 6687 ObjCInstanceMessage, 6688 /// \brief The message is a class message, and the identifier is a type 6689 /// name. 6690 ObjCClassMessage 6691 }; 6692 6693 ObjCMessageKind getObjCMessageKind(Scope *S, 6694 IdentifierInfo *Name, 6695 SourceLocation NameLoc, 6696 bool IsSuper, 6697 bool HasTrailingDot, 6698 ParsedType &ReceiverType); 6699 6700 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 6701 Selector Sel, 6702 SourceLocation LBracLoc, 6703 ArrayRef<SourceLocation> SelectorLocs, 6704 SourceLocation RBracLoc, 6705 MultiExprArg Args); 6706 6707 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 6708 QualType ReceiverType, 6709 SourceLocation SuperLoc, 6710 Selector Sel, 6711 ObjCMethodDecl *Method, 6712 SourceLocation LBracLoc, 6713 ArrayRef<SourceLocation> SelectorLocs, 6714 SourceLocation RBracLoc, 6715 MultiExprArg Args, 6716 bool isImplicit = false); 6717 6718 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 6719 bool isSuperReceiver, 6720 SourceLocation Loc, 6721 Selector Sel, 6722 ObjCMethodDecl *Method, 6723 MultiExprArg Args); 6724 6725 ExprResult ActOnClassMessage(Scope *S, 6726 ParsedType Receiver, 6727 Selector Sel, 6728 SourceLocation LBracLoc, 6729 ArrayRef<SourceLocation> SelectorLocs, 6730 SourceLocation RBracLoc, 6731 MultiExprArg Args); 6732 6733 ExprResult BuildInstanceMessage(Expr *Receiver, 6734 QualType ReceiverType, 6735 SourceLocation SuperLoc, 6736 Selector Sel, 6737 ObjCMethodDecl *Method, 6738 SourceLocation LBracLoc, 6739 ArrayRef<SourceLocation> SelectorLocs, 6740 SourceLocation RBracLoc, 6741 MultiExprArg Args, 6742 bool isImplicit = false); 6743 6744 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 6745 QualType ReceiverType, 6746 SourceLocation Loc, 6747 Selector Sel, 6748 ObjCMethodDecl *Method, 6749 MultiExprArg Args); 6750 6751 ExprResult ActOnInstanceMessage(Scope *S, 6752 Expr *Receiver, 6753 Selector Sel, 6754 SourceLocation LBracLoc, 6755 ArrayRef<SourceLocation> SelectorLocs, 6756 SourceLocation RBracLoc, 6757 MultiExprArg Args); 6758 6759 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 6760 ObjCBridgeCastKind Kind, 6761 SourceLocation BridgeKeywordLoc, 6762 TypeSourceInfo *TSInfo, 6763 Expr *SubExpr); 6764 6765 ExprResult ActOnObjCBridgedCast(Scope *S, 6766 SourceLocation LParenLoc, 6767 ObjCBridgeCastKind Kind, 6768 SourceLocation BridgeKeywordLoc, 6769 ParsedType Type, 6770 SourceLocation RParenLoc, 6771 Expr *SubExpr); 6772 6773 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 6774 6775 /// \brief Check whether the given new method is a valid override of the 6776 /// given overridden method, and set any properties that should be inherited. 6777 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 6778 const ObjCMethodDecl *Overridden); 6779 6780 /// \brief Describes the compatibility of a result type with its method. 6781 enum ResultTypeCompatibilityKind { 6782 RTC_Compatible, 6783 RTC_Incompatible, 6784 RTC_Unknown 6785 }; 6786 6787 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 6788 ObjCInterfaceDecl *CurrentClass, 6789 ResultTypeCompatibilityKind RTC); 6790 6791 enum PragmaOptionsAlignKind { 6792 POAK_Native, // #pragma options align=native 6793 POAK_Natural, // #pragma options align=natural 6794 POAK_Packed, // #pragma options align=packed 6795 POAK_Power, // #pragma options align=power 6796 POAK_Mac68k, // #pragma options align=mac68k 6797 POAK_Reset // #pragma options align=reset 6798 }; 6799 6800 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 6801 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 6802 SourceLocation PragmaLoc); 6803 6804 enum PragmaPackKind { 6805 PPK_Default, // #pragma pack([n]) 6806 PPK_Show, // #pragma pack(show), only supported by MSVC. 6807 PPK_Push, // #pragma pack(push, [identifier], [n]) 6808 PPK_Pop // #pragma pack(pop, [identifier], [n]) 6809 }; 6810 6811 enum PragmaMSStructKind { 6812 PMSST_OFF, // #pragms ms_struct off 6813 PMSST_ON // #pragms ms_struct on 6814 }; 6815 6816 enum PragmaMSCommentKind { 6817 PCK_Unknown, 6818 PCK_Linker, // #pragma comment(linker, ...) 6819 PCK_Lib, // #pragma comment(lib, ...) 6820 PCK_Compiler, // #pragma comment(compiler, ...) 6821 PCK_ExeStr, // #pragma comment(exestr, ...) 6822 PCK_User // #pragma comment(user, ...) 6823 }; 6824 6825 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 6826 void ActOnPragmaPack(PragmaPackKind Kind, 6827 IdentifierInfo *Name, 6828 Expr *Alignment, 6829 SourceLocation PragmaLoc, 6830 SourceLocation LParenLoc, 6831 SourceLocation RParenLoc); 6832 6833 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 6834 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 6835 6836 /// ActOnPragmaMSComment - Called on well formed 6837 /// \#pragma comment(kind, "arg"). 6838 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg); 6839 6840 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 6841 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value); 6842 6843 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 6844 void ActOnPragmaUnused(const Token &Identifier, 6845 Scope *curScope, 6846 SourceLocation PragmaLoc); 6847 6848 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 6849 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 6850 SourceLocation PragmaLoc); 6851 6852 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 6853 SourceLocation Loc); 6854 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 6855 6856 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 6857 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 6858 SourceLocation PragmaLoc, 6859 SourceLocation WeakNameLoc); 6860 6861 /// ActOnPragmaRedefineExtname - Called on well formed 6862 /// \#pragma redefine_extname oldname newname. 6863 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 6864 IdentifierInfo* AliasName, 6865 SourceLocation PragmaLoc, 6866 SourceLocation WeakNameLoc, 6867 SourceLocation AliasNameLoc); 6868 6869 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 6870 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 6871 IdentifierInfo* AliasName, 6872 SourceLocation PragmaLoc, 6873 SourceLocation WeakNameLoc, 6874 SourceLocation AliasNameLoc); 6875 6876 /// ActOnPragmaFPContract - Called on well formed 6877 /// \#pragma {STDC,OPENCL} FP_CONTRACT 6878 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 6879 6880 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 6881 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 6882 void AddAlignmentAttributesForRecord(RecordDecl *RD); 6883 6884 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 6885 void AddMsStructLayoutForRecord(RecordDecl *RD); 6886 6887 /// FreePackedContext - Deallocate and null out PackContext. 6888 void FreePackedContext(); 6889 6890 /// PushNamespaceVisibilityAttr - Note that we've entered a 6891 /// namespace with a visibility attribute. 6892 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 6893 SourceLocation Loc); 6894 6895 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 6896 /// add an appropriate visibility attribute. 6897 void AddPushedVisibilityAttribute(Decl *RD); 6898 6899 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 6900 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 6901 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 6902 6903 /// FreeVisContext - Deallocate and null out VisContext. 6904 void FreeVisContext(); 6905 6906 /// AddCFAuditedAttribute - Check whether we're currently within 6907 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 6908 /// the appropriate attribute. 6909 void AddCFAuditedAttribute(Decl *D); 6910 6911 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 6912 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 6913 unsigned SpellingListIndex, bool IsPackExpansion); 6914 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, 6915 unsigned SpellingListIndex, bool IsPackExpansion); 6916 6917 // OpenMP directives and clauses. 6918private: 6919 void *VarDataSharingAttributesStack; 6920 /// \brief Initialization of data-sharing attributes stack. 6921 void InitDataSharingAttributesStack(); 6922 void DestroyDataSharingAttributesStack(); 6923public: 6924 /// \brief Called on start of new data sharing attribute block. 6925 void StartOpenMPDSABlock(OpenMPDirectiveKind K, 6926 const DeclarationNameInfo &DirName, 6927 Scope *CurScope); 6928 /// \brief Called on end of data sharing attribute block. 6929 void EndOpenMPDSABlock(Stmt *CurDirective); 6930 6931 // OpenMP directives and clauses. 6932 /// \brief Called on correct id-expression from the '#pragma omp 6933 /// threadprivate'. 6934 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, 6935 CXXScopeSpec &ScopeSpec, 6936 const DeclarationNameInfo &Id); 6937 /// \brief Called on well-formed '#pragma omp threadprivate'. 6938 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( 6939 SourceLocation Loc, 6940 ArrayRef<Expr *> VarList); 6941 // \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness. 6942 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl( 6943 SourceLocation Loc, 6944 ArrayRef<Expr *> VarList); 6945 6946 StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind, 6947 ArrayRef<OMPClause *> Clauses, 6948 Stmt *AStmt, 6949 SourceLocation StartLoc, 6950 SourceLocation EndLoc); 6951 /// \brief Called on well-formed '\#pragma omp parallel' after parsing 6952 /// of the associated statement. 6953 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 6954 Stmt *AStmt, 6955 SourceLocation StartLoc, 6956 SourceLocation EndLoc); 6957 6958 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, 6959 unsigned Argument, 6960 SourceLocation ArgumentLoc, 6961 SourceLocation StartLoc, 6962 SourceLocation LParenLoc, 6963 SourceLocation EndLoc); 6964 /// \brief Called on well-formed 'default' clause. 6965 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 6966 SourceLocation KindLoc, 6967 SourceLocation StartLoc, 6968 SourceLocation LParenLoc, 6969 SourceLocation EndLoc); 6970 6971 OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind, 6972 ArrayRef<Expr *> Vars, 6973 SourceLocation StartLoc, 6974 SourceLocation LParenLoc, 6975 SourceLocation EndLoc); 6976 /// \brief Called on well-formed 'private' clause. 6977 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 6978 SourceLocation StartLoc, 6979 SourceLocation LParenLoc, 6980 SourceLocation EndLoc); 6981 /// \brief Called on well-formed 'shared' clause. 6982 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 6983 SourceLocation StartLoc, 6984 SourceLocation LParenLoc, 6985 SourceLocation EndLoc); 6986 6987 /// \brief The kind of conversion being performed. 6988 enum CheckedConversionKind { 6989 /// \brief An implicit conversion. 6990 CCK_ImplicitConversion, 6991 /// \brief A C-style cast. 6992 CCK_CStyleCast, 6993 /// \brief A functional-style cast. 6994 CCK_FunctionalCast, 6995 /// \brief A cast other than a C-style cast. 6996 CCK_OtherCast 6997 }; 6998 6999 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 7000 /// cast. If there is already an implicit cast, merge into the existing one. 7001 /// If isLvalue, the result of the cast is an lvalue. 7002 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 7003 ExprValueKind VK = VK_RValue, 7004 const CXXCastPath *BasePath = 0, 7005 CheckedConversionKind CCK 7006 = CCK_ImplicitConversion); 7007 7008 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 7009 /// to the conversion from scalar type ScalarTy to the Boolean type. 7010 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 7011 7012 /// IgnoredValueConversions - Given that an expression's result is 7013 /// syntactically ignored, perform any conversions that are 7014 /// required. 7015 ExprResult IgnoredValueConversions(Expr *E); 7016 7017 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 7018 // functions and arrays to their respective pointers (C99 6.3.2.1). 7019 ExprResult UsualUnaryConversions(Expr *E); 7020 7021 // DefaultFunctionArrayConversion - converts functions and arrays 7022 // to their respective pointers (C99 6.3.2.1). 7023 ExprResult DefaultFunctionArrayConversion(Expr *E); 7024 7025 // DefaultFunctionArrayLvalueConversion - converts functions and 7026 // arrays to their respective pointers and performs the 7027 // lvalue-to-rvalue conversion. 7028 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 7029 7030 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 7031 // the operand. This is DefaultFunctionArrayLvalueConversion, 7032 // except that it assumes the operand isn't of function or array 7033 // type. 7034 ExprResult DefaultLvalueConversion(Expr *E); 7035 7036 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 7037 // do not have a prototype. Integer promotions are performed on each 7038 // argument, and arguments that have type float are promoted to double. 7039 ExprResult DefaultArgumentPromotion(Expr *E); 7040 7041 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 7042 enum VariadicCallType { 7043 VariadicFunction, 7044 VariadicBlock, 7045 VariadicMethod, 7046 VariadicConstructor, 7047 VariadicDoesNotApply 7048 }; 7049 7050 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 7051 const FunctionProtoType *Proto, 7052 Expr *Fn); 7053 7054 // Used for determining in which context a type is allowed to be passed to a 7055 // vararg function. 7056 enum VarArgKind { 7057 VAK_Valid, 7058 VAK_ValidInCXX11, 7059 VAK_Undefined, 7060 VAK_Invalid 7061 }; 7062 7063 // Determines which VarArgKind fits an expression. 7064 VarArgKind isValidVarArgType(const QualType &Ty); 7065 7066 /// Check to see if the given expression is a valid argument to a variadic 7067 /// function, issuing a diagnostic if not. 7068 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 7069 7070 /// GatherArgumentsForCall - Collector argument expressions for various 7071 /// form of call prototypes. 7072 bool GatherArgumentsForCall(SourceLocation CallLoc, 7073 FunctionDecl *FDecl, 7074 const FunctionProtoType *Proto, 7075 unsigned FirstProtoArg, 7076 ArrayRef<Expr *> Args, 7077 SmallVectorImpl<Expr *> &AllArgs, 7078 VariadicCallType CallType = VariadicDoesNotApply, 7079 bool AllowExplicit = false, 7080 bool IsListInitialization = false); 7081 7082 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 7083 // will create a runtime trap if the resulting type is not a POD type. 7084 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 7085 FunctionDecl *FDecl); 7086 7087 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 7088 // operands and then handles various conversions that are common to binary 7089 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 7090 // routine returns the first non-arithmetic type found. The client is 7091 // responsible for emitting appropriate error diagnostics. 7092 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 7093 bool IsCompAssign = false); 7094 7095 /// AssignConvertType - All of the 'assignment' semantic checks return this 7096 /// enum to indicate whether the assignment was allowed. These checks are 7097 /// done for simple assignments, as well as initialization, return from 7098 /// function, argument passing, etc. The query is phrased in terms of a 7099 /// source and destination type. 7100 enum AssignConvertType { 7101 /// Compatible - the types are compatible according to the standard. 7102 Compatible, 7103 7104 /// PointerToInt - The assignment converts a pointer to an int, which we 7105 /// accept as an extension. 7106 PointerToInt, 7107 7108 /// IntToPointer - The assignment converts an int to a pointer, which we 7109 /// accept as an extension. 7110 IntToPointer, 7111 7112 /// FunctionVoidPointer - The assignment is between a function pointer and 7113 /// void*, which the standard doesn't allow, but we accept as an extension. 7114 FunctionVoidPointer, 7115 7116 /// IncompatiblePointer - The assignment is between two pointers types that 7117 /// are not compatible, but we accept them as an extension. 7118 IncompatiblePointer, 7119 7120 /// IncompatiblePointer - The assignment is between two pointers types which 7121 /// point to integers which have a different sign, but are otherwise 7122 /// identical. This is a subset of the above, but broken out because it's by 7123 /// far the most common case of incompatible pointers. 7124 IncompatiblePointerSign, 7125 7126 /// CompatiblePointerDiscardsQualifiers - The assignment discards 7127 /// c/v/r qualifiers, which we accept as an extension. 7128 CompatiblePointerDiscardsQualifiers, 7129 7130 /// IncompatiblePointerDiscardsQualifiers - The assignment 7131 /// discards qualifiers that we don't permit to be discarded, 7132 /// like address spaces. 7133 IncompatiblePointerDiscardsQualifiers, 7134 7135 /// IncompatibleNestedPointerQualifiers - The assignment is between two 7136 /// nested pointer types, and the qualifiers other than the first two 7137 /// levels differ e.g. char ** -> const char **, but we accept them as an 7138 /// extension. 7139 IncompatibleNestedPointerQualifiers, 7140 7141 /// IncompatibleVectors - The assignment is between two vector types that 7142 /// have the same size, which we accept as an extension. 7143 IncompatibleVectors, 7144 7145 /// IntToBlockPointer - The assignment converts an int to a block 7146 /// pointer. We disallow this. 7147 IntToBlockPointer, 7148 7149 /// IncompatibleBlockPointer - The assignment is between two block 7150 /// pointers types that are not compatible. 7151 IncompatibleBlockPointer, 7152 7153 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 7154 /// id type and something else (that is incompatible with it). For example, 7155 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 7156 IncompatibleObjCQualifiedId, 7157 7158 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 7159 /// object with __weak qualifier. 7160 IncompatibleObjCWeakRef, 7161 7162 /// Incompatible - We reject this conversion outright, it is invalid to 7163 /// represent it in the AST. 7164 Incompatible 7165 }; 7166 7167 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 7168 /// assignment conversion type specified by ConvTy. This returns true if the 7169 /// conversion was invalid or false if the conversion was accepted. 7170 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 7171 SourceLocation Loc, 7172 QualType DstType, QualType SrcType, 7173 Expr *SrcExpr, AssignmentAction Action, 7174 bool *Complained = 0); 7175 7176 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 7177 /// integer not in the range of enum values. 7178 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 7179 Expr *SrcExpr); 7180 7181 /// CheckAssignmentConstraints - Perform type checking for assignment, 7182 /// argument passing, variable initialization, and function return values. 7183 /// C99 6.5.16. 7184 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 7185 QualType LHSType, 7186 QualType RHSType); 7187 7188 /// Check assignment constraints and prepare for a conversion of the 7189 /// RHS to the LHS type. 7190 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 7191 ExprResult &RHS, 7192 CastKind &Kind); 7193 7194 // CheckSingleAssignmentConstraints - Currently used by 7195 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 7196 // this routine performs the default function/array converions. 7197 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 7198 ExprResult &RHS, 7199 bool Diagnose = true, 7200 bool DiagnoseCFAudited = false); 7201 7202 // \brief If the lhs type is a transparent union, check whether we 7203 // can initialize the transparent union with the given expression. 7204 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 7205 ExprResult &RHS); 7206 7207 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 7208 7209 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 7210 7211 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 7212 AssignmentAction Action, 7213 bool AllowExplicit = false); 7214 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 7215 AssignmentAction Action, 7216 bool AllowExplicit, 7217 ImplicitConversionSequence& ICS); 7218 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 7219 const ImplicitConversionSequence& ICS, 7220 AssignmentAction Action, 7221 CheckedConversionKind CCK 7222 = CCK_ImplicitConversion); 7223 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 7224 const StandardConversionSequence& SCS, 7225 AssignmentAction Action, 7226 CheckedConversionKind CCK); 7227 7228 /// the following "Check" methods will return a valid/converted QualType 7229 /// or a null QualType (indicating an error diagnostic was issued). 7230 7231 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 7232 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7233 ExprResult &RHS); 7234 QualType CheckPointerToMemberOperands( // C++ 5.5 7235 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 7236 SourceLocation OpLoc, bool isIndirect); 7237 QualType CheckMultiplyDivideOperands( // C99 6.5.5 7238 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 7239 bool IsDivide); 7240 QualType CheckRemainderOperands( // C99 6.5.5 7241 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7242 bool IsCompAssign = false); 7243 QualType CheckAdditionOperands( // C99 6.5.6 7244 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7245 QualType* CompLHSTy = 0); 7246 QualType CheckSubtractionOperands( // C99 6.5.6 7247 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7248 QualType* CompLHSTy = 0); 7249 QualType CheckShiftOperands( // C99 6.5.7 7250 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7251 bool IsCompAssign = false); 7252 QualType CheckCompareOperands( // C99 6.5.8/9 7253 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 7254 bool isRelational); 7255 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 7256 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7257 bool IsCompAssign = false); 7258 QualType CheckLogicalOperands( // C99 6.5.[13,14] 7259 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 7260 // CheckAssignmentOperands is used for both simple and compound assignment. 7261 // For simple assignment, pass both expressions and a null converted type. 7262 // For compound assignment, pass both expressions and the converted type. 7263 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 7264 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 7265 7266 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 7267 UnaryOperatorKind Opcode, Expr *Op); 7268 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 7269 BinaryOperatorKind Opcode, 7270 Expr *LHS, Expr *RHS); 7271 ExprResult checkPseudoObjectRValue(Expr *E); 7272 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 7273 7274 QualType CheckConditionalOperands( // C99 6.5.15 7275 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 7276 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 7277 QualType CXXCheckConditionalOperands( // C++ 5.16 7278 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 7279 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 7280 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 7281 bool *NonStandardCompositeType = 0); 7282 QualType FindCompositePointerType(SourceLocation Loc, 7283 ExprResult &E1, ExprResult &E2, 7284 bool *NonStandardCompositeType = 0) { 7285 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take(); 7286 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, 7287 NonStandardCompositeType); 7288 E1 = Owned(E1Tmp); 7289 E2 = Owned(E2Tmp); 7290 return Composite; 7291 } 7292 7293 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7294 SourceLocation QuestionLoc); 7295 7296 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7297 SourceLocation QuestionLoc); 7298 7299 /// type checking for vector binary operators. 7300 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7301 SourceLocation Loc, bool IsCompAssign); 7302 QualType GetSignedVectorType(QualType V); 7303 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7304 SourceLocation Loc, bool isRelational); 7305 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7306 SourceLocation Loc); 7307 7308 /// type checking declaration initializers (C99 6.7.8) 7309 bool CheckForConstantInitializer(Expr *e, QualType t); 7310 7311 // type checking C++ declaration initializers (C++ [dcl.init]). 7312 7313 /// ReferenceCompareResult - Expresses the result of comparing two 7314 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 7315 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 7316 enum ReferenceCompareResult { 7317 /// Ref_Incompatible - The two types are incompatible, so direct 7318 /// reference binding is not possible. 7319 Ref_Incompatible = 0, 7320 /// Ref_Related - The two types are reference-related, which means 7321 /// that their unqualified forms (T1 and T2) are either the same 7322 /// or T1 is a base class of T2. 7323 Ref_Related, 7324 /// Ref_Compatible_With_Added_Qualification - The two types are 7325 /// reference-compatible with added qualification, meaning that 7326 /// they are reference-compatible and the qualifiers on T1 (cv1) 7327 /// are greater than the qualifiers on T2 (cv2). 7328 Ref_Compatible_With_Added_Qualification, 7329 /// Ref_Compatible - The two types are reference-compatible and 7330 /// have equivalent qualifiers (cv1 == cv2). 7331 Ref_Compatible 7332 }; 7333 7334 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 7335 QualType T1, QualType T2, 7336 bool &DerivedToBase, 7337 bool &ObjCConversion, 7338 bool &ObjCLifetimeConversion); 7339 7340 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 7341 Expr *CastExpr, CastKind &CastKind, 7342 ExprValueKind &VK, CXXCastPath &Path); 7343 7344 /// \brief Force an expression with unknown-type to an expression of the 7345 /// given type. 7346 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 7347 7348 /// \brief Type-check an expression that's being passed to an 7349 /// __unknown_anytype parameter. 7350 ExprResult checkUnknownAnyArg(SourceLocation callLoc, 7351 Expr *result, QualType ¶mType); 7352 7353 // CheckVectorCast - check type constraints for vectors. 7354 // Since vectors are an extension, there are no C standard reference for this. 7355 // We allow casting between vectors and integer datatypes of the same size. 7356 // returns true if the cast is invalid 7357 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7358 CastKind &Kind); 7359 7360 // CheckExtVectorCast - check type constraints for extended vectors. 7361 // Since vectors are an extension, there are no C standard reference for this. 7362 // We allow casting between vectors and integer datatypes of the same size, 7363 // or vectors and the element type of that vector. 7364 // returns the cast expr 7365 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 7366 CastKind &Kind); 7367 7368 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, 7369 SourceLocation LParenLoc, 7370 Expr *CastExpr, 7371 SourceLocation RParenLoc); 7372 7373 enum ARCConversionResult { ACR_okay, ACR_unbridged }; 7374 7375 /// \brief Checks for invalid conversions and casts between 7376 /// retainable pointers and other pointer kinds. 7377 ARCConversionResult CheckObjCARCConversion(SourceRange castRange, 7378 QualType castType, Expr *&op, 7379 CheckedConversionKind CCK, 7380 bool DiagnoseCFAudited = false); 7381 7382 Expr *stripARCUnbridgedCast(Expr *e); 7383 void diagnoseARCUnbridgedCast(Expr *e); 7384 7385 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 7386 QualType ExprType); 7387 7388 /// checkRetainCycles - Check whether an Objective-C message send 7389 /// might create an obvious retain cycle. 7390 void checkRetainCycles(ObjCMessageExpr *msg); 7391 void checkRetainCycles(Expr *receiver, Expr *argument); 7392 void checkRetainCycles(VarDecl *Var, Expr *Init); 7393 7394 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 7395 /// to weak/__unsafe_unretained type. 7396 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 7397 7398 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 7399 /// to weak/__unsafe_unretained expression. 7400 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 7401 7402 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 7403 /// \param Method - May be null. 7404 /// \param [out] ReturnType - The return type of the send. 7405 /// \return true iff there were any incompatible types. 7406 bool CheckMessageArgumentTypes(QualType ReceiverType, 7407 MultiExprArg Args, Selector Sel, 7408 ArrayRef<SourceLocation> SelectorLocs, 7409 ObjCMethodDecl *Method, bool isClassMessage, 7410 bool isSuperMessage, 7411 SourceLocation lbrac, SourceLocation rbrac, 7412 QualType &ReturnType, ExprValueKind &VK); 7413 7414 /// \brief Determine the result of a message send expression based on 7415 /// the type of the receiver, the method expected to receive the message, 7416 /// and the form of the message send. 7417 QualType getMessageSendResultType(QualType ReceiverType, 7418 ObjCMethodDecl *Method, 7419 bool isClassMessage, bool isSuperMessage); 7420 7421 /// \brief If the given expression involves a message send to a method 7422 /// with a related result type, emit a note describing what happened. 7423 void EmitRelatedResultTypeNote(const Expr *E); 7424 7425 /// \brief Given that we had incompatible pointer types in a return 7426 /// statement, check whether we're in a method with a related result 7427 /// type, and if so, emit a note describing what happened. 7428 void EmitRelatedResultTypeNoteForReturn(QualType destType); 7429 7430 /// CheckBooleanCondition - Diagnose problems involving the use of 7431 /// the given expression as a boolean condition (e.g. in an if 7432 /// statement). Also performs the standard function and array 7433 /// decays, possibly changing the input variable. 7434 /// 7435 /// \param Loc - A location associated with the condition, e.g. the 7436 /// 'if' keyword. 7437 /// \return true iff there were any errors 7438 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 7439 7440 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 7441 Expr *SubExpr); 7442 7443 /// DiagnoseAssignmentAsCondition - Given that an expression is 7444 /// being used as a boolean condition, warn if it's an assignment. 7445 void DiagnoseAssignmentAsCondition(Expr *E); 7446 7447 /// \brief Redundant parentheses over an equality comparison can indicate 7448 /// that the user intended an assignment used as condition. 7449 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 7450 7451 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 7452 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 7453 7454 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 7455 /// the specified width and sign. If an overflow occurs, detect it and emit 7456 /// the specified diagnostic. 7457 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 7458 unsigned NewWidth, bool NewSign, 7459 SourceLocation Loc, unsigned DiagID); 7460 7461 /// Checks that the Objective-C declaration is declared in the global scope. 7462 /// Emits an error and marks the declaration as invalid if it's not declared 7463 /// in the global scope. 7464 bool CheckObjCDeclScope(Decl *D); 7465 7466 /// \brief Abstract base class used for diagnosing integer constant 7467 /// expression violations. 7468 class VerifyICEDiagnoser { 7469 public: 7470 bool Suppress; 7471 7472 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 7473 7474 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 7475 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); 7476 virtual ~VerifyICEDiagnoser() { } 7477 }; 7478 7479 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 7480 /// and reports the appropriate diagnostics. Returns false on success. 7481 /// Can optionally return the value of the expression. 7482 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 7483 VerifyICEDiagnoser &Diagnoser, 7484 bool AllowFold = true); 7485 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 7486 unsigned DiagID, 7487 bool AllowFold = true); 7488 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0); 7489 7490 /// VerifyBitField - verifies that a bit field expression is an ICE and has 7491 /// the correct width, and that the field type is valid. 7492 /// Returns false on success. 7493 /// Can optionally return whether the bit-field is of width 0 7494 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 7495 QualType FieldTy, bool IsMsStruct, 7496 Expr *BitWidth, bool *ZeroWidth = 0); 7497 7498 enum CUDAFunctionTarget { 7499 CFT_Device, 7500 CFT_Global, 7501 CFT_Host, 7502 CFT_HostDevice 7503 }; 7504 7505 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); 7506 7507 bool CheckCUDATarget(CUDAFunctionTarget CallerTarget, 7508 CUDAFunctionTarget CalleeTarget); 7509 7510 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) { 7511 return CheckCUDATarget(IdentifyCUDATarget(Caller), 7512 IdentifyCUDATarget(Callee)); 7513 } 7514 7515 /// \name Code completion 7516 //@{ 7517 /// \brief Describes the context in which code completion occurs. 7518 enum ParserCompletionContext { 7519 /// \brief Code completion occurs at top-level or namespace context. 7520 PCC_Namespace, 7521 /// \brief Code completion occurs within a class, struct, or union. 7522 PCC_Class, 7523 /// \brief Code completion occurs within an Objective-C interface, protocol, 7524 /// or category. 7525 PCC_ObjCInterface, 7526 /// \brief Code completion occurs within an Objective-C implementation or 7527 /// category implementation 7528 PCC_ObjCImplementation, 7529 /// \brief Code completion occurs within the list of instance variables 7530 /// in an Objective-C interface, protocol, category, or implementation. 7531 PCC_ObjCInstanceVariableList, 7532 /// \brief Code completion occurs following one or more template 7533 /// headers. 7534 PCC_Template, 7535 /// \brief Code completion occurs following one or more template 7536 /// headers within a class. 7537 PCC_MemberTemplate, 7538 /// \brief Code completion occurs within an expression. 7539 PCC_Expression, 7540 /// \brief Code completion occurs within a statement, which may 7541 /// also be an expression or a declaration. 7542 PCC_Statement, 7543 /// \brief Code completion occurs at the beginning of the 7544 /// initialization statement (or expression) in a for loop. 7545 PCC_ForInit, 7546 /// \brief Code completion occurs within the condition of an if, 7547 /// while, switch, or for statement. 7548 PCC_Condition, 7549 /// \brief Code completion occurs within the body of a function on a 7550 /// recovery path, where we do not have a specific handle on our position 7551 /// in the grammar. 7552 PCC_RecoveryInFunction, 7553 /// \brief Code completion occurs where only a type is permitted. 7554 PCC_Type, 7555 /// \brief Code completion occurs in a parenthesized expression, which 7556 /// might also be a type cast. 7557 PCC_ParenthesizedExpression, 7558 /// \brief Code completion occurs within a sequence of declaration 7559 /// specifiers within a function, method, or block. 7560 PCC_LocalDeclarationSpecifiers 7561 }; 7562 7563 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 7564 void CodeCompleteOrdinaryName(Scope *S, 7565 ParserCompletionContext CompletionContext); 7566 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 7567 bool AllowNonIdentifiers, 7568 bool AllowNestedNameSpecifiers); 7569 7570 struct CodeCompleteExpressionData; 7571 void CodeCompleteExpression(Scope *S, 7572 const CodeCompleteExpressionData &Data); 7573 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 7574 SourceLocation OpLoc, 7575 bool IsArrow); 7576 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 7577 void CodeCompleteTag(Scope *S, unsigned TagSpec); 7578 void CodeCompleteTypeQualifiers(DeclSpec &DS); 7579 void CodeCompleteCase(Scope *S); 7580 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args); 7581 void CodeCompleteInitializer(Scope *S, Decl *D); 7582 void CodeCompleteReturn(Scope *S); 7583 void CodeCompleteAfterIf(Scope *S); 7584 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 7585 7586 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 7587 bool EnteringContext); 7588 void CodeCompleteUsing(Scope *S); 7589 void CodeCompleteUsingDirective(Scope *S); 7590 void CodeCompleteNamespaceDecl(Scope *S); 7591 void CodeCompleteNamespaceAliasDecl(Scope *S); 7592 void CodeCompleteOperatorName(Scope *S); 7593 void CodeCompleteConstructorInitializer( 7594 Decl *Constructor, 7595 ArrayRef<CXXCtorInitializer *> Initializers); 7596 7597 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 7598 bool AfterAmpersand); 7599 7600 void CodeCompleteObjCAtDirective(Scope *S); 7601 void CodeCompleteObjCAtVisibility(Scope *S); 7602 void CodeCompleteObjCAtStatement(Scope *S); 7603 void CodeCompleteObjCAtExpression(Scope *S); 7604 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 7605 void CodeCompleteObjCPropertyGetter(Scope *S); 7606 void CodeCompleteObjCPropertySetter(Scope *S); 7607 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 7608 bool IsParameter); 7609 void CodeCompleteObjCMessageReceiver(Scope *S); 7610 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 7611 ArrayRef<IdentifierInfo *> SelIdents, 7612 bool AtArgumentExpression); 7613 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 7614 ArrayRef<IdentifierInfo *> SelIdents, 7615 bool AtArgumentExpression, 7616 bool IsSuper = false); 7617 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 7618 ArrayRef<IdentifierInfo *> SelIdents, 7619 bool AtArgumentExpression, 7620 ObjCInterfaceDecl *Super = 0); 7621 void CodeCompleteObjCForCollection(Scope *S, 7622 DeclGroupPtrTy IterationVar); 7623 void CodeCompleteObjCSelector(Scope *S, 7624 ArrayRef<IdentifierInfo *> SelIdents); 7625 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 7626 unsigned NumProtocols); 7627 void CodeCompleteObjCProtocolDecl(Scope *S); 7628 void CodeCompleteObjCInterfaceDecl(Scope *S); 7629 void CodeCompleteObjCSuperclass(Scope *S, 7630 IdentifierInfo *ClassName, 7631 SourceLocation ClassNameLoc); 7632 void CodeCompleteObjCImplementationDecl(Scope *S); 7633 void CodeCompleteObjCInterfaceCategory(Scope *S, 7634 IdentifierInfo *ClassName, 7635 SourceLocation ClassNameLoc); 7636 void CodeCompleteObjCImplementationCategory(Scope *S, 7637 IdentifierInfo *ClassName, 7638 SourceLocation ClassNameLoc); 7639 void CodeCompleteObjCPropertyDefinition(Scope *S); 7640 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 7641 IdentifierInfo *PropertyName); 7642 void CodeCompleteObjCMethodDecl(Scope *S, 7643 bool IsInstanceMethod, 7644 ParsedType ReturnType); 7645 void CodeCompleteObjCMethodDeclSelector(Scope *S, 7646 bool IsInstanceMethod, 7647 bool AtParameterName, 7648 ParsedType ReturnType, 7649 ArrayRef<IdentifierInfo *> SelIdents); 7650 void CodeCompletePreprocessorDirective(bool InConditional); 7651 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 7652 void CodeCompletePreprocessorMacroName(bool IsDefinition); 7653 void CodeCompletePreprocessorExpression(); 7654 void CodeCompletePreprocessorMacroArgument(Scope *S, 7655 IdentifierInfo *Macro, 7656 MacroInfo *MacroInfo, 7657 unsigned Argument); 7658 void CodeCompleteNaturalLanguage(); 7659 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 7660 CodeCompletionTUInfo &CCTUInfo, 7661 SmallVectorImpl<CodeCompletionResult> &Results); 7662 //@} 7663 7664 //===--------------------------------------------------------------------===// 7665 // Extra semantic analysis beyond the C type system 7666 7667public: 7668 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 7669 unsigned ByteNo) const; 7670 7671private: 7672 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 7673 const ArraySubscriptExpr *ASE=0, 7674 bool AllowOnePastEnd=true, bool IndexNegated=false); 7675 void CheckArrayAccess(const Expr *E); 7676 // Used to grab the relevant information from a FormatAttr and a 7677 // FunctionDeclaration. 7678 struct FormatStringInfo { 7679 unsigned FormatIdx; 7680 unsigned FirstDataArg; 7681 bool HasVAListArg; 7682 }; 7683 7684 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 7685 FormatStringInfo *FSI); 7686 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 7687 const FunctionProtoType *Proto); 7688 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 7689 ArrayRef<const Expr *> Args); 7690 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 7691 const FunctionProtoType *Proto); 7692 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 7693 void CheckConstructorCall(FunctionDecl *FDecl, 7694 ArrayRef<const Expr *> Args, 7695 const FunctionProtoType *Proto, 7696 SourceLocation Loc); 7697 7698 void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args, 7699 unsigned NumProtoArgs, bool IsMemberFunction, 7700 SourceLocation Loc, SourceRange Range, 7701 VariadicCallType CallType); 7702 7703 7704 bool CheckObjCString(Expr *Arg); 7705 7706 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7707 7708 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall); 7709 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7710 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7711 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7712 7713 bool SemaBuiltinVAStart(CallExpr *TheCall); 7714 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 7715 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 7716 7717public: 7718 // Used by C++ template instantiation. 7719 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 7720 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 7721 SourceLocation BuiltinLoc, 7722 SourceLocation RParenLoc); 7723 7724private: 7725 bool SemaBuiltinPrefetch(CallExpr *TheCall); 7726 bool SemaBuiltinObjectSize(CallExpr *TheCall); 7727 bool SemaBuiltinLongjmp(CallExpr *TheCall); 7728 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 7729 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 7730 AtomicExpr::AtomicOp Op); 7731 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7732 llvm::APSInt &Result); 7733 7734public: 7735 enum FormatStringType { 7736 FST_Scanf, 7737 FST_Printf, 7738 FST_NSString, 7739 FST_Strftime, 7740 FST_Strfmon, 7741 FST_Kprintf, 7742 FST_Unknown 7743 }; 7744 static FormatStringType GetFormatStringType(const FormatAttr *Format); 7745 7746 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 7747 ArrayRef<const Expr *> Args, bool HasVAListArg, 7748 unsigned format_idx, unsigned firstDataArg, 7749 FormatStringType Type, bool inFunctionCall, 7750 VariadicCallType CallType, 7751 llvm::SmallBitVector &CheckedVarArgs); 7752 7753private: 7754 bool CheckFormatArguments(const FormatAttr *Format, 7755 ArrayRef<const Expr *> Args, 7756 bool IsCXXMember, 7757 VariadicCallType CallType, 7758 SourceLocation Loc, SourceRange Range, 7759 llvm::SmallBitVector &CheckedVarArgs); 7760 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 7761 bool HasVAListArg, unsigned format_idx, 7762 unsigned firstDataArg, FormatStringType Type, 7763 VariadicCallType CallType, 7764 SourceLocation Loc, SourceRange range, 7765 llvm::SmallBitVector &CheckedVarArgs); 7766 7767 void CheckNonNullArguments(const NonNullAttr *NonNull, 7768 const Expr * const *ExprArgs, 7769 SourceLocation CallSiteLoc); 7770 7771 void CheckMemaccessArguments(const CallExpr *Call, 7772 unsigned BId, 7773 IdentifierInfo *FnName); 7774 7775 void CheckStrlcpycatArguments(const CallExpr *Call, 7776 IdentifierInfo *FnName); 7777 7778 void CheckStrncatArguments(const CallExpr *Call, 7779 IdentifierInfo *FnName); 7780 7781 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 7782 SourceLocation ReturnLoc); 7783 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); 7784 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 7785 void CheckForIntOverflow(Expr *E); 7786 void CheckUnsequencedOperations(Expr *E); 7787 7788 /// \brief Perform semantic checks on a completed expression. This will either 7789 /// be a full-expression or a default argument expression. 7790 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 7791 bool IsConstexpr = false); 7792 7793 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 7794 Expr *Init); 7795 7796public: 7797 /// \brief Register a magic integral constant to be used as a type tag. 7798 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 7799 uint64_t MagicValue, QualType Type, 7800 bool LayoutCompatible, bool MustBeNull); 7801 7802 struct TypeTagData { 7803 TypeTagData() {} 7804 7805 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 7806 Type(Type), LayoutCompatible(LayoutCompatible), 7807 MustBeNull(MustBeNull) 7808 {} 7809 7810 QualType Type; 7811 7812 /// If true, \c Type should be compared with other expression's types for 7813 /// layout-compatibility. 7814 unsigned LayoutCompatible : 1; 7815 unsigned MustBeNull : 1; 7816 }; 7817 7818 /// A pair of ArgumentKind identifier and magic value. This uniquely 7819 /// identifies the magic value. 7820 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 7821 7822private: 7823 /// \brief A map from magic value to type information. 7824 OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> > 7825 TypeTagForDatatypeMagicValues; 7826 7827 /// \brief Peform checks on a call of a function with argument_with_type_tag 7828 /// or pointer_with_type_tag attributes. 7829 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 7830 const Expr * const *ExprArgs); 7831 7832 /// \brief The parser's current scope. 7833 /// 7834 /// The parser maintains this state here. 7835 Scope *CurScope; 7836 7837 mutable IdentifierInfo *Ident_super; 7838 mutable IdentifierInfo *Ident___float128; 7839 7840protected: 7841 friend class Parser; 7842 friend class InitializationSequence; 7843 friend class ASTReader; 7844 friend class ASTWriter; 7845 7846public: 7847 /// \brief Retrieve the parser's current scope. 7848 /// 7849 /// This routine must only be used when it is certain that semantic analysis 7850 /// and the parser are in precisely the same context, which is not the case 7851 /// when, e.g., we are performing any kind of template instantiation. 7852 /// Therefore, the only safe places to use this scope are in the parser 7853 /// itself and in routines directly invoked from the parser and *never* from 7854 /// template substitution or instantiation. 7855 Scope *getCurScope() const { return CurScope; } 7856 7857 IdentifierInfo *getSuperIdentifier() const; 7858 IdentifierInfo *getFloat128Identifier() const; 7859 7860 Decl *getObjCDeclContext() const; 7861 7862 DeclContext *getCurLexicalContext() const { 7863 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 7864 } 7865 7866 AvailabilityResult getCurContextAvailability() const; 7867 7868 const DeclContext *getCurObjCLexicalContext() const { 7869 const DeclContext *DC = getCurLexicalContext(); 7870 // A category implicitly has the attribute of the interface. 7871 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 7872 DC = CatD->getClassInterface(); 7873 return DC; 7874 } 7875}; 7876 7877/// \brief RAII object that enters a new expression evaluation context. 7878class EnterExpressionEvaluationContext { 7879 Sema &Actions; 7880 7881public: 7882 EnterExpressionEvaluationContext(Sema &Actions, 7883 Sema::ExpressionEvaluationContext NewContext, 7884 Decl *LambdaContextDecl = 0, 7885 bool IsDecltype = false) 7886 : Actions(Actions) { 7887 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 7888 IsDecltype); 7889 } 7890 EnterExpressionEvaluationContext(Sema &Actions, 7891 Sema::ExpressionEvaluationContext NewContext, 7892 Sema::ReuseLambdaContextDecl_t, 7893 bool IsDecltype = false) 7894 : Actions(Actions) { 7895 Actions.PushExpressionEvaluationContext(NewContext, 7896 Sema::ReuseLambdaContextDecl, 7897 IsDecltype); 7898 } 7899 7900 ~EnterExpressionEvaluationContext() { 7901 Actions.PopExpressionEvaluationContext(); 7902 } 7903}; 7904 7905DeductionFailureInfo 7906MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, 7907 sema::TemplateDeductionInfo &Info); 7908 7909/// \brief Contains a late templated function. 7910/// Will be parsed at the end of the translation unit, used by Sema & Parser. 7911struct LateParsedTemplate { 7912 CachedTokens Toks; 7913 /// \brief The template function declaration to be late parsed. 7914 Decl *D; 7915}; 7916 7917} // end namespace clang 7918 7919#endif 7920