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