Sema.h revision dc05b11c67331016473fbc7909827b1b89c9616b
1ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// 2ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// 3ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// The LLVM Compiler Infrastructure 4ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// 5ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// This file is distributed under the University of Illinois Open Source 6ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// License. See LICENSE.TXT for details. 7ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// 8026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com//===----------------------------------------------------------------------===// 9026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com// 10026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com// This file defines the Sema class, which performs semantic analysis and 11026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com// builds ASTs. 12026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com// 13026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com//===----------------------------------------------------------------------===// 14026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com 15026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#ifndef LLVM_CLANG_SEMA_SEMA_H 16026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#define LLVM_CLANG_SEMA_SEMA_H 17026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com 18026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/Ownership.h" 19026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/AnalysisBasedWarnings.h" 20026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/IdentifierResolver.h" 21026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/ObjCMethodList.h" 22026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/DeclSpec.h" 23026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/ExternalSemaSource.h" 24026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/LocInfoType.h" 25026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/TypoCorrection.h" 26026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Sema/Weak.h" 27026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/AST/Expr.h" 28d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com#include "clang/AST/DeclarationName.h" 29026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/AST/ExternalASTSource.h" 30d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com#include "clang/AST/TypeLoc.h" 31d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com#include "clang/Basic/Specifiers.h" 32026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Basic/TemplateKinds.h" 33026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Basic/TypeTraits.h" 34026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "clang/Basic/ExpressionTraits.h" 35026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "llvm/ADT/OwningPtr.h" 36d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com#include "llvm/ADT/SmallPtrSet.h" 37026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include "llvm/ADT/SmallVector.h" 38026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include <deque> 39026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com#include <string> 40d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com 41026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.comnamespace llvm { 42026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class APSInt; 43026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com template <typename ValueT> struct DenseMapInfo; 44026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com template <typename ValueT, typename ValueInfoT> class DenseSet; 45026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com} 46d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com 47026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.comnamespace clang { 48026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class ADLResult; 49026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class ASTConsumer; 50026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class ASTContext; 51026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class ASTMutationListener; 52026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class ASTReader; 53d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com class ASTWriter; 54026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class ArrayType; 55026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class AttributeList; 56026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class BlockDecl; 57026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXBasePath; 58d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com class CXXBasePaths; 59d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 60026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXConstructorDecl; 61026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXConversionDecl; 62026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXDestructorDecl; 63026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXFieldCollector; 64026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXMemberCallExpr; 65026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXMethodDecl; 66026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXScopeSpec; 67026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXTemporary; 68026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CXXTryStmt; 69d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com class CallExpr; 70026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class ClassTemplateDecl; 71d6176b0dcacb124539e0cfd051e6d93a9782f020rmistry@google.com class ClassTemplatePartialSpecializationDecl; 72026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class ClassTemplateSpecializationDecl; 73026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CodeCompleteConsumer; 74026427654f7a8d968c3a150c5f9ec9a6596fd40dyangsu@google.com class CodeCompletionAllocator; 75bda03db28935eef7f9a3aae05fdedca57cd984adrmistry@google.com class CodeCompletionResult; 76 class Decl; 77 class DeclAccessPair; 78 class DeclContext; 79 class DeclRefExpr; 80 class DeclaratorDecl; 81 class DeducedTemplateArgument; 82 class DependentDiagnostic; 83 class DesignatedInitExpr; 84 class Designation; 85 class EnumConstantDecl; 86 class Expr; 87 class ExtVectorType; 88 class ExternalSemaSource; 89 class FormatAttr; 90 class FriendDecl; 91 class FunctionDecl; 92 class FunctionProtoType; 93 class FunctionTemplateDecl; 94 class ImplicitConversionSequence; 95 class InitListExpr; 96 class InitializationKind; 97 class InitializationSequence; 98 class InitializedEntity; 99 class IntegerLiteral; 100 class LabelStmt; 101 class LangOptions; 102 class LocalInstantiationScope; 103 class LookupResult; 104 class MacroInfo; 105 class MultiLevelTemplateArgumentList; 106 class NamedDecl; 107 class NonNullAttr; 108 class ObjCCategoryDecl; 109 class ObjCCategoryImplDecl; 110 class ObjCCompatibleAliasDecl; 111 class ObjCContainerDecl; 112 class ObjCImplDecl; 113 class ObjCImplementationDecl; 114 class ObjCInterfaceDecl; 115 class ObjCIvarDecl; 116 template <class T> class ObjCList; 117 class ObjCMessageExpr; 118 class ObjCMethodDecl; 119 class ObjCPropertyDecl; 120 class ObjCProtocolDecl; 121 class OverloadCandidateSet; 122 class OverloadExpr; 123 class ParenListExpr; 124 class ParmVarDecl; 125 class Preprocessor; 126 class PseudoDestructorTypeStorage; 127 class QualType; 128 class StandardConversionSequence; 129 class Stmt; 130 class StringLiteral; 131 class SwitchStmt; 132 class TargetAttributesSema; 133 class TemplateArgument; 134 class TemplateArgumentList; 135 class TemplateArgumentLoc; 136 class TemplateDecl; 137 class TemplateParameterList; 138 class TemplatePartialOrderingContext; 139 class TemplateTemplateParmDecl; 140 class Token; 141 class TypeAliasDecl; 142 class TypedefDecl; 143 class TypedefNameDecl; 144 class TypeLoc; 145 class UnqualifiedId; 146 class UnresolvedLookupExpr; 147 class UnresolvedMemberExpr; 148 class UnresolvedSetImpl; 149 class UnresolvedSetIterator; 150 class UsingDecl; 151 class UsingShadowDecl; 152 class ValueDecl; 153 class VarDecl; 154 class VisibilityAttr; 155 class VisibleDeclConsumer; 156 class IndirectFieldDecl; 157 158namespace sema { 159 class AccessedEntity; 160 class BlockScopeInfo; 161 class DelayedDiagnostic; 162 class FunctionScopeInfo; 163 class TemplateDeductionInfo; 164} 165 166// FIXME: No way to easily map from TemplateTypeParmTypes to 167// TemplateTypeParmDecls, so we have this horrible PointerUnion. 168typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 169 SourceLocation> UnexpandedParameterPack; 170 171/// Sema - This implements semantic analysis and AST building for C. 172class Sema { 173 Sema(const Sema&); // DO NOT IMPLEMENT 174 void operator=(const Sema&); // DO NOT IMPLEMENT 175 mutable const TargetAttributesSema* TheTargetAttributesSema; 176public: 177 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 178 typedef OpaquePtr<TemplateName> TemplateTy; 179 typedef OpaquePtr<QualType> TypeTy; 180 181 OpenCLOptions OpenCLFeatures; 182 FPOptions FPFeatures; 183 184 const LangOptions &LangOpts; 185 Preprocessor &PP; 186 ASTContext &Context; 187 ASTConsumer &Consumer; 188 Diagnostic &Diags; 189 SourceManager &SourceMgr; 190 191 /// \brief Flag indicating whether or not to collect detailed statistics. 192 bool CollectStats; 193 194 /// \brief Source of additional semantic information. 195 ExternalSemaSource *ExternalSource; 196 197 /// \brief Code-completion consumer. 198 CodeCompleteConsumer *CodeCompleter; 199 200 /// CurContext - This is the current declaration context of parsing. 201 DeclContext *CurContext; 202 203 /// VAListTagName - The declaration name corresponding to __va_list_tag. 204 /// This is used as part of a hack to omit that class from ADL results. 205 DeclarationName VAListTagName; 206 207 /// PackContext - Manages the stack for #pragma pack. An alignment 208 /// of 0 indicates default alignment. 209 void *PackContext; // Really a "PragmaPackStack*" 210 211 bool MSStructPragmaOn; // True when #pragma ms_struct on 212 213 /// VisContext - Manages the stack for #pragma GCC visibility. 214 void *VisContext; // Really a "PragmaVisStack*" 215 216 /// ExprNeedsCleanups - True if the current evaluation context 217 /// requires cleanups to be run at its conclusion. 218 bool ExprNeedsCleanups; 219 220 /// \brief Stack containing information about each of the nested 221 /// function, block, and method scopes that are currently active. 222 /// 223 /// This array is never empty. Clients should ignore the first 224 /// element, which is used to cache a single FunctionScopeInfo 225 /// that's used to parse every top-level function. 226 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 227 228 /// ExprTemporaries - This is the stack of temporaries that are created by 229 /// the current full expression. 230 SmallVector<CXXTemporary*, 8> ExprTemporaries; 231 232 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 233 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 234 ExtVectorDeclsType; 235 236 /// ExtVectorDecls - This is a list all the extended vector types. This allows 237 /// us to associate a raw vector type with one of the ext_vector type names. 238 /// This is only necessary for issuing pretty diagnostics. 239 ExtVectorDeclsType ExtVectorDecls; 240 241 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 242 llvm::OwningPtr<CXXFieldCollector> FieldCollector; 243 244 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 245 246 /// PureVirtualClassDiagSet - a set of class declarations which we have 247 /// emitted a list of pure virtual functions. Used to prevent emitting the 248 /// same list more than once. 249 llvm::OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet; 250 251 /// ParsingInitForAutoVars - a set of declarations with auto types for which 252 /// we are currently parsing the initializer. 253 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 254 255 /// \brief A mapping from external names to the most recent 256 /// locally-scoped external declaration with that name. 257 /// 258 /// This map contains external declarations introduced in local 259 /// scoped, e.g., 260 /// 261 /// \code 262 /// void f() { 263 /// void foo(int, int); 264 /// } 265 /// \endcode 266 /// 267 /// Here, the name "foo" will be associated with the declaration on 268 /// "foo" within f. This name is not visible outside of 269 /// "f". However, we still find it in two cases: 270 /// 271 /// - If we are declaring another external with the name "foo", we 272 /// can find "foo" as a previous declaration, so that the types 273 /// of this external declaration can be checked for 274 /// compatibility. 275 /// 276 /// - If we would implicitly declare "foo" (e.g., due to a call to 277 /// "foo" in C when no prototype or definition is visible), then 278 /// we find this declaration of "foo" and complain that it is 279 /// not visible. 280 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls; 281 282 /// \brief Look for a locally scoped external declaration by the given name. 283 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 284 findLocallyScopedExternalDecl(DeclarationName Name); 285 286 typedef LazyVector<VarDecl *, ExternalSemaSource, 287 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 288 TentativeDefinitionsType; 289 290 /// \brief All the tentative definitions encountered in the TU. 291 TentativeDefinitionsType TentativeDefinitions; 292 293 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 294 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 295 UnusedFileScopedDeclsType; 296 297 /// \brief The set of file scoped decls seen so far that have not been used 298 /// and must warn if not used. Only contains the first declaration. 299 UnusedFileScopedDeclsType UnusedFileScopedDecls; 300 301 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 302 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 303 DelegatingCtorDeclsType; 304 305 /// \brief All the delegating constructors seen so far in the file, used for 306 /// cycle detection at the end of the TU. 307 DelegatingCtorDeclsType DelegatingCtorDecls; 308 309 /// \brief All the overriding destructors seen during a class definition 310 /// (there could be multiple due to nested classes) that had their exception 311 /// spec checks delayed, plus the overridden destructor. 312 SmallVector<std::pair<const CXXDestructorDecl*, 313 const CXXDestructorDecl*>, 2> 314 DelayedDestructorExceptionSpecChecks; 315 316 /// \brief Callback to the parser to parse templated functions when needed. 317 typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD); 318 LateTemplateParserCB *LateTemplateParser; 319 void *OpaqueParser; 320 321 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) { 322 LateTemplateParser = LTP; 323 OpaqueParser = P; 324 } 325 326 class DelayedDiagnostics; 327 328 class ParsingDeclState { 329 unsigned SavedStackSize; 330 friend class Sema::DelayedDiagnostics; 331 }; 332 333 class ProcessingContextState { 334 unsigned SavedParsingDepth; 335 unsigned SavedActiveStackBase; 336 friend class Sema::DelayedDiagnostics; 337 }; 338 339 /// A class which encapsulates the logic for delaying diagnostics 340 /// during parsing and other processing. 341 class DelayedDiagnostics { 342 /// \brief The stack of diagnostics that were delayed due to being 343 /// produced during the parsing of a declaration. 344 sema::DelayedDiagnostic *Stack; 345 346 /// \brief The number of objects on the delayed-diagnostics stack. 347 unsigned StackSize; 348 349 /// \brief The current capacity of the delayed-diagnostics stack. 350 unsigned StackCapacity; 351 352 /// \brief The index of the first "active" delayed diagnostic in 353 /// the stack. When parsing class definitions, we ignore active 354 /// delayed diagnostics from the surrounding context. 355 unsigned ActiveStackBase; 356 357 /// \brief The depth of the declarations we're currently parsing. 358 /// This gets saved and reset whenever we enter a class definition. 359 unsigned ParsingDepth; 360 361 public: 362 DelayedDiagnostics() : Stack(0), StackSize(0), StackCapacity(0), 363 ActiveStackBase(0), ParsingDepth(0) {} 364 365 ~DelayedDiagnostics() { 366 delete[] reinterpret_cast<char*>(Stack); 367 } 368 369 /// Adds a delayed diagnostic. 370 void add(const sema::DelayedDiagnostic &diag); 371 372 /// Determines whether diagnostics should be delayed. 373 bool shouldDelayDiagnostics() { return ParsingDepth > 0; } 374 375 /// Observe that we've started parsing a declaration. Access and 376 /// deprecation diagnostics will be delayed; when the declaration 377 /// is completed, all active delayed diagnostics will be evaluated 378 /// in its context, and then active diagnostics stack will be 379 /// popped down to the saved depth. 380 ParsingDeclState pushParsingDecl() { 381 ParsingDepth++; 382 383 ParsingDeclState state; 384 state.SavedStackSize = StackSize; 385 return state; 386 } 387 388 /// Observe that we're completed parsing a declaration. 389 static void popParsingDecl(Sema &S, ParsingDeclState state, Decl *decl); 390 391 /// Observe that we've started processing a different context, the 392 /// contents of which are semantically separate from the 393 /// declarations it may lexically appear in. This sets aside the 394 /// current stack of active diagnostics and starts afresh. 395 ProcessingContextState pushContext() { 396 assert(StackSize >= ActiveStackBase); 397 398 ProcessingContextState state; 399 state.SavedParsingDepth = ParsingDepth; 400 state.SavedActiveStackBase = ActiveStackBase; 401 402 ActiveStackBase = StackSize; 403 ParsingDepth = 0; 404 405 return state; 406 } 407 408 /// Observe that we've stopped processing a context. This 409 /// restores the previous stack of active diagnostics. 410 void popContext(ProcessingContextState state) { 411 assert(ActiveStackBase == StackSize); 412 assert(ParsingDepth == 0); 413 ActiveStackBase = state.SavedActiveStackBase; 414 ParsingDepth = state.SavedParsingDepth; 415 } 416 } DelayedDiagnostics; 417 418 /// A RAII object to temporarily push a declaration context. 419 class ContextRAII { 420 private: 421 Sema &S; 422 DeclContext *SavedContext; 423 ProcessingContextState SavedContextState; 424 425 public: 426 ContextRAII(Sema &S, DeclContext *ContextToPush) 427 : S(S), SavedContext(S.CurContext), 428 SavedContextState(S.DelayedDiagnostics.pushContext()) 429 { 430 assert(ContextToPush && "pushing null context"); 431 S.CurContext = ContextToPush; 432 } 433 434 void pop() { 435 if (!SavedContext) return; 436 S.CurContext = SavedContext; 437 S.DelayedDiagnostics.popContext(SavedContextState); 438 SavedContext = 0; 439 } 440 441 ~ContextRAII() { 442 pop(); 443 } 444 }; 445 446 /// WeakUndeclaredIdentifiers - Identifiers contained in 447 /// #pragma weak before declared. rare. may alias another 448 /// identifier, declared or undeclared 449 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers; 450 451 /// \brief Load weak undeclared identifiers from the external source. 452 void LoadExternalWeakUndeclaredIdentifiers(); 453 454 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 455 /// #pragma weak during processing of other Decls. 456 /// I couldn't figure out a clean way to generate these in-line, so 457 /// we store them here and handle separately -- which is a hack. 458 /// It would be best to refactor this. 459 SmallVector<Decl*,2> WeakTopLevelDecl; 460 461 IdentifierResolver IdResolver; 462 463 /// Translation Unit Scope - useful to Objective-C actions that need 464 /// to lookup file scope declarations in the "ordinary" C decl namespace. 465 /// For example, user-defined classes, built-in "id" type, etc. 466 Scope *TUScope; 467 468 /// \brief The C++ "std" namespace, where the standard library resides. 469 LazyDeclPtr StdNamespace; 470 471 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ 472 /// standard library. 473 LazyDeclPtr StdBadAlloc; 474 475 /// \brief The C++ "type_info" declaration, which is defined in <typeinfo>. 476 RecordDecl *CXXTypeInfoDecl; 477 478 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. 479 RecordDecl *MSVCGuidDecl; 480 481 /// A flag to remember whether the implicit forms of operator new and delete 482 /// have been declared. 483 bool GlobalNewDeleteDeclared; 484 485 486 /// A flag that is set when parsing a -dealloc method and no [super dealloc] 487 /// call was found yet. 488 bool ObjCShouldCallSuperDealloc; 489 /// A flag that is set when parsing a -finalize method and no [super finalize] 490 /// call was found yet. 491 bool ObjCShouldCallSuperFinalize; 492 493 /// \brief The set of declarations that have been referenced within 494 /// a potentially evaluated expression. 495 typedef SmallVector<std::pair<SourceLocation, Decl *>, 10> 496 PotentiallyReferencedDecls; 497 498 /// \brief A set of diagnostics that may be emitted. 499 typedef SmallVector<std::pair<SourceLocation, PartialDiagnostic>, 10> 500 PotentiallyEmittedDiagnostics; 501 502 /// \brief Describes how the expressions currently being parsed are 503 /// evaluated at run-time, if at all. 504 enum ExpressionEvaluationContext { 505 /// \brief The current expression and its subexpressions occur within an 506 /// unevaluated operand (C++0x [expr]p8), such as a constant expression 507 /// or the subexpression of \c sizeof, where the type or the value of the 508 /// expression may be significant but no code will be generated to evaluate 509 /// the value of the expression at run time. 510 Unevaluated, 511 512 /// \brief The current expression is potentially evaluated at run time, 513 /// which means that code may be generated to evaluate the value of the 514 /// expression at run time. 515 PotentiallyEvaluated, 516 517 /// \brief The current expression may be potentially evaluated or it may 518 /// be unevaluated, but it is impossible to tell from the lexical context. 519 /// This evaluation context is used primary for the operand of the C++ 520 /// \c typeid expression, whose argument is potentially evaluated only when 521 /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2). 522 PotentiallyPotentiallyEvaluated, 523 524 /// \brief The current expression is potentially evaluated, but any 525 /// declarations referenced inside that expression are only used if 526 /// in fact the current expression is used. 527 /// 528 /// This value is used when parsing default function arguments, for which 529 /// we would like to provide diagnostics (e.g., passing non-POD arguments 530 /// through varargs) but do not want to mark declarations as "referenced" 531 /// until the default argument is used. 532 PotentiallyEvaluatedIfUsed 533 }; 534 535 /// \brief Data structure used to record current or nested 536 /// expression evaluation contexts. 537 struct ExpressionEvaluationContextRecord { 538 /// \brief The expression evaluation context. 539 ExpressionEvaluationContext Context; 540 541 /// \brief Whether the enclosing context needed a cleanup. 542 bool ParentNeedsCleanups; 543 544 /// \brief The number of temporaries that were active when we 545 /// entered this expression evaluation context. 546 unsigned NumTemporaries; 547 548 /// \brief The set of declarations referenced within a 549 /// potentially potentially-evaluated context. 550 /// 551 /// When leaving a potentially potentially-evaluated context, each 552 /// of these elements will be as referenced if the corresponding 553 /// potentially potentially evaluated expression is potentially 554 /// evaluated. 555 PotentiallyReferencedDecls *PotentiallyReferenced; 556 557 /// \brief The set of diagnostics to emit should this potentially 558 /// potentially-evaluated context become evaluated. 559 PotentiallyEmittedDiagnostics *PotentiallyDiagnosed; 560 561 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 562 unsigned NumTemporaries, 563 bool ParentNeedsCleanups) 564 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups), 565 NumTemporaries(NumTemporaries), 566 PotentiallyReferenced(0), PotentiallyDiagnosed(0) { } 567 568 void addReferencedDecl(SourceLocation Loc, Decl *Decl) { 569 if (!PotentiallyReferenced) 570 PotentiallyReferenced = new PotentiallyReferencedDecls; 571 PotentiallyReferenced->push_back(std::make_pair(Loc, Decl)); 572 } 573 574 void addDiagnostic(SourceLocation Loc, const PartialDiagnostic &PD) { 575 if (!PotentiallyDiagnosed) 576 PotentiallyDiagnosed = new PotentiallyEmittedDiagnostics; 577 PotentiallyDiagnosed->push_back(std::make_pair(Loc, PD)); 578 } 579 580 void Destroy() { 581 delete PotentiallyReferenced; 582 delete PotentiallyDiagnosed; 583 PotentiallyReferenced = 0; 584 PotentiallyDiagnosed = 0; 585 } 586 }; 587 588 /// A stack of expression evaluation contexts. 589 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 590 591 /// SpecialMemberOverloadResult - The overloading result for a special member 592 /// function. 593 /// 594 /// This is basically a wrapper around PointerIntPair. The lowest bit of the 595 /// integer is used to determine whether we have a parameter qualification 596 /// match, the second-lowest is whether we had success in resolving the 597 /// overload to a unique non-deleted function. 598 /// 599 /// The ConstParamMatch bit represents whether, when looking up a copy 600 /// constructor or assignment operator, we found a potential copy 601 /// constructor/assignment operator whose first parameter is const-qualified. 602 /// This is used for determining parameter types of other objects and is 603 /// utterly meaningless on other types of special members. 604 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode { 605 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 606 public: 607 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID) 608 : FastFoldingSetNode(ID) 609 {} 610 611 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } 612 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 613 614 bool hasSuccess() const { return Pair.getInt() & 0x1; } 615 void setSuccess(bool B) { 616 Pair.setInt(unsigned(B) | hasConstParamMatch() << 1); 617 } 618 619 bool hasConstParamMatch() const { return Pair.getInt() & 0x2; } 620 void setConstParamMatch(bool B) { 621 Pair.setInt(B << 1 | unsigned(hasSuccess())); 622 } 623 }; 624 625 /// \brief A cache of special member function overload resolution results 626 /// for C++ records. 627 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache; 628 629 /// \brief The kind of translation unit we are processing. 630 /// 631 /// When we're processing a complete translation unit, Sema will perform 632 /// end-of-translation-unit semantic tasks (such as creating 633 /// initializers for tentative definitions in C) once parsing has 634 /// completed. Modules and precompiled headers perform different kinds of 635 /// checks. 636 TranslationUnitKind TUKind; 637 638 llvm::BumpPtrAllocator BumpAlloc; 639 640 /// \brief The number of SFINAE diagnostics that have been trapped. 641 unsigned NumSFINAEErrors; 642 643 typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> > 644 UnparsedDefaultArgInstantiationsMap; 645 646 /// \brief A mapping from parameters with unparsed default arguments to the 647 /// set of instantiations of each parameter. 648 /// 649 /// This mapping is a temporary data structure used when parsing 650 /// nested class templates or nested classes of class templates, 651 /// where we might end up instantiating an inner class before the 652 /// default arguments of its methods have been parsed. 653 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 654 655 // Contains the locations of the beginning of unparsed default 656 // argument locations. 657 llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs; 658 659 /// UndefinedInternals - all the used, undefined objects with 660 /// internal linkage in this translation unit. 661 llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals; 662 663 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 664 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 665 666 /// Method Pool - allows efficient lookup when typechecking messages to "id". 667 /// We need to maintain a list, since selectors can have differing signatures 668 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 669 /// of selectors are "overloaded"). 670 GlobalMethodPool MethodPool; 671 672 /// Method selectors used in a @selector expression. Used for implementation 673 /// of -Wselector. 674 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors; 675 676 GlobalMethodPool::iterator ReadMethodPool(Selector Sel); 677 678 /// Private Helper predicate to check for 'self'. 679 bool isSelfExpr(Expr *RExpr); 680public: 681 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 682 TranslationUnitKind TUKind = TU_Complete, 683 CodeCompleteConsumer *CompletionConsumer = 0); 684 ~Sema(); 685 686 /// \brief Perform initialization that occurs after the parser has been 687 /// initialized but before it parses anything. 688 void Initialize(); 689 690 const LangOptions &getLangOptions() const { return LangOpts; } 691 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } 692 FPOptions &getFPOptions() { return FPFeatures; } 693 694 Diagnostic &getDiagnostics() const { return Diags; } 695 SourceManager &getSourceManager() const { return SourceMgr; } 696 const TargetAttributesSema &getTargetAttributesSema() const; 697 Preprocessor &getPreprocessor() const { return PP; } 698 ASTContext &getASTContext() const { return Context; } 699 ASTConsumer &getASTConsumer() const { return Consumer; } 700 ASTMutationListener *getASTMutationListener() const; 701 702 void PrintStats() const; 703 704 /// \brief Helper class that creates diagnostics with optional 705 /// template instantiation stacks. 706 /// 707 /// This class provides a wrapper around the basic DiagnosticBuilder 708 /// class that emits diagnostics. SemaDiagnosticBuilder is 709 /// responsible for emitting the diagnostic (as DiagnosticBuilder 710 /// does) and, if the diagnostic comes from inside a template 711 /// instantiation, printing the template instantiation stack as 712 /// well. 713 class SemaDiagnosticBuilder : public DiagnosticBuilder { 714 Sema &SemaRef; 715 unsigned DiagID; 716 717 public: 718 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 719 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 720 721 explicit SemaDiagnosticBuilder(Sema &SemaRef) 722 : DiagnosticBuilder(DiagnosticBuilder::Suppress), SemaRef(SemaRef) { } 723 724 ~SemaDiagnosticBuilder(); 725 }; 726 727 /// \brief Emit a diagnostic. 728 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 729 730 /// \brief Emit a partial diagnostic. 731 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 732 733 /// \brief Build a partial diagnostic. 734 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 735 736 bool findMacroSpelling(SourceLocation &loc, StringRef name); 737 738 ExprResult Owned(Expr* E) { return E; } 739 ExprResult Owned(ExprResult R) { return R; } 740 StmtResult Owned(Stmt* S) { return S; } 741 742 void ActOnEndOfTranslationUnit(); 743 744 void CheckDelegatingCtorCycles(); 745 746 Scope *getScopeForContext(DeclContext *Ctx); 747 748 void PushFunctionScope(); 749 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 750 void PopFunctionOrBlockScope(const sema::AnalysisBasedWarnings::Policy *WP =0, 751 const Decl *D = 0, const BlockExpr *blkExpr = 0); 752 753 sema::FunctionScopeInfo *getCurFunction() const { 754 return FunctionScopes.back(); 755 } 756 757 bool hasAnyUnrecoverableErrorsInThisFunction() const; 758 759 /// \brief Retrieve the current block, if any. 760 sema::BlockScopeInfo *getCurBlock(); 761 762 /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls 763 SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 764 765 //===--------------------------------------------------------------------===// 766 // Type Analysis / Processing: SemaType.cpp. 767 // 768 769 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs); 770 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) { 771 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR)); 772 } 773 QualType BuildPointerType(QualType T, 774 SourceLocation Loc, DeclarationName Entity); 775 QualType BuildReferenceType(QualType T, bool LValueRef, 776 SourceLocation Loc, DeclarationName Entity); 777 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 778 Expr *ArraySize, unsigned Quals, 779 SourceRange Brackets, DeclarationName Entity); 780 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 781 SourceLocation AttrLoc); 782 QualType BuildFunctionType(QualType T, 783 QualType *ParamTypes, unsigned NumParamTypes, 784 bool Variadic, unsigned Quals, 785 RefQualifierKind RefQualifier, 786 SourceLocation Loc, DeclarationName Entity, 787 FunctionType::ExtInfo Info); 788 QualType BuildMemberPointerType(QualType T, QualType Class, 789 SourceLocation Loc, 790 DeclarationName Entity); 791 QualType BuildBlockPointerType(QualType T, 792 SourceLocation Loc, DeclarationName Entity); 793 QualType BuildParenType(QualType T); 794 795 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 796 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 797 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 798 TypeSourceInfo *ReturnTypeInfo); 799 /// \brief Package the given type and TSI into a ParsedType. 800 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 801 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 802 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 803 static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0); 804 bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range); 805 bool CheckDistantExceptionSpec(QualType T); 806 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 807 bool CheckEquivalentExceptionSpec( 808 const FunctionProtoType *Old, SourceLocation OldLoc, 809 const FunctionProtoType *New, SourceLocation NewLoc); 810 bool CheckEquivalentExceptionSpec( 811 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 812 const FunctionProtoType *Old, SourceLocation OldLoc, 813 const FunctionProtoType *New, SourceLocation NewLoc, 814 bool *MissingExceptionSpecification = 0, 815 bool *MissingEmptyExceptionSpecification = 0, 816 bool AllowNoexceptAllMatchWithNoSpec = false, 817 bool IsOperatorNew = false); 818 bool CheckExceptionSpecSubset( 819 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 820 const FunctionProtoType *Superset, SourceLocation SuperLoc, 821 const FunctionProtoType *Subset, SourceLocation SubLoc); 822 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID, 823 const FunctionProtoType *Target, SourceLocation TargetLoc, 824 const FunctionProtoType *Source, SourceLocation SourceLoc); 825 826 TypeResult ActOnTypeName(Scope *S, Declarator &D); 827 828 /// \brief The parser has parsed the context-sensitive type 'instancetype' 829 /// in an Objective-C message declaration. Return the appropriate type. 830 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 831 832 bool RequireCompleteType(SourceLocation Loc, QualType T, 833 const PartialDiagnostic &PD, 834 std::pair<SourceLocation, PartialDiagnostic> Note); 835 bool RequireCompleteType(SourceLocation Loc, QualType T, 836 const PartialDiagnostic &PD); 837 bool RequireCompleteType(SourceLocation Loc, QualType T, 838 unsigned DiagID); 839 bool RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD, 840 std::pair<SourceLocation, 841 PartialDiagnostic> Note); 842 843 844 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 845 const CXXScopeSpec &SS, QualType T); 846 847 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 848 QualType BuildDecltypeType(Expr *E, SourceLocation Loc); 849 QualType BuildUnaryTransformType(QualType BaseType, 850 UnaryTransformType::UTTKind UKind, 851 SourceLocation Loc); 852 853 //===--------------------------------------------------------------------===// 854 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 855 // 856 857 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0); 858 859 void DiagnoseUseOfUnimplementedSelectors(); 860 861 ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 862 Scope *S, CXXScopeSpec *SS = 0, 863 bool isClassName = false, 864 bool HasTrailingDot = false, 865 ParsedType ObjectType = ParsedType(), 866 bool WantNontrivialTypeSourceInfo = false); 867 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 868 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS); 869 bool DiagnoseUnknownTypeName(const IdentifierInfo &II, 870 SourceLocation IILoc, 871 Scope *S, 872 CXXScopeSpec *SS, 873 ParsedType &SuggestedType); 874 875 /// \brief Describes the result of the name lookup and resolution performed 876 /// by \c ClassifyName(). 877 enum NameClassificationKind { 878 NC_Unknown, 879 NC_Error, 880 NC_Keyword, 881 NC_Type, 882 NC_Expression, 883 NC_NestedNameSpecifier, 884 NC_TypeTemplate, 885 NC_FunctionTemplate 886 }; 887 888 class NameClassification { 889 NameClassificationKind Kind; 890 ExprResult Expr; 891 TemplateName Template; 892 ParsedType Type; 893 const IdentifierInfo *Keyword; 894 895 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 896 897 public: 898 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} 899 900 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 901 902 NameClassification(const IdentifierInfo *Keyword) 903 : Kind(NC_Keyword), Keyword(Keyword) { } 904 905 static NameClassification Error() { 906 return NameClassification(NC_Error); 907 } 908 909 static NameClassification Unknown() { 910 return NameClassification(NC_Unknown); 911 } 912 913 static NameClassification NestedNameSpecifier() { 914 return NameClassification(NC_NestedNameSpecifier); 915 } 916 917 static NameClassification TypeTemplate(TemplateName Name) { 918 NameClassification Result(NC_TypeTemplate); 919 Result.Template = Name; 920 return Result; 921 } 922 923 static NameClassification FunctionTemplate(TemplateName Name) { 924 NameClassification Result(NC_FunctionTemplate); 925 Result.Template = Name; 926 return Result; 927 } 928 929 NameClassificationKind getKind() const { return Kind; } 930 931 ParsedType getType() const { 932 assert(Kind == NC_Type); 933 return Type; 934 } 935 936 ExprResult getExpression() const { 937 assert(Kind == NC_Expression); 938 return Expr; 939 } 940 941 TemplateName getTemplateName() const { 942 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate); 943 return Template; 944 } 945 946 TemplateNameKind getTemplateNameKind() const { 947 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate); 948 return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template; 949 } 950}; 951 952 /// \brief Perform name lookup on the given name, classifying it based on 953 /// the results of name lookup and the following token. 954 /// 955 /// This routine is used by the parser to resolve identifiers and help direct 956 /// parsing. When the identifier cannot be found, this routine will attempt 957 /// to correct the typo and classify based on the resulting name. 958 /// 959 /// \param S The scope in which we're performing name lookup. 960 /// 961 /// \param SS The nested-name-specifier that precedes the name. 962 /// 963 /// \param Name The identifier. If typo correction finds an alternative name, 964 /// this pointer parameter will be updated accordingly. 965 /// 966 /// \param NameLoc The location of the identifier. 967 /// 968 /// \param NextToken The token following the identifier. Used to help 969 /// disambiguate the name. 970 NameClassification ClassifyName(Scope *S, 971 CXXScopeSpec &SS, 972 IdentifierInfo *&Name, 973 SourceLocation NameLoc, 974 const Token &NextToken); 975 976 Decl *ActOnDeclarator(Scope *S, Declarator &D); 977 978 Decl *HandleDeclarator(Scope *S, Declarator &D, 979 MultiTemplateParamsArg TemplateParameterLists, 980 bool IsFunctionDefinition); 981 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, 982 const LookupResult &Previous, 983 Scope *S); 984 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 985 void DiagnoseFunctionSpecifiers(Declarator& D); 986 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R); 987 void CheckShadow(Scope *S, VarDecl *D); 988 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 989 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 990 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 991 QualType R, TypeSourceInfo *TInfo, 992 LookupResult &Previous, bool &Redeclaration); 993 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 994 LookupResult &Previous, bool &Redeclaration); 995 NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 996 QualType R, TypeSourceInfo *TInfo, 997 LookupResult &Previous, 998 MultiTemplateParamsArg TemplateParamLists, 999 bool &Redeclaration); 1000 void CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous, 1001 bool &Redeclaration); 1002 void CheckCompleteVariableDeclaration(VarDecl *var); 1003 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1004 QualType R, TypeSourceInfo *TInfo, 1005 LookupResult &Previous, 1006 MultiTemplateParamsArg TemplateParamLists, 1007 bool IsFunctionDefinition, 1008 bool &Redeclaration, 1009 bool &AddToScope); 1010 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1011 void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1012 void CheckFunctionDeclaration(Scope *S, 1013 FunctionDecl *NewFD, LookupResult &Previous, 1014 bool IsExplicitSpecialization, 1015 bool &Redeclaration); 1016 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 1017 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 1018 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 1019 SourceLocation Loc, 1020 QualType T); 1021 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 1022 SourceLocation NameLoc, IdentifierInfo *Name, 1023 QualType T, TypeSourceInfo *TSInfo, 1024 StorageClass SC, StorageClass SCAsWritten); 1025 void ActOnParamDefaultArgument(Decl *param, 1026 SourceLocation EqualLoc, 1027 Expr *defarg); 1028 void ActOnParamUnparsedDefaultArgument(Decl *param, 1029 SourceLocation EqualLoc, 1030 SourceLocation ArgLoc); 1031 void ActOnParamDefaultArgumentError(Decl *param); 1032 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 1033 SourceLocation EqualLoc); 1034 1035 void CheckSelfReference(Decl *OrigDecl, Expr *E); 1036 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, 1037 bool TypeMayContainAuto); 1038 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto); 1039 void ActOnInitializerError(Decl *Dcl); 1040 void ActOnCXXForRangeDecl(Decl *D); 1041 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 1042 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 1043 void FinalizeDeclaration(Decl *D); 1044 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 1045 Decl **Group, 1046 unsigned NumDecls); 1047 DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 1048 bool TypeMayContainAuto = true); 1049 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 1050 SourceLocation LocAfterDecls); 1051 void CheckForFunctionRedefinition(FunctionDecl *FD); 1052 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D); 1053 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D); 1054 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); 1055 1056 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 1057 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 1058 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 1059 1060 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 1061 /// attribute for which parsing is delayed. 1062 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 1063 1064 /// \brief Diagnose any unused parameters in the given sequence of 1065 /// ParmVarDecl pointers. 1066 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin, 1067 ParmVarDecl * const *End); 1068 1069 /// \brief Diagnose whether the size of parameters or return value of a 1070 /// function or obj-c method definition is pass-by-value and larger than a 1071 /// specified threshold. 1072 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin, 1073 ParmVarDecl * const *End, 1074 QualType ReturnTy, 1075 NamedDecl *D); 1076 1077 void DiagnoseInvalidJumps(Stmt *Body); 1078 Decl *ActOnFileScopeAsmDecl(Expr *expr, 1079 SourceLocation AsmLoc, 1080 SourceLocation RParenLoc); 1081 1082 /// \brief The parser has processed a module import declaration. 1083 /// 1084 /// \param ImportLoc The location of the '__import_module__' keyword. 1085 /// 1086 /// \param ModuleName The name of the module. 1087 /// 1088 /// \param ModuleNameLoc The location of the module name. 1089 DeclResult ActOnModuleImport(SourceLocation ImportLoc, 1090 IdentifierInfo &ModuleName, 1091 SourceLocation ModuleNameLoc); 1092 1093 /// \brief Diagnose that \p New is a module-private redeclaration of 1094 /// \p Old. 1095 void diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old, 1096 SourceLocation ModulePrivateKeyword 1097 = SourceLocation()); 1098 1099 /// Scope actions. 1100 void ActOnPopScope(SourceLocation Loc, Scope *S); 1101 void ActOnTranslationUnitScope(Scope *S); 1102 1103 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1104 DeclSpec &DS); 1105 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1106 DeclSpec &DS, 1107 MultiTemplateParamsArg TemplateParams); 1108 1109 StmtResult ActOnVlaStmt(const DeclSpec &DS); 1110 1111 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1112 AccessSpecifier AS, 1113 RecordDecl *Record); 1114 1115 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 1116 RecordDecl *Record); 1117 1118 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 1119 TagTypeKind NewTag, bool isDefinition, 1120 SourceLocation NewTagLoc, 1121 const IdentifierInfo &Name); 1122 1123 enum TagUseKind { 1124 TUK_Reference, // Reference to a tag: 'struct foo *X;' 1125 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 1126 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 1127 TUK_Friend // Friend declaration: 'friend struct foo;' 1128 }; 1129 1130 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 1131 SourceLocation KWLoc, CXXScopeSpec &SS, 1132 IdentifierInfo *Name, SourceLocation NameLoc, 1133 AttributeList *Attr, AccessSpecifier AS, 1134 SourceLocation ModulePrivateLoc, 1135 MultiTemplateParamsArg TemplateParameterLists, 1136 bool &OwnedDecl, bool &IsDependent, bool ScopedEnum, 1137 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType); 1138 1139 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 1140 unsigned TagSpec, SourceLocation TagLoc, 1141 CXXScopeSpec &SS, 1142 IdentifierInfo *Name, SourceLocation NameLoc, 1143 AttributeList *Attr, 1144 MultiTemplateParamsArg TempParamLists); 1145 1146 TypeResult ActOnDependentTag(Scope *S, 1147 unsigned TagSpec, 1148 TagUseKind TUK, 1149 const CXXScopeSpec &SS, 1150 IdentifierInfo *Name, 1151 SourceLocation TagLoc, 1152 SourceLocation NameLoc); 1153 1154 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 1155 IdentifierInfo *ClassName, 1156 SmallVectorImpl<Decl *> &Decls); 1157 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 1158 Declarator &D, Expr *BitfieldWidth); 1159 1160 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 1161 Declarator &D, Expr *BitfieldWidth, bool HasInit, 1162 AccessSpecifier AS); 1163 1164 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 1165 TypeSourceInfo *TInfo, 1166 RecordDecl *Record, SourceLocation Loc, 1167 bool Mutable, Expr *BitfieldWidth, bool HasInit, 1168 SourceLocation TSSL, 1169 AccessSpecifier AS, NamedDecl *PrevDecl, 1170 Declarator *D = 0); 1171 1172 enum CXXSpecialMember { 1173 CXXDefaultConstructor, 1174 CXXCopyConstructor, 1175 CXXMoveConstructor, 1176 CXXCopyAssignment, 1177 CXXMoveAssignment, 1178 CXXDestructor, 1179 CXXInvalid 1180 }; 1181 bool CheckNontrivialField(FieldDecl *FD); 1182 void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem); 1183 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); 1184 void ActOnLastBitfield(SourceLocation DeclStart, 1185 SmallVectorImpl<Decl *> &AllIvarDecls); 1186 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 1187 Declarator &D, Expr *BitfieldWidth, 1188 tok::ObjCKeywordKind visibility); 1189 1190 // This is used for both record definitions and ObjC interface declarations. 1191 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl, 1192 Decl **Fields, unsigned NumFields, 1193 SourceLocation LBrac, SourceLocation RBrac, 1194 AttributeList *AttrList); 1195 1196 /// ActOnTagStartDefinition - Invoked when we have entered the 1197 /// scope of a tag's definition (e.g., for an enumeration, class, 1198 /// struct, or union). 1199 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 1200 1201 void ActOnObjCContainerStartDefinition(Decl *IDecl); 1202 1203 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 1204 /// C++ record definition's base-specifiers clause and are starting its 1205 /// member declarations. 1206 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 1207 SourceLocation FinalLoc, 1208 SourceLocation LBraceLoc); 1209 1210 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 1211 /// the definition of a tag (enumeration, class, struct, or union). 1212 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 1213 SourceLocation RBraceLoc); 1214 1215 void ActOnObjCContainerFinishDefinition(); 1216 1217 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 1218 /// error parsing the definition of a tag. 1219 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 1220 1221 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 1222 EnumConstantDecl *LastEnumConst, 1223 SourceLocation IdLoc, 1224 IdentifierInfo *Id, 1225 Expr *val); 1226 1227 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 1228 SourceLocation IdLoc, IdentifierInfo *Id, 1229 AttributeList *Attrs, 1230 SourceLocation EqualLoc, Expr *Val); 1231 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 1232 SourceLocation RBraceLoc, Decl *EnumDecl, 1233 Decl **Elements, unsigned NumElements, 1234 Scope *S, AttributeList *Attr); 1235 1236 DeclContext *getContainingDC(DeclContext *DC); 1237 1238 /// Set the current declaration context until it gets popped. 1239 void PushDeclContext(Scope *S, DeclContext *DC); 1240 void PopDeclContext(); 1241 1242 /// EnterDeclaratorContext - Used when we must lookup names in the context 1243 /// of a declarator's nested name specifier. 1244 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 1245 void ExitDeclaratorContext(Scope *S); 1246 1247 /// Push the parameters of D, which must be a function, into scope. 1248 void ActOnReenterFunctionContext(Scope* S, Decl* D); 1249 void ActOnExitFunctionContext() { PopDeclContext(); } 1250 1251 DeclContext *getFunctionLevelDeclContext(); 1252 1253 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1254 /// to the function decl for the function being parsed. If we're currently 1255 /// in a 'block', this returns the containing context. 1256 FunctionDecl *getCurFunctionDecl(); 1257 1258 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 1259 /// the method decl for the method being parsed. If we're currently 1260 /// in a 'block', this returns the containing context. 1261 ObjCMethodDecl *getCurMethodDecl(); 1262 1263 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 1264 /// or C function we're in, otherwise return null. If we're currently 1265 /// in a 'block', this returns the containing context. 1266 NamedDecl *getCurFunctionOrMethodDecl(); 1267 1268 /// Add this decl to the scope shadowed decl chains. 1269 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 1270 1271 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 1272 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 1273 /// true if 'D' belongs to the given declaration context. 1274 /// 1275 /// \param ExplicitInstantiationOrSpecialization When true, we are checking 1276 /// whether the declaration is in scope for the purposes of explicit template 1277 /// instantiation or specialization. The default is false. 1278 bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0, 1279 bool ExplicitInstantiationOrSpecialization = false); 1280 1281 /// Finds the scope corresponding to the given decl context, if it 1282 /// happens to be an enclosing scope. Otherwise return NULL. 1283 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 1284 1285 /// Subroutines of ActOnDeclarator(). 1286 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1287 TypeSourceInfo *TInfo); 1288 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 1289 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old); 1290 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old); 1291 void mergeObjCMethodDecls(ObjCMethodDecl *New, const ObjCMethodDecl *Old); 1292 void MergeVarDecl(VarDecl *New, LookupResult &OldDecls); 1293 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old); 1294 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 1295 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old); 1296 1297 // AssignmentAction - This is used by all the assignment diagnostic functions 1298 // to represent what is actually causing the operation 1299 enum AssignmentAction { 1300 AA_Assigning, 1301 AA_Passing, 1302 AA_Returning, 1303 AA_Converting, 1304 AA_Initializing, 1305 AA_Sending, 1306 AA_Casting 1307 }; 1308 1309 /// C++ Overloading. 1310 enum OverloadKind { 1311 /// This is a legitimate overload: the existing declarations are 1312 /// functions or function templates with different signatures. 1313 Ovl_Overload, 1314 1315 /// This is not an overload because the signature exactly matches 1316 /// an existing declaration. 1317 Ovl_Match, 1318 1319 /// This is not an overload because the lookup results contain a 1320 /// non-function. 1321 Ovl_NonFunction 1322 }; 1323 OverloadKind CheckOverload(Scope *S, 1324 FunctionDecl *New, 1325 const LookupResult &OldDecls, 1326 NamedDecl *&OldDecl, 1327 bool IsForUsingDecl); 1328 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 1329 1330 /// \brief Checks availability of the function depending on the current 1331 /// function context.Inside an unavailable function,unavailability is ignored. 1332 /// 1333 /// \returns true if \arg FD is unavailable and current context is inside 1334 /// an available function, false otherwise. 1335 bool isFunctionConsideredUnavailable(FunctionDecl *FD); 1336 1337 ImplicitConversionSequence 1338 TryImplicitConversion(Expr *From, QualType ToType, 1339 bool SuppressUserConversions, 1340 bool AllowExplicit, 1341 bool InOverloadResolution, 1342 bool CStyle, 1343 bool AllowObjCWritebackConversion); 1344 1345 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 1346 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 1347 bool IsComplexPromotion(QualType FromType, QualType ToType); 1348 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1349 bool InOverloadResolution, 1350 QualType& ConvertedType, bool &IncompatibleObjC); 1351 bool isObjCPointerConversion(QualType FromType, QualType ToType, 1352 QualType& ConvertedType, bool &IncompatibleObjC); 1353 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 1354 QualType &ConvertedType); 1355 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 1356 QualType& ConvertedType); 1357 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 1358 const FunctionProtoType *NewType); 1359 1360 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 1361 bool CheckPointerConversion(Expr *From, QualType ToType, 1362 CastKind &Kind, 1363 CXXCastPath& BasePath, 1364 bool IgnoreBaseAccess); 1365 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 1366 bool InOverloadResolution, 1367 QualType &ConvertedType); 1368 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 1369 CastKind &Kind, 1370 CXXCastPath &BasePath, 1371 bool IgnoreBaseAccess); 1372 bool IsQualificationConversion(QualType FromType, QualType ToType, 1373 bool CStyle, bool &ObjCLifetimeConversion); 1374 bool IsNoReturnConversion(QualType FromType, QualType ToType, 1375 QualType &ResultTy); 1376 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 1377 1378 1379 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1380 const VarDecl *NRVOCandidate, 1381 QualType ResultType, 1382 Expr *Value, 1383 bool AllowNRVO = true); 1384 1385 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 1386 ExprResult Init); 1387 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 1388 SourceLocation EqualLoc, 1389 ExprResult Init, 1390 bool TopLevelOfInitList = false); 1391 ExprResult PerformObjectArgumentInitialization(Expr *From, 1392 NestedNameSpecifier *Qualifier, 1393 NamedDecl *FoundDecl, 1394 CXXMethodDecl *Method); 1395 1396 ExprResult PerformContextuallyConvertToBool(Expr *From); 1397 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 1398 1399 ExprResult 1400 ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE, 1401 const PartialDiagnostic &NotIntDiag, 1402 const PartialDiagnostic &IncompleteDiag, 1403 const PartialDiagnostic &ExplicitConvDiag, 1404 const PartialDiagnostic &ExplicitConvNote, 1405 const PartialDiagnostic &AmbigDiag, 1406 const PartialDiagnostic &AmbigNote, 1407 const PartialDiagnostic &ConvDiag); 1408 1409 ExprResult PerformObjectMemberConversion(Expr *From, 1410 NestedNameSpecifier *Qualifier, 1411 NamedDecl *FoundDecl, 1412 NamedDecl *Member); 1413 1414 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 1415 // TODO: make this is a typesafe union. 1416 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 1417 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 1418 1419 void AddOverloadCandidate(NamedDecl *Function, 1420 DeclAccessPair FoundDecl, 1421 Expr **Args, unsigned NumArgs, 1422 OverloadCandidateSet &CandidateSet); 1423 1424 void AddOverloadCandidate(FunctionDecl *Function, 1425 DeclAccessPair FoundDecl, 1426 Expr **Args, unsigned NumArgs, 1427 OverloadCandidateSet& CandidateSet, 1428 bool SuppressUserConversions = false, 1429 bool PartialOverloading = false); 1430 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 1431 Expr **Args, unsigned NumArgs, 1432 OverloadCandidateSet& CandidateSet, 1433 bool SuppressUserConversions = false); 1434 void AddMethodCandidate(DeclAccessPair FoundDecl, 1435 QualType ObjectType, 1436 Expr::Classification ObjectClassification, 1437 Expr **Args, unsigned NumArgs, 1438 OverloadCandidateSet& CandidateSet, 1439 bool SuppressUserConversion = false); 1440 void AddMethodCandidate(CXXMethodDecl *Method, 1441 DeclAccessPair FoundDecl, 1442 CXXRecordDecl *ActingContext, QualType ObjectType, 1443 Expr::Classification ObjectClassification, 1444 Expr **Args, unsigned NumArgs, 1445 OverloadCandidateSet& CandidateSet, 1446 bool SuppressUserConversions = false); 1447 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 1448 DeclAccessPair FoundDecl, 1449 CXXRecordDecl *ActingContext, 1450 TemplateArgumentListInfo *ExplicitTemplateArgs, 1451 QualType ObjectType, 1452 Expr::Classification ObjectClassification, 1453 Expr **Args, unsigned NumArgs, 1454 OverloadCandidateSet& CandidateSet, 1455 bool SuppressUserConversions = false); 1456 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 1457 DeclAccessPair FoundDecl, 1458 TemplateArgumentListInfo *ExplicitTemplateArgs, 1459 Expr **Args, unsigned NumArgs, 1460 OverloadCandidateSet& CandidateSet, 1461 bool SuppressUserConversions = false); 1462 void AddConversionCandidate(CXXConversionDecl *Conversion, 1463 DeclAccessPair FoundDecl, 1464 CXXRecordDecl *ActingContext, 1465 Expr *From, QualType ToType, 1466 OverloadCandidateSet& CandidateSet); 1467 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 1468 DeclAccessPair FoundDecl, 1469 CXXRecordDecl *ActingContext, 1470 Expr *From, QualType ToType, 1471 OverloadCandidateSet &CandidateSet); 1472 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 1473 DeclAccessPair FoundDecl, 1474 CXXRecordDecl *ActingContext, 1475 const FunctionProtoType *Proto, 1476 Expr *Object, Expr **Args, unsigned NumArgs, 1477 OverloadCandidateSet& CandidateSet); 1478 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 1479 SourceLocation OpLoc, 1480 Expr **Args, unsigned NumArgs, 1481 OverloadCandidateSet& CandidateSet, 1482 SourceRange OpRange = SourceRange()); 1483 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 1484 Expr **Args, unsigned NumArgs, 1485 OverloadCandidateSet& CandidateSet, 1486 bool IsAssignmentOperator = false, 1487 unsigned NumContextualBoolArguments = 0); 1488 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 1489 SourceLocation OpLoc, 1490 Expr **Args, unsigned NumArgs, 1491 OverloadCandidateSet& CandidateSet); 1492 void AddArgumentDependentLookupCandidates(DeclarationName Name, 1493 bool Operator, 1494 Expr **Args, unsigned NumArgs, 1495 TemplateArgumentListInfo *ExplicitTemplateArgs, 1496 OverloadCandidateSet& CandidateSet, 1497 bool PartialOverloading = false, 1498 bool StdNamespaceIsAssociated = false); 1499 1500 // Emit as a 'note' the specific overload candidate 1501 void NoteOverloadCandidate(FunctionDecl *Fn); 1502 1503 // Emit as a series of 'note's all template and non-templates 1504 // identified by the expression Expr 1505 void NoteAllOverloadCandidates(Expr* E); 1506 1507 // [PossiblyAFunctionType] --> [Return] 1508 // NonFunctionType --> NonFunctionType 1509 // R (A) --> R(A) 1510 // R (*)(A) --> R (A) 1511 // R (&)(A) --> R (A) 1512 // R (S::*)(A) --> R (A) 1513 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 1514 1515 FunctionDecl *ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, 1516 bool Complain, 1517 DeclAccessPair &Found); 1518 1519 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 1520 bool Complain = false, 1521 DeclAccessPair* Found = 0); 1522 1523 ExprResult ResolveAndFixSingleFunctionTemplateSpecialization( 1524 Expr *SrcExpr, bool DoFunctionPointerConverion = false, 1525 bool Complain = false, 1526 const SourceRange& OpRangeForComplaining = SourceRange(), 1527 QualType DestTypeForComplaining = QualType(), 1528 unsigned DiagIDForComplaining = 0); 1529 1530 1531 Expr *FixOverloadedFunctionReference(Expr *E, 1532 DeclAccessPair FoundDecl, 1533 FunctionDecl *Fn); 1534 ExprResult FixOverloadedFunctionReference(ExprResult, 1535 DeclAccessPair FoundDecl, 1536 FunctionDecl *Fn); 1537 1538 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 1539 Expr **Args, unsigned NumArgs, 1540 OverloadCandidateSet &CandidateSet, 1541 bool PartialOverloading = false); 1542 1543 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 1544 UnresolvedLookupExpr *ULE, 1545 SourceLocation LParenLoc, 1546 Expr **Args, unsigned NumArgs, 1547 SourceLocation RParenLoc, 1548 Expr *ExecConfig); 1549 1550 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 1551 unsigned Opc, 1552 const UnresolvedSetImpl &Fns, 1553 Expr *input); 1554 1555 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 1556 unsigned Opc, 1557 const UnresolvedSetImpl &Fns, 1558 Expr *LHS, Expr *RHS); 1559 1560 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 1561 SourceLocation RLoc, 1562 Expr *Base,Expr *Idx); 1563 1564 ExprResult 1565 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 1566 SourceLocation LParenLoc, Expr **Args, 1567 unsigned NumArgs, SourceLocation RParenLoc); 1568 ExprResult 1569 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 1570 Expr **Args, unsigned NumArgs, 1571 SourceLocation RParenLoc); 1572 1573 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 1574 SourceLocation OpLoc); 1575 1576 /// CheckCallReturnType - Checks that a call expression's return type is 1577 /// complete. Returns true on failure. The location passed in is the location 1578 /// that best represents the call. 1579 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 1580 CallExpr *CE, FunctionDecl *FD); 1581 1582 /// Helpers for dealing with blocks and functions. 1583 bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd, 1584 bool CheckParameterNames); 1585 void CheckCXXDefaultArguments(FunctionDecl *FD); 1586 void CheckExtraCXXDefaultArguments(Declarator &D); 1587 Scope *getNonFieldDeclScope(Scope *S); 1588 1589 /// \name Name lookup 1590 /// 1591 /// These routines provide name lookup that is used during semantic 1592 /// analysis to resolve the various kinds of names (identifiers, 1593 /// overloaded operator names, constructor names, etc.) into zero or 1594 /// more declarations within a particular scope. The major entry 1595 /// points are LookupName, which performs unqualified name lookup, 1596 /// and LookupQualifiedName, which performs qualified name lookup. 1597 /// 1598 /// All name lookup is performed based on some specific criteria, 1599 /// which specify what names will be visible to name lookup and how 1600 /// far name lookup should work. These criteria are important both 1601 /// for capturing language semantics (certain lookups will ignore 1602 /// certain names, for example) and for performance, since name 1603 /// lookup is often a bottleneck in the compilation of C++. Name 1604 /// lookup criteria is specified via the LookupCriteria enumeration. 1605 /// 1606 /// The results of name lookup can vary based on the kind of name 1607 /// lookup performed, the current language, and the translation 1608 /// unit. In C, for example, name lookup will either return nothing 1609 /// (no entity found) or a single declaration. In C++, name lookup 1610 /// can additionally refer to a set of overloaded functions or 1611 /// result in an ambiguity. All of the possible results of name 1612 /// lookup are captured by the LookupResult class, which provides 1613 /// the ability to distinguish among them. 1614 //@{ 1615 1616 /// @brief Describes the kind of name lookup to perform. 1617 enum LookupNameKind { 1618 /// Ordinary name lookup, which finds ordinary names (functions, 1619 /// variables, typedefs, etc.) in C and most kinds of names 1620 /// (functions, variables, members, types, etc.) in C++. 1621 LookupOrdinaryName = 0, 1622 /// Tag name lookup, which finds the names of enums, classes, 1623 /// structs, and unions. 1624 LookupTagName, 1625 /// Label name lookup. 1626 LookupLabel, 1627 /// Member name lookup, which finds the names of 1628 /// class/struct/union members. 1629 LookupMemberName, 1630 /// Look up of an operator name (e.g., operator+) for use with 1631 /// operator overloading. This lookup is similar to ordinary name 1632 /// lookup, but will ignore any declarations that are class members. 1633 LookupOperatorName, 1634 /// Look up of a name that precedes the '::' scope resolution 1635 /// operator in C++. This lookup completely ignores operator, object, 1636 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 1637 LookupNestedNameSpecifierName, 1638 /// Look up a namespace name within a C++ using directive or 1639 /// namespace alias definition, ignoring non-namespace names (C++ 1640 /// [basic.lookup.udir]p1). 1641 LookupNamespaceName, 1642 /// Look up all declarations in a scope with the given name, 1643 /// including resolved using declarations. This is appropriate 1644 /// for checking redeclarations for a using declaration. 1645 LookupUsingDeclName, 1646 /// Look up an ordinary name that is going to be redeclared as a 1647 /// name with linkage. This lookup ignores any declarations that 1648 /// are outside of the current scope unless they have linkage. See 1649 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 1650 LookupRedeclarationWithLinkage, 1651 /// Look up the name of an Objective-C protocol. 1652 LookupObjCProtocolName, 1653 /// Look up implicit 'self' parameter of an objective-c method. 1654 LookupObjCImplicitSelfParam, 1655 /// \brief Look up any declaration with any name. 1656 LookupAnyName 1657 }; 1658 1659 /// \brief Specifies whether (or how) name lookup is being performed for a 1660 /// redeclaration (vs. a reference). 1661 enum RedeclarationKind { 1662 /// \brief The lookup is a reference to this name that is not for the 1663 /// purpose of redeclaring the name. 1664 NotForRedeclaration = 0, 1665 /// \brief The lookup results will be used for redeclaration of a name, 1666 /// if an entity by that name already exists. 1667 ForRedeclaration 1668 }; 1669 1670private: 1671 bool CppLookupName(LookupResult &R, Scope *S); 1672 1673 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D, 1674 CXXSpecialMember SM, 1675 bool ConstArg, 1676 bool VolatileArg, 1677 bool RValueThis, 1678 bool ConstThis, 1679 bool VolatileThis); 1680 1681 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. 1682 // 1683 // The boolean value will be true to indicate that the namespace was loaded 1684 // from an AST/PCH file, or false otherwise. 1685 llvm::DenseMap<NamespaceDecl*, bool> KnownNamespaces; 1686 1687 /// \brief Whether we have already loaded known namespaces from an extenal 1688 /// source. 1689 bool LoadedExternalKnownNamespaces; 1690 1691public: 1692 /// \brief Look up a name, looking for a single declaration. Return 1693 /// null if the results were absent, ambiguous, or overloaded. 1694 /// 1695 /// It is preferable to use the elaborated form and explicitly handle 1696 /// ambiguity and overloaded. 1697 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 1698 SourceLocation Loc, 1699 LookupNameKind NameKind, 1700 RedeclarationKind Redecl 1701 = NotForRedeclaration); 1702 bool LookupName(LookupResult &R, Scope *S, 1703 bool AllowBuiltinCreation = false); 1704 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 1705 bool InUnqualifiedLookup = false); 1706 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1707 bool AllowBuiltinCreation = false, 1708 bool EnteringContext = false); 1709 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc); 1710 1711 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 1712 QualType T1, QualType T2, 1713 UnresolvedSetImpl &Functions); 1714 1715 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 1716 SourceLocation GnuLabelLoc = SourceLocation()); 1717 1718 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 1719 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 1720 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 1721 unsigned Quals, 1722 bool *ConstParam = 0); 1723 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 1724 bool RValueThis, unsigned ThisQuals, 1725 bool *ConstParam = 0); 1726 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class); 1727 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, bool RValueThis, 1728 unsigned ThisQuals); 1729 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 1730 1731 void ArgumentDependentLookup(DeclarationName Name, bool Operator, 1732 Expr **Args, unsigned NumArgs, 1733 ADLResult &Functions, 1734 bool StdNamespaceIsAssociated = false); 1735 1736 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 1737 VisibleDeclConsumer &Consumer, 1738 bool IncludeGlobalScope = true); 1739 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 1740 VisibleDeclConsumer &Consumer, 1741 bool IncludeGlobalScope = true); 1742 1743 /// \brief The context in which typo-correction occurs. 1744 /// 1745 /// The typo-correction context affects which keywords (if any) are 1746 /// considered when trying to correct for typos. 1747 enum CorrectTypoContext { 1748 /// \brief An unknown context, where any keyword might be valid. 1749 CTC_Unknown, 1750 /// \brief A context where no keywords are used (e.g. we expect an actual 1751 /// name). 1752 CTC_NoKeywords, 1753 /// \brief A context where we're correcting a type name. 1754 CTC_Type, 1755 /// \brief An expression context. 1756 CTC_Expression, 1757 /// \brief A type cast, or anything else that can be followed by a '<'. 1758 CTC_CXXCasts, 1759 /// \brief A member lookup context. 1760 CTC_MemberLookup, 1761 /// \brief An Objective-C ivar lookup context (e.g., self->ivar). 1762 CTC_ObjCIvarLookup, 1763 /// \brief An Objective-C property lookup context (e.g., self.prop). 1764 CTC_ObjCPropertyLookup, 1765 /// \brief The receiver of an Objective-C message send within an 1766 /// Objective-C method where 'super' is a valid keyword. 1767 CTC_ObjCMessageReceiver 1768 }; 1769 1770 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 1771 Sema::LookupNameKind LookupKind, 1772 Scope *S, CXXScopeSpec *SS, 1773 DeclContext *MemberContext = NULL, 1774 bool EnteringContext = false, 1775 CorrectTypoContext CTC = CTC_Unknown, 1776 const ObjCObjectPointerType *OPT = NULL); 1777 1778 void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs, 1779 AssociatedNamespaceSet &AssociatedNamespaces, 1780 AssociatedClassSet &AssociatedClasses); 1781 1782 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1783 bool ConsiderLinkage, 1784 bool ExplicitInstantiationOrSpecialization); 1785 1786 bool DiagnoseAmbiguousLookup(LookupResult &Result); 1787 //@} 1788 1789 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 1790 SourceLocation IdLoc, 1791 bool TypoCorrection = false); 1792 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1793 Scope *S, bool ForRedeclaration, 1794 SourceLocation Loc); 1795 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 1796 Scope *S); 1797 void AddKnownFunctionAttributes(FunctionDecl *FD); 1798 1799 // More parsing and symbol table subroutines. 1800 1801 // Decl attributes - this routine is the top level dispatcher. 1802 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD, 1803 bool NonInheritable = true, bool Inheritable = true); 1804 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 1805 bool NonInheritable = true, bool Inheritable = true); 1806 1807 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 1808 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC); 1809 bool CheckNoReturnAttr(const AttributeList &attr); 1810 1811 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 1812 bool &IncompleteImpl, unsigned DiagID); 1813 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 1814 ObjCMethodDecl *MethodDecl, 1815 bool IsProtocolMethodDecl, 1816 bool IsDeclaration = false); 1817 1818 /// WarnExactTypedMethods - This routine issues a warning if method 1819 /// implementation declaration matches exactly that of its declaration. 1820 void WarnExactTypedMethods(ObjCMethodDecl *Method, 1821 ObjCMethodDecl *MethodDecl, 1822 bool IsProtocolMethodDecl); 1823 1824 bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl, 1825 ObjCInterfaceDecl *IDecl); 1826 1827 typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet; 1828 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; 1829 1830 /// CheckProtocolMethodDefs - This routine checks unimplemented 1831 /// methods declared in protocol, and those referenced by it. 1832 /// \param IDecl - Used for checking for methods which may have been 1833 /// inherited. 1834 void CheckProtocolMethodDefs(SourceLocation ImpLoc, 1835 ObjCProtocolDecl *PDecl, 1836 bool& IncompleteImpl, 1837 const SelectorSet &InsMap, 1838 const SelectorSet &ClsMap, 1839 ObjCContainerDecl *CDecl); 1840 1841 /// CheckImplementationIvars - This routine checks if the instance variables 1842 /// listed in the implelementation match those listed in the interface. 1843 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 1844 ObjCIvarDecl **Fields, unsigned nIvars, 1845 SourceLocation Loc); 1846 1847 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 1848 /// remains unimplemented in the class or category @implementation. 1849 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 1850 ObjCContainerDecl* IDecl, 1851 bool IncompleteImpl = false); 1852 1853 /// DiagnoseUnimplementedProperties - This routine warns on those properties 1854 /// which must be implemented by this implementation. 1855 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 1856 ObjCContainerDecl *CDecl, 1857 const SelectorSet &InsMap); 1858 1859 /// DefaultSynthesizeProperties - This routine default synthesizes all 1860 /// properties which must be synthesized in class's @implementation. 1861 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 1862 ObjCInterfaceDecl *IDecl); 1863 void DefaultSynthesizeProperties(Scope *S, Decl *D); 1864 1865 /// CollectImmediateProperties - This routine collects all properties in 1866 /// the class and its conforming protocols; but not those it its super class. 1867 void CollectImmediateProperties(ObjCContainerDecl *CDecl, 1868 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap, 1869 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap); 1870 1871 1872 /// LookupPropertyDecl - Looks up a property in the current class and all 1873 /// its protocols. 1874 ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl, 1875 IdentifierInfo *II); 1876 1877 /// Called by ActOnProperty to handle @property declarations in 1878 //// class extensions. 1879 Decl *HandlePropertyInClassExtension(Scope *S, 1880 SourceLocation AtLoc, 1881 FieldDeclarator &FD, 1882 Selector GetterSel, 1883 Selector SetterSel, 1884 const bool isAssign, 1885 const bool isReadWrite, 1886 const unsigned Attributes, 1887 bool *isOverridingProperty, 1888 TypeSourceInfo *T, 1889 tok::ObjCKeywordKind MethodImplKind); 1890 1891 /// Called by ActOnProperty and HandlePropertyInClassExtension to 1892 /// handle creating the ObjcPropertyDecl for a category or @interface. 1893 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 1894 ObjCContainerDecl *CDecl, 1895 SourceLocation AtLoc, 1896 FieldDeclarator &FD, 1897 Selector GetterSel, 1898 Selector SetterSel, 1899 const bool isAssign, 1900 const bool isReadWrite, 1901 const unsigned Attributes, 1902 TypeSourceInfo *T, 1903 tok::ObjCKeywordKind MethodImplKind, 1904 DeclContext *lexicalDC = 0); 1905 1906 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 1907 /// warning) when atomic property has one but not the other user-declared 1908 /// setter or getter. 1909 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 1910 ObjCContainerDecl* IDecl); 1911 1912 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 1913 1914 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 1915 1916 enum MethodMatchStrategy { 1917 MMS_loose, 1918 MMS_strict 1919 }; 1920 1921 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 1922 /// true, or false, accordingly. 1923 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 1924 const ObjCMethodDecl *PrevMethod, 1925 MethodMatchStrategy strategy = MMS_strict); 1926 1927 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 1928 /// or protocol against those declared in their implementations. 1929 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 1930 const SelectorSet &ClsMap, 1931 SelectorSet &InsMapSeen, 1932 SelectorSet &ClsMapSeen, 1933 ObjCImplDecl* IMPDecl, 1934 ObjCContainerDecl* IDecl, 1935 bool &IncompleteImpl, 1936 bool ImmediateClass, 1937 bool WarnExactMatch=false); 1938 1939 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 1940 /// category matches with those implemented in its primary class and 1941 /// warns each time an exact match is found. 1942 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 1943 1944private: 1945 /// AddMethodToGlobalPool - Add an instance or factory method to the global 1946 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 1947 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 1948 1949 /// LookupMethodInGlobalPool - Returns the instance or factory method and 1950 /// optionally warns if there are multiple signatures. 1951 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 1952 bool receiverIdOrClass, 1953 bool warn, bool instance); 1954 1955public: 1956 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 1957 /// unit are added to a global pool. This allows us to efficiently associate 1958 /// a selector with a method declaraation for purposes of typechecking 1959 /// messages sent to "id" (where the class of the object is unknown). 1960 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 1961 AddMethodToGlobalPool(Method, impl, /*instance*/true); 1962 } 1963 1964 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 1965 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 1966 AddMethodToGlobalPool(Method, impl, /*instance*/false); 1967 } 1968 1969 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 1970 /// pool. 1971 void AddAnyMethodToGlobalPool(Decl *D); 1972 1973 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 1974 /// there are multiple signatures. 1975 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 1976 bool receiverIdOrClass=false, 1977 bool warn=true) { 1978 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 1979 warn, /*instance*/true); 1980 } 1981 1982 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 1983 /// there are multiple signatures. 1984 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 1985 bool receiverIdOrClass=false, 1986 bool warn=true) { 1987 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 1988 warn, /*instance*/false); 1989 } 1990 1991 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 1992 /// implementation. 1993 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 1994 1995 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 1996 /// initialization. 1997 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 1998 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 1999 2000 //===--------------------------------------------------------------------===// 2001 // Statement Parsing Callbacks: SemaStmt.cpp. 2002public: 2003 class FullExprArg { 2004 public: 2005 FullExprArg(Sema &actions) : E(0) { } 2006 2007 // FIXME: The const_cast here is ugly. RValue references would make this 2008 // much nicer (or we could duplicate a bunch of the move semantics 2009 // emulation code from Ownership.h). 2010 FullExprArg(const FullExprArg& Other) : E(Other.E) {} 2011 2012 ExprResult release() { 2013 return move(E); 2014 } 2015 2016 Expr *get() const { return E; } 2017 2018 Expr *operator->() { 2019 return E; 2020 } 2021 2022 private: 2023 // FIXME: No need to make the entire Sema class a friend when it's just 2024 // Sema::MakeFullExpr that needs access to the constructor below. 2025 friend class Sema; 2026 2027 explicit FullExprArg(Expr *expr) : E(expr) {} 2028 2029 Expr *E; 2030 }; 2031 2032 FullExprArg MakeFullExpr(Expr *Arg) { 2033 return FullExprArg(ActOnFinishFullExpr(Arg).release()); 2034 } 2035 2036 StmtResult ActOnExprStmt(FullExprArg Expr); 2037 2038 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 2039 bool HasLeadingEmptyMacro = false); 2040 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 2041 MultiStmtArg Elts, 2042 bool isStmtExpr); 2043 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 2044 SourceLocation StartLoc, 2045 SourceLocation EndLoc); 2046 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 2047 StmtResult ActOnForEachLValueExpr(Expr *E); 2048 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 2049 SourceLocation DotDotDotLoc, Expr *RHSVal, 2050 SourceLocation ColonLoc); 2051 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 2052 2053 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 2054 SourceLocation ColonLoc, 2055 Stmt *SubStmt, Scope *CurScope); 2056 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 2057 SourceLocation ColonLoc, Stmt *SubStmt); 2058 2059 StmtResult ActOnIfStmt(SourceLocation IfLoc, 2060 FullExprArg CondVal, Decl *CondVar, 2061 Stmt *ThenVal, 2062 SourceLocation ElseLoc, Stmt *ElseVal); 2063 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 2064 Expr *Cond, 2065 Decl *CondVar); 2066 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 2067 Stmt *Switch, Stmt *Body); 2068 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 2069 FullExprArg Cond, 2070 Decl *CondVar, Stmt *Body); 2071 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 2072 SourceLocation WhileLoc, 2073 SourceLocation CondLParen, Expr *Cond, 2074 SourceLocation CondRParen); 2075 2076 StmtResult ActOnForStmt(SourceLocation ForLoc, 2077 SourceLocation LParenLoc, 2078 Stmt *First, FullExprArg Second, 2079 Decl *SecondVar, 2080 FullExprArg Third, 2081 SourceLocation RParenLoc, 2082 Stmt *Body); 2083 ExprResult ActOnObjCForCollectionOperand(SourceLocation forLoc, 2084 Expr *collection); 2085 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 2086 SourceLocation LParenLoc, 2087 Stmt *First, Expr *Second, 2088 SourceLocation RParenLoc, Stmt *Body); 2089 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, 2090 SourceLocation LParenLoc, Stmt *LoopVar, 2091 SourceLocation ColonLoc, Expr *Collection, 2092 SourceLocation RParenLoc); 2093 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 2094 SourceLocation ColonLoc, 2095 Stmt *RangeDecl, Stmt *BeginEndDecl, 2096 Expr *Cond, Expr *Inc, 2097 Stmt *LoopVarDecl, 2098 SourceLocation RParenLoc); 2099 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 2100 2101 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 2102 SourceLocation LabelLoc, 2103 LabelDecl *TheDecl); 2104 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 2105 SourceLocation StarLoc, 2106 Expr *DestExp); 2107 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 2108 StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope); 2109 2110 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 2111 bool AllowFunctionParameters); 2112 2113 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2114 StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2115 2116 StmtResult ActOnAsmStmt(SourceLocation AsmLoc, 2117 bool IsSimple, bool IsVolatile, 2118 unsigned NumOutputs, unsigned NumInputs, 2119 IdentifierInfo **Names, 2120 MultiExprArg Constraints, 2121 MultiExprArg Exprs, 2122 Expr *AsmString, 2123 MultiExprArg Clobbers, 2124 SourceLocation RParenLoc, 2125 bool MSAsm = false); 2126 2127 2128 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 2129 SourceLocation StartLoc, 2130 SourceLocation IdLoc, IdentifierInfo *Id, 2131 bool Invalid = false); 2132 2133 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 2134 2135 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 2136 Decl *Parm, Stmt *Body); 2137 2138 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 2139 2140 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2141 MultiStmtArg Catch, Stmt *Finally); 2142 2143 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 2144 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2145 Scope *CurScope); 2146 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 2147 Expr *operand); 2148 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 2149 Expr *SynchExpr, 2150 Stmt *SynchBody); 2151 2152 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 2153 2154 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 2155 SourceLocation StartLoc, 2156 SourceLocation IdLoc, 2157 IdentifierInfo *Id); 2158 2159 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 2160 2161 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 2162 Decl *ExDecl, Stmt *HandlerBlock); 2163 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2164 MultiStmtArg Handlers); 2165 2166 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 2167 SourceLocation TryLoc, 2168 Stmt *TryBlock, 2169 Stmt *Handler); 2170 2171 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 2172 Expr *FilterExpr, 2173 Stmt *Block); 2174 2175 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, 2176 Stmt *Block); 2177 2178 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 2179 2180 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 2181 2182 /// \brief If it's a file scoped decl that must warn if not used, keep track 2183 /// of it. 2184 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 2185 2186 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 2187 /// whose result is unused, warn. 2188 void DiagnoseUnusedExprResult(const Stmt *S); 2189 void DiagnoseUnusedDecl(const NamedDecl *ND); 2190 2191 ParsingDeclState PushParsingDeclaration() { 2192 return DelayedDiagnostics.pushParsingDecl(); 2193 } 2194 void PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 2195 DelayedDiagnostics::popParsingDecl(*this, state, decl); 2196 } 2197 2198 typedef ProcessingContextState ParsingClassState; 2199 ParsingClassState PushParsingClass() { 2200 return DelayedDiagnostics.pushContext(); 2201 } 2202 void PopParsingClass(ParsingClassState state) { 2203 DelayedDiagnostics.popContext(state); 2204 } 2205 2206 void EmitDeprecationWarning(NamedDecl *D, StringRef Message, 2207 SourceLocation Loc, 2208 const ObjCInterfaceDecl *UnknownObjCClass=0); 2209 2210 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 2211 2212 bool makeUnavailableInSystemHeader(SourceLocation loc, 2213 StringRef message); 2214 2215 //===--------------------------------------------------------------------===// 2216 // Expression Parsing Callbacks: SemaExpr.cpp. 2217 2218 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 2219 const ObjCInterfaceDecl *UnknownObjCClass=0); 2220 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 2221 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 2222 ObjCMethodDecl *Getter, 2223 SourceLocation Loc); 2224 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 2225 Expr **Args, unsigned NumArgs); 2226 2227 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext); 2228 2229 void PopExpressionEvaluationContext(); 2230 2231 void DiscardCleanupsInEvaluationContext(); 2232 2233 void MarkDeclarationReferenced(SourceLocation Loc, Decl *D); 2234 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 2235 void MarkDeclarationsReferencedInExpr(Expr *E); 2236 2237 /// \brief Figure out if an expression could be turned into a call. 2238 bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 2239 UnresolvedSetImpl &NonTemplateOverloads); 2240 /// \brief Give notes for a set of overloads. 2241 void NoteOverloads(const UnresolvedSetImpl &Overloads, 2242 const SourceLocation FinalNoteLoc); 2243 2244 /// \brief Conditionally issue a diagnostic based on the current 2245 /// evaluation context. 2246 /// 2247 /// \param stmt - If stmt is non-null, delay reporting the diagnostic until 2248 /// the function body is parsed, and then do a basic reachability analysis to 2249 /// determine if the statement is reachable. If it is unreachable, the 2250 /// diagnostic will not be emitted. 2251 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 2252 const PartialDiagnostic &PD); 2253 2254 // Primary Expressions. 2255 SourceRange getExprRange(Expr *E) const; 2256 2257 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Id, 2258 bool HasTrailingLParen, bool IsAddressOfOperand); 2259 2260 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 2261 TemplateArgumentListInfo &Buffer, 2262 DeclarationNameInfo &NameInfo, 2263 const TemplateArgumentListInfo *&TemplateArgs); 2264 2265 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2266 CorrectTypoContext CTC = CTC_Unknown, 2267 TemplateArgumentListInfo *ExplicitTemplateArgs = 0, 2268 Expr **Args = 0, unsigned NumArgs = 0); 2269 2270 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 2271 IdentifierInfo *II, 2272 bool AllowBuiltinCreation=false); 2273 2274 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 2275 const DeclarationNameInfo &NameInfo, 2276 bool isAddressOfOperand, 2277 const TemplateArgumentListInfo *TemplateArgs); 2278 2279 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2280 ExprValueKind VK, 2281 SourceLocation Loc, 2282 const CXXScopeSpec *SS = 0); 2283 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2284 ExprValueKind VK, 2285 const DeclarationNameInfo &NameInfo, 2286 const CXXScopeSpec *SS = 0); 2287 ExprResult 2288 BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 2289 SourceLocation nameLoc, 2290 IndirectFieldDecl *indirectField, 2291 Expr *baseObjectExpr = 0, 2292 SourceLocation opLoc = SourceLocation()); 2293 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 2294 LookupResult &R, 2295 const TemplateArgumentListInfo *TemplateArgs); 2296 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 2297 LookupResult &R, 2298 const TemplateArgumentListInfo *TemplateArgs, 2299 bool IsDefiniteInstance); 2300 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 2301 const LookupResult &R, 2302 bool HasTrailingLParen); 2303 2304 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2305 const DeclarationNameInfo &NameInfo); 2306 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 2307 const DeclarationNameInfo &NameInfo, 2308 const TemplateArgumentListInfo *TemplateArgs); 2309 2310 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2311 LookupResult &R, 2312 bool NeedsADL); 2313 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2314 const DeclarationNameInfo &NameInfo, 2315 NamedDecl *D); 2316 2317 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 2318 ExprResult ActOnNumericConstant(const Token &Tok); 2319 ExprResult ActOnCharacterConstant(const Token &Tok); 2320 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 2321 ExprResult ActOnParenOrParenListExpr(SourceLocation L, 2322 SourceLocation R, 2323 MultiExprArg Val); 2324 2325 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 2326 /// fragments (e.g. "foo" "bar" L"baz"). 2327 ExprResult ActOnStringLiteral(const Token *StringToks, 2328 unsigned NumStringToks); 2329 2330 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 2331 SourceLocation DefaultLoc, 2332 SourceLocation RParenLoc, 2333 Expr *ControllingExpr, 2334 MultiTypeArg ArgTypes, 2335 MultiExprArg ArgExprs); 2336 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 2337 SourceLocation DefaultLoc, 2338 SourceLocation RParenLoc, 2339 Expr *ControllingExpr, 2340 TypeSourceInfo **Types, 2341 Expr **Exprs, 2342 unsigned NumAssocs); 2343 2344 // Binary/Unary Operators. 'Tok' is the token for the operator. 2345 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 2346 Expr *InputExpr); 2347 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 2348 UnaryOperatorKind Opc, Expr *Input); 2349 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 2350 tok::TokenKind Op, Expr *Input); 2351 2352 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2353 SourceLocation OpLoc, 2354 UnaryExprOrTypeTrait ExprKind, 2355 SourceRange R); 2356 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2357 UnaryExprOrTypeTrait ExprKind); 2358 ExprResult 2359 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2360 UnaryExprOrTypeTrait ExprKind, 2361 bool IsType, void *TyOrEx, 2362 const SourceRange &ArgRange); 2363 2364 ExprResult CheckPlaceholderExpr(Expr *E); 2365 bool CheckVecStepExpr(Expr *E); 2366 2367 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 2368 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 2369 SourceRange ExprRange, 2370 UnaryExprOrTypeTrait ExprKind); 2371 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 2372 SourceLocation OpLoc, 2373 IdentifierInfo &Name, 2374 SourceLocation NameLoc, 2375 SourceLocation RParenLoc); 2376 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2377 tok::TokenKind Kind, Expr *Input); 2378 2379 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2380 Expr *Idx, SourceLocation RLoc); 2381 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2382 Expr *Idx, SourceLocation RLoc); 2383 2384 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2385 SourceLocation OpLoc, bool IsArrow, 2386 CXXScopeSpec &SS, 2387 NamedDecl *FirstQualifierInScope, 2388 const DeclarationNameInfo &NameInfo, 2389 const TemplateArgumentListInfo *TemplateArgs); 2390 2391 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2392 SourceLocation OpLoc, bool IsArrow, 2393 const CXXScopeSpec &SS, 2394 NamedDecl *FirstQualifierInScope, 2395 LookupResult &R, 2396 const TemplateArgumentListInfo *TemplateArgs, 2397 bool SuppressQualifierCheck = false); 2398 2399 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base, 2400 bool &IsArrow, SourceLocation OpLoc, 2401 CXXScopeSpec &SS, 2402 Decl *ObjCImpDecl, 2403 bool HasTemplateArgs); 2404 2405 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 2406 const CXXScopeSpec &SS, 2407 const LookupResult &R); 2408 2409 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 2410 bool IsArrow, SourceLocation OpLoc, 2411 const CXXScopeSpec &SS, 2412 NamedDecl *FirstQualifierInScope, 2413 const DeclarationNameInfo &NameInfo, 2414 const TemplateArgumentListInfo *TemplateArgs); 2415 2416 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 2417 SourceLocation OpLoc, 2418 tok::TokenKind OpKind, 2419 CXXScopeSpec &SS, 2420 UnqualifiedId &Member, 2421 Decl *ObjCImpDecl, 2422 bool HasTrailingLParen); 2423 2424 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 2425 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2426 FunctionDecl *FDecl, 2427 const FunctionProtoType *Proto, 2428 Expr **Args, unsigned NumArgs, 2429 SourceLocation RParenLoc); 2430 2431 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2432 /// This provides the location of the left/right parens and a list of comma 2433 /// locations. 2434 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 2435 MultiExprArg ArgExprs, SourceLocation RParenLoc, 2436 Expr *ExecConfig = 0); 2437 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 2438 SourceLocation LParenLoc, 2439 Expr **Args, unsigned NumArgs, 2440 SourceLocation RParenLoc, 2441 Expr *Config = 0); 2442 2443 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 2444 MultiExprArg ExecConfig, 2445 SourceLocation GGGLoc); 2446 2447 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 2448 Declarator &D, ParsedType &Ty, 2449 SourceLocation RParenLoc, Expr *CastExpr); 2450 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 2451 TypeSourceInfo *Ty, 2452 SourceLocation RParenLoc, 2453 Expr *Op); 2454 2455 /// \brief Build an altivec or OpenCL literal. 2456 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 2457 SourceLocation RParenLoc, Expr *E, 2458 TypeSourceInfo *TInfo); 2459 2460 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 2461 2462 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 2463 ParsedType Ty, 2464 SourceLocation RParenLoc, 2465 Expr *InitExpr); 2466 2467 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 2468 TypeSourceInfo *TInfo, 2469 SourceLocation RParenLoc, 2470 Expr *LiteralExpr); 2471 2472 ExprResult ActOnInitList(SourceLocation LBraceLoc, 2473 MultiExprArg InitArgList, 2474 SourceLocation RBraceLoc); 2475 2476 ExprResult ActOnDesignatedInitializer(Designation &Desig, 2477 SourceLocation Loc, 2478 bool GNUSyntax, 2479 ExprResult Init); 2480 2481 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 2482 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 2483 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 2484 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 2485 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 2486 Expr *LHSExpr, Expr *RHSExpr); 2487 2488 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 2489 /// in the case of a the GNU conditional expr extension. 2490 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 2491 SourceLocation ColonLoc, 2492 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 2493 2494 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 2495 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 2496 LabelDecl *TheDecl); 2497 2498 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 2499 SourceLocation RPLoc); // "({..})" 2500 2501 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 2502 struct OffsetOfComponent { 2503 SourceLocation LocStart, LocEnd; 2504 bool isBrackets; // true if [expr], false if .ident 2505 union { 2506 IdentifierInfo *IdentInfo; 2507 Expr *E; 2508 } U; 2509 }; 2510 2511 /// __builtin_offsetof(type, a.b[123][456].c) 2512 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 2513 TypeSourceInfo *TInfo, 2514 OffsetOfComponent *CompPtr, 2515 unsigned NumComponents, 2516 SourceLocation RParenLoc); 2517 ExprResult ActOnBuiltinOffsetOf(Scope *S, 2518 SourceLocation BuiltinLoc, 2519 SourceLocation TypeLoc, 2520 ParsedType ParsedArgTy, 2521 OffsetOfComponent *CompPtr, 2522 unsigned NumComponents, 2523 SourceLocation RParenLoc); 2524 2525 // __builtin_choose_expr(constExpr, expr1, expr2) 2526 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 2527 Expr *CondExpr, Expr *LHSExpr, 2528 Expr *RHSExpr, SourceLocation RPLoc); 2529 2530 // __builtin_va_arg(expr, type) 2531 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 2532 SourceLocation RPLoc); 2533 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 2534 TypeSourceInfo *TInfo, SourceLocation RPLoc); 2535 2536 // __null 2537 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 2538 2539 bool CheckCaseExpression(Expr *E); 2540 2541 bool CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS, UnqualifiedId &Name); 2542 2543 //===------------------------- "Block" Extension ------------------------===// 2544 2545 /// ActOnBlockStart - This callback is invoked when a block literal is 2546 /// started. 2547 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 2548 2549 /// ActOnBlockArguments - This callback allows processing of block arguments. 2550 /// If there are no arguments, this is still invoked. 2551 void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope); 2552 2553 /// ActOnBlockError - If there is an error parsing a block, this callback 2554 /// is invoked to pop the information about the block from the action impl. 2555 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 2556 2557 /// ActOnBlockStmtExpr - This is called when the body of a block statement 2558 /// literal was successfully completed. ^(int x){...} 2559 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 2560 Scope *CurScope); 2561 2562 //===---------------------------- OpenCL Features -----------------------===// 2563 2564 /// __builtin_astype(...) 2565 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 2566 SourceLocation BuiltinLoc, 2567 SourceLocation RParenLoc); 2568 2569 //===---------------------------- C++ Features --------------------------===// 2570 2571 // Act on C++ namespaces 2572 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 2573 SourceLocation NamespaceLoc, 2574 SourceLocation IdentLoc, 2575 IdentifierInfo *Ident, 2576 SourceLocation LBrace, 2577 AttributeList *AttrList); 2578 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 2579 2580 NamespaceDecl *getStdNamespace() const; 2581 NamespaceDecl *getOrCreateStdNamespace(); 2582 2583 CXXRecordDecl *getStdBadAlloc() const; 2584 2585 Decl *ActOnUsingDirective(Scope *CurScope, 2586 SourceLocation UsingLoc, 2587 SourceLocation NamespcLoc, 2588 CXXScopeSpec &SS, 2589 SourceLocation IdentLoc, 2590 IdentifierInfo *NamespcName, 2591 AttributeList *AttrList); 2592 2593 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 2594 2595 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 2596 SourceLocation NamespaceLoc, 2597 SourceLocation AliasLoc, 2598 IdentifierInfo *Alias, 2599 CXXScopeSpec &SS, 2600 SourceLocation IdentLoc, 2601 IdentifierInfo *Ident); 2602 2603 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 2604 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 2605 const LookupResult &PreviousDecls); 2606 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 2607 NamedDecl *Target); 2608 2609 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 2610 bool isTypeName, 2611 const CXXScopeSpec &SS, 2612 SourceLocation NameLoc, 2613 const LookupResult &Previous); 2614 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 2615 const CXXScopeSpec &SS, 2616 SourceLocation NameLoc); 2617 2618 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 2619 SourceLocation UsingLoc, 2620 CXXScopeSpec &SS, 2621 const DeclarationNameInfo &NameInfo, 2622 AttributeList *AttrList, 2623 bool IsInstantiation, 2624 bool IsTypeName, 2625 SourceLocation TypenameLoc); 2626 2627 bool CheckInheritedConstructorUsingDecl(UsingDecl *UD); 2628 2629 Decl *ActOnUsingDeclaration(Scope *CurScope, 2630 AccessSpecifier AS, 2631 bool HasUsingKeyword, 2632 SourceLocation UsingLoc, 2633 CXXScopeSpec &SS, 2634 UnqualifiedId &Name, 2635 AttributeList *AttrList, 2636 bool IsTypeName, 2637 SourceLocation TypenameLoc); 2638 Decl *ActOnAliasDeclaration(Scope *CurScope, 2639 AccessSpecifier AS, 2640 MultiTemplateParamsArg TemplateParams, 2641 SourceLocation UsingLoc, 2642 UnqualifiedId &Name, 2643 TypeResult Type); 2644 2645 /// AddCXXDirectInitializerToDecl - This action is called immediately after 2646 /// ActOnDeclarator, when a C++ direct initializer is present. 2647 /// e.g: "int x(1);" 2648 void AddCXXDirectInitializerToDecl(Decl *Dcl, 2649 SourceLocation LParenLoc, 2650 MultiExprArg Exprs, 2651 SourceLocation RParenLoc, 2652 bool TypeMayContainAuto); 2653 2654 /// InitializeVarWithConstructor - Creates an CXXConstructExpr 2655 /// and sets it as the initializer for the the passed in VarDecl. 2656 bool InitializeVarWithConstructor(VarDecl *VD, 2657 CXXConstructorDecl *Constructor, 2658 MultiExprArg Exprs); 2659 2660 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 2661 /// including handling of its default argument expressions. 2662 /// 2663 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 2664 ExprResult 2665 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2666 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 2667 bool RequiresZeroInit, unsigned ConstructKind, 2668 SourceRange ParenRange); 2669 2670 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if 2671 // the constructor can be elidable? 2672 ExprResult 2673 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2674 CXXConstructorDecl *Constructor, bool Elidable, 2675 MultiExprArg Exprs, bool RequiresZeroInit, 2676 unsigned ConstructKind, 2677 SourceRange ParenRange); 2678 2679 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 2680 /// the default expr if needed. 2681 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 2682 FunctionDecl *FD, 2683 ParmVarDecl *Param); 2684 2685 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 2686 /// constructed variable. 2687 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 2688 2689 /// \brief Helper class that collects exception specifications for 2690 /// implicitly-declared special member functions. 2691 class ImplicitExceptionSpecification { 2692 // Pointer to allow copying 2693 ASTContext *Context; 2694 // We order exception specifications thus: 2695 // noexcept is the most restrictive, but is only used in C++0x. 2696 // throw() comes next. 2697 // Then a throw(collected exceptions) 2698 // Finally no specification. 2699 // throw(...) is used instead if any called function uses it. 2700 // 2701 // If this exception specification cannot be known yet (for instance, 2702 // because this is the exception specification for a defaulted default 2703 // constructor and we haven't finished parsing the deferred parts of the 2704 // class yet), the C++0x standard does not specify how to behave. We 2705 // record this as an 'unknown' exception specification, which overrules 2706 // any other specification (even 'none', to keep this rule simple). 2707 ExceptionSpecificationType ComputedEST; 2708 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 2709 SmallVector<QualType, 4> Exceptions; 2710 2711 void ClearExceptions() { 2712 ExceptionsSeen.clear(); 2713 Exceptions.clear(); 2714 } 2715 2716 public: 2717 explicit ImplicitExceptionSpecification(ASTContext &Context) 2718 : Context(&Context), ComputedEST(EST_BasicNoexcept) { 2719 if (!Context.getLangOptions().CPlusPlus0x) 2720 ComputedEST = EST_DynamicNone; 2721 } 2722 2723 /// \brief Get the computed exception specification type. 2724 ExceptionSpecificationType getExceptionSpecType() const { 2725 assert(ComputedEST != EST_ComputedNoexcept && 2726 "noexcept(expr) should not be a possible result"); 2727 return ComputedEST; 2728 } 2729 2730 /// \brief The number of exceptions in the exception specification. 2731 unsigned size() const { return Exceptions.size(); } 2732 2733 /// \brief The set of exceptions in the exception specification. 2734 const QualType *data() const { return Exceptions.data(); } 2735 2736 /// \brief Integrate another called method into the collected data. 2737 void CalledDecl(CXXMethodDecl *Method); 2738 2739 /// \brief Integrate an invoked expression into the collected data. 2740 void CalledExpr(Expr *E); 2741 2742 /// \brief Specify that the exception specification can't be detemined yet. 2743 void SetDelayed() { 2744 ClearExceptions(); 2745 ComputedEST = EST_Delayed; 2746 } 2747 2748 FunctionProtoType::ExtProtoInfo getEPI() const { 2749 FunctionProtoType::ExtProtoInfo EPI; 2750 EPI.ExceptionSpecType = getExceptionSpecType(); 2751 EPI.NumExceptions = size(); 2752 EPI.Exceptions = data(); 2753 return EPI; 2754 } 2755 }; 2756 2757 /// \brief Determine what sort of exception specification a defaulted 2758 /// copy constructor of a class will have. 2759 ImplicitExceptionSpecification 2760 ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl); 2761 2762 /// \brief Determine what sort of exception specification a defaulted 2763 /// default constructor of a class will have, and whether the parameter 2764 /// will be const. 2765 std::pair<ImplicitExceptionSpecification, bool> 2766 ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl); 2767 2768 /// \brief Determine what sort of exception specification a defautled 2769 /// copy assignment operator of a class will have, and whether the 2770 /// parameter will be const. 2771 std::pair<ImplicitExceptionSpecification, bool> 2772 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl); 2773 2774 /// \brief Determine what sort of exception specification a defaulted move 2775 /// constructor of a class will have. 2776 ImplicitExceptionSpecification 2777 ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl); 2778 2779 /// \brief Determine what sort of exception specification a defaulted move 2780 /// assignment operator of a class will have. 2781 ImplicitExceptionSpecification 2782 ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl); 2783 2784 /// \brief Determine what sort of exception specification a defaulted 2785 /// destructor of a class will have. 2786 ImplicitExceptionSpecification 2787 ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl); 2788 2789 /// \brief Determine if a defaulted default constructor ought to be 2790 /// deleted. 2791 bool ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD); 2792 2793 /// \brief Determine if a defaulted copy constructor ought to be 2794 /// deleted. 2795 bool ShouldDeleteCopyConstructor(CXXConstructorDecl *CD); 2796 2797 /// \brief Determine if a defaulted copy assignment operator ought to be 2798 /// deleted. 2799 bool ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD); 2800 2801 /// \brief Determine if a defaulted move constructor ought to be deleted. 2802 bool ShouldDeleteMoveConstructor(CXXConstructorDecl *CD); 2803 2804 /// \brief Determine if a defaulted move assignment operator ought to be 2805 /// deleted. 2806 bool ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD); 2807 2808 /// \brief Determine if a defaulted destructor ought to be deleted. 2809 bool ShouldDeleteDestructor(CXXDestructorDecl *DD); 2810 2811 /// \brief Declare the implicit default constructor for the given class. 2812 /// 2813 /// \param ClassDecl The class declaration into which the implicit 2814 /// default constructor will be added. 2815 /// 2816 /// \returns The implicitly-declared default constructor. 2817 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 2818 CXXRecordDecl *ClassDecl); 2819 2820 /// DefineImplicitDefaultConstructor - Checks for feasibility of 2821 /// defining this constructor as the default constructor. 2822 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 2823 CXXConstructorDecl *Constructor); 2824 2825 /// \brief Declare the implicit destructor for the given class. 2826 /// 2827 /// \param ClassDecl The class declaration into which the implicit 2828 /// destructor will be added. 2829 /// 2830 /// \returns The implicitly-declared destructor. 2831 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 2832 2833 /// DefineImplicitDestructor - Checks for feasibility of 2834 /// defining this destructor as the default destructor. 2835 void DefineImplicitDestructor(SourceLocation CurrentLocation, 2836 CXXDestructorDecl *Destructor); 2837 2838 /// \brief Build an exception spec for destructors that don't have one. 2839 /// 2840 /// C++11 says that user-defined destructors with no exception spec get one 2841 /// that looks as if the destructor was implicitly declared. 2842 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 2843 CXXDestructorDecl *Destructor); 2844 2845 /// \brief Declare all inherited constructors for the given class. 2846 /// 2847 /// \param ClassDecl The class declaration into which the inherited 2848 /// constructors will be added. 2849 void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl); 2850 2851 /// \brief Declare the implicit copy constructor for the given class. 2852 /// 2853 /// \param ClassDecl The class declaration into which the implicit 2854 /// copy constructor will be added. 2855 /// 2856 /// \returns The implicitly-declared copy constructor. 2857 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 2858 2859 /// DefineImplicitCopyConstructor - Checks for feasibility of 2860 /// defining this constructor as the copy constructor. 2861 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 2862 CXXConstructorDecl *Constructor); 2863 2864 /// \brief Declare the implicit move constructor for the given class. 2865 /// 2866 /// \param ClassDecl The Class declaration into which the implicit 2867 /// move constructor will be added. 2868 /// 2869 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 2870 /// declared. 2871 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 2872 2873 /// DefineImplicitMoveConstructor - Checks for feasibility of 2874 /// defining this constructor as the move constructor. 2875 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 2876 CXXConstructorDecl *Constructor); 2877 2878 /// \brief Declare the implicit copy assignment operator for the given class. 2879 /// 2880 /// \param ClassDecl The class declaration into which the implicit 2881 /// copy assignment operator will be added. 2882 /// 2883 /// \returns The implicitly-declared copy assignment operator. 2884 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 2885 2886 /// \brief Defines an implicitly-declared copy assignment operator. 2887 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 2888 CXXMethodDecl *MethodDecl); 2889 2890 /// \brief Declare the implicit move assignment operator for the given class. 2891 /// 2892 /// \param ClassDecl The Class declaration into which the implicit 2893 /// move assignment operator will be added. 2894 /// 2895 /// \returns The implicitly-declared move assignment operator, or NULL if it 2896 /// wasn't declared. 2897 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 2898 2899 /// \brief Defines an implicitly-declared move assignment operator. 2900 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 2901 CXXMethodDecl *MethodDecl); 2902 2903 /// \brief Force the declaration of any implicitly-declared members of this 2904 /// class. 2905 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 2906 2907 /// MaybeBindToTemporary - If the passed in expression has a record type with 2908 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 2909 /// it simply returns the passed in expression. 2910 ExprResult MaybeBindToTemporary(Expr *E); 2911 2912 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 2913 MultiExprArg ArgsPtr, 2914 SourceLocation Loc, 2915 ASTOwningVector<Expr*> &ConvertedArgs); 2916 2917 ParsedType getDestructorName(SourceLocation TildeLoc, 2918 IdentifierInfo &II, SourceLocation NameLoc, 2919 Scope *S, CXXScopeSpec &SS, 2920 ParsedType ObjectType, 2921 bool EnteringContext); 2922 2923 // Checks that reinterpret casts don't have undefined behavior. 2924 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 2925 bool IsDereference, SourceRange Range); 2926 2927 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 2928 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 2929 tok::TokenKind Kind, 2930 SourceLocation LAngleBracketLoc, 2931 Declarator &D, 2932 SourceLocation RAngleBracketLoc, 2933 SourceLocation LParenLoc, 2934 Expr *E, 2935 SourceLocation RParenLoc); 2936 2937 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 2938 tok::TokenKind Kind, 2939 TypeSourceInfo *Ty, 2940 Expr *E, 2941 SourceRange AngleBrackets, 2942 SourceRange Parens); 2943 2944 ExprResult BuildCXXTypeId(QualType TypeInfoType, 2945 SourceLocation TypeidLoc, 2946 TypeSourceInfo *Operand, 2947 SourceLocation RParenLoc); 2948 ExprResult BuildCXXTypeId(QualType TypeInfoType, 2949 SourceLocation TypeidLoc, 2950 Expr *Operand, 2951 SourceLocation RParenLoc); 2952 2953 /// ActOnCXXTypeid - Parse typeid( something ). 2954 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 2955 SourceLocation LParenLoc, bool isType, 2956 void *TyOrExpr, 2957 SourceLocation RParenLoc); 2958 2959 ExprResult BuildCXXUuidof(QualType TypeInfoType, 2960 SourceLocation TypeidLoc, 2961 TypeSourceInfo *Operand, 2962 SourceLocation RParenLoc); 2963 ExprResult BuildCXXUuidof(QualType TypeInfoType, 2964 SourceLocation TypeidLoc, 2965 Expr *Operand, 2966 SourceLocation RParenLoc); 2967 2968 /// ActOnCXXUuidof - Parse __uuidof( something ). 2969 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 2970 SourceLocation LParenLoc, bool isType, 2971 void *TyOrExpr, 2972 SourceLocation RParenLoc); 2973 2974 2975 //// ActOnCXXThis - Parse 'this' pointer. 2976 ExprResult ActOnCXXThis(SourceLocation loc); 2977 2978 /// getAndCaptureCurrentThisType - Try to capture a 'this' pointer. Returns 2979 /// the type of the 'this' pointer, or a null type if this is not possible. 2980 QualType getAndCaptureCurrentThisType(); 2981 2982 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 2983 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 2984 2985 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 2986 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 2987 2988 //// ActOnCXXThrow - Parse throw expressions. 2989 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 2990 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 2991 bool IsThrownVarInScope); 2992 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 2993 bool IsThrownVarInScope); 2994 2995 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 2996 /// Can be interpreted either as function-style casting ("int(x)") 2997 /// or class type construction ("ClassType(x,y,z)") 2998 /// or creation of a value-initialized type ("int()"). 2999 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 3000 SourceLocation LParenLoc, 3001 MultiExprArg Exprs, 3002 SourceLocation RParenLoc); 3003 3004 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 3005 SourceLocation LParenLoc, 3006 MultiExprArg Exprs, 3007 SourceLocation RParenLoc); 3008 3009 /// ActOnCXXNew - Parsed a C++ 'new' expression. 3010 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 3011 SourceLocation PlacementLParen, 3012 MultiExprArg PlacementArgs, 3013 SourceLocation PlacementRParen, 3014 SourceRange TypeIdParens, Declarator &D, 3015 SourceLocation ConstructorLParen, 3016 MultiExprArg ConstructorArgs, 3017 SourceLocation ConstructorRParen); 3018 ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 3019 SourceLocation PlacementLParen, 3020 MultiExprArg PlacementArgs, 3021 SourceLocation PlacementRParen, 3022 SourceRange TypeIdParens, 3023 QualType AllocType, 3024 TypeSourceInfo *AllocTypeInfo, 3025 Expr *ArraySize, 3026 SourceLocation ConstructorLParen, 3027 MultiExprArg ConstructorArgs, 3028 SourceLocation ConstructorRParen, 3029 bool TypeMayContainAuto = true); 3030 3031 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 3032 SourceRange R); 3033 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 3034 bool UseGlobal, QualType AllocType, bool IsArray, 3035 Expr **PlaceArgs, unsigned NumPlaceArgs, 3036 FunctionDecl *&OperatorNew, 3037 FunctionDecl *&OperatorDelete); 3038 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 3039 DeclarationName Name, Expr** Args, 3040 unsigned NumArgs, DeclContext *Ctx, 3041 bool AllowMissing, FunctionDecl *&Operator, 3042 bool Diagnose = true); 3043 void DeclareGlobalNewDelete(); 3044 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 3045 QualType Argument, 3046 bool addMallocAttr = false); 3047 3048 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3049 DeclarationName Name, FunctionDecl* &Operator, 3050 bool Diagnose = true); 3051 3052 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 3053 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 3054 bool UseGlobal, bool ArrayForm, 3055 Expr *Operand); 3056 3057 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 3058 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 3059 SourceLocation StmtLoc, 3060 bool ConvertToBoolean); 3061 3062 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 3063 Expr *Operand, SourceLocation RParen); 3064 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3065 SourceLocation RParen); 3066 3067 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support 3068 /// pseudo-functions. 3069 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 3070 SourceLocation KWLoc, 3071 ParsedType Ty, 3072 SourceLocation RParen); 3073 3074 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT, 3075 SourceLocation KWLoc, 3076 TypeSourceInfo *T, 3077 SourceLocation RParen); 3078 3079 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support 3080 /// pseudo-functions. 3081 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT, 3082 SourceLocation KWLoc, 3083 ParsedType LhsTy, 3084 ParsedType RhsTy, 3085 SourceLocation RParen); 3086 3087 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT, 3088 SourceLocation KWLoc, 3089 TypeSourceInfo *LhsT, 3090 TypeSourceInfo *RhsT, 3091 SourceLocation RParen); 3092 3093 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 3094 /// pseudo-functions. 3095 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 3096 SourceLocation KWLoc, 3097 ParsedType LhsTy, 3098 Expr *DimExpr, 3099 SourceLocation RParen); 3100 3101 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 3102 SourceLocation KWLoc, 3103 TypeSourceInfo *TSInfo, 3104 Expr *DimExpr, 3105 SourceLocation RParen); 3106 3107 /// ActOnExpressionTrait - Parsed one of the unary type trait support 3108 /// pseudo-functions. 3109 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 3110 SourceLocation KWLoc, 3111 Expr *Queried, 3112 SourceLocation RParen); 3113 3114 ExprResult BuildExpressionTrait(ExpressionTrait OET, 3115 SourceLocation KWLoc, 3116 Expr *Queried, 3117 SourceLocation RParen); 3118 3119 ExprResult ActOnStartCXXMemberReference(Scope *S, 3120 Expr *Base, 3121 SourceLocation OpLoc, 3122 tok::TokenKind OpKind, 3123 ParsedType &ObjectType, 3124 bool &MayBePseudoDestructor); 3125 3126 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 3127 3128 ExprResult BuildPseudoDestructorExpr(Expr *Base, 3129 SourceLocation OpLoc, 3130 tok::TokenKind OpKind, 3131 const CXXScopeSpec &SS, 3132 TypeSourceInfo *ScopeType, 3133 SourceLocation CCLoc, 3134 SourceLocation TildeLoc, 3135 PseudoDestructorTypeStorage DestroyedType, 3136 bool HasTrailingLParen); 3137 3138 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3139 SourceLocation OpLoc, 3140 tok::TokenKind OpKind, 3141 CXXScopeSpec &SS, 3142 UnqualifiedId &FirstTypeName, 3143 SourceLocation CCLoc, 3144 SourceLocation TildeLoc, 3145 UnqualifiedId &SecondTypeName, 3146 bool HasTrailingLParen); 3147 3148 /// MaybeCreateExprWithCleanups - If the current full-expression 3149 /// requires any cleanups, surround it with a ExprWithCleanups node. 3150 /// Otherwise, just returns the passed-in expression. 3151 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 3152 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 3153 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 3154 3155 ExprResult ActOnFinishFullExpr(Expr *Expr); 3156 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 3157 3158 // Marks SS invalid if it represents an incomplete type. 3159 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 3160 3161 DeclContext *computeDeclContext(QualType T); 3162 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 3163 bool EnteringContext = false); 3164 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 3165 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 3166 bool isUnknownSpecialization(const CXXScopeSpec &SS); 3167 3168 /// \brief The parser has parsed a global nested-name-specifier '::'. 3169 /// 3170 /// \param S The scope in which this nested-name-specifier occurs. 3171 /// 3172 /// \param CCLoc The location of the '::'. 3173 /// 3174 /// \param SS The nested-name-specifier, which will be updated in-place 3175 /// to reflect the parsed nested-name-specifier. 3176 /// 3177 /// \returns true if an error occurred, false otherwise. 3178 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 3179 CXXScopeSpec &SS); 3180 3181 bool isAcceptableNestedNameSpecifier(NamedDecl *SD); 3182 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 3183 3184 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 3185 SourceLocation IdLoc, 3186 IdentifierInfo &II, 3187 ParsedType ObjectType); 3188 3189 bool BuildCXXNestedNameSpecifier(Scope *S, 3190 IdentifierInfo &Identifier, 3191 SourceLocation IdentifierLoc, 3192 SourceLocation CCLoc, 3193 QualType ObjectType, 3194 bool EnteringContext, 3195 CXXScopeSpec &SS, 3196 NamedDecl *ScopeLookupResult, 3197 bool ErrorRecoveryLookup); 3198 3199 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 3200 /// 3201 /// \param S The scope in which this nested-name-specifier occurs. 3202 /// 3203 /// \param Identifier The identifier preceding the '::'. 3204 /// 3205 /// \param IdentifierLoc The location of the identifier. 3206 /// 3207 /// \param CCLoc The location of the '::'. 3208 /// 3209 /// \param ObjectType The type of the object, if we're parsing 3210 /// nested-name-specifier in a member access expression. 3211 /// 3212 /// \param EnteringContext Whether we're entering the context nominated by 3213 /// this nested-name-specifier. 3214 /// 3215 /// \param SS The nested-name-specifier, which is both an input 3216 /// parameter (the nested-name-specifier before this type) and an 3217 /// output parameter (containing the full nested-name-specifier, 3218 /// including this new type). 3219 /// 3220 /// \returns true if an error occurred, false otherwise. 3221 bool ActOnCXXNestedNameSpecifier(Scope *S, 3222 IdentifierInfo &Identifier, 3223 SourceLocation IdentifierLoc, 3224 SourceLocation CCLoc, 3225 ParsedType ObjectType, 3226 bool EnteringContext, 3227 CXXScopeSpec &SS); 3228 3229 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 3230 IdentifierInfo &Identifier, 3231 SourceLocation IdentifierLoc, 3232 SourceLocation ColonLoc, 3233 ParsedType ObjectType, 3234 bool EnteringContext); 3235 3236 /// \brief The parser has parsed a nested-name-specifier 3237 /// 'template[opt] template-name < template-args >::'. 3238 /// 3239 /// \param S The scope in which this nested-name-specifier occurs. 3240 /// 3241 /// \param TemplateLoc The location of the 'template' keyword, if any. 3242 /// 3243 /// \param SS The nested-name-specifier, which is both an input 3244 /// parameter (the nested-name-specifier before this type) and an 3245 /// output parameter (containing the full nested-name-specifier, 3246 /// including this new type). 3247 /// 3248 /// \param TemplateLoc the location of the 'template' keyword, if any. 3249 /// \param TemplateName The template name. 3250 /// \param TemplateNameLoc The location of the template name. 3251 /// \param LAngleLoc The location of the opening angle bracket ('<'). 3252 /// \param TemplateArgs The template arguments. 3253 /// \param RAngleLoc The location of the closing angle bracket ('>'). 3254 /// \param CCLoc The location of the '::'. 3255 3256 /// \param EnteringContext Whether we're entering the context of the 3257 /// nested-name-specifier. 3258 /// 3259 /// 3260 /// \returns true if an error occurred, false otherwise. 3261 bool ActOnCXXNestedNameSpecifier(Scope *S, 3262 SourceLocation TemplateLoc, 3263 CXXScopeSpec &SS, 3264 TemplateTy Template, 3265 SourceLocation TemplateNameLoc, 3266 SourceLocation LAngleLoc, 3267 ASTTemplateArgsPtr TemplateArgs, 3268 SourceLocation RAngleLoc, 3269 SourceLocation CCLoc, 3270 bool EnteringContext); 3271 3272 /// \brief Given a C++ nested-name-specifier, produce an annotation value 3273 /// that the parser can use later to reconstruct the given 3274 /// nested-name-specifier. 3275 /// 3276 /// \param SS A nested-name-specifier. 3277 /// 3278 /// \returns A pointer containing all of the information in the 3279 /// nested-name-specifier \p SS. 3280 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 3281 3282 /// \brief Given an annotation pointer for a nested-name-specifier, restore 3283 /// the nested-name-specifier structure. 3284 /// 3285 /// \param Annotation The annotation pointer, produced by 3286 /// \c SaveNestedNameSpecifierAnnotation(). 3287 /// 3288 /// \param AnnotationRange The source range corresponding to the annotation. 3289 /// 3290 /// \param SS The nested-name-specifier that will be updated with the contents 3291 /// of the annotation pointer. 3292 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 3293 SourceRange AnnotationRange, 3294 CXXScopeSpec &SS); 3295 3296 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3297 3298 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 3299 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 3300 /// After this method is called, according to [C++ 3.4.3p3], names should be 3301 /// looked up in the declarator-id's scope, until the declarator is parsed and 3302 /// ActOnCXXExitDeclaratorScope is called. 3303 /// The 'SS' should be a non-empty valid CXXScopeSpec. 3304 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 3305 3306 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 3307 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 3308 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 3309 /// Used to indicate that names should revert to being looked up in the 3310 /// defining scope. 3311 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3312 3313 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 3314 /// initializer for the declaration 'Dcl'. 3315 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 3316 /// static data member of class X, names should be looked up in the scope of 3317 /// class X. 3318 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 3319 3320 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 3321 /// initializer for the declaration 'Dcl'. 3322 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 3323 3324 // ParseObjCStringLiteral - Parse Objective-C string literals. 3325 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 3326 Expr **Strings, 3327 unsigned NumStrings); 3328 3329 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 3330 TypeSourceInfo *EncodedTypeInfo, 3331 SourceLocation RParenLoc); 3332 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 3333 CXXMethodDecl *Method); 3334 3335 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 3336 SourceLocation EncodeLoc, 3337 SourceLocation LParenLoc, 3338 ParsedType Ty, 3339 SourceLocation RParenLoc); 3340 3341 // ParseObjCSelectorExpression - Build selector expression for @selector 3342 ExprResult ParseObjCSelectorExpression(Selector Sel, 3343 SourceLocation AtLoc, 3344 SourceLocation SelLoc, 3345 SourceLocation LParenLoc, 3346 SourceLocation RParenLoc); 3347 3348 // ParseObjCProtocolExpression - Build protocol expression for @protocol 3349 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 3350 SourceLocation AtLoc, 3351 SourceLocation ProtoLoc, 3352 SourceLocation LParenLoc, 3353 SourceLocation RParenLoc); 3354 3355 //===--------------------------------------------------------------------===// 3356 // C++ Declarations 3357 // 3358 Decl *ActOnStartLinkageSpecification(Scope *S, 3359 SourceLocation ExternLoc, 3360 SourceLocation LangLoc, 3361 StringRef Lang, 3362 SourceLocation LBraceLoc); 3363 Decl *ActOnFinishLinkageSpecification(Scope *S, 3364 Decl *LinkageSpec, 3365 SourceLocation RBraceLoc); 3366 3367 3368 //===--------------------------------------------------------------------===// 3369 // C++ Classes 3370 // 3371 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 3372 const CXXScopeSpec *SS = 0); 3373 3374 Decl *ActOnAccessSpecifier(AccessSpecifier Access, 3375 SourceLocation ASLoc, 3376 SourceLocation ColonLoc); 3377 3378 Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 3379 Declarator &D, 3380 MultiTemplateParamsArg TemplateParameterLists, 3381 Expr *BitfieldWidth, const VirtSpecifiers &VS, 3382 Expr *Init, bool HasDeferredInit, 3383 bool IsDefinition); 3384 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, 3385 Expr *Init); 3386 3387 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 3388 Scope *S, 3389 CXXScopeSpec &SS, 3390 IdentifierInfo *MemberOrBase, 3391 ParsedType TemplateTypeTy, 3392 SourceLocation IdLoc, 3393 SourceLocation LParenLoc, 3394 Expr **Args, unsigned NumArgs, 3395 SourceLocation RParenLoc, 3396 SourceLocation EllipsisLoc); 3397 3398 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr **Args, 3399 unsigned NumArgs, SourceLocation IdLoc, 3400 SourceLocation LParenLoc, 3401 SourceLocation RParenLoc); 3402 3403 MemInitResult BuildBaseInitializer(QualType BaseType, 3404 TypeSourceInfo *BaseTInfo, 3405 Expr **Args, unsigned NumArgs, 3406 SourceLocation LParenLoc, 3407 SourceLocation RParenLoc, 3408 CXXRecordDecl *ClassDecl, 3409 SourceLocation EllipsisLoc); 3410 3411 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 3412 Expr **Args, unsigned NumArgs, 3413 SourceLocation BaseLoc, 3414 SourceLocation RParenLoc, 3415 SourceLocation LParenLoc, 3416 CXXRecordDecl *ClassDecl); 3417 3418 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3419 CXXCtorInitializer *Initializer); 3420 3421 bool SetCtorInitializers(CXXConstructorDecl *Constructor, 3422 CXXCtorInitializer **Initializers, 3423 unsigned NumInitializers, bool AnyErrors); 3424 3425 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 3426 3427 3428 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 3429 /// mark all the non-trivial destructors of its members and bases as 3430 /// referenced. 3431 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 3432 CXXRecordDecl *Record); 3433 3434 /// \brief The list of classes whose vtables have been used within 3435 /// this translation unit, and the source locations at which the 3436 /// first use occurred. 3437 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 3438 3439 /// \brief The list of vtables that are required but have not yet been 3440 /// materialized. 3441 SmallVector<VTableUse, 16> VTableUses; 3442 3443 /// \brief The set of classes whose vtables have been used within 3444 /// this translation unit, and a bit that will be true if the vtable is 3445 /// required to be emitted (otherwise, it should be emitted only if needed 3446 /// by code generation). 3447 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 3448 3449 /// \brief Load any externally-stored vtable uses. 3450 void LoadExternalVTableUses(); 3451 3452 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, 3453 &ExternalSemaSource::ReadDynamicClasses, 2, 2> 3454 DynamicClassesType; 3455 3456 /// \brief A list of all of the dynamic classes in this translation 3457 /// unit. 3458 DynamicClassesType DynamicClasses; 3459 3460 /// \brief Note that the vtable for the given class was used at the 3461 /// given location. 3462 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 3463 bool DefinitionRequired = false); 3464 3465 /// MarkVirtualMembersReferenced - Will mark all members of the given 3466 /// CXXRecordDecl referenced. 3467 void MarkVirtualMembersReferenced(SourceLocation Loc, 3468 const CXXRecordDecl *RD); 3469 3470 /// \brief Define all of the vtables that have been used in this 3471 /// translation unit and reference any virtual members used by those 3472 /// vtables. 3473 /// 3474 /// \returns true if any work was done, false otherwise. 3475 bool DefineUsedVTables(); 3476 3477 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 3478 3479 void ActOnMemInitializers(Decl *ConstructorDecl, 3480 SourceLocation ColonLoc, 3481 CXXCtorInitializer **MemInits, 3482 unsigned NumMemInits, 3483 bool AnyErrors); 3484 3485 void CheckCompletedCXXClass(CXXRecordDecl *Record); 3486 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 3487 Decl *TagDecl, 3488 SourceLocation LBrac, 3489 SourceLocation RBrac, 3490 AttributeList *AttrList); 3491 3492 void ActOnReenterTemplateScope(Scope *S, Decl *Template); 3493 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D); 3494 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 3495 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 3496 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 3497 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 3498 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 3499 void ActOnFinishDelayedMemberInitializers(Decl *Record); 3500 void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true); 3501 bool IsInsideALocalClassWithinATemplateFunction(); 3502 3503 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 3504 Expr *AssertExpr, 3505 Expr *AssertMessageExpr, 3506 SourceLocation RParenLoc); 3507 3508 FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc, 3509 TypeSourceInfo *TSInfo); 3510 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 3511 MultiTemplateParamsArg TemplateParams); 3512 Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 3513 MultiTemplateParamsArg TemplateParams); 3514 3515 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 3516 StorageClass& SC); 3517 void CheckConstructor(CXXConstructorDecl *Constructor); 3518 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 3519 StorageClass& SC); 3520 bool CheckDestructor(CXXDestructorDecl *Destructor); 3521 void CheckConversionDeclarator(Declarator &D, QualType &R, 3522 StorageClass& SC); 3523 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 3524 3525 void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record); 3526 void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor); 3527 void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor); 3528 void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method); 3529 void CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *Ctor); 3530 void CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *Method); 3531 void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor); 3532 3533 //===--------------------------------------------------------------------===// 3534 // C++ Derived Classes 3535 // 3536 3537 /// ActOnBaseSpecifier - Parsed a base specifier 3538 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 3539 SourceRange SpecifierRange, 3540 bool Virtual, AccessSpecifier Access, 3541 TypeSourceInfo *TInfo, 3542 SourceLocation EllipsisLoc); 3543 3544 BaseResult ActOnBaseSpecifier(Decl *classdecl, 3545 SourceRange SpecifierRange, 3546 bool Virtual, AccessSpecifier Access, 3547 ParsedType basetype, 3548 SourceLocation BaseLoc, 3549 SourceLocation EllipsisLoc); 3550 3551 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 3552 unsigned NumBases); 3553 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 3554 unsigned NumBases); 3555 3556 bool IsDerivedFrom(QualType Derived, QualType Base); 3557 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 3558 3559 // FIXME: I don't like this name. 3560 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 3561 3562 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 3563 3564 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3565 SourceLocation Loc, SourceRange Range, 3566 CXXCastPath *BasePath = 0, 3567 bool IgnoreAccess = false); 3568 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3569 unsigned InaccessibleBaseID, 3570 unsigned AmbigiousBaseConvID, 3571 SourceLocation Loc, SourceRange Range, 3572 DeclarationName Name, 3573 CXXCastPath *BasePath); 3574 3575 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 3576 3577 /// CheckOverridingFunctionReturnType - Checks whether the return types are 3578 /// covariant, according to C++ [class.virtual]p5. 3579 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 3580 const CXXMethodDecl *Old); 3581 3582 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 3583 /// spec is a subset of base spec. 3584 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 3585 const CXXMethodDecl *Old); 3586 3587 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 3588 3589 /// CheckOverrideControl - Check C++0x override control semantics. 3590 void CheckOverrideControl(const Decl *D); 3591 3592 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 3593 /// overrides a virtual member function marked 'final', according to 3594 /// C++0x [class.virtual]p3. 3595 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3596 const CXXMethodDecl *Old); 3597 3598 3599 //===--------------------------------------------------------------------===// 3600 // C++ Access Control 3601 // 3602 3603 enum AccessResult { 3604 AR_accessible, 3605 AR_inaccessible, 3606 AR_dependent, 3607 AR_delayed 3608 }; 3609 3610 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 3611 NamedDecl *PrevMemberDecl, 3612 AccessSpecifier LexicalAS); 3613 3614 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 3615 DeclAccessPair FoundDecl); 3616 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 3617 DeclAccessPair FoundDecl); 3618 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 3619 SourceRange PlacementRange, 3620 CXXRecordDecl *NamingClass, 3621 DeclAccessPair FoundDecl, 3622 bool Diagnose = true); 3623 AccessResult CheckConstructorAccess(SourceLocation Loc, 3624 CXXConstructorDecl *D, 3625 const InitializedEntity &Entity, 3626 AccessSpecifier Access, 3627 bool IsCopyBindingRefToTemp = false); 3628 AccessResult CheckConstructorAccess(SourceLocation Loc, 3629 CXXConstructorDecl *D, 3630 AccessSpecifier Access, 3631 PartialDiagnostic PD); 3632 AccessResult CheckDestructorAccess(SourceLocation Loc, 3633 CXXDestructorDecl *Dtor, 3634 const PartialDiagnostic &PDiag); 3635 AccessResult CheckDirectMemberAccess(SourceLocation Loc, 3636 NamedDecl *D, 3637 const PartialDiagnostic &PDiag); 3638 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 3639 Expr *ObjectExpr, 3640 Expr *ArgExpr, 3641 DeclAccessPair FoundDecl); 3642 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 3643 DeclAccessPair FoundDecl); 3644 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 3645 QualType Base, QualType Derived, 3646 const CXXBasePath &Path, 3647 unsigned DiagID, 3648 bool ForceCheck = false, 3649 bool ForceUnprivileged = false); 3650 void CheckLookupAccess(const LookupResult &R); 3651 3652 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 3653 const MultiLevelTemplateArgumentList &TemplateArgs); 3654 void PerformDependentDiagnostics(const DeclContext *Pattern, 3655 const MultiLevelTemplateArgumentList &TemplateArgs); 3656 3657 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 3658 3659 /// A flag to suppress access checking. 3660 bool SuppressAccessChecking; 3661 3662 /// \brief When true, access checking violations are treated as SFINAE 3663 /// failures rather than hard errors. 3664 bool AccessCheckingSFINAE; 3665 3666 void ActOnStartSuppressingAccessChecks(); 3667 void ActOnStopSuppressingAccessChecks(); 3668 3669 enum AbstractDiagSelID { 3670 AbstractNone = -1, 3671 AbstractReturnType, 3672 AbstractParamType, 3673 AbstractVariableType, 3674 AbstractFieldType, 3675 AbstractArrayType 3676 }; 3677 3678 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 3679 const PartialDiagnostic &PD); 3680 void DiagnoseAbstractType(const CXXRecordDecl *RD); 3681 3682 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 3683 AbstractDiagSelID SelID = AbstractNone); 3684 3685 //===--------------------------------------------------------------------===// 3686 // C++ Overloaded Operators [C++ 13.5] 3687 // 3688 3689 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 3690 3691 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 3692 3693 //===--------------------------------------------------------------------===// 3694 // C++ Templates [C++ 14] 3695 // 3696 void FilterAcceptableTemplateNames(LookupResult &R); 3697 bool hasAnyAcceptableTemplateNames(LookupResult &R); 3698 3699 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 3700 QualType ObjectType, bool EnteringContext, 3701 bool &MemberOfUnknownSpecialization); 3702 3703 TemplateNameKind isTemplateName(Scope *S, 3704 CXXScopeSpec &SS, 3705 bool hasTemplateKeyword, 3706 UnqualifiedId &Name, 3707 ParsedType ObjectType, 3708 bool EnteringContext, 3709 TemplateTy &Template, 3710 bool &MemberOfUnknownSpecialization); 3711 3712 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 3713 SourceLocation IILoc, 3714 Scope *S, 3715 const CXXScopeSpec *SS, 3716 TemplateTy &SuggestedTemplate, 3717 TemplateNameKind &SuggestedKind); 3718 3719 bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 3720 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 3721 3722 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 3723 SourceLocation EllipsisLoc, 3724 SourceLocation KeyLoc, 3725 IdentifierInfo *ParamName, 3726 SourceLocation ParamNameLoc, 3727 unsigned Depth, unsigned Position, 3728 SourceLocation EqualLoc, 3729 ParsedType DefaultArg); 3730 3731 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 3732 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 3733 unsigned Depth, 3734 unsigned Position, 3735 SourceLocation EqualLoc, 3736 Expr *DefaultArg); 3737 Decl *ActOnTemplateTemplateParameter(Scope *S, 3738 SourceLocation TmpLoc, 3739 TemplateParameterList *Params, 3740 SourceLocation EllipsisLoc, 3741 IdentifierInfo *ParamName, 3742 SourceLocation ParamNameLoc, 3743 unsigned Depth, 3744 unsigned Position, 3745 SourceLocation EqualLoc, 3746 ParsedTemplateArgument DefaultArg); 3747 3748 TemplateParameterList * 3749 ActOnTemplateParameterList(unsigned Depth, 3750 SourceLocation ExportLoc, 3751 SourceLocation TemplateLoc, 3752 SourceLocation LAngleLoc, 3753 Decl **Params, unsigned NumParams, 3754 SourceLocation RAngleLoc); 3755 3756 /// \brief The context in which we are checking a template parameter 3757 /// list. 3758 enum TemplateParamListContext { 3759 TPC_ClassTemplate, 3760 TPC_FunctionTemplate, 3761 TPC_ClassTemplateMember, 3762 TPC_FriendFunctionTemplate, 3763 TPC_FriendFunctionTemplateDefinition, 3764 TPC_TypeAliasTemplate 3765 }; 3766 3767 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 3768 TemplateParameterList *OldParams, 3769 TemplateParamListContext TPC); 3770 TemplateParameterList * 3771 MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 3772 SourceLocation DeclLoc, 3773 const CXXScopeSpec &SS, 3774 TemplateParameterList **ParamLists, 3775 unsigned NumParamLists, 3776 bool IsFriend, 3777 bool &IsExplicitSpecialization, 3778 bool &Invalid); 3779 3780 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 3781 SourceLocation KWLoc, CXXScopeSpec &SS, 3782 IdentifierInfo *Name, SourceLocation NameLoc, 3783 AttributeList *Attr, 3784 TemplateParameterList *TemplateParams, 3785 AccessSpecifier AS, 3786 SourceLocation ModulePrivateLoc, 3787 unsigned NumOuterTemplateParamLists, 3788 TemplateParameterList **OuterTemplateParamLists); 3789 3790 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 3791 TemplateArgumentListInfo &Out); 3792 3793 void NoteAllFoundTemplates(TemplateName Name); 3794 3795 QualType CheckTemplateIdType(TemplateName Template, 3796 SourceLocation TemplateLoc, 3797 TemplateArgumentListInfo &TemplateArgs); 3798 3799 TypeResult 3800 ActOnTemplateIdType(CXXScopeSpec &SS, 3801 TemplateTy Template, SourceLocation TemplateLoc, 3802 SourceLocation LAngleLoc, 3803 ASTTemplateArgsPtr TemplateArgs, 3804 SourceLocation RAngleLoc); 3805 3806 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 3807 /// such as \c class T::template apply<U>. 3808 /// 3809 /// \param TUK 3810 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 3811 TypeSpecifierType TagSpec, 3812 SourceLocation TagLoc, 3813 CXXScopeSpec &SS, 3814 TemplateTy TemplateD, 3815 SourceLocation TemplateLoc, 3816 SourceLocation LAngleLoc, 3817 ASTTemplateArgsPtr TemplateArgsIn, 3818 SourceLocation RAngleLoc); 3819 3820 3821 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 3822 LookupResult &R, 3823 bool RequiresADL, 3824 const TemplateArgumentListInfo &TemplateArgs); 3825 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 3826 const DeclarationNameInfo &NameInfo, 3827 const TemplateArgumentListInfo &TemplateArgs); 3828 3829 TemplateNameKind ActOnDependentTemplateName(Scope *S, 3830 SourceLocation TemplateKWLoc, 3831 CXXScopeSpec &SS, 3832 UnqualifiedId &Name, 3833 ParsedType ObjectType, 3834 bool EnteringContext, 3835 TemplateTy &Template); 3836 3837 DeclResult 3838 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 3839 SourceLocation KWLoc, 3840 SourceLocation ModulePrivateLoc, 3841 CXXScopeSpec &SS, 3842 TemplateTy Template, 3843 SourceLocation TemplateNameLoc, 3844 SourceLocation LAngleLoc, 3845 ASTTemplateArgsPtr TemplateArgs, 3846 SourceLocation RAngleLoc, 3847 AttributeList *Attr, 3848 MultiTemplateParamsArg TemplateParameterLists); 3849 3850 Decl *ActOnTemplateDeclarator(Scope *S, 3851 MultiTemplateParamsArg TemplateParameterLists, 3852 Declarator &D); 3853 3854 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 3855 MultiTemplateParamsArg TemplateParameterLists, 3856 Declarator &D); 3857 3858 bool 3859 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 3860 TemplateSpecializationKind NewTSK, 3861 NamedDecl *PrevDecl, 3862 TemplateSpecializationKind PrevTSK, 3863 SourceLocation PrevPtOfInstantiation, 3864 bool &SuppressNew); 3865 3866 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 3867 const TemplateArgumentListInfo &ExplicitTemplateArgs, 3868 LookupResult &Previous); 3869 3870 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 3871 TemplateArgumentListInfo *ExplicitTemplateArgs, 3872 LookupResult &Previous); 3873 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 3874 3875 DeclResult 3876 ActOnExplicitInstantiation(Scope *S, 3877 SourceLocation ExternLoc, 3878 SourceLocation TemplateLoc, 3879 unsigned TagSpec, 3880 SourceLocation KWLoc, 3881 const CXXScopeSpec &SS, 3882 TemplateTy Template, 3883 SourceLocation TemplateNameLoc, 3884 SourceLocation LAngleLoc, 3885 ASTTemplateArgsPtr TemplateArgs, 3886 SourceLocation RAngleLoc, 3887 AttributeList *Attr); 3888 3889 DeclResult 3890 ActOnExplicitInstantiation(Scope *S, 3891 SourceLocation ExternLoc, 3892 SourceLocation TemplateLoc, 3893 unsigned TagSpec, 3894 SourceLocation KWLoc, 3895 CXXScopeSpec &SS, 3896 IdentifierInfo *Name, 3897 SourceLocation NameLoc, 3898 AttributeList *Attr); 3899 3900 DeclResult ActOnExplicitInstantiation(Scope *S, 3901 SourceLocation ExternLoc, 3902 SourceLocation TemplateLoc, 3903 Declarator &D); 3904 3905 TemplateArgumentLoc 3906 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 3907 SourceLocation TemplateLoc, 3908 SourceLocation RAngleLoc, 3909 Decl *Param, 3910 SmallVectorImpl<TemplateArgument> &Converted); 3911 3912 /// \brief Specifies the context in which a particular template 3913 /// argument is being checked. 3914 enum CheckTemplateArgumentKind { 3915 /// \brief The template argument was specified in the code or was 3916 /// instantiated with some deduced template arguments. 3917 CTAK_Specified, 3918 3919 /// \brief The template argument was deduced via template argument 3920 /// deduction. 3921 CTAK_Deduced, 3922 3923 /// \brief The template argument was deduced from an array bound 3924 /// via template argument deduction. 3925 CTAK_DeducedFromArrayBound 3926 }; 3927 3928 bool CheckTemplateArgument(NamedDecl *Param, 3929 const TemplateArgumentLoc &Arg, 3930 NamedDecl *Template, 3931 SourceLocation TemplateLoc, 3932 SourceLocation RAngleLoc, 3933 unsigned ArgumentPackIndex, 3934 SmallVectorImpl<TemplateArgument> &Converted, 3935 CheckTemplateArgumentKind CTAK = CTAK_Specified); 3936 3937 /// \brief Check that the given template arguments can be be provided to 3938 /// the given template, converting the arguments along the way. 3939 /// 3940 /// \param Template The template to which the template arguments are being 3941 /// provided. 3942 /// 3943 /// \param TemplateLoc The location of the template name in the source. 3944 /// 3945 /// \param TemplateArgs The list of template arguments. If the template is 3946 /// a template template parameter, this function may extend the set of 3947 /// template arguments to also include substituted, defaulted template 3948 /// arguments. 3949 /// 3950 /// \param PartialTemplateArgs True if the list of template arguments is 3951 /// intentionally partial, e.g., because we're checking just the initial 3952 /// set of template arguments. 3953 /// 3954 /// \param Converted Will receive the converted, canonicalized template 3955 /// arguments. 3956 /// 3957 /// \returns True if an error occurred, false otherwise. 3958 bool CheckTemplateArgumentList(TemplateDecl *Template, 3959 SourceLocation TemplateLoc, 3960 TemplateArgumentListInfo &TemplateArgs, 3961 bool PartialTemplateArgs, 3962 SmallVectorImpl<TemplateArgument> &Converted); 3963 3964 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 3965 const TemplateArgumentLoc &Arg, 3966 SmallVectorImpl<TemplateArgument> &Converted); 3967 3968 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 3969 TypeSourceInfo *Arg); 3970 bool CheckTemplateArgumentPointerToMember(Expr *Arg, 3971 TemplateArgument &Converted); 3972 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 3973 QualType InstantiatedParamType, Expr *Arg, 3974 TemplateArgument &Converted, 3975 CheckTemplateArgumentKind CTAK = CTAK_Specified); 3976 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 3977 const TemplateArgumentLoc &Arg); 3978 3979 ExprResult 3980 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 3981 QualType ParamType, 3982 SourceLocation Loc); 3983 ExprResult 3984 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 3985 SourceLocation Loc); 3986 3987 /// \brief Enumeration describing how template parameter lists are compared 3988 /// for equality. 3989 enum TemplateParameterListEqualKind { 3990 /// \brief We are matching the template parameter lists of two templates 3991 /// that might be redeclarations. 3992 /// 3993 /// \code 3994 /// template<typename T> struct X; 3995 /// template<typename T> struct X; 3996 /// \endcode 3997 TPL_TemplateMatch, 3998 3999 /// \brief We are matching the template parameter lists of two template 4000 /// template parameters as part of matching the template parameter lists 4001 /// of two templates that might be redeclarations. 4002 /// 4003 /// \code 4004 /// template<template<int I> class TT> struct X; 4005 /// template<template<int Value> class Other> struct X; 4006 /// \endcode 4007 TPL_TemplateTemplateParmMatch, 4008 4009 /// \brief We are matching the template parameter lists of a template 4010 /// template argument against the template parameter lists of a template 4011 /// template parameter. 4012 /// 4013 /// \code 4014 /// template<template<int Value> class Metafun> struct X; 4015 /// template<int Value> struct integer_c; 4016 /// X<integer_c> xic; 4017 /// \endcode 4018 TPL_TemplateTemplateArgumentMatch 4019 }; 4020 4021 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 4022 TemplateParameterList *Old, 4023 bool Complain, 4024 TemplateParameterListEqualKind Kind, 4025 SourceLocation TemplateArgLoc 4026 = SourceLocation()); 4027 4028 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 4029 4030 /// \brief Called when the parser has parsed a C++ typename 4031 /// specifier, e.g., "typename T::type". 4032 /// 4033 /// \param S The scope in which this typename type occurs. 4034 /// \param TypenameLoc the location of the 'typename' keyword 4035 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4036 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 4037 /// \param IdLoc the location of the identifier. 4038 TypeResult 4039 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4040 const CXXScopeSpec &SS, const IdentifierInfo &II, 4041 SourceLocation IdLoc); 4042 4043 /// \brief Called when the parser has parsed a C++ typename 4044 /// specifier that ends in a template-id, e.g., 4045 /// "typename MetaFun::template apply<T1, T2>". 4046 /// 4047 /// \param S The scope in which this typename type occurs. 4048 /// \param TypenameLoc the location of the 'typename' keyword 4049 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4050 /// \param TemplateLoc the location of the 'template' keyword, if any. 4051 /// \param TemplateName The template name. 4052 /// \param TemplateNameLoc The location of the template name. 4053 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4054 /// \param TemplateArgs The template arguments. 4055 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4056 TypeResult 4057 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4058 const CXXScopeSpec &SS, 4059 SourceLocation TemplateLoc, 4060 TemplateTy Template, 4061 SourceLocation TemplateNameLoc, 4062 SourceLocation LAngleLoc, 4063 ASTTemplateArgsPtr TemplateArgs, 4064 SourceLocation RAngleLoc); 4065 4066 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 4067 SourceLocation KeywordLoc, 4068 NestedNameSpecifierLoc QualifierLoc, 4069 const IdentifierInfo &II, 4070 SourceLocation IILoc); 4071 4072 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 4073 SourceLocation Loc, 4074 DeclarationName Name); 4075 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 4076 4077 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 4078 4079 std::string 4080 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4081 const TemplateArgumentList &Args); 4082 4083 std::string 4084 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4085 const TemplateArgument *Args, 4086 unsigned NumArgs); 4087 4088 //===--------------------------------------------------------------------===// 4089 // C++ Variadic Templates (C++0x [temp.variadic]) 4090 //===--------------------------------------------------------------------===// 4091 4092 /// \brief The context in which an unexpanded parameter pack is 4093 /// being diagnosed. 4094 /// 4095 /// Note that the values of this enumeration line up with the first 4096 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 4097 enum UnexpandedParameterPackContext { 4098 /// \brief An arbitrary expression. 4099 UPPC_Expression = 0, 4100 4101 /// \brief The base type of a class type. 4102 UPPC_BaseType, 4103 4104 /// \brief The type of an arbitrary declaration. 4105 UPPC_DeclarationType, 4106 4107 /// \brief The type of a data member. 4108 UPPC_DataMemberType, 4109 4110 /// \brief The size of a bit-field. 4111 UPPC_BitFieldWidth, 4112 4113 /// \brief The expression in a static assertion. 4114 UPPC_StaticAssertExpression, 4115 4116 /// \brief The fixed underlying type of an enumeration. 4117 UPPC_FixedUnderlyingType, 4118 4119 /// \brief The enumerator value. 4120 UPPC_EnumeratorValue, 4121 4122 /// \brief A using declaration. 4123 UPPC_UsingDeclaration, 4124 4125 /// \brief A friend declaration. 4126 UPPC_FriendDeclaration, 4127 4128 /// \brief A declaration qualifier. 4129 UPPC_DeclarationQualifier, 4130 4131 /// \brief An initializer. 4132 UPPC_Initializer, 4133 4134 /// \brief A default argument. 4135 UPPC_DefaultArgument, 4136 4137 /// \brief The type of a non-type template parameter. 4138 UPPC_NonTypeTemplateParameterType, 4139 4140 /// \brief The type of an exception. 4141 UPPC_ExceptionType, 4142 4143 /// \brief Partial specialization. 4144 UPPC_PartialSpecialization 4145 }; 4146 4147 /// \brief If the given type contains an unexpanded parameter pack, 4148 /// diagnose the error. 4149 /// 4150 /// \param Loc The source location where a diagnostc should be emitted. 4151 /// 4152 /// \param T The type that is being checked for unexpanded parameter 4153 /// packs. 4154 /// 4155 /// \returns true if an error occurred, false otherwise. 4156 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 4157 UnexpandedParameterPackContext UPPC); 4158 4159 /// \brief If the given expression contains an unexpanded parameter 4160 /// pack, diagnose the error. 4161 /// 4162 /// \param E The expression that is being checked for unexpanded 4163 /// parameter packs. 4164 /// 4165 /// \returns true if an error occurred, false otherwise. 4166 bool DiagnoseUnexpandedParameterPack(Expr *E, 4167 UnexpandedParameterPackContext UPPC = UPPC_Expression); 4168 4169 /// \brief If the given nested-name-specifier contains an unexpanded 4170 /// parameter pack, diagnose the error. 4171 /// 4172 /// \param SS The nested-name-specifier that is being checked for 4173 /// unexpanded parameter packs. 4174 /// 4175 /// \returns true if an error occurred, false otherwise. 4176 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 4177 UnexpandedParameterPackContext UPPC); 4178 4179 /// \brief If the given name contains an unexpanded parameter pack, 4180 /// diagnose the error. 4181 /// 4182 /// \param NameInfo The name (with source location information) that 4183 /// is being checked for unexpanded parameter packs. 4184 /// 4185 /// \returns true if an error occurred, false otherwise. 4186 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 4187 UnexpandedParameterPackContext UPPC); 4188 4189 /// \brief If the given template name contains an unexpanded parameter pack, 4190 /// diagnose the error. 4191 /// 4192 /// \param Loc The location of the template name. 4193 /// 4194 /// \param Template The template name that is being checked for unexpanded 4195 /// parameter packs. 4196 /// 4197 /// \returns true if an error occurred, false otherwise. 4198 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 4199 TemplateName Template, 4200 UnexpandedParameterPackContext UPPC); 4201 4202 /// \brief If the given template argument contains an unexpanded parameter 4203 /// pack, diagnose the error. 4204 /// 4205 /// \param Arg The template argument that is being checked for unexpanded 4206 /// parameter packs. 4207 /// 4208 /// \returns true if an error occurred, false otherwise. 4209 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 4210 UnexpandedParameterPackContext UPPC); 4211 4212 /// \brief Collect the set of unexpanded parameter packs within the given 4213 /// template argument. 4214 /// 4215 /// \param Arg The template argument that will be traversed to find 4216 /// unexpanded parameter packs. 4217 void collectUnexpandedParameterPacks(TemplateArgument Arg, 4218 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 4219 4220 /// \brief Collect the set of unexpanded parameter packs within the given 4221 /// template argument. 4222 /// 4223 /// \param Arg The template argument that will be traversed to find 4224 /// unexpanded parameter packs. 4225 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 4226 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 4227 4228 /// \brief Collect the set of unexpanded parameter packs within the given 4229 /// type. 4230 /// 4231 /// \param T The type that will be traversed to find 4232 /// unexpanded parameter packs. 4233 void collectUnexpandedParameterPacks(QualType T, 4234 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 4235 4236 /// \brief Collect the set of unexpanded parameter packs within the given 4237 /// type. 4238 /// 4239 /// \param TL The type that will be traversed to find 4240 /// unexpanded parameter packs. 4241 void collectUnexpandedParameterPacks(TypeLoc TL, 4242 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 4243 4244 /// \brief Invoked when parsing a template argument followed by an 4245 /// ellipsis, which creates a pack expansion. 4246 /// 4247 /// \param Arg The template argument preceding the ellipsis, which 4248 /// may already be invalid. 4249 /// 4250 /// \param EllipsisLoc The location of the ellipsis. 4251 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 4252 SourceLocation EllipsisLoc); 4253 4254 /// \brief Invoked when parsing a type followed by an ellipsis, which 4255 /// creates a pack expansion. 4256 /// 4257 /// \param Type The type preceding the ellipsis, which will become 4258 /// the pattern of the pack expansion. 4259 /// 4260 /// \param EllipsisLoc The location of the ellipsis. 4261 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 4262 4263 /// \brief Construct a pack expansion type from the pattern of the pack 4264 /// expansion. 4265 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 4266 SourceLocation EllipsisLoc, 4267 llvm::Optional<unsigned> NumExpansions); 4268 4269 /// \brief Construct a pack expansion type from the pattern of the pack 4270 /// expansion. 4271 QualType CheckPackExpansion(QualType Pattern, 4272 SourceRange PatternRange, 4273 SourceLocation EllipsisLoc, 4274 llvm::Optional<unsigned> NumExpansions); 4275 4276 /// \brief Invoked when parsing an expression followed by an ellipsis, which 4277 /// creates a pack expansion. 4278 /// 4279 /// \param Pattern The expression preceding the ellipsis, which will become 4280 /// the pattern of the pack expansion. 4281 /// 4282 /// \param EllipsisLoc The location of the ellipsis. 4283 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 4284 4285 /// \brief Invoked when parsing an expression followed by an ellipsis, which 4286 /// creates a pack expansion. 4287 /// 4288 /// \param Pattern The expression preceding the ellipsis, which will become 4289 /// the pattern of the pack expansion. 4290 /// 4291 /// \param EllipsisLoc The location of the ellipsis. 4292 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 4293 llvm::Optional<unsigned> NumExpansions); 4294 4295 /// \brief Determine whether we could expand a pack expansion with the 4296 /// given set of parameter packs into separate arguments by repeatedly 4297 /// transforming the pattern. 4298 /// 4299 /// \param EllipsisLoc The location of the ellipsis that identifies the 4300 /// pack expansion. 4301 /// 4302 /// \param PatternRange The source range that covers the entire pattern of 4303 /// the pack expansion. 4304 /// 4305 /// \param Unexpanded The set of unexpanded parameter packs within the 4306 /// pattern. 4307 /// 4308 /// \param NumUnexpanded The number of unexpanded parameter packs in 4309 /// \p Unexpanded. 4310 /// 4311 /// \param ShouldExpand Will be set to \c true if the transformer should 4312 /// expand the corresponding pack expansions into separate arguments. When 4313 /// set, \c NumExpansions must also be set. 4314 /// 4315 /// \param RetainExpansion Whether the caller should add an unexpanded 4316 /// pack expansion after all of the expanded arguments. This is used 4317 /// when extending explicitly-specified template argument packs per 4318 /// C++0x [temp.arg.explicit]p9. 4319 /// 4320 /// \param NumExpansions The number of separate arguments that will be in 4321 /// the expanded form of the corresponding pack expansion. This is both an 4322 /// input and an output parameter, which can be set by the caller if the 4323 /// number of expansions is known a priori (e.g., due to a prior substitution) 4324 /// and will be set by the callee when the number of expansions is known. 4325 /// The callee must set this value when \c ShouldExpand is \c true; it may 4326 /// set this value in other cases. 4327 /// 4328 /// \returns true if an error occurred (e.g., because the parameter packs 4329 /// are to be instantiated with arguments of different lengths), false 4330 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 4331 /// must be set. 4332 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 4333 SourceRange PatternRange, 4334 const UnexpandedParameterPack *Unexpanded, 4335 unsigned NumUnexpanded, 4336 const MultiLevelTemplateArgumentList &TemplateArgs, 4337 bool &ShouldExpand, 4338 bool &RetainExpansion, 4339 llvm::Optional<unsigned> &NumExpansions); 4340 4341 /// \brief Determine the number of arguments in the given pack expansion 4342 /// type. 4343 /// 4344 /// This routine already assumes that the pack expansion type can be 4345 /// expanded and that the number of arguments in the expansion is 4346 /// consistent across all of the unexpanded parameter packs in its pattern. 4347 unsigned getNumArgumentsInExpansion(QualType T, 4348 const MultiLevelTemplateArgumentList &TemplateArgs); 4349 4350 /// \brief Determine whether the given declarator contains any unexpanded 4351 /// parameter packs. 4352 /// 4353 /// This routine is used by the parser to disambiguate function declarators 4354 /// with an ellipsis prior to the ')', e.g., 4355 /// 4356 /// \code 4357 /// void f(T...); 4358 /// \endcode 4359 /// 4360 /// To determine whether we have an (unnamed) function parameter pack or 4361 /// a variadic function. 4362 /// 4363 /// \returns true if the declarator contains any unexpanded parameter packs, 4364 /// false otherwise. 4365 bool containsUnexpandedParameterPacks(Declarator &D); 4366 4367 //===--------------------------------------------------------------------===// 4368 // C++ Template Argument Deduction (C++ [temp.deduct]) 4369 //===--------------------------------------------------------------------===// 4370 4371 /// \brief Describes the result of template argument deduction. 4372 /// 4373 /// The TemplateDeductionResult enumeration describes the result of 4374 /// template argument deduction, as returned from 4375 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 4376 /// structure provides additional information about the results of 4377 /// template argument deduction, e.g., the deduced template argument 4378 /// list (if successful) or the specific template parameters or 4379 /// deduced arguments that were involved in the failure. 4380 enum TemplateDeductionResult { 4381 /// \brief Template argument deduction was successful. 4382 TDK_Success = 0, 4383 /// \brief Template argument deduction exceeded the maximum template 4384 /// instantiation depth (which has already been diagnosed). 4385 TDK_InstantiationDepth, 4386 /// \brief Template argument deduction did not deduce a value 4387 /// for every template parameter. 4388 TDK_Incomplete, 4389 /// \brief Template argument deduction produced inconsistent 4390 /// deduced values for the given template parameter. 4391 TDK_Inconsistent, 4392 /// \brief Template argument deduction failed due to inconsistent 4393 /// cv-qualifiers on a template parameter type that would 4394 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 4395 /// but were given a non-const "X". 4396 TDK_Underqualified, 4397 /// \brief Substitution of the deduced template argument values 4398 /// resulted in an error. 4399 TDK_SubstitutionFailure, 4400 /// \brief Substitution of the deduced template argument values 4401 /// into a non-deduced context produced a type or value that 4402 /// produces a type that does not match the original template 4403 /// arguments provided. 4404 TDK_NonDeducedMismatch, 4405 /// \brief When performing template argument deduction for a function 4406 /// template, there were too many call arguments. 4407 TDK_TooManyArguments, 4408 /// \brief When performing template argument deduction for a function 4409 /// template, there were too few call arguments. 4410 TDK_TooFewArguments, 4411 /// \brief The explicitly-specified template arguments were not valid 4412 /// template arguments for the given template. 4413 TDK_InvalidExplicitArguments, 4414 /// \brief The arguments included an overloaded function name that could 4415 /// not be resolved to a suitable function. 4416 TDK_FailedOverloadResolution 4417 }; 4418 4419 TemplateDeductionResult 4420 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 4421 const TemplateArgumentList &TemplateArgs, 4422 sema::TemplateDeductionInfo &Info); 4423 4424 TemplateDeductionResult 4425 SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4426 TemplateArgumentListInfo &ExplicitTemplateArgs, 4427 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 4428 SmallVectorImpl<QualType> &ParamTypes, 4429 QualType *FunctionType, 4430 sema::TemplateDeductionInfo &Info); 4431 4432 /// brief A function argument from which we performed template argument 4433 // deduction for a call. 4434 struct OriginalCallArg { 4435 OriginalCallArg(QualType OriginalParamType, 4436 unsigned ArgIdx, 4437 QualType OriginalArgType) 4438 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 4439 OriginalArgType(OriginalArgType) { } 4440 4441 QualType OriginalParamType; 4442 unsigned ArgIdx; 4443 QualType OriginalArgType; 4444 }; 4445 4446 TemplateDeductionResult 4447 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 4448 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 4449 unsigned NumExplicitlySpecified, 4450 FunctionDecl *&Specialization, 4451 sema::TemplateDeductionInfo &Info, 4452 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0); 4453 4454 TemplateDeductionResult 4455 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4456 TemplateArgumentListInfo *ExplicitTemplateArgs, 4457 Expr **Args, unsigned NumArgs, 4458 FunctionDecl *&Specialization, 4459 sema::TemplateDeductionInfo &Info); 4460 4461 TemplateDeductionResult 4462 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4463 TemplateArgumentListInfo *ExplicitTemplateArgs, 4464 QualType ArgFunctionType, 4465 FunctionDecl *&Specialization, 4466 sema::TemplateDeductionInfo &Info); 4467 4468 TemplateDeductionResult 4469 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4470 QualType ToType, 4471 CXXConversionDecl *&Specialization, 4472 sema::TemplateDeductionInfo &Info); 4473 4474 TemplateDeductionResult 4475 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4476 TemplateArgumentListInfo *ExplicitTemplateArgs, 4477 FunctionDecl *&Specialization, 4478 sema::TemplateDeductionInfo &Info); 4479 4480 bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer, 4481 TypeSourceInfo *&Result); 4482 4483 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 4484 FunctionTemplateDecl *FT2, 4485 SourceLocation Loc, 4486 TemplatePartialOrderingContext TPOC, 4487 unsigned NumCallArguments); 4488 UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, 4489 UnresolvedSetIterator SEnd, 4490 TemplatePartialOrderingContext TPOC, 4491 unsigned NumCallArguments, 4492 SourceLocation Loc, 4493 const PartialDiagnostic &NoneDiag, 4494 const PartialDiagnostic &AmbigDiag, 4495 const PartialDiagnostic &CandidateDiag, 4496 bool Complain = true); 4497 4498 ClassTemplatePartialSpecializationDecl * 4499 getMoreSpecializedPartialSpecialization( 4500 ClassTemplatePartialSpecializationDecl *PS1, 4501 ClassTemplatePartialSpecializationDecl *PS2, 4502 SourceLocation Loc); 4503 4504 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 4505 bool OnlyDeduced, 4506 unsigned Depth, 4507 SmallVectorImpl<bool> &Used); 4508 void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate, 4509 SmallVectorImpl<bool> &Deduced); 4510 4511 //===--------------------------------------------------------------------===// 4512 // C++ Template Instantiation 4513 // 4514 4515 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, 4516 const TemplateArgumentList *Innermost = 0, 4517 bool RelativeToPrimary = false, 4518 const FunctionDecl *Pattern = 0); 4519 4520 /// \brief A template instantiation that is currently in progress. 4521 struct ActiveTemplateInstantiation { 4522 /// \brief The kind of template instantiation we are performing 4523 enum InstantiationKind { 4524 /// We are instantiating a template declaration. The entity is 4525 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 4526 TemplateInstantiation, 4527 4528 /// We are instantiating a default argument for a template 4529 /// parameter. The Entity is the template, and 4530 /// TemplateArgs/NumTemplateArguments provides the template 4531 /// arguments as specified. 4532 /// FIXME: Use a TemplateArgumentList 4533 DefaultTemplateArgumentInstantiation, 4534 4535 /// We are instantiating a default argument for a function. 4536 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 4537 /// provides the template arguments as specified. 4538 DefaultFunctionArgumentInstantiation, 4539 4540 /// We are substituting explicit template arguments provided for 4541 /// a function template. The entity is a FunctionTemplateDecl. 4542 ExplicitTemplateArgumentSubstitution, 4543 4544 /// We are substituting template argument determined as part of 4545 /// template argument deduction for either a class template 4546 /// partial specialization or a function template. The 4547 /// Entity is either a ClassTemplatePartialSpecializationDecl or 4548 /// a FunctionTemplateDecl. 4549 DeducedTemplateArgumentSubstitution, 4550 4551 /// We are substituting prior template arguments into a new 4552 /// template parameter. The template parameter itself is either a 4553 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 4554 PriorTemplateArgumentSubstitution, 4555 4556 /// We are checking the validity of a default template argument that 4557 /// has been used when naming a template-id. 4558 DefaultTemplateArgumentChecking 4559 } Kind; 4560 4561 /// \brief The point of instantiation within the source code. 4562 SourceLocation PointOfInstantiation; 4563 4564 /// \brief The template (or partial specialization) in which we are 4565 /// performing the instantiation, for substitutions of prior template 4566 /// arguments. 4567 NamedDecl *Template; 4568 4569 /// \brief The entity that is being instantiated. 4570 uintptr_t Entity; 4571 4572 /// \brief The list of template arguments we are substituting, if they 4573 /// are not part of the entity. 4574 const TemplateArgument *TemplateArgs; 4575 4576 /// \brief The number of template arguments in TemplateArgs. 4577 unsigned NumTemplateArgs; 4578 4579 /// \brief The template deduction info object associated with the 4580 /// substitution or checking of explicit or deduced template arguments. 4581 sema::TemplateDeductionInfo *DeductionInfo; 4582 4583 /// \brief The source range that covers the construct that cause 4584 /// the instantiation, e.g., the template-id that causes a class 4585 /// template instantiation. 4586 SourceRange InstantiationRange; 4587 4588 ActiveTemplateInstantiation() 4589 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0), 4590 NumTemplateArgs(0), DeductionInfo(0) {} 4591 4592 /// \brief Determines whether this template is an actual instantiation 4593 /// that should be counted toward the maximum instantiation depth. 4594 bool isInstantiationRecord() const; 4595 4596 friend bool operator==(const ActiveTemplateInstantiation &X, 4597 const ActiveTemplateInstantiation &Y) { 4598 if (X.Kind != Y.Kind) 4599 return false; 4600 4601 if (X.Entity != Y.Entity) 4602 return false; 4603 4604 switch (X.Kind) { 4605 case TemplateInstantiation: 4606 return true; 4607 4608 case PriorTemplateArgumentSubstitution: 4609 case DefaultTemplateArgumentChecking: 4610 if (X.Template != Y.Template) 4611 return false; 4612 4613 // Fall through 4614 4615 case DefaultTemplateArgumentInstantiation: 4616 case ExplicitTemplateArgumentSubstitution: 4617 case DeducedTemplateArgumentSubstitution: 4618 case DefaultFunctionArgumentInstantiation: 4619 return X.TemplateArgs == Y.TemplateArgs; 4620 4621 } 4622 4623 return true; 4624 } 4625 4626 friend bool operator!=(const ActiveTemplateInstantiation &X, 4627 const ActiveTemplateInstantiation &Y) { 4628 return !(X == Y); 4629 } 4630 }; 4631 4632 /// \brief List of active template instantiations. 4633 /// 4634 /// This vector is treated as a stack. As one template instantiation 4635 /// requires another template instantiation, additional 4636 /// instantiations are pushed onto the stack up to a 4637 /// user-configurable limit LangOptions::InstantiationDepth. 4638 SmallVector<ActiveTemplateInstantiation, 16> 4639 ActiveTemplateInstantiations; 4640 4641 /// \brief Whether we are in a SFINAE context that is not associated with 4642 /// template instantiation. 4643 /// 4644 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 4645 /// of a template instantiation or template argument deduction. 4646 bool InNonInstantiationSFINAEContext; 4647 4648 /// \brief The number of ActiveTemplateInstantiation entries in 4649 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 4650 /// therefore, should not be counted as part of the instantiation depth. 4651 unsigned NonInstantiationEntries; 4652 4653 /// \brief The last template from which a template instantiation 4654 /// error or warning was produced. 4655 /// 4656 /// This value is used to suppress printing of redundant template 4657 /// instantiation backtraces when there are multiple errors in the 4658 /// same instantiation. FIXME: Does this belong in Sema? It's tough 4659 /// to implement it anywhere else. 4660 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 4661 4662 /// \brief The current index into pack expansion arguments that will be 4663 /// used for substitution of parameter packs. 4664 /// 4665 /// The pack expansion index will be -1 to indicate that parameter packs 4666 /// should be instantiated as themselves. Otherwise, the index specifies 4667 /// which argument within the parameter pack will be used for substitution. 4668 int ArgumentPackSubstitutionIndex; 4669 4670 /// \brief RAII object used to change the argument pack substitution index 4671 /// within a \c Sema object. 4672 /// 4673 /// See \c ArgumentPackSubstitutionIndex for more information. 4674 class ArgumentPackSubstitutionIndexRAII { 4675 Sema &Self; 4676 int OldSubstitutionIndex; 4677 4678 public: 4679 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 4680 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 4681 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 4682 } 4683 4684 ~ArgumentPackSubstitutionIndexRAII() { 4685 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 4686 } 4687 }; 4688 4689 friend class ArgumentPackSubstitutionRAII; 4690 4691 /// \brief The stack of calls expression undergoing template instantiation. 4692 /// 4693 /// The top of this stack is used by a fixit instantiating unresolved 4694 /// function calls to fix the AST to match the textual change it prints. 4695 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 4696 4697 /// \brief For each declaration that involved template argument deduction, the 4698 /// set of diagnostics that were suppressed during that template argument 4699 /// deduction. 4700 /// 4701 /// FIXME: Serialize this structure to the AST file. 4702 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 4703 SuppressedDiagnostics; 4704 4705 /// \brief A stack object to be created when performing template 4706 /// instantiation. 4707 /// 4708 /// Construction of an object of type \c InstantiatingTemplate 4709 /// pushes the current instantiation onto the stack of active 4710 /// instantiations. If the size of this stack exceeds the maximum 4711 /// number of recursive template instantiations, construction 4712 /// produces an error and evaluates true. 4713 /// 4714 /// Destruction of this object will pop the named instantiation off 4715 /// the stack. 4716 struct InstantiatingTemplate { 4717 /// \brief Note that we are instantiating a class template, 4718 /// function template, or a member thereof. 4719 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4720 Decl *Entity, 4721 SourceRange InstantiationRange = SourceRange()); 4722 4723 /// \brief Note that we are instantiating a default argument in a 4724 /// template-id. 4725 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4726 TemplateDecl *Template, 4727 const TemplateArgument *TemplateArgs, 4728 unsigned NumTemplateArgs, 4729 SourceRange InstantiationRange = SourceRange()); 4730 4731 /// \brief Note that we are instantiating a default argument in a 4732 /// template-id. 4733 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4734 FunctionTemplateDecl *FunctionTemplate, 4735 const TemplateArgument *TemplateArgs, 4736 unsigned NumTemplateArgs, 4737 ActiveTemplateInstantiation::InstantiationKind Kind, 4738 sema::TemplateDeductionInfo &DeductionInfo, 4739 SourceRange InstantiationRange = SourceRange()); 4740 4741 /// \brief Note that we are instantiating as part of template 4742 /// argument deduction for a class template partial 4743 /// specialization. 4744 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4745 ClassTemplatePartialSpecializationDecl *PartialSpec, 4746 const TemplateArgument *TemplateArgs, 4747 unsigned NumTemplateArgs, 4748 sema::TemplateDeductionInfo &DeductionInfo, 4749 SourceRange InstantiationRange = SourceRange()); 4750 4751 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4752 ParmVarDecl *Param, 4753 const TemplateArgument *TemplateArgs, 4754 unsigned NumTemplateArgs, 4755 SourceRange InstantiationRange = SourceRange()); 4756 4757 /// \brief Note that we are substituting prior template arguments into a 4758 /// non-type or template template parameter. 4759 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4760 NamedDecl *Template, 4761 NonTypeTemplateParmDecl *Param, 4762 const TemplateArgument *TemplateArgs, 4763 unsigned NumTemplateArgs, 4764 SourceRange InstantiationRange); 4765 4766 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4767 NamedDecl *Template, 4768 TemplateTemplateParmDecl *Param, 4769 const TemplateArgument *TemplateArgs, 4770 unsigned NumTemplateArgs, 4771 SourceRange InstantiationRange); 4772 4773 /// \brief Note that we are checking the default template argument 4774 /// against the template parameter for a given template-id. 4775 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4776 TemplateDecl *Template, 4777 NamedDecl *Param, 4778 const TemplateArgument *TemplateArgs, 4779 unsigned NumTemplateArgs, 4780 SourceRange InstantiationRange); 4781 4782 4783 /// \brief Note that we have finished instantiating this template. 4784 void Clear(); 4785 4786 ~InstantiatingTemplate() { Clear(); } 4787 4788 /// \brief Determines whether we have exceeded the maximum 4789 /// recursive template instantiations. 4790 operator bool() const { return Invalid; } 4791 4792 private: 4793 Sema &SemaRef; 4794 bool Invalid; 4795 bool SavedInNonInstantiationSFINAEContext; 4796 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 4797 SourceRange InstantiationRange); 4798 4799 InstantiatingTemplate(const InstantiatingTemplate&); // not implemented 4800 4801 InstantiatingTemplate& 4802 operator=(const InstantiatingTemplate&); // not implemented 4803 }; 4804 4805 void PrintInstantiationStack(); 4806 4807 /// \brief Determines whether we are currently in a context where 4808 /// template argument substitution failures are not considered 4809 /// errors. 4810 /// 4811 /// \returns An empty \c llvm::Optional if we're not in a SFINAE context. 4812 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 4813 /// template-deduction context object, which can be used to capture 4814 /// diagnostics that will be suppressed. 4815 llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 4816 4817 /// \brief RAII class used to determine whether SFINAE has 4818 /// trapped any errors that occur during template argument 4819 /// deduction.` 4820 class SFINAETrap { 4821 Sema &SemaRef; 4822 unsigned PrevSFINAEErrors; 4823 bool PrevInNonInstantiationSFINAEContext; 4824 bool PrevAccessCheckingSFINAE; 4825 4826 public: 4827 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 4828 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 4829 PrevInNonInstantiationSFINAEContext( 4830 SemaRef.InNonInstantiationSFINAEContext), 4831 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 4832 { 4833 if (!SemaRef.isSFINAEContext()) 4834 SemaRef.InNonInstantiationSFINAEContext = true; 4835 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 4836 } 4837 4838 ~SFINAETrap() { 4839 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 4840 SemaRef.InNonInstantiationSFINAEContext 4841 = PrevInNonInstantiationSFINAEContext; 4842 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 4843 } 4844 4845 /// \brief Determine whether any SFINAE errors have been trapped. 4846 bool hasErrorOccurred() const { 4847 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 4848 } 4849 }; 4850 4851 /// \brief The current instantiation scope used to store local 4852 /// variables. 4853 LocalInstantiationScope *CurrentInstantiationScope; 4854 4855 /// \brief The number of typos corrected by CorrectTypo. 4856 unsigned TyposCorrected; 4857 4858 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection> 4859 UnqualifiedTyposCorrectedMap; 4860 4861 /// \brief A cache containing the results of typo correction for unqualified 4862 /// name lookup. 4863 /// 4864 /// The string is the string that we corrected to (which may be empty, if 4865 /// there was no correction), while the boolean will be true when the 4866 /// string represents a keyword. 4867 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; 4868 4869 /// \brief Worker object for performing CFG-based warnings. 4870 sema::AnalysisBasedWarnings AnalysisWarnings; 4871 4872 /// \brief An entity for which implicit template instantiation is required. 4873 /// 4874 /// The source location associated with the declaration is the first place in 4875 /// the source code where the declaration was "used". It is not necessarily 4876 /// the point of instantiation (which will be either before or after the 4877 /// namespace-scope declaration that triggered this implicit instantiation), 4878 /// However, it is the location that diagnostics should generally refer to, 4879 /// because users will need to know what code triggered the instantiation. 4880 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 4881 4882 /// \brief The queue of implicit template instantiations that are required 4883 /// but have not yet been performed. 4884 std::deque<PendingImplicitInstantiation> PendingInstantiations; 4885 4886 /// \brief The queue of implicit template instantiations that are required 4887 /// and must be performed within the current local scope. 4888 /// 4889 /// This queue is only used for member functions of local classes in 4890 /// templates, which must be instantiated in the same scope as their 4891 /// enclosing function, so that they can reference function-local 4892 /// types, static variables, enumerators, etc. 4893 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 4894 4895 void PerformPendingInstantiations(bool LocalOnly = false); 4896 4897 TypeSourceInfo *SubstType(TypeSourceInfo *T, 4898 const MultiLevelTemplateArgumentList &TemplateArgs, 4899 SourceLocation Loc, DeclarationName Entity); 4900 4901 QualType SubstType(QualType T, 4902 const MultiLevelTemplateArgumentList &TemplateArgs, 4903 SourceLocation Loc, DeclarationName Entity); 4904 4905 TypeSourceInfo *SubstType(TypeLoc TL, 4906 const MultiLevelTemplateArgumentList &TemplateArgs, 4907 SourceLocation Loc, DeclarationName Entity); 4908 4909 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 4910 const MultiLevelTemplateArgumentList &TemplateArgs, 4911 SourceLocation Loc, 4912 DeclarationName Entity); 4913 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 4914 const MultiLevelTemplateArgumentList &TemplateArgs, 4915 int indexAdjustment, 4916 llvm::Optional<unsigned> NumExpansions); 4917 bool SubstParmTypes(SourceLocation Loc, 4918 ParmVarDecl **Params, unsigned NumParams, 4919 const MultiLevelTemplateArgumentList &TemplateArgs, 4920 SmallVectorImpl<QualType> &ParamTypes, 4921 SmallVectorImpl<ParmVarDecl *> *OutParams = 0); 4922 ExprResult SubstExpr(Expr *E, 4923 const MultiLevelTemplateArgumentList &TemplateArgs); 4924 4925 /// \brief Substitute the given template arguments into a list of 4926 /// expressions, expanding pack expansions if required. 4927 /// 4928 /// \param Exprs The list of expressions to substitute into. 4929 /// 4930 /// \param NumExprs The number of expressions in \p Exprs. 4931 /// 4932 /// \param IsCall Whether this is some form of call, in which case 4933 /// default arguments will be dropped. 4934 /// 4935 /// \param TemplateArgs The set of template arguments to substitute. 4936 /// 4937 /// \param Outputs Will receive all of the substituted arguments. 4938 /// 4939 /// \returns true if an error occurred, false otherwise. 4940 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 4941 const MultiLevelTemplateArgumentList &TemplateArgs, 4942 SmallVectorImpl<Expr *> &Outputs); 4943 4944 StmtResult SubstStmt(Stmt *S, 4945 const MultiLevelTemplateArgumentList &TemplateArgs); 4946 4947 Decl *SubstDecl(Decl *D, DeclContext *Owner, 4948 const MultiLevelTemplateArgumentList &TemplateArgs); 4949 4950 bool 4951 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 4952 CXXRecordDecl *Pattern, 4953 const MultiLevelTemplateArgumentList &TemplateArgs); 4954 4955 bool 4956 InstantiateClass(SourceLocation PointOfInstantiation, 4957 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 4958 const MultiLevelTemplateArgumentList &TemplateArgs, 4959 TemplateSpecializationKind TSK, 4960 bool Complain = true); 4961 4962 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 4963 const Decl *Pattern, Decl *Inst); 4964 4965 bool 4966 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 4967 ClassTemplateSpecializationDecl *ClassTemplateSpec, 4968 TemplateSpecializationKind TSK, 4969 bool Complain = true); 4970 4971 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 4972 CXXRecordDecl *Instantiation, 4973 const MultiLevelTemplateArgumentList &TemplateArgs, 4974 TemplateSpecializationKind TSK); 4975 4976 void InstantiateClassTemplateSpecializationMembers( 4977 SourceLocation PointOfInstantiation, 4978 ClassTemplateSpecializationDecl *ClassTemplateSpec, 4979 TemplateSpecializationKind TSK); 4980 4981 NestedNameSpecifierLoc 4982 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 4983 const MultiLevelTemplateArgumentList &TemplateArgs); 4984 4985 DeclarationNameInfo 4986 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 4987 const MultiLevelTemplateArgumentList &TemplateArgs); 4988 TemplateName 4989 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 4990 SourceLocation Loc, 4991 const MultiLevelTemplateArgumentList &TemplateArgs); 4992 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 4993 TemplateArgumentListInfo &Result, 4994 const MultiLevelTemplateArgumentList &TemplateArgs); 4995 4996 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 4997 FunctionDecl *Function, 4998 bool Recursive = false, 4999 bool DefinitionRequired = false); 5000 void InstantiateStaticDataMemberDefinition( 5001 SourceLocation PointOfInstantiation, 5002 VarDecl *Var, 5003 bool Recursive = false, 5004 bool DefinitionRequired = false); 5005 5006 void InstantiateMemInitializers(CXXConstructorDecl *New, 5007 const CXXConstructorDecl *Tmpl, 5008 const MultiLevelTemplateArgumentList &TemplateArgs); 5009 bool InstantiateInitializer(Expr *Init, 5010 const MultiLevelTemplateArgumentList &TemplateArgs, 5011 SourceLocation &LParenLoc, 5012 ASTOwningVector<Expr*> &NewArgs, 5013 SourceLocation &RParenLoc); 5014 5015 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5016 const MultiLevelTemplateArgumentList &TemplateArgs); 5017 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 5018 const MultiLevelTemplateArgumentList &TemplateArgs); 5019 5020 // Objective-C declarations. 5021 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 5022 IdentifierInfo *ClassName, 5023 SourceLocation ClassLoc, 5024 IdentifierInfo *SuperName, 5025 SourceLocation SuperLoc, 5026 Decl * const *ProtoRefs, 5027 unsigned NumProtoRefs, 5028 const SourceLocation *ProtoLocs, 5029 SourceLocation EndProtoLoc, 5030 AttributeList *AttrList); 5031 5032 Decl *ActOnCompatiblityAlias( 5033 SourceLocation AtCompatibilityAliasLoc, 5034 IdentifierInfo *AliasName, SourceLocation AliasLocation, 5035 IdentifierInfo *ClassName, SourceLocation ClassLocation); 5036 5037 bool CheckForwardProtocolDeclarationForCircularDependency( 5038 IdentifierInfo *PName, 5039 SourceLocation &PLoc, SourceLocation PrevLoc, 5040 const ObjCList<ObjCProtocolDecl> &PList); 5041 5042 Decl *ActOnStartProtocolInterface( 5043 SourceLocation AtProtoInterfaceLoc, 5044 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 5045 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 5046 const SourceLocation *ProtoLocs, 5047 SourceLocation EndProtoLoc, 5048 AttributeList *AttrList); 5049 5050 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 5051 IdentifierInfo *ClassName, 5052 SourceLocation ClassLoc, 5053 IdentifierInfo *CategoryName, 5054 SourceLocation CategoryLoc, 5055 Decl * const *ProtoRefs, 5056 unsigned NumProtoRefs, 5057 const SourceLocation *ProtoLocs, 5058 SourceLocation EndProtoLoc); 5059 5060 Decl *ActOnStartClassImplementation( 5061 SourceLocation AtClassImplLoc, 5062 IdentifierInfo *ClassName, SourceLocation ClassLoc, 5063 IdentifierInfo *SuperClassname, 5064 SourceLocation SuperClassLoc); 5065 5066 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 5067 IdentifierInfo *ClassName, 5068 SourceLocation ClassLoc, 5069 IdentifierInfo *CatName, 5070 SourceLocation CatLoc); 5071 5072 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 5073 IdentifierInfo **IdentList, 5074 SourceLocation *IdentLocs, 5075 unsigned NumElts); 5076 5077 Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 5078 const IdentifierLocPair *IdentList, 5079 unsigned NumElts, 5080 AttributeList *attrList); 5081 5082 void FindProtocolDeclaration(bool WarnOnDeclarations, 5083 const IdentifierLocPair *ProtocolId, 5084 unsigned NumProtocols, 5085 SmallVectorImpl<Decl *> &Protocols); 5086 5087 /// Ensure attributes are consistent with type. 5088 /// \param [in, out] Attributes The attributes to check; they will 5089 /// be modified to be consistent with \arg PropertyTy. 5090 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 5091 SourceLocation Loc, 5092 unsigned &Attributes); 5093 5094 /// Process the specified property declaration and create decls for the 5095 /// setters and getters as needed. 5096 /// \param property The property declaration being processed 5097 /// \param DC The semantic container for the property 5098 /// \param redeclaredProperty Declaration for property if redeclared 5099 /// in class extension. 5100 /// \param lexicalDC Container for redeclaredProperty. 5101 void ProcessPropertyDecl(ObjCPropertyDecl *property, 5102 ObjCContainerDecl *DC, 5103 ObjCPropertyDecl *redeclaredProperty = 0, 5104 ObjCContainerDecl *lexicalDC = 0); 5105 5106 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 5107 ObjCPropertyDecl *SuperProperty, 5108 const IdentifierInfo *Name); 5109 void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl); 5110 5111 void CompareMethodParamsInBaseAndSuper(Decl *IDecl, 5112 ObjCMethodDecl *MethodDecl, 5113 bool IsInstance); 5114 5115 void CompareProperties(Decl *CDecl, Decl *MergeProtocols); 5116 5117 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 5118 ObjCInterfaceDecl *ID); 5119 5120 void MatchOneProtocolPropertiesInClass(Decl *CDecl, 5121 ObjCProtocolDecl *PDecl); 5122 5123 void ActOnAtEnd(Scope *S, SourceRange AtEnd, 5124 Decl **allMethods = 0, unsigned allNum = 0, 5125 Decl **allProperties = 0, unsigned pNum = 0, 5126 DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0); 5127 5128 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 5129 FieldDeclarator &FD, ObjCDeclSpec &ODS, 5130 Selector GetterSel, Selector SetterSel, 5131 bool *OverridingProperty, 5132 tok::ObjCKeywordKind MethodImplKind, 5133 DeclContext *lexicalDC = 0); 5134 5135 Decl *ActOnPropertyImplDecl(Scope *S, 5136 SourceLocation AtLoc, 5137 SourceLocation PropertyLoc, 5138 bool ImplKind, 5139 IdentifierInfo *PropertyId, 5140 IdentifierInfo *PropertyIvar, 5141 SourceLocation PropertyIvarLoc); 5142 5143 enum ObjCSpecialMethodKind { 5144 OSMK_None, 5145 OSMK_Alloc, 5146 OSMK_New, 5147 OSMK_Copy, 5148 OSMK_RetainingInit, 5149 OSMK_NonRetainingInit 5150 }; 5151 5152 struct ObjCArgInfo { 5153 IdentifierInfo *Name; 5154 SourceLocation NameLoc; 5155 // The Type is null if no type was specified, and the DeclSpec is invalid 5156 // in this case. 5157 ParsedType Type; 5158 ObjCDeclSpec DeclSpec; 5159 5160 /// ArgAttrs - Attribute list for this argument. 5161 AttributeList *ArgAttrs; 5162 }; 5163 5164 Decl *ActOnMethodDeclaration( 5165 Scope *S, 5166 SourceLocation BeginLoc, // location of the + or -. 5167 SourceLocation EndLoc, // location of the ; or {. 5168 tok::TokenKind MethodType, 5169 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 5170 SourceLocation SelectorStartLoc, Selector Sel, 5171 // optional arguments. The number of types/arguments is obtained 5172 // from the Sel.getNumArgs(). 5173 ObjCArgInfo *ArgInfo, 5174 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 5175 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 5176 bool isVariadic, bool MethodDefinition); 5177 5178 // Helper method for ActOnClassMethod/ActOnInstanceMethod. 5179 // Will search "local" class/category implementations for a method decl. 5180 // Will also search in class's root looking for instance method. 5181 // Returns 0 if no method is found. 5182 ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel, 5183 ObjCInterfaceDecl *CDecl); 5184 ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel, 5185 ObjCInterfaceDecl *ClassDecl); 5186 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 5187 const ObjCObjectPointerType *OPT, 5188 bool IsInstance); 5189 5190 bool inferObjCARCLifetime(ValueDecl *decl); 5191 5192 ExprResult 5193 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 5194 Expr *BaseExpr, 5195 SourceLocation OpLoc, 5196 DeclarationName MemberName, 5197 SourceLocation MemberLoc, 5198 SourceLocation SuperLoc, QualType SuperType, 5199 bool Super); 5200 5201 ExprResult 5202 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 5203 IdentifierInfo &propertyName, 5204 SourceLocation receiverNameLoc, 5205 SourceLocation propertyNameLoc); 5206 5207 ObjCMethodDecl *tryCaptureObjCSelf(); 5208 5209 /// \brief Describes the kind of message expression indicated by a message 5210 /// send that starts with an identifier. 5211 enum ObjCMessageKind { 5212 /// \brief The message is sent to 'super'. 5213 ObjCSuperMessage, 5214 /// \brief The message is an instance message. 5215 ObjCInstanceMessage, 5216 /// \brief The message is a class message, and the identifier is a type 5217 /// name. 5218 ObjCClassMessage 5219 }; 5220 5221 ObjCMessageKind getObjCMessageKind(Scope *S, 5222 IdentifierInfo *Name, 5223 SourceLocation NameLoc, 5224 bool IsSuper, 5225 bool HasTrailingDot, 5226 ParsedType &ReceiverType); 5227 5228 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 5229 Selector Sel, 5230 SourceLocation LBracLoc, 5231 SourceLocation SelectorLoc, 5232 SourceLocation RBracLoc, 5233 MultiExprArg Args); 5234 5235 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 5236 QualType ReceiverType, 5237 SourceLocation SuperLoc, 5238 Selector Sel, 5239 ObjCMethodDecl *Method, 5240 SourceLocation LBracLoc, 5241 SourceLocation SelectorLoc, 5242 SourceLocation RBracLoc, 5243 MultiExprArg Args); 5244 5245 ExprResult ActOnClassMessage(Scope *S, 5246 ParsedType Receiver, 5247 Selector Sel, 5248 SourceLocation LBracLoc, 5249 SourceLocation SelectorLoc, 5250 SourceLocation RBracLoc, 5251 MultiExprArg Args); 5252 5253 ExprResult BuildInstanceMessage(Expr *Receiver, 5254 QualType ReceiverType, 5255 SourceLocation SuperLoc, 5256 Selector Sel, 5257 ObjCMethodDecl *Method, 5258 SourceLocation LBracLoc, 5259 SourceLocation SelectorLoc, 5260 SourceLocation RBracLoc, 5261 MultiExprArg Args); 5262 5263 ExprResult ActOnInstanceMessage(Scope *S, 5264 Expr *Receiver, 5265 Selector Sel, 5266 SourceLocation LBracLoc, 5267 SourceLocation SelectorLoc, 5268 SourceLocation RBracLoc, 5269 MultiExprArg Args); 5270 5271 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 5272 ObjCBridgeCastKind Kind, 5273 SourceLocation BridgeKeywordLoc, 5274 TypeSourceInfo *TSInfo, 5275 Expr *SubExpr); 5276 5277 ExprResult ActOnObjCBridgedCast(Scope *S, 5278 SourceLocation LParenLoc, 5279 ObjCBridgeCastKind Kind, 5280 SourceLocation BridgeKeywordLoc, 5281 ParsedType Type, 5282 SourceLocation RParenLoc, 5283 Expr *SubExpr); 5284 5285 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 5286 5287 /// \brief Check whether the given new method is a valid override of the 5288 /// given overridden method, and set any properties that should be inherited. 5289 /// 5290 /// \returns True if an error occurred. 5291 bool CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 5292 const ObjCMethodDecl *Overridden, 5293 bool IsImplementation); 5294 5295 /// \brief Check whether the given method overrides any methods in its class, 5296 /// calling \c CheckObjCMethodOverride for each overridden method. 5297 bool CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, DeclContext *DC); 5298 5299 enum PragmaOptionsAlignKind { 5300 POAK_Native, // #pragma options align=native 5301 POAK_Natural, // #pragma options align=natural 5302 POAK_Packed, // #pragma options align=packed 5303 POAK_Power, // #pragma options align=power 5304 POAK_Mac68k, // #pragma options align=mac68k 5305 POAK_Reset // #pragma options align=reset 5306 }; 5307 5308 /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align. 5309 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 5310 SourceLocation PragmaLoc, 5311 SourceLocation KindLoc); 5312 5313 enum PragmaPackKind { 5314 PPK_Default, // #pragma pack([n]) 5315 PPK_Show, // #pragma pack(show), only supported by MSVC. 5316 PPK_Push, // #pragma pack(push, [identifier], [n]) 5317 PPK_Pop // #pragma pack(pop, [identifier], [n]) 5318 }; 5319 5320 enum PragmaMSStructKind { 5321 PMSST_OFF, // #pragms ms_struct off 5322 PMSST_ON // #pragms ms_struct on 5323 }; 5324 5325 /// ActOnPragmaPack - Called on well formed #pragma pack(...). 5326 void ActOnPragmaPack(PragmaPackKind Kind, 5327 IdentifierInfo *Name, 5328 Expr *Alignment, 5329 SourceLocation PragmaLoc, 5330 SourceLocation LParenLoc, 5331 SourceLocation RParenLoc); 5332 5333 /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off]. 5334 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 5335 5336 /// ActOnPragmaUnused - Called on well-formed '#pragma unused'. 5337 void ActOnPragmaUnused(const Token &Identifier, 5338 Scope *curScope, 5339 SourceLocation PragmaLoc); 5340 5341 /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... . 5342 void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType, 5343 SourceLocation PragmaLoc); 5344 5345 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 5346 SourceLocation Loc); 5347 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 5348 5349 /// ActOnPragmaWeakID - Called on well formed #pragma weak ident. 5350 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 5351 SourceLocation PragmaLoc, 5352 SourceLocation WeakNameLoc); 5353 5354 /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident. 5355 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 5356 IdentifierInfo* AliasName, 5357 SourceLocation PragmaLoc, 5358 SourceLocation WeakNameLoc, 5359 SourceLocation AliasNameLoc); 5360 5361 /// ActOnPragmaFPContract - Called on well formed 5362 /// #pragma {STDC,OPENCL} FP_CONTRACT 5363 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 5364 5365 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 5366 /// a the record decl, to handle '#pragma pack' and '#pragma options align'. 5367 void AddAlignmentAttributesForRecord(RecordDecl *RD); 5368 5369 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 5370 void AddMsStructLayoutForRecord(RecordDecl *RD); 5371 5372 /// FreePackedContext - Deallocate and null out PackContext. 5373 void FreePackedContext(); 5374 5375 /// PushNamespaceVisibilityAttr - Note that we've entered a 5376 /// namespace with a visibility attribute. 5377 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr); 5378 5379 /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, 5380 /// add an appropriate visibility attribute. 5381 void AddPushedVisibilityAttribute(Decl *RD); 5382 5383 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 5384 /// for '#pragma GCC visibility' and visibility attributes on namespaces. 5385 void PopPragmaVisibility(); 5386 5387 /// FreeVisContext - Deallocate and null out VisContext. 5388 void FreeVisContext(); 5389 5390 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 5391 void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E); 5392 void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *T); 5393 5394 /// CastCategory - Get the correct forwarded implicit cast result category 5395 /// from the inner expression. 5396 ExprValueKind CastCategory(Expr *E); 5397 5398 /// \brief The kind of conversion being performed. 5399 enum CheckedConversionKind { 5400 /// \brief An implicit conversion. 5401 CCK_ImplicitConversion, 5402 /// \brief A C-style cast. 5403 CCK_CStyleCast, 5404 /// \brief A functional-style cast. 5405 CCK_FunctionalCast, 5406 /// \brief A cast other than a C-style cast. 5407 CCK_OtherCast 5408 }; 5409 5410 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 5411 /// cast. If there is already an implicit cast, merge into the existing one. 5412 /// If isLvalue, the result of the cast is an lvalue. 5413 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 5414 ExprValueKind VK = VK_RValue, 5415 const CXXCastPath *BasePath = 0, 5416 CheckedConversionKind CCK 5417 = CCK_ImplicitConversion); 5418 5419 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 5420 /// to the conversion from scalar type ScalarTy to the Boolean type. 5421 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 5422 5423 /// IgnoredValueConversions - Given that an expression's result is 5424 /// syntactically ignored, perform any conversions that are 5425 /// required. 5426 ExprResult IgnoredValueConversions(Expr *E); 5427 5428 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 5429 // functions and arrays to their respective pointers (C99 6.3.2.1). 5430 ExprResult UsualUnaryConversions(Expr *E); 5431 5432 // DefaultFunctionArrayConversion - converts functions and arrays 5433 // to their respective pointers (C99 6.3.2.1). 5434 ExprResult DefaultFunctionArrayConversion(Expr *E); 5435 5436 // DefaultFunctionArrayLvalueConversion - converts functions and 5437 // arrays to their respective pointers and performs the 5438 // lvalue-to-rvalue conversion. 5439 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 5440 5441 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 5442 // the operand. This is DefaultFunctionArrayLvalueConversion, 5443 // except that it assumes the operand isn't of function or array 5444 // type. 5445 ExprResult DefaultLvalueConversion(Expr *E); 5446 5447 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 5448 // do not have a prototype. Integer promotions are performed on each 5449 // argument, and arguments that have type float are promoted to double. 5450 ExprResult DefaultArgumentPromotion(Expr *E); 5451 5452 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 5453 enum VariadicCallType { 5454 VariadicFunction, 5455 VariadicBlock, 5456 VariadicMethod, 5457 VariadicConstructor, 5458 VariadicDoesNotApply 5459 }; 5460 5461 /// GatherArgumentsForCall - Collector argument expressions for various 5462 /// form of call prototypes. 5463 bool GatherArgumentsForCall(SourceLocation CallLoc, 5464 FunctionDecl *FDecl, 5465 const FunctionProtoType *Proto, 5466 unsigned FirstProtoArg, 5467 Expr **Args, unsigned NumArgs, 5468 SmallVector<Expr *, 8> &AllArgs, 5469 VariadicCallType CallType = VariadicDoesNotApply); 5470 5471 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 5472 // will warn if the resulting type is not a POD type. 5473 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 5474 FunctionDecl *FDecl); 5475 5476 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 5477 // operands and then handles various conversions that are common to binary 5478 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 5479 // routine returns the first non-arithmetic type found. The client is 5480 // responsible for emitting appropriate error diagnostics. 5481 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 5482 bool IsCompAssign = false); 5483 5484 /// AssignConvertType - All of the 'assignment' semantic checks return this 5485 /// enum to indicate whether the assignment was allowed. These checks are 5486 /// done for simple assignments, as well as initialization, return from 5487 /// function, argument passing, etc. The query is phrased in terms of a 5488 /// source and destination type. 5489 enum AssignConvertType { 5490 /// Compatible - the types are compatible according to the standard. 5491 Compatible, 5492 5493 /// PointerToInt - The assignment converts a pointer to an int, which we 5494 /// accept as an extension. 5495 PointerToInt, 5496 5497 /// IntToPointer - The assignment converts an int to a pointer, which we 5498 /// accept as an extension. 5499 IntToPointer, 5500 5501 /// FunctionVoidPointer - The assignment is between a function pointer and 5502 /// void*, which the standard doesn't allow, but we accept as an extension. 5503 FunctionVoidPointer, 5504 5505 /// IncompatiblePointer - The assignment is between two pointers types that 5506 /// are not compatible, but we accept them as an extension. 5507 IncompatiblePointer, 5508 5509 /// IncompatiblePointer - The assignment is between two pointers types which 5510 /// point to integers which have a different sign, but are otherwise identical. 5511 /// This is a subset of the above, but broken out because it's by far the most 5512 /// common case of incompatible pointers. 5513 IncompatiblePointerSign, 5514 5515 /// CompatiblePointerDiscardsQualifiers - The assignment discards 5516 /// c/v/r qualifiers, which we accept as an extension. 5517 CompatiblePointerDiscardsQualifiers, 5518 5519 /// IncompatiblePointerDiscardsQualifiers - The assignment 5520 /// discards qualifiers that we don't permit to be discarded, 5521 /// like address spaces. 5522 IncompatiblePointerDiscardsQualifiers, 5523 5524 /// IncompatibleNestedPointerQualifiers - The assignment is between two 5525 /// nested pointer types, and the qualifiers other than the first two 5526 /// levels differ e.g. char ** -> const char **, but we accept them as an 5527 /// extension. 5528 IncompatibleNestedPointerQualifiers, 5529 5530 /// IncompatibleVectors - The assignment is between two vector types that 5531 /// have the same size, which we accept as an extension. 5532 IncompatibleVectors, 5533 5534 /// IntToBlockPointer - The assignment converts an int to a block 5535 /// pointer. We disallow this. 5536 IntToBlockPointer, 5537 5538 /// IncompatibleBlockPointer - The assignment is between two block 5539 /// pointers types that are not compatible. 5540 IncompatibleBlockPointer, 5541 5542 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 5543 /// id type and something else (that is incompatible with it). For example, 5544 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 5545 IncompatibleObjCQualifiedId, 5546 5547 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 5548 /// object with __weak qualifier. 5549 IncompatibleObjCWeakRef, 5550 5551 /// Incompatible - We reject this conversion outright, it is invalid to 5552 /// represent it in the AST. 5553 Incompatible 5554 }; 5555 5556 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 5557 /// assignment conversion type specified by ConvTy. This returns true if the 5558 /// conversion was invalid or false if the conversion was accepted. 5559 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 5560 SourceLocation Loc, 5561 QualType DstType, QualType SrcType, 5562 Expr *SrcExpr, AssignmentAction Action, 5563 bool *Complained = 0); 5564 5565 /// CheckAssignmentConstraints - Perform type checking for assignment, 5566 /// argument passing, variable initialization, and function return values. 5567 /// C99 6.5.16. 5568 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 5569 QualType LHSType, 5570 QualType RHSType); 5571 5572 /// Check assignment constraints and prepare for a conversion of the 5573 /// RHS to the LHS type. 5574 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 5575 ExprResult &RHS, 5576 CastKind &Kind); 5577 5578 // CheckSingleAssignmentConstraints - Currently used by 5579 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 5580 // this routine performs the default function/array converions. 5581 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 5582 ExprResult &RHS); 5583 5584 // \brief If the lhs type is a transparent union, check whether we 5585 // can initialize the transparent union with the given expression. 5586 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 5587 ExprResult &RHS); 5588 5589 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 5590 5591 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 5592 5593 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5594 AssignmentAction Action, 5595 bool AllowExplicit = false); 5596 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5597 AssignmentAction Action, 5598 bool AllowExplicit, 5599 ImplicitConversionSequence& ICS); 5600 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5601 const ImplicitConversionSequence& ICS, 5602 AssignmentAction Action, 5603 CheckedConversionKind CCK 5604 = CCK_ImplicitConversion); 5605 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5606 const StandardConversionSequence& SCS, 5607 AssignmentAction Action, 5608 CheckedConversionKind CCK); 5609 5610 /// the following "Check" methods will return a valid/converted QualType 5611 /// or a null QualType (indicating an error diagnostic was issued). 5612 5613 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 5614 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 5615 ExprResult &RHS); 5616 QualType CheckPointerToMemberOperands( // C++ 5.5 5617 ExprResult &lex, ExprResult &rex, ExprValueKind &VK, 5618 SourceLocation OpLoc, bool isIndirect); 5619 QualType CheckMultiplyDivideOperands( // C99 6.5.5 5620 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 5621 bool IsDivide); 5622 QualType CheckRemainderOperands( // C99 6.5.5 5623 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 5624 bool IsCompAssign = false); 5625 QualType CheckAdditionOperands( // C99 6.5.6 5626 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 5627 QualType* CompLHSTy = 0); 5628 QualType CheckSubtractionOperands( // C99 6.5.6 5629 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 5630 QualType* CompLHSTy = 0); 5631 QualType CheckShiftOperands( // C99 6.5.7 5632 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 5633 bool IsCompAssign = false); 5634 QualType CheckCompareOperands( // C99 6.5.8/9 5635 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 5636 bool isRelational); 5637 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 5638 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 5639 bool IsCompAssign = false); 5640 QualType CheckLogicalOperands( // C99 6.5.[13,14] 5641 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 5642 // CheckAssignmentOperands is used for both simple and compound assignment. 5643 // For simple assignment, pass both expressions and a null converted type. 5644 // For compound assignment, pass both expressions and the converted type. 5645 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 5646 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 5647 5648 void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, 5649 QualType& LHSTy); 5650 ExprResult ConvertPropertyForRValue(Expr *E); 5651 5652 QualType CheckConditionalOperands( // C99 6.5.15 5653 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 5654 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 5655 QualType CXXCheckConditionalOperands( // C++ 5.16 5656 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 5657 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 5658 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 5659 bool *NonStandardCompositeType = 0); 5660 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, 5661 bool *NonStandardCompositeType = 0) { 5662 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take(); 5663 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType); 5664 E1 = Owned(E1Tmp); 5665 E2 = Owned(E2Tmp); 5666 return Composite; 5667 } 5668 5669 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5670 SourceLocation QuestionLoc); 5671 5672 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5673 SourceLocation QuestionLoc); 5674 5675 /// type checking for vector binary operators. 5676 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 5677 SourceLocation Loc, bool IsCompAssign); 5678 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 5679 SourceLocation Loc, bool isRelational); 5680 5681 /// type checking declaration initializers (C99 6.7.8) 5682 bool CheckInitList(const InitializedEntity &Entity, 5683 InitListExpr *&InitList, QualType &DeclType); 5684 bool CheckForConstantInitializer(Expr *e, QualType t); 5685 5686 // type checking C++ declaration initializers (C++ [dcl.init]). 5687 5688 /// ReferenceCompareResult - Expresses the result of comparing two 5689 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 5690 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 5691 enum ReferenceCompareResult { 5692 /// Ref_Incompatible - The two types are incompatible, so direct 5693 /// reference binding is not possible. 5694 Ref_Incompatible = 0, 5695 /// Ref_Related - The two types are reference-related, which means 5696 /// that their unqualified forms (T1 and T2) are either the same 5697 /// or T1 is a base class of T2. 5698 Ref_Related, 5699 /// Ref_Compatible_With_Added_Qualification - The two types are 5700 /// reference-compatible with added qualification, meaning that 5701 /// they are reference-compatible and the qualifiers on T1 (cv1) 5702 /// are greater than the qualifiers on T2 (cv2). 5703 Ref_Compatible_With_Added_Qualification, 5704 /// Ref_Compatible - The two types are reference-compatible and 5705 /// have equivalent qualifiers (cv1 == cv2). 5706 Ref_Compatible 5707 }; 5708 5709 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 5710 QualType T1, QualType T2, 5711 bool &DerivedToBase, 5712 bool &ObjCConversion, 5713 bool &ObjCLifetimeConversion); 5714 5715 /// CheckCastTypes - Check type constraints for casting between types under 5716 /// C semantics, or forward to CXXCheckCStyleCast in C++. 5717 ExprResult CheckCastTypes(SourceLocation CastStartLoc, SourceRange TypeRange, 5718 QualType CastType, Expr *CastExpr, CastKind &Kind, 5719 ExprValueKind &VK, CXXCastPath &BasePath, 5720 bool FunctionalStyle = false); 5721 5722 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 5723 Expr *CastExpr, CastKind &CastKind, 5724 ExprValueKind &VK, CXXCastPath &Path); 5725 5726 // CheckVectorCast - check type constraints for vectors. 5727 // Since vectors are an extension, there are no C standard reference for this. 5728 // We allow casting between vectors and integer datatypes of the same size. 5729 // returns true if the cast is invalid 5730 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5731 CastKind &Kind); 5732 5733 // CheckExtVectorCast - check type constraints for extended vectors. 5734 // Since vectors are an extension, there are no C standard reference for this. 5735 // We allow casting between vectors and integer datatypes of the same size, 5736 // or vectors and the element type of that vector. 5737 // returns the cast expr 5738 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 5739 CastKind &Kind); 5740 5741 /// CXXCheckCStyleCast - Check constraints of a C-style or function-style 5742 /// cast under C++ semantics. 5743 ExprResult CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK, 5744 Expr *CastExpr, CastKind &Kind, 5745 CXXCastPath &BasePath, bool FunctionalStyle); 5746 5747 /// \brief Checks for valid expressions which can be cast to an ObjC 5748 /// pointer without needing a bridge cast. 5749 bool ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType); 5750 5751 /// \brief Checks for invalid conversions and casts between 5752 /// retainable pointers and other pointer kinds. 5753 void CheckObjCARCConversion(SourceRange castRange, QualType castType, 5754 Expr *&op, CheckedConversionKind CCK); 5755 5756 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 5757 QualType ExprType); 5758 5759 /// checkRetainCycles - Check whether an Objective-C message send 5760 /// might create an obvious retain cycle. 5761 void checkRetainCycles(ObjCMessageExpr *msg); 5762 void checkRetainCycles(Expr *receiver, Expr *argument); 5763 5764 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 5765 /// to weak/__unsafe_unretained type. 5766 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 5767 5768 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 5769 /// to weak/__unsafe_unretained expression. 5770 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 5771 5772 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 5773 /// \param Method - May be null. 5774 /// \param [out] ReturnType - The return type of the send. 5775 /// \return true iff there were any incompatible types. 5776 bool CheckMessageArgumentTypes(QualType ReceiverType, 5777 Expr **Args, unsigned NumArgs, Selector Sel, 5778 ObjCMethodDecl *Method, bool isClassMessage, 5779 bool isSuperMessage, 5780 SourceLocation lbrac, SourceLocation rbrac, 5781 QualType &ReturnType, ExprValueKind &VK); 5782 5783 /// \brief Determine the result of a message send expression based on 5784 /// the type of the receiver, the method expected to receive the message, 5785 /// and the form of the message send. 5786 QualType getMessageSendResultType(QualType ReceiverType, 5787 ObjCMethodDecl *Method, 5788 bool isClassMessage, bool isSuperMessage); 5789 5790 /// \brief If the given expression involves a message send to a method 5791 /// with a related result type, emit a note describing what happened. 5792 void EmitRelatedResultTypeNote(const Expr *E); 5793 5794 /// CheckBooleanCondition - Diagnose problems involving the use of 5795 /// the given expression as a boolean condition (e.g. in an if 5796 /// statement). Also performs the standard function and array 5797 /// decays, possibly changing the input variable. 5798 /// 5799 /// \param Loc - A location associated with the condition, e.g. the 5800 /// 'if' keyword. 5801 /// \return true iff there were any errors 5802 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 5803 5804 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 5805 Expr *SubExpr); 5806 5807 /// DiagnoseAssignmentAsCondition - Given that an expression is 5808 /// being used as a boolean condition, warn if it's an assignment. 5809 void DiagnoseAssignmentAsCondition(Expr *E); 5810 5811 /// \brief Redundant parentheses over an equality comparison can indicate 5812 /// that the user intended an assignment used as condition. 5813 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 5814 5815 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 5816 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 5817 5818 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 5819 /// the specified width and sign. If an overflow occurs, detect it and emit 5820 /// the specified diagnostic. 5821 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 5822 unsigned NewWidth, bool NewSign, 5823 SourceLocation Loc, unsigned DiagID); 5824 5825 /// Checks that the Objective-C declaration is declared in the global scope. 5826 /// Emits an error and marks the declaration as invalid if it's not declared 5827 /// in the global scope. 5828 bool CheckObjCDeclScope(Decl *D); 5829 5830 /// VerifyIntegerConstantExpression - verifies that an expression is an ICE, 5831 /// and reports the appropriate diagnostics. Returns false on success. 5832 /// Can optionally return the value of the expression. 5833 bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0); 5834 5835 /// VerifyBitField - verifies that a bit field expression is an ICE and has 5836 /// the correct width, and that the field type is valid. 5837 /// Returns false on success. 5838 /// Can optionally return whether the bit-field is of width 0 5839 bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 5840 QualType FieldTy, const Expr *BitWidth, 5841 bool *ZeroWidth = 0); 5842 5843 /// \name Code completion 5844 //@{ 5845 /// \brief Describes the context in which code completion occurs. 5846 enum ParserCompletionContext { 5847 /// \brief Code completion occurs at top-level or namespace context. 5848 PCC_Namespace, 5849 /// \brief Code completion occurs within a class, struct, or union. 5850 PCC_Class, 5851 /// \brief Code completion occurs within an Objective-C interface, protocol, 5852 /// or category. 5853 PCC_ObjCInterface, 5854 /// \brief Code completion occurs within an Objective-C implementation or 5855 /// category implementation 5856 PCC_ObjCImplementation, 5857 /// \brief Code completion occurs within the list of instance variables 5858 /// in an Objective-C interface, protocol, category, or implementation. 5859 PCC_ObjCInstanceVariableList, 5860 /// \brief Code completion occurs following one or more template 5861 /// headers. 5862 PCC_Template, 5863 /// \brief Code completion occurs following one or more template 5864 /// headers within a class. 5865 PCC_MemberTemplate, 5866 /// \brief Code completion occurs within an expression. 5867 PCC_Expression, 5868 /// \brief Code completion occurs within a statement, which may 5869 /// also be an expression or a declaration. 5870 PCC_Statement, 5871 /// \brief Code completion occurs at the beginning of the 5872 /// initialization statement (or expression) in a for loop. 5873 PCC_ForInit, 5874 /// \brief Code completion occurs within the condition of an if, 5875 /// while, switch, or for statement. 5876 PCC_Condition, 5877 /// \brief Code completion occurs within the body of a function on a 5878 /// recovery path, where we do not have a specific handle on our position 5879 /// in the grammar. 5880 PCC_RecoveryInFunction, 5881 /// \brief Code completion occurs where only a type is permitted. 5882 PCC_Type, 5883 /// \brief Code completion occurs in a parenthesized expression, which 5884 /// might also be a type cast. 5885 PCC_ParenthesizedExpression, 5886 /// \brief Code completion occurs within a sequence of declaration 5887 /// specifiers within a function, method, or block. 5888 PCC_LocalDeclarationSpecifiers 5889 }; 5890 5891 void CodeCompleteOrdinaryName(Scope *S, 5892 ParserCompletionContext CompletionContext); 5893 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 5894 bool AllowNonIdentifiers, 5895 bool AllowNestedNameSpecifiers); 5896 5897 struct CodeCompleteExpressionData; 5898 void CodeCompleteExpression(Scope *S, 5899 const CodeCompleteExpressionData &Data); 5900 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 5901 SourceLocation OpLoc, 5902 bool IsArrow); 5903 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 5904 void CodeCompleteTag(Scope *S, unsigned TagSpec); 5905 void CodeCompleteTypeQualifiers(DeclSpec &DS); 5906 void CodeCompleteCase(Scope *S); 5907 void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs); 5908 void CodeCompleteInitializer(Scope *S, Decl *D); 5909 void CodeCompleteReturn(Scope *S); 5910 void CodeCompleteAfterIf(Scope *S); 5911 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 5912 5913 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 5914 bool EnteringContext); 5915 void CodeCompleteUsing(Scope *S); 5916 void CodeCompleteUsingDirective(Scope *S); 5917 void CodeCompleteNamespaceDecl(Scope *S); 5918 void CodeCompleteNamespaceAliasDecl(Scope *S); 5919 void CodeCompleteOperatorName(Scope *S); 5920 void CodeCompleteConstructorInitializer(Decl *Constructor, 5921 CXXCtorInitializer** Initializers, 5922 unsigned NumInitializers); 5923 5924 void CodeCompleteObjCAtDirective(Scope *S); 5925 void CodeCompleteObjCAtVisibility(Scope *S); 5926 void CodeCompleteObjCAtStatement(Scope *S); 5927 void CodeCompleteObjCAtExpression(Scope *S); 5928 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 5929 void CodeCompleteObjCPropertyGetter(Scope *S); 5930 void CodeCompleteObjCPropertySetter(Scope *S); 5931 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 5932 bool IsParameter); 5933 void CodeCompleteObjCMessageReceiver(Scope *S); 5934 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 5935 IdentifierInfo **SelIdents, 5936 unsigned NumSelIdents, 5937 bool AtArgumentExpression); 5938 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 5939 IdentifierInfo **SelIdents, 5940 unsigned NumSelIdents, 5941 bool AtArgumentExpression, 5942 bool IsSuper = false); 5943 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 5944 IdentifierInfo **SelIdents, 5945 unsigned NumSelIdents, 5946 bool AtArgumentExpression, 5947 ObjCInterfaceDecl *Super = 0); 5948 void CodeCompleteObjCForCollection(Scope *S, 5949 DeclGroupPtrTy IterationVar); 5950 void CodeCompleteObjCSelector(Scope *S, 5951 IdentifierInfo **SelIdents, 5952 unsigned NumSelIdents); 5953 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 5954 unsigned NumProtocols); 5955 void CodeCompleteObjCProtocolDecl(Scope *S); 5956 void CodeCompleteObjCInterfaceDecl(Scope *S); 5957 void CodeCompleteObjCSuperclass(Scope *S, 5958 IdentifierInfo *ClassName, 5959 SourceLocation ClassNameLoc); 5960 void CodeCompleteObjCImplementationDecl(Scope *S); 5961 void CodeCompleteObjCInterfaceCategory(Scope *S, 5962 IdentifierInfo *ClassName, 5963 SourceLocation ClassNameLoc); 5964 void CodeCompleteObjCImplementationCategory(Scope *S, 5965 IdentifierInfo *ClassName, 5966 SourceLocation ClassNameLoc); 5967 void CodeCompleteObjCPropertyDefinition(Scope *S); 5968 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 5969 IdentifierInfo *PropertyName); 5970 void CodeCompleteObjCMethodDecl(Scope *S, 5971 bool IsInstanceMethod, 5972 ParsedType ReturnType); 5973 void CodeCompleteObjCMethodDeclSelector(Scope *S, 5974 bool IsInstanceMethod, 5975 bool AtParameterName, 5976 ParsedType ReturnType, 5977 IdentifierInfo **SelIdents, 5978 unsigned NumSelIdents); 5979 void CodeCompletePreprocessorDirective(bool InConditional); 5980 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 5981 void CodeCompletePreprocessorMacroName(bool IsDefinition); 5982 void CodeCompletePreprocessorExpression(); 5983 void CodeCompletePreprocessorMacroArgument(Scope *S, 5984 IdentifierInfo *Macro, 5985 MacroInfo *MacroInfo, 5986 unsigned Argument); 5987 void CodeCompleteNaturalLanguage(); 5988 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 5989 SmallVectorImpl<CodeCompletionResult> &Results); 5990 //@} 5991 5992 //===--------------------------------------------------------------------===// 5993 // Extra semantic analysis beyond the C type system 5994 5995public: 5996 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 5997 unsigned ByteNo) const; 5998 5999private: 6000 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 6001 bool isSubscript=false, bool AllowOnePastEnd=true); 6002 void CheckArrayAccess(const Expr *E); 6003 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall); 6004 bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall); 6005 6006 bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall); 6007 bool CheckObjCString(Expr *Arg); 6008 6009 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 6010 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 6011 6012 bool SemaBuiltinVAStart(CallExpr *TheCall); 6013 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 6014 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 6015 6016public: 6017 // Used by C++ template instantiation. 6018 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 6019 6020private: 6021 bool SemaBuiltinPrefetch(CallExpr *TheCall); 6022 bool SemaBuiltinObjectSize(CallExpr *TheCall); 6023 bool SemaBuiltinLongjmp(CallExpr *TheCall); 6024 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 6025 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6026 llvm::APSInt &Result); 6027 6028 bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 6029 bool HasVAListArg, unsigned format_idx, 6030 unsigned firstDataArg, bool isPrintf); 6031 6032 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 6033 const CallExpr *TheCall, bool HasVAListArg, 6034 unsigned format_idx, unsigned firstDataArg, 6035 bool isPrintf); 6036 6037 void CheckNonNullArguments(const NonNullAttr *NonNull, 6038 const Expr * const *ExprArgs, 6039 SourceLocation CallSiteLoc); 6040 6041 void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg, 6042 unsigned format_idx, unsigned firstDataArg, 6043 bool isPrintf); 6044 6045 /// \brief Enumeration used to describe which of the memory setting or copying 6046 /// functions is being checked by \c CheckMemaccessArguments(). 6047 enum CheckedMemoryFunction { 6048 CMF_Memset, 6049 CMF_Memcpy, 6050 CMF_Memmove, 6051 CMF_Memcmp 6052 }; 6053 6054 void CheckMemaccessArguments(const CallExpr *Call, CheckedMemoryFunction CMF, 6055 IdentifierInfo *FnName); 6056 6057 void CheckStrlcpycatArguments(const CallExpr *Call, 6058 IdentifierInfo *FnName); 6059 6060 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 6061 SourceLocation ReturnLoc); 6062 void CheckFloatComparison(SourceLocation loc, Expr* lex, Expr* rex); 6063 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 6064 6065 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 6066 Expr *Init); 6067 6068 /// \brief The parser's current scope. 6069 /// 6070 /// The parser maintains this state here. 6071 Scope *CurScope; 6072 6073protected: 6074 friend class Parser; 6075 friend class InitializationSequence; 6076 friend class ASTReader; 6077 friend class ASTWriter; 6078 6079public: 6080 /// \brief Retrieve the parser's current scope. 6081 /// 6082 /// This routine must only be used when it is certain that semantic analysis 6083 /// and the parser are in precisely the same context, which is not the case 6084 /// when, e.g., we are performing any kind of template instantiation. 6085 /// Therefore, the only safe places to use this scope are in the parser 6086 /// itself and in routines directly invoked from the parser and *never* from 6087 /// template substitution or instantiation. 6088 Scope *getCurScope() const { return CurScope; } 6089 6090 Decl *getObjCDeclContext() const; 6091}; 6092 6093/// \brief RAII object that enters a new expression evaluation context. 6094class EnterExpressionEvaluationContext { 6095 Sema &Actions; 6096 6097public: 6098 EnterExpressionEvaluationContext(Sema &Actions, 6099 Sema::ExpressionEvaluationContext NewContext) 6100 : Actions(Actions) { 6101 Actions.PushExpressionEvaluationContext(NewContext); 6102 } 6103 6104 ~EnterExpressionEvaluationContext() { 6105 Actions.PopExpressionEvaluationContext(); 6106 } 6107}; 6108 6109} // end namespace clang 6110 6111#endif 6112