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