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