Initialization.h revision 13b228dacb6154d8b48d2f3a51e4e078fa7a7b9e
1//===--- Initialization.h - Semantic Analysis for Initializers --*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file provides supporting data types for initialization of objects. 11// 12//===----------------------------------------------------------------------===// 13#ifndef LLVM_CLANG_SEMA_INITIALIZATION_H 14#define LLVM_CLANG_SEMA_INITIALIZATION_H 15 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/Attr.h" 18#include "clang/AST/Type.h" 19#include "clang/AST/UnresolvedSet.h" 20#include "clang/Basic/SourceLocation.h" 21#include "clang/Sema/Overload.h" 22#include "clang/Sema/Ownership.h" 23#include "llvm/ADT/PointerIntPair.h" 24#include "llvm/ADT/SmallVector.h" 25#include <cassert> 26 27namespace clang { 28 29class CXXBaseSpecifier; 30class DeclaratorDecl; 31class DeclaratorInfo; 32class FieldDecl; 33class FunctionDecl; 34class ParmVarDecl; 35class Sema; 36class TypeLoc; 37class VarDecl; 38class ObjCMethodDecl; 39 40/// \brief Describes an entity that is being initialized. 41class InitializedEntity { 42public: 43 /// \brief Specifies the kind of entity being initialized. 44 enum EntityKind { 45 /// \brief The entity being initialized is a variable. 46 EK_Variable, 47 /// \brief The entity being initialized is a function parameter. 48 EK_Parameter, 49 /// \brief The entity being initialized is the result of a function call. 50 EK_Result, 51 /// \brief The entity being initialized is an exception object that 52 /// is being thrown. 53 EK_Exception, 54 /// \brief The entity being initialized is a non-static data member 55 /// subobject. 56 EK_Member, 57 /// \brief The entity being initialized is an element of an array. 58 EK_ArrayElement, 59 /// \brief The entity being initialized is an object (or array of 60 /// objects) allocated via new. 61 EK_New, 62 /// \brief The entity being initialized is a temporary object. 63 EK_Temporary, 64 /// \brief The entity being initialized is a base member subobject. 65 EK_Base, 66 /// \brief The initialization is being done by a delegating constructor. 67 EK_Delegating, 68 /// \brief The entity being initialized is an element of a vector. 69 /// or vector. 70 EK_VectorElement, 71 /// \brief The entity being initialized is a field of block descriptor for 72 /// the copied-in c++ object. 73 EK_BlockElement, 74 /// \brief The entity being initialized is the real or imaginary part of a 75 /// complex number. 76 EK_ComplexElement, 77 /// \brief The entity being initialized is the field that captures a 78 /// variable in a lambda. 79 EK_LambdaCapture, 80 /// \brief The entity being initialized is the initializer for a compound 81 /// literal. 82 EK_CompoundLiteralInit, 83 /// \brief The entity being implicitly initialized back to the formal 84 /// result type. 85 EK_RelatedResult, 86 /// \brief The entity being initialized is a function parameter; function 87 /// is member of group of audited CF APIs. 88 EK_Parameter_CF_Audited 89 90 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this 91 // enum as an index for its first %select. When modifying this list, 92 // that diagnostic text needs to be updated as well. 93 }; 94 95private: 96 /// \brief The kind of entity being initialized. 97 EntityKind Kind; 98 99 /// \brief If non-NULL, the parent entity in which this 100 /// initialization occurs. 101 const InitializedEntity *Parent; 102 103 /// \brief The type of the object or reference being initialized. 104 QualType Type; 105 106 struct LN { 107 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the 108 /// location of the 'return', 'throw', or 'new' keyword, 109 /// respectively. When Kind == EK_Temporary, the location where 110 /// the temporary is being created. 111 unsigned Location; 112 113 /// \brief Whether the entity being initialized may end up using the 114 /// named return value optimization (NRVO). 115 bool NRVO; 116 }; 117 118 struct C { 119 /// \brief The variable being captured by an EK_LambdaCapture. 120 VarDecl *Var; 121 122 /// \brief The source location at which the capture occurs. 123 unsigned Location; 124 }; 125 126 union { 127 /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or 128 /// FieldDecl, respectively. 129 DeclaratorDecl *VariableOrMember; 130 131 /// \brief When Kind == EK_RelatedResult, the ObjectiveC method where 132 /// result type was implicitly changed to accomodate ARC semantics. 133 ObjCMethodDecl *MethodDecl; 134 135 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the 136 /// low bit indicating whether the parameter is "consumed". 137 uintptr_t Parameter; 138 139 /// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type 140 /// source information for the temporary. 141 TypeSourceInfo *TypeInfo; 142 143 struct LN LocAndNRVO; 144 145 /// \brief When Kind == EK_Base, the base specifier that provides the 146 /// base class. The lower bit specifies whether the base is an inherited 147 /// virtual base. 148 uintptr_t Base; 149 150 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or 151 /// EK_ComplexElement, the index of the array or vector element being 152 /// initialized. 153 unsigned Index; 154 155 struct C Capture; 156 }; 157 158 InitializedEntity() { } 159 160 /// \brief Create the initialization entity for a variable. 161 InitializedEntity(VarDecl *Var) 162 : Kind(EK_Variable), Parent(0), Type(Var->getType()), 163 VariableOrMember(Var) { } 164 165 /// \brief Create the initialization entity for the result of a 166 /// function, throwing an object, performing an explicit cast, or 167 /// initializing a parameter for which there is no declaration. 168 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type, 169 bool NRVO = false) 170 : Kind(Kind), Parent(0), Type(Type) 171 { 172 LocAndNRVO.Location = Loc.getRawEncoding(); 173 LocAndNRVO.NRVO = NRVO; 174 } 175 176 /// \brief Create the initialization entity for a member subobject. 177 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent) 178 : Kind(EK_Member), Parent(Parent), Type(Member->getType()), 179 VariableOrMember(Member) { } 180 181 /// \brief Create the initialization entity for an array element. 182 InitializedEntity(ASTContext &Context, unsigned Index, 183 const InitializedEntity &Parent); 184 185 /// \brief Create the initialization entity for a lambda capture. 186 InitializedEntity(VarDecl *Var, FieldDecl *Field, SourceLocation Loc) 187 : Kind(EK_LambdaCapture), Parent(0), Type(Field->getType()) 188 { 189 Capture.Var = Var; 190 Capture.Location = Loc.getRawEncoding(); 191 } 192 193public: 194 /// \brief Create the initialization entity for a variable. 195 static InitializedEntity InitializeVariable(VarDecl *Var) { 196 return InitializedEntity(Var); 197 } 198 199 /// \brief Create the initialization entity for a parameter. 200 static InitializedEntity InitializeParameter(ASTContext &Context, 201 ParmVarDecl *Parm) { 202 return InitializeParameter(Context, Parm, Parm->getType()); 203 } 204 205 /// \brief Create the initialization entity for a parameter, but use 206 /// another type. 207 static InitializedEntity InitializeParameter(ASTContext &Context, 208 ParmVarDecl *Parm, 209 QualType Type) { 210 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount && 211 Parm->hasAttr<NSConsumedAttr>()); 212 213 InitializedEntity Entity; 214 Entity.Kind = EK_Parameter; 215 Entity.Type = 216 Context.getVariableArrayDecayedType(Type.getUnqualifiedType()); 217 Entity.Parent = 0; 218 Entity.Parameter 219 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm)); 220 return Entity; 221 } 222 223 /// \brief Create the initialization entity for a parameter that is 224 /// only known by its type. 225 static InitializedEntity InitializeParameter(ASTContext &Context, 226 QualType Type, 227 bool Consumed) { 228 InitializedEntity Entity; 229 Entity.Kind = EK_Parameter; 230 Entity.Type = Context.getVariableArrayDecayedType(Type); 231 Entity.Parent = 0; 232 Entity.Parameter = (Consumed); 233 return Entity; 234 } 235 236 /// \brief Create the initialization entity for the result of a function. 237 static InitializedEntity InitializeResult(SourceLocation ReturnLoc, 238 QualType Type, bool NRVO) { 239 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO); 240 } 241 242 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, 243 QualType Type, bool NRVO) { 244 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO); 245 } 246 247 /// \brief Create the initialization entity for an exception object. 248 static InitializedEntity InitializeException(SourceLocation ThrowLoc, 249 QualType Type, bool NRVO) { 250 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO); 251 } 252 253 /// \brief Create the initialization entity for an object allocated via new. 254 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) { 255 return InitializedEntity(EK_New, NewLoc, Type); 256 } 257 258 /// \brief Create the initialization entity for a temporary. 259 static InitializedEntity InitializeTemporary(QualType Type) { 260 InitializedEntity Result(EK_Temporary, SourceLocation(), Type); 261 Result.TypeInfo = 0; 262 return Result; 263 } 264 265 /// \brief Create the initialization entity for a temporary. 266 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) { 267 InitializedEntity Result(EK_Temporary, SourceLocation(), 268 TypeInfo->getType()); 269 Result.TypeInfo = TypeInfo; 270 return Result; 271 } 272 273 /// \brief Create the initialization entity for a related result. 274 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD, 275 QualType Type) { 276 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type); 277 Result.MethodDecl = MD; 278 return Result; 279 } 280 281 282 /// \brief Create the initialization entity for a base class subobject. 283 static InitializedEntity InitializeBase(ASTContext &Context, 284 const CXXBaseSpecifier *Base, 285 bool IsInheritedVirtualBase); 286 287 /// \brief Create the initialization entity for a delegated constructor. 288 static InitializedEntity InitializeDelegation(QualType Type) { 289 return InitializedEntity(EK_Delegating, SourceLocation(), Type); 290 } 291 292 /// \brief Create the initialization entity for a member subobject. 293 static InitializedEntity InitializeMember(FieldDecl *Member, 294 const InitializedEntity *Parent = 0) { 295 return InitializedEntity(Member, Parent); 296 } 297 298 /// \brief Create the initialization entity for a member subobject. 299 static InitializedEntity InitializeMember(IndirectFieldDecl *Member, 300 const InitializedEntity *Parent = 0) { 301 return InitializedEntity(Member->getAnonField(), Parent); 302 } 303 304 /// \brief Create the initialization entity for an array element. 305 static InitializedEntity InitializeElement(ASTContext &Context, 306 unsigned Index, 307 const InitializedEntity &Parent) { 308 return InitializedEntity(Context, Index, Parent); 309 } 310 311 /// \brief Create the initialization entity for a lambda capture. 312 static InitializedEntity InitializeLambdaCapture(VarDecl *Var, 313 FieldDecl *Field, 314 SourceLocation Loc) { 315 return InitializedEntity(Var, Field, Loc); 316 } 317 318 /// \brief Create the entity for a compound literal initializer. 319 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) { 320 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(), 321 TSI->getType()); 322 Result.TypeInfo = TSI; 323 return Result; 324 } 325 326 327 /// \brief Determine the kind of initialization. 328 EntityKind getKind() const { return Kind; } 329 330 /// \brief Retrieve the parent of the entity being initialized, when 331 /// the initialization itself is occurring within the context of a 332 /// larger initialization. 333 const InitializedEntity *getParent() const { return Parent; } 334 335 /// \brief Retrieve type being initialized. 336 QualType getType() const { return Type; } 337 338 /// \brief Retrieve complete type-source information for the object being 339 /// constructed, if known. 340 TypeSourceInfo *getTypeSourceInfo() const { 341 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit) 342 return TypeInfo; 343 344 return 0; 345 } 346 347 /// \brief Retrieve the name of the entity being initialized. 348 DeclarationName getName() const; 349 350 /// \brief Retrieve the variable, parameter, or field being 351 /// initialized. 352 DeclaratorDecl *getDecl() const; 353 354 /// \brief Retrieve the ObjectiveC method being initialized. 355 ObjCMethodDecl *getMethodDecl() const { return MethodDecl; } 356 357 /// \brief Determine whether this initialization allows the named return 358 /// value optimization, which also applies to thrown objects. 359 bool allowsNRVO() const; 360 361 bool isParameterKind() const { 362 return (getKind() == EK_Parameter || 363 getKind() == EK_Parameter_CF_Audited); 364 } 365 /// \brief Determine whether this initialization consumes the 366 /// parameter. 367 bool isParameterConsumed() const { 368 assert(isParameterKind() && "Not a parameter"); 369 return (Parameter & 1); 370 } 371 372 /// \brief Retrieve the base specifier. 373 const CXXBaseSpecifier *getBaseSpecifier() const { 374 assert(getKind() == EK_Base && "Not a base specifier"); 375 return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1); 376 } 377 378 /// \brief Return whether the base is an inherited virtual base. 379 bool isInheritedVirtualBase() const { 380 assert(getKind() == EK_Base && "Not a base specifier"); 381 return Base & 0x1; 382 } 383 384 /// \brief Determine the location of the 'return' keyword when initializing 385 /// the result of a function call. 386 SourceLocation getReturnLoc() const { 387 assert(getKind() == EK_Result && "No 'return' location!"); 388 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location); 389 } 390 391 /// \brief Determine the location of the 'throw' keyword when initializing 392 /// an exception object. 393 SourceLocation getThrowLoc() const { 394 assert(getKind() == EK_Exception && "No 'throw' location!"); 395 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location); 396 } 397 398 /// \brief If this is already the initializer for an array or vector 399 /// element, sets the element index. 400 void setElementIndex(unsigned Index) { 401 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement || 402 getKind() == EK_ComplexElement); 403 this->Index = Index; 404 } 405 406 /// \brief Retrieve the variable for a captured variable in a lambda. 407 VarDecl *getCapturedVar() const { 408 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!"); 409 return Capture.Var; 410 } 411 412 /// \brief Determine the location of the capture when initializing 413 /// field from a captured variable in a lambda. 414 SourceLocation getCaptureLoc() const { 415 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!"); 416 return SourceLocation::getFromRawEncoding(Capture.Location); 417 } 418 419 void setParameterCFAudited() { 420 Kind = EK_Parameter_CF_Audited; 421 } 422 423 /// Dump a representation of the initialized entity to standard error, 424 /// for debugging purposes. 425 void dump() const; 426 427private: 428 unsigned dumpImpl(raw_ostream &OS) const; 429}; 430 431/// \brief Describes the kind of initialization being performed, along with 432/// location information for tokens related to the initialization (equal sign, 433/// parentheses). 434class InitializationKind { 435public: 436 /// \brief The kind of initialization being performed. 437 enum InitKind { 438 IK_Direct, ///< Direct initialization 439 IK_DirectList, ///< Direct list-initialization 440 IK_Copy, ///< Copy initialization 441 IK_Default, ///< Default initialization 442 IK_Value ///< Value initialization 443 }; 444 445private: 446 /// \brief The context of the initialization. 447 enum InitContext { 448 IC_Normal, ///< Normal context 449 IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs 450 IC_Implicit, ///< Implicit context (value initialization) 451 IC_StaticCast, ///< Static cast context 452 IC_CStyleCast, ///< C-style cast context 453 IC_FunctionalCast ///< Functional cast context 454 }; 455 456 /// \brief The kind of initialization being performed. 457 InitKind Kind : 8; 458 459 /// \brief The context of the initialization. 460 InitContext Context : 8; 461 462 /// \brief The source locations involved in the initialization. 463 SourceLocation Locations[3]; 464 465 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1, 466 SourceLocation Loc2, SourceLocation Loc3) 467 : Kind(Kind), Context(Context) 468 { 469 Locations[0] = Loc1; 470 Locations[1] = Loc2; 471 Locations[2] = Loc3; 472 } 473 474public: 475 /// \brief Create a direct initialization. 476 static InitializationKind CreateDirect(SourceLocation InitLoc, 477 SourceLocation LParenLoc, 478 SourceLocation RParenLoc) { 479 return InitializationKind(IK_Direct, IC_Normal, 480 InitLoc, LParenLoc, RParenLoc); 481 } 482 483 static InitializationKind CreateDirectList(SourceLocation InitLoc) { 484 return InitializationKind(IK_DirectList, IC_Normal, 485 InitLoc, InitLoc, InitLoc); 486 } 487 488 /// \brief Create a direct initialization due to a cast that isn't a C-style 489 /// or functional cast. 490 static InitializationKind CreateCast(SourceRange TypeRange) { 491 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(), 492 TypeRange.getBegin(), TypeRange.getEnd()); 493 } 494 495 /// \brief Create a direct initialization for a C-style cast. 496 static InitializationKind CreateCStyleCast(SourceLocation StartLoc, 497 SourceRange TypeRange, 498 bool InitList) { 499 // C++ cast syntax doesn't permit init lists, but C compound literals are 500 // exactly that. 501 return InitializationKind(InitList ? IK_DirectList : IK_Direct, 502 IC_CStyleCast, StartLoc, TypeRange.getBegin(), 503 TypeRange.getEnd()); 504 } 505 506 /// \brief Create a direct initialization for a functional cast. 507 static InitializationKind CreateFunctionalCast(SourceRange TypeRange, 508 bool InitList) { 509 return InitializationKind(InitList ? IK_DirectList : IK_Direct, 510 IC_FunctionalCast, TypeRange.getBegin(), 511 TypeRange.getBegin(), TypeRange.getEnd()); 512 } 513 514 /// \brief Create a copy initialization. 515 static InitializationKind CreateCopy(SourceLocation InitLoc, 516 SourceLocation EqualLoc, 517 bool AllowExplicitConvs = false) { 518 return InitializationKind(IK_Copy, 519 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal, 520 InitLoc, EqualLoc, EqualLoc); 521 } 522 523 /// \brief Create a default initialization. 524 static InitializationKind CreateDefault(SourceLocation InitLoc) { 525 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc); 526 } 527 528 /// \brief Create a value initialization. 529 static InitializationKind CreateValue(SourceLocation InitLoc, 530 SourceLocation LParenLoc, 531 SourceLocation RParenLoc, 532 bool isImplicit = false) { 533 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal, 534 InitLoc, LParenLoc, RParenLoc); 535 } 536 537 /// \brief Determine the initialization kind. 538 InitKind getKind() const { 539 return Kind; 540 } 541 542 /// \brief Determine whether this initialization is an explicit cast. 543 bool isExplicitCast() const { 544 return Context >= IC_StaticCast; 545 } 546 547 /// \brief Determine whether this initialization is a C-style cast. 548 bool isCStyleOrFunctionalCast() const { 549 return Context >= IC_CStyleCast; 550 } 551 552 /// \brief Determine whether this is a C-style cast. 553 bool isCStyleCast() const { 554 return Context == IC_CStyleCast; 555 } 556 557 /// \brief Determine whether this is a functional-style cast. 558 bool isFunctionalCast() const { 559 return Context == IC_FunctionalCast; 560 } 561 562 /// \brief Determine whether this initialization is an implicit 563 /// value-initialization, e.g., as occurs during aggregate 564 /// initialization. 565 bool isImplicitValueInit() const { return Context == IC_Implicit; } 566 567 /// \brief Retrieve the location at which initialization is occurring. 568 SourceLocation getLocation() const { return Locations[0]; } 569 570 /// \brief Retrieve the source range that covers the initialization. 571 SourceRange getRange() const { 572 return SourceRange(Locations[0], Locations[2]); 573 } 574 575 /// \brief Retrieve the location of the equal sign for copy initialization 576 /// (if present). 577 SourceLocation getEqualLoc() const { 578 assert(Kind == IK_Copy && "Only copy initialization has an '='"); 579 return Locations[1]; 580 } 581 582 bool isCopyInit() const { return Kind == IK_Copy; } 583 584 /// \brief Retrieve whether this initialization allows the use of explicit 585 /// constructors. 586 bool AllowExplicit() const { return !isCopyInit(); } 587 588 /// \brief Retrieve whether this initialization allows the use of explicit 589 /// conversion functions. 590 bool allowExplicitConversionFunctions() const { 591 return !isCopyInit() || Context == IC_ExplicitConvs; 592 } 593 594 /// \brief Retrieve the source range containing the locations of the open 595 /// and closing parentheses for value and direct initializations. 596 SourceRange getParenRange() const { 597 assert((Kind == IK_Direct || Kind == IK_Value) && 598 "Only direct- and value-initialization have parentheses"); 599 return SourceRange(Locations[1], Locations[2]); 600 } 601}; 602 603/// \brief Describes the sequence of initializations required to initialize 604/// a given object or reference with a set of arguments. 605class InitializationSequence { 606public: 607 /// \brief Describes the kind of initialization sequence computed. 608 enum SequenceKind { 609 /// \brief A failed initialization sequence. The failure kind tells what 610 /// happened. 611 FailedSequence = 0, 612 613 /// \brief A dependent initialization, which could not be 614 /// type-checked due to the presence of dependent types or 615 /// dependently-typed expressions. 616 DependentSequence, 617 618 /// \brief A normal sequence. 619 NormalSequence 620 }; 621 622 /// \brief Describes the kind of a particular step in an initialization 623 /// sequence. 624 enum StepKind { 625 /// \brief Resolve the address of an overloaded function to a specific 626 /// function declaration. 627 SK_ResolveAddressOfOverloadedFunction, 628 /// \brief Perform a derived-to-base cast, producing an rvalue. 629 SK_CastDerivedToBaseRValue, 630 /// \brief Perform a derived-to-base cast, producing an xvalue. 631 SK_CastDerivedToBaseXValue, 632 /// \brief Perform a derived-to-base cast, producing an lvalue. 633 SK_CastDerivedToBaseLValue, 634 /// \brief Reference binding to an lvalue. 635 SK_BindReference, 636 /// \brief Reference binding to a temporary. 637 SK_BindReferenceToTemporary, 638 /// \brief An optional copy of a temporary object to another 639 /// temporary object, which is permitted (but not required) by 640 /// C++98/03 but not C++0x. 641 SK_ExtraneousCopyToTemporary, 642 /// \brief Perform a user-defined conversion, either via a conversion 643 /// function or via a constructor. 644 SK_UserConversion, 645 /// \brief Perform a qualification conversion, producing an rvalue. 646 SK_QualificationConversionRValue, 647 /// \brief Perform a qualification conversion, producing an xvalue. 648 SK_QualificationConversionXValue, 649 /// \brief Perform a qualification conversion, producing an lvalue. 650 SK_QualificationConversionLValue, 651 /// \brief Perform a load from a glvalue, producing an rvalue. 652 SK_LValueToRValue, 653 /// \brief Perform an implicit conversion sequence. 654 SK_ConversionSequence, 655 /// \brief Perform an implicit conversion sequence without narrowing. 656 SK_ConversionSequenceNoNarrowing, 657 /// \brief Perform list-initialization without a constructor 658 SK_ListInitialization, 659 /// \brief Perform list-initialization with a constructor. 660 SK_ListConstructorCall, 661 /// \brief Unwrap the single-element initializer list for a reference. 662 SK_UnwrapInitList, 663 /// \brief Rewrap the single-element initializer list for a reference. 664 SK_RewrapInitList, 665 /// \brief Perform initialization via a constructor. 666 SK_ConstructorInitialization, 667 /// \brief Zero-initialize the object 668 SK_ZeroInitialization, 669 /// \brief C assignment 670 SK_CAssignment, 671 /// \brief Initialization by string 672 SK_StringInit, 673 /// \brief An initialization that "converts" an Objective-C object 674 /// (not a point to an object) to another Objective-C object type. 675 SK_ObjCObjectConversion, 676 /// \brief Array initialization (from an array rvalue). 677 /// This is a GNU C extension. 678 SK_ArrayInit, 679 /// \brief Array initialization from a parenthesized initializer list. 680 /// This is a GNU C++ extension. 681 SK_ParenthesizedArrayInit, 682 /// \brief Pass an object by indirect copy-and-restore. 683 SK_PassByIndirectCopyRestore, 684 /// \brief Pass an object by indirect restore. 685 SK_PassByIndirectRestore, 686 /// \brief Produce an Objective-C object pointer. 687 SK_ProduceObjCObject, 688 /// \brief Construct a std::initializer_list from an initializer list. 689 SK_StdInitializerList, 690 /// \brief Initialize an OpenCL sampler from an integer. 691 SK_OCLSamplerInit, 692 /// \brief Passing zero to a function where OpenCL event_t is expected. 693 SK_OCLZeroEvent 694 }; 695 696 /// \brief A single step in the initialization sequence. 697 class Step { 698 public: 699 /// \brief The kind of conversion or initialization step we are taking. 700 StepKind Kind; 701 702 // \brief The type that results from this initialization. 703 QualType Type; 704 705 struct F { 706 bool HadMultipleCandidates; 707 FunctionDecl *Function; 708 DeclAccessPair FoundDecl; 709 }; 710 711 union { 712 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind == 713 /// SK_UserConversion, the function that the expression should be 714 /// resolved to or the conversion function to call, respectively. 715 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction, 716 /// the constructor to be called. 717 /// 718 /// Always a FunctionDecl, plus a Boolean flag telling if it was 719 /// selected from an overloaded set having size greater than 1. 720 /// For conversion decls, the naming class is the source type. 721 /// For construct decls, the naming class is the target type. 722 struct F Function; 723 724 /// \brief When Kind = SK_ConversionSequence, the implicit conversion 725 /// sequence. 726 ImplicitConversionSequence *ICS; 727 728 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the 729 /// wrapping list. 730 InitListExpr *WrappingSyntacticList; 731 }; 732 733 void Destroy(); 734 }; 735 736private: 737 /// \brief The kind of initialization sequence computed. 738 enum SequenceKind SequenceKind; 739 740 /// \brief Steps taken by this initialization. 741 SmallVector<Step, 4> Steps; 742 743public: 744 /// \brief Describes why initialization failed. 745 enum FailureKind { 746 /// \brief Too many initializers provided for a reference. 747 FK_TooManyInitsForReference, 748 /// \brief Array must be initialized with an initializer list. 749 FK_ArrayNeedsInitList, 750 /// \brief Array must be initialized with an initializer list or a 751 /// string literal. 752 FK_ArrayNeedsInitListOrStringLiteral, 753 /// \brief Array must be initialized with an initializer list or a 754 /// wide string literal. 755 FK_ArrayNeedsInitListOrWideStringLiteral, 756 /// \brief Initializing a wide char array with narrow string literal. 757 FK_NarrowStringIntoWideCharArray, 758 /// \brief Initializing char array with wide string literal. 759 FK_WideStringIntoCharArray, 760 /// \brief Initializing wide char array with incompatible wide string 761 /// literal. 762 FK_IncompatWideStringIntoWideChar, 763 /// \brief Array type mismatch. 764 FK_ArrayTypeMismatch, 765 /// \brief Non-constant array initializer 766 FK_NonConstantArrayInit, 767 /// \brief Cannot resolve the address of an overloaded function. 768 FK_AddressOfOverloadFailed, 769 /// \brief Overloading due to reference initialization failed. 770 FK_ReferenceInitOverloadFailed, 771 /// \brief Non-const lvalue reference binding to a temporary. 772 FK_NonConstLValueReferenceBindingToTemporary, 773 /// \brief Non-const lvalue reference binding to an lvalue of unrelated 774 /// type. 775 FK_NonConstLValueReferenceBindingToUnrelated, 776 /// \brief Rvalue reference binding to an lvalue. 777 FK_RValueReferenceBindingToLValue, 778 /// \brief Reference binding drops qualifiers. 779 FK_ReferenceInitDropsQualifiers, 780 /// \brief Reference binding failed. 781 FK_ReferenceInitFailed, 782 /// \brief Implicit conversion failed. 783 FK_ConversionFailed, 784 /// \brief Implicit conversion failed. 785 FK_ConversionFromPropertyFailed, 786 /// \brief Too many initializers for scalar 787 FK_TooManyInitsForScalar, 788 /// \brief Reference initialization from an initializer list 789 FK_ReferenceBindingToInitList, 790 /// \brief Initialization of some unused destination type with an 791 /// initializer list. 792 FK_InitListBadDestinationType, 793 /// \brief Overloading for a user-defined conversion failed. 794 FK_UserConversionOverloadFailed, 795 /// \brief Overloading for initialization by constructor failed. 796 FK_ConstructorOverloadFailed, 797 /// \brief Overloading for list-initialization by constructor failed. 798 FK_ListConstructorOverloadFailed, 799 /// \brief Default-initialization of a 'const' object. 800 FK_DefaultInitOfConst, 801 /// \brief Initialization of an incomplete type. 802 FK_Incomplete, 803 /// \brief Variable-length array must not have an initializer. 804 FK_VariableLengthArrayHasInitializer, 805 /// \brief List initialization failed at some point. 806 FK_ListInitializationFailed, 807 /// \brief Initializer has a placeholder type which cannot be 808 /// resolved by initialization. 809 FK_PlaceholderType, 810 /// \brief List-copy-initialization chose an explicit constructor. 811 FK_ExplicitConstructor 812 }; 813 814private: 815 /// \brief The reason why initialization failed. 816 FailureKind Failure; 817 818 /// \brief The failed result of overload resolution. 819 OverloadingResult FailedOverloadResult; 820 821 /// \brief The candidate set created when initialization failed. 822 OverloadCandidateSet FailedCandidateSet; 823 824 /// \brief The incomplete type that caused a failure. 825 QualType FailedIncompleteType; 826 827 /// \brief Prints a follow-up note that highlights the location of 828 /// the initialized entity, if it's remote. 829 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity); 830 831public: 832 /// \brief Try to perform initialization of the given entity, creating a 833 /// record of the steps required to perform the initialization. 834 /// 835 /// The generated initialization sequence will either contain enough 836 /// information to diagnose 837 /// 838 /// \param S the semantic analysis object. 839 /// 840 /// \param Entity the entity being initialized. 841 /// 842 /// \param Kind the kind of initialization being performed. 843 /// 844 /// \param Args the argument(s) provided for initialization. 845 /// 846 /// \param InInitList true if we are initializing from an expression within 847 /// an initializer list. This disallows narrowing conversions in C++11 848 /// onwards. 849 InitializationSequence(Sema &S, 850 const InitializedEntity &Entity, 851 const InitializationKind &Kind, 852 MultiExprArg Args, 853 bool InInitList = false); 854 ~InitializationSequence(); 855 856 /// \brief Perform the actual initialization of the given entity based on 857 /// the computed initialization sequence. 858 /// 859 /// \param S the semantic analysis object. 860 /// 861 /// \param Entity the entity being initialized. 862 /// 863 /// \param Kind the kind of initialization being performed. 864 /// 865 /// \param Args the argument(s) provided for initialization, ownership of 866 /// which is transferred into the routine. 867 /// 868 /// \param ResultType if non-NULL, will be set to the type of the 869 /// initialized object, which is the type of the declaration in most 870 /// cases. However, when the initialized object is a variable of 871 /// incomplete array type and the initializer is an initializer 872 /// list, this type will be set to the completed array type. 873 /// 874 /// \returns an expression that performs the actual object initialization, if 875 /// the initialization is well-formed. Otherwise, emits diagnostics 876 /// and returns an invalid expression. 877 ExprResult Perform(Sema &S, 878 const InitializedEntity &Entity, 879 const InitializationKind &Kind, 880 MultiExprArg Args, 881 QualType *ResultType = 0); 882 883 /// \brief Diagnose an potentially-invalid initialization sequence. 884 /// 885 /// \returns true if the initialization sequence was ill-formed, 886 /// false otherwise. 887 bool Diagnose(Sema &S, 888 const InitializedEntity &Entity, 889 const InitializationKind &Kind, 890 ArrayRef<Expr *> Args); 891 892 /// \brief Determine the kind of initialization sequence computed. 893 enum SequenceKind getKind() const { return SequenceKind; } 894 895 /// \brief Set the kind of sequence computed. 896 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; } 897 898 /// \brief Determine whether the initialization sequence is valid. 899 LLVM_EXPLICIT operator bool() const { return !Failed(); } 900 901 /// \brief Determine whether the initialization sequence is invalid. 902 bool Failed() const { return SequenceKind == FailedSequence; } 903 904 typedef SmallVectorImpl<Step>::const_iterator step_iterator; 905 step_iterator step_begin() const { return Steps.begin(); } 906 step_iterator step_end() const { return Steps.end(); } 907 908 /// \brief Determine whether this initialization is a direct reference 909 /// binding (C++ [dcl.init.ref]). 910 bool isDirectReferenceBinding() const; 911 912 /// \brief Determine whether this initialization failed due to an ambiguity. 913 bool isAmbiguous() const; 914 915 /// \brief Determine whether this initialization is direct call to a 916 /// constructor. 917 bool isConstructorInitialization() const; 918 919 /// \brief Returns whether the last step in this initialization sequence is a 920 /// narrowing conversion, defined by C++0x [dcl.init.list]p7. 921 /// 922 /// If this function returns true, *isInitializerConstant will be set to 923 /// describe whether *Initializer was a constant expression. If 924 /// *isInitializerConstant is set to true, *ConstantValue will be set to the 925 /// evaluated value of *Initializer. 926 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer, 927 bool *isInitializerConstant, 928 APValue *ConstantValue) const; 929 930 /// \brief Add a new step in the initialization that resolves the address 931 /// of an overloaded function to a specific function declaration. 932 /// 933 /// \param Function the function to which the overloaded function reference 934 /// resolves. 935 void AddAddressOverloadResolutionStep(FunctionDecl *Function, 936 DeclAccessPair Found, 937 bool HadMultipleCandidates); 938 939 /// \brief Add a new step in the initialization that performs a derived-to- 940 /// base cast. 941 /// 942 /// \param BaseType the base type to which we will be casting. 943 /// 944 /// \param Category Indicates whether the result will be treated as an 945 /// rvalue, an xvalue, or an lvalue. 946 void AddDerivedToBaseCastStep(QualType BaseType, 947 ExprValueKind Category); 948 949 /// \brief Add a new step binding a reference to an object. 950 /// 951 /// \param BindingTemporary True if we are binding a reference to a temporary 952 /// object (thereby extending its lifetime); false if we are binding to an 953 /// lvalue or an lvalue treated as an rvalue. 954 void AddReferenceBindingStep(QualType T, bool BindingTemporary); 955 956 /// \brief Add a new step that makes an extraneous copy of the input 957 /// to a temporary of the same class type. 958 /// 959 /// This extraneous copy only occurs during reference binding in 960 /// C++98/03, where we are permitted (but not required) to introduce 961 /// an extra copy. At a bare minimum, we must check that we could 962 /// call the copy constructor, and produce a diagnostic if the copy 963 /// constructor is inaccessible or no copy constructor matches. 964 // 965 /// \param T The type of the temporary being created. 966 void AddExtraneousCopyToTemporary(QualType T); 967 968 /// \brief Add a new step invoking a conversion function, which is either 969 /// a constructor or a conversion function. 970 void AddUserConversionStep(FunctionDecl *Function, 971 DeclAccessPair FoundDecl, 972 QualType T, 973 bool HadMultipleCandidates); 974 975 /// \brief Add a new step that performs a qualification conversion to the 976 /// given type. 977 void AddQualificationConversionStep(QualType Ty, 978 ExprValueKind Category); 979 980 /// \brief Add a new step that performs a load of the given type. 981 /// 982 /// Although the term "LValueToRValue" is conventional, this applies to both 983 /// lvalues and xvalues. 984 void AddLValueToRValueStep(QualType Ty); 985 986 /// \brief Add a new step that applies an implicit conversion sequence. 987 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, 988 QualType T, bool TopLevelOfInitList = false); 989 990 /// \brief Add a list-initialization step. 991 void AddListInitializationStep(QualType T); 992 993 /// \brief Add a constructor-initialization step. 994 /// 995 /// \param FromInitList The constructor call is syntactically an initializer 996 /// list. 997 /// \param AsInitList The constructor is called as an init list constructor. 998 void AddConstructorInitializationStep(CXXConstructorDecl *Constructor, 999 AccessSpecifier Access, 1000 QualType T, 1001 bool HadMultipleCandidates, 1002 bool FromInitList, bool AsInitList); 1003 1004 /// \brief Add a zero-initialization step. 1005 void AddZeroInitializationStep(QualType T); 1006 1007 /// \brief Add a C assignment step. 1008 // 1009 // FIXME: It isn't clear whether this should ever be needed; 1010 // ideally, we would handle everything needed in C in the common 1011 // path. However, that isn't the case yet. 1012 void AddCAssignmentStep(QualType T); 1013 1014 /// \brief Add a string init step. 1015 void AddStringInitStep(QualType T); 1016 1017 /// \brief Add an Objective-C object conversion step, which is 1018 /// always a no-op. 1019 void AddObjCObjectConversionStep(QualType T); 1020 1021 /// \brief Add an array initialization step. 1022 void AddArrayInitStep(QualType T); 1023 1024 /// \brief Add a parenthesized array initialization step. 1025 void AddParenthesizedArrayInitStep(QualType T); 1026 1027 /// \brief Add a step to pass an object by indirect copy-restore. 1028 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy); 1029 1030 /// \brief Add a step to "produce" an Objective-C object (by 1031 /// retaining it). 1032 void AddProduceObjCObjectStep(QualType T); 1033 1034 /// \brief Add a step to construct a std::initializer_list object from an 1035 /// initializer list. 1036 void AddStdInitializerListConstructionStep(QualType T); 1037 1038 /// \brief Add a step to initialize an OpenCL sampler from an integer 1039 /// constant. 1040 void AddOCLSamplerInitStep(QualType T); 1041 1042 /// \brief Add a step to initialize an OpenCL event_t from a NULL 1043 /// constant. 1044 void AddOCLZeroEventStep(QualType T); 1045 1046 /// \brief Add steps to unwrap a initializer list for a reference around a 1047 /// single element and rewrap it at the end. 1048 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic); 1049 1050 /// \brief Note that this initialization sequence failed. 1051 void SetFailed(FailureKind Failure) { 1052 SequenceKind = FailedSequence; 1053 this->Failure = Failure; 1054 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) && 1055 "Incomplete type failure requires a type!"); 1056 } 1057 1058 /// \brief Note that this initialization sequence failed due to failed 1059 /// overload resolution. 1060 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result); 1061 1062 /// \brief Retrieve a reference to the candidate set when overload 1063 /// resolution fails. 1064 OverloadCandidateSet &getFailedCandidateSet() { 1065 return FailedCandidateSet; 1066 } 1067 1068 /// \brief Get the overloading result, for when the initialization 1069 /// sequence failed due to a bad overload. 1070 OverloadingResult getFailedOverloadResult() const { 1071 return FailedOverloadResult; 1072 } 1073 1074 /// \brief Note that this initialization sequence failed due to an 1075 /// incomplete type. 1076 void setIncompleteTypeFailure(QualType IncompleteType) { 1077 FailedIncompleteType = IncompleteType; 1078 SetFailed(FK_Incomplete); 1079 } 1080 1081 /// \brief Determine why initialization failed. 1082 FailureKind getFailureKind() const { 1083 assert(Failed() && "Not an initialization failure!"); 1084 return Failure; 1085 } 1086 1087 /// \brief Dump a representation of this initialization sequence to 1088 /// the given stream, for debugging purposes. 1089 void dump(raw_ostream &OS) const; 1090 1091 /// \brief Dump a representation of this initialization sequence to 1092 /// standard error, for debugging purposes. 1093 void dump() const; 1094}; 1095 1096} // end namespace clang 1097 1098#endif // LLVM_CLANG_SEMA_INITIALIZATION_H 1099