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