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