• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   /// \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 
InitializedEntity()161   InitializedEntity() : ManglingNumber(0) {}
162 
163   /// \brief Create the initialization entity for a variable.
InitializedEntity(VarDecl * Var)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)
Kind(Kind)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.
InitializedEntity(FieldDecl * Member,const InitializedEntity * Parent)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.
InitializedEntity(IdentifierInfo * VarID,QualType FieldType,SourceLocation Loc)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 
197 public:
198   /// \brief Create the initialization entity for a variable.
InitializeVariable(VarDecl * Var)199   static InitializedEntity InitializeVariable(VarDecl *Var) {
200     return InitializedEntity(Var);
201   }
202 
203   /// \brief Create the initialization entity for a parameter.
InitializeParameter(ASTContext & Context,ParmVarDecl * Parm)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.
InitializeParameter(ASTContext & Context,ParmVarDecl * Parm,QualType 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.
InitializeParameter(ASTContext & Context,QualType Type,bool Consumed)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.
InitializeResult(SourceLocation ReturnLoc,QualType Type,bool NRVO)241   static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
242                                             QualType Type, bool NRVO) {
243     return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
244   }
245 
InitializeBlock(SourceLocation BlockVarLoc,QualType Type,bool NRVO)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.
InitializeException(SourceLocation ThrowLoc,QualType Type,bool NRVO)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.
InitializeNew(SourceLocation NewLoc,QualType Type)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.
InitializeTemporary(QualType Type)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.
InitializeTemporary(TypeSourceInfo * TypeInfo)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.
InitializeRelatedResult(ObjCMethodDecl * MD,QualType Type)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.
InitializeDelegation(QualType Type)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.
InitializeElement(ASTContext & Context,unsigned Index,const InitializedEntity & Parent)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.
InitializeLambdaCapture(IdentifierInfo * VarID,QualType FieldType,SourceLocation Loc)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.
InitializeCompoundLiteralInit(TypeSourceInfo * TSI)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.
getKind()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.
getParent()339   const InitializedEntity *getParent() const { return Parent; }
340 
341   /// \brief Retrieve type being initialized.
getType()342   QualType getType() const { return Type; }
343 
344   /// \brief Retrieve complete type-source information for the object being
345   /// constructed, if known.
getTypeSourceInfo()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.
getMethodDecl()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 
isParameterKind()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.
isParameterConsumed()373   bool isParameterConsumed() const {
374     assert(isParameterKind() && "Not a parameter");
375     return (Parameter & 1);
376   }
377 
378   /// \brief Retrieve the base specifier.
getBaseSpecifier()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.
isInheritedVirtualBase()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.
getReturnLoc()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.
getThrowLoc()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 an array, vector, or complex number element, get the
405   /// element's index.
getElementIndex()406   unsigned getElementIndex() const {
407     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
408            getKind() == EK_ComplexElement);
409     return Index;
410   }
411   /// \brief If this is already the initializer for an array or vector
412   /// element, sets the element index.
setElementIndex(unsigned Index)413   void setElementIndex(unsigned Index) {
414     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
415            getKind() == EK_ComplexElement);
416     this->Index = Index;
417   }
418   /// \brief For a lambda capture, return the capture's name.
getCapturedVarName()419   StringRef getCapturedVarName() const {
420     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
421     return Capture.VarID->getName();
422   }
423   /// \brief Determine the location of the capture when initializing
424   /// field from a captured variable in a lambda.
getCaptureLoc()425   SourceLocation getCaptureLoc() const {
426     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
427     return SourceLocation::getFromRawEncoding(Capture.Location);
428   }
429 
setParameterCFAudited()430   void setParameterCFAudited() {
431     Kind = EK_Parameter_CF_Audited;
432   }
433 
allocateManglingNumber()434   unsigned allocateManglingNumber() const { return ++ManglingNumber; }
435 
436   /// Dump a representation of the initialized entity to standard error,
437   /// for debugging purposes.
438   void dump() const;
439 
440 private:
441   unsigned dumpImpl(raw_ostream &OS) const;
442 };
443 
444 /// \brief Describes the kind of initialization being performed, along with
445 /// location information for tokens related to the initialization (equal sign,
446 /// parentheses).
447 class InitializationKind {
448 public:
449   /// \brief The kind of initialization being performed.
450   enum InitKind {
451     IK_Direct,       ///< Direct initialization
452     IK_DirectList,   ///< Direct list-initialization
453     IK_Copy,         ///< Copy initialization
454     IK_Default,      ///< Default initialization
455     IK_Value         ///< Value initialization
456   };
457 
458 private:
459   /// \brief The context of the initialization.
460   enum InitContext {
461     IC_Normal,         ///< Normal context
462     IC_ExplicitConvs,  ///< Normal context, but allows explicit conversion funcs
463     IC_Implicit,       ///< Implicit context (value initialization)
464     IC_StaticCast,     ///< Static cast context
465     IC_CStyleCast,     ///< C-style cast context
466     IC_FunctionalCast  ///< Functional cast context
467   };
468 
469   /// \brief The kind of initialization being performed.
470   InitKind Kind : 8;
471 
472   /// \brief The context of the initialization.
473   InitContext Context : 8;
474 
475   /// \brief The source locations involved in the initialization.
476   SourceLocation Locations[3];
477 
InitializationKind(InitKind Kind,InitContext Context,SourceLocation Loc1,SourceLocation Loc2,SourceLocation Loc3)478   InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
479                      SourceLocation Loc2, SourceLocation Loc3)
480     : Kind(Kind), Context(Context)
481   {
482     Locations[0] = Loc1;
483     Locations[1] = Loc2;
484     Locations[2] = Loc3;
485   }
486 
487 public:
488   /// \brief Create a direct initialization.
CreateDirect(SourceLocation InitLoc,SourceLocation LParenLoc,SourceLocation RParenLoc)489   static InitializationKind CreateDirect(SourceLocation InitLoc,
490                                          SourceLocation LParenLoc,
491                                          SourceLocation RParenLoc) {
492     return InitializationKind(IK_Direct, IC_Normal,
493                               InitLoc, LParenLoc, RParenLoc);
494   }
495 
CreateDirectList(SourceLocation InitLoc)496   static InitializationKind CreateDirectList(SourceLocation InitLoc) {
497     return InitializationKind(IK_DirectList, IC_Normal,
498                               InitLoc, InitLoc, InitLoc);
499   }
500 
501   /// \brief Create a direct initialization due to a cast that isn't a C-style
502   /// or functional cast.
CreateCast(SourceRange TypeRange)503   static InitializationKind CreateCast(SourceRange TypeRange) {
504     return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
505                               TypeRange.getBegin(), TypeRange.getEnd());
506   }
507 
508   /// \brief Create a direct initialization for a C-style cast.
CreateCStyleCast(SourceLocation StartLoc,SourceRange TypeRange,bool InitList)509   static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
510                                              SourceRange TypeRange,
511                                              bool InitList) {
512     // C++ cast syntax doesn't permit init lists, but C compound literals are
513     // exactly that.
514     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
515                               IC_CStyleCast, StartLoc, TypeRange.getBegin(),
516                               TypeRange.getEnd());
517   }
518 
519   /// \brief Create a direct initialization for a functional cast.
CreateFunctionalCast(SourceRange TypeRange,bool InitList)520   static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
521                                                  bool InitList) {
522     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
523                               IC_FunctionalCast, TypeRange.getBegin(),
524                               TypeRange.getBegin(), TypeRange.getEnd());
525   }
526 
527   /// \brief Create a copy initialization.
528   static InitializationKind CreateCopy(SourceLocation InitLoc,
529                                        SourceLocation EqualLoc,
530                                        bool AllowExplicitConvs = false) {
531     return InitializationKind(IK_Copy,
532                               AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
533                               InitLoc, EqualLoc, EqualLoc);
534   }
535 
536   /// \brief Create a default initialization.
CreateDefault(SourceLocation InitLoc)537   static InitializationKind CreateDefault(SourceLocation InitLoc) {
538     return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
539   }
540 
541   /// \brief Create a value initialization.
542   static InitializationKind CreateValue(SourceLocation InitLoc,
543                                         SourceLocation LParenLoc,
544                                         SourceLocation RParenLoc,
545                                         bool isImplicit = false) {
546     return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
547                               InitLoc, LParenLoc, RParenLoc);
548   }
549 
550   /// \brief Determine the initialization kind.
getKind()551   InitKind getKind() const {
552     return Kind;
553   }
554 
555   /// \brief Determine whether this initialization is an explicit cast.
isExplicitCast()556   bool isExplicitCast() const {
557     return Context >= IC_StaticCast;
558   }
559 
560   /// \brief Determine whether this initialization is a C-style cast.
isCStyleOrFunctionalCast()561   bool isCStyleOrFunctionalCast() const {
562     return Context >= IC_CStyleCast;
563   }
564 
565   /// \brief Determine whether this is a C-style cast.
isCStyleCast()566   bool isCStyleCast() const {
567     return Context == IC_CStyleCast;
568   }
569 
570   /// \brief Determine whether this is a functional-style cast.
isFunctionalCast()571   bool isFunctionalCast() const {
572     return Context == IC_FunctionalCast;
573   }
574 
575   /// \brief Determine whether this initialization is an implicit
576   /// value-initialization, e.g., as occurs during aggregate
577   /// initialization.
isImplicitValueInit()578   bool isImplicitValueInit() const { return Context == IC_Implicit; }
579 
580   /// \brief Retrieve the location at which initialization is occurring.
getLocation()581   SourceLocation getLocation() const { return Locations[0]; }
582 
583   /// \brief Retrieve the source range that covers the initialization.
getRange()584   SourceRange getRange() const {
585     return SourceRange(Locations[0], Locations[2]);
586   }
587 
588   /// \brief Retrieve the location of the equal sign for copy initialization
589   /// (if present).
getEqualLoc()590   SourceLocation getEqualLoc() const {
591     assert(Kind == IK_Copy && "Only copy initialization has an '='");
592     return Locations[1];
593   }
594 
isCopyInit()595   bool isCopyInit() const { return Kind == IK_Copy; }
596 
597   /// \brief Retrieve whether this initialization allows the use of explicit
598   ///        constructors.
AllowExplicit()599   bool AllowExplicit() const { return !isCopyInit(); }
600 
601   /// \brief Retrieve whether this initialization allows the use of explicit
602   /// conversion functions when binding a reference. If the reference is the
603   /// first parameter in a copy or move constructor, such conversions are
604   /// permitted even though we are performing copy-initialization.
allowExplicitConversionFunctionsInRefBinding()605   bool allowExplicitConversionFunctionsInRefBinding() const {
606     return !isCopyInit() || Context == IC_ExplicitConvs;
607   }
608 
609   /// \brief Retrieve the source range containing the locations of the open
610   /// and closing parentheses for value and direct initializations.
getParenRange()611   SourceRange getParenRange() const {
612     assert((Kind == IK_Direct || Kind == IK_Value) &&
613            "Only direct- and value-initialization have parentheses");
614     return SourceRange(Locations[1], Locations[2]);
615   }
616 };
617 
618 /// \brief Describes the sequence of initializations required to initialize
619 /// a given object or reference with a set of arguments.
620 class InitializationSequence {
621 public:
622   /// \brief Describes the kind of initialization sequence computed.
623   enum SequenceKind {
624     /// \brief A failed initialization sequence. The failure kind tells what
625     /// happened.
626     FailedSequence = 0,
627 
628     /// \brief A dependent initialization, which could not be
629     /// type-checked due to the presence of dependent types or
630     /// dependently-typed expressions.
631     DependentSequence,
632 
633     /// \brief A normal sequence.
634     NormalSequence
635   };
636 
637   /// \brief Describes the kind of a particular step in an initialization
638   /// sequence.
639   enum StepKind {
640     /// \brief Resolve the address of an overloaded function to a specific
641     /// function declaration.
642     SK_ResolveAddressOfOverloadedFunction,
643     /// \brief Perform a derived-to-base cast, producing an rvalue.
644     SK_CastDerivedToBaseRValue,
645     /// \brief Perform a derived-to-base cast, producing an xvalue.
646     SK_CastDerivedToBaseXValue,
647     /// \brief Perform a derived-to-base cast, producing an lvalue.
648     SK_CastDerivedToBaseLValue,
649     /// \brief Reference binding to an lvalue.
650     SK_BindReference,
651     /// \brief Reference binding to a temporary.
652     SK_BindReferenceToTemporary,
653     /// \brief An optional copy of a temporary object to another
654     /// temporary object, which is permitted (but not required) by
655     /// C++98/03 but not C++0x.
656     SK_ExtraneousCopyToTemporary,
657     /// \brief Perform a user-defined conversion, either via a conversion
658     /// function or via a constructor.
659     SK_UserConversion,
660     /// \brief Perform a qualification conversion, producing an rvalue.
661     SK_QualificationConversionRValue,
662     /// \brief Perform a qualification conversion, producing an xvalue.
663     SK_QualificationConversionXValue,
664     /// \brief Perform a qualification conversion, producing an lvalue.
665     SK_QualificationConversionLValue,
666     /// \brief Perform a load from a glvalue, producing an rvalue.
667     SK_LValueToRValue,
668     /// \brief Perform an implicit conversion sequence.
669     SK_ConversionSequence,
670     /// \brief Perform an implicit conversion sequence without narrowing.
671     SK_ConversionSequenceNoNarrowing,
672     /// \brief Perform list-initialization without a constructor
673     SK_ListInitialization,
674     /// \brief Perform list-initialization with a constructor.
675     SK_ListConstructorCall,
676     /// \brief Unwrap the single-element initializer list for a reference.
677     SK_UnwrapInitList,
678     /// \brief Rewrap the single-element initializer list for a reference.
679     SK_RewrapInitList,
680     /// \brief Perform initialization via a constructor.
681     SK_ConstructorInitialization,
682     /// \brief Zero-initialize the object
683     SK_ZeroInitialization,
684     /// \brief C assignment
685     SK_CAssignment,
686     /// \brief Initialization by string
687     SK_StringInit,
688     /// \brief An initialization that "converts" an Objective-C object
689     /// (not a point to an object) to another Objective-C object type.
690     SK_ObjCObjectConversion,
691     /// \brief Array initialization (from an array rvalue).
692     /// This is a GNU C extension.
693     SK_ArrayInit,
694     /// \brief Array initialization from a parenthesized initializer list.
695     /// This is a GNU C++ extension.
696     SK_ParenthesizedArrayInit,
697     /// \brief Pass an object by indirect copy-and-restore.
698     SK_PassByIndirectCopyRestore,
699     /// \brief Pass an object by indirect restore.
700     SK_PassByIndirectRestore,
701     /// \brief Produce an Objective-C object pointer.
702     SK_ProduceObjCObject,
703     /// \brief Construct a std::initializer_list from an initializer list.
704     SK_StdInitializerList,
705     /// \brief Initialize an OpenCL sampler from an integer.
706     SK_OCLSamplerInit,
707     /// \brief Passing zero to a function where OpenCL event_t is expected.
708     SK_OCLZeroEvent
709   };
710 
711   /// \brief A single step in the initialization sequence.
712   class Step {
713   public:
714     /// \brief The kind of conversion or initialization step we are taking.
715     StepKind Kind;
716 
717     // \brief The type that results from this initialization.
718     QualType Type;
719 
720     struct F {
721       bool HadMultipleCandidates;
722       FunctionDecl *Function;
723       DeclAccessPair FoundDecl;
724     };
725 
726     union {
727       /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
728       /// SK_UserConversion, the function that the expression should be
729       /// resolved to or the conversion function to call, respectively.
730       /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
731       /// the constructor to be called.
732       ///
733       /// Always a FunctionDecl, plus a Boolean flag telling if it was
734       /// selected from an overloaded set having size greater than 1.
735       /// For conversion decls, the naming class is the source type.
736       /// For construct decls, the naming class is the target type.
737       struct F Function;
738 
739       /// \brief When Kind = SK_ConversionSequence, the implicit conversion
740       /// sequence.
741       ImplicitConversionSequence *ICS;
742 
743       /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
744       /// wrapping list.
745       InitListExpr *WrappingSyntacticList;
746     };
747 
748     void Destroy();
749   };
750 
751 private:
752   /// \brief The kind of initialization sequence computed.
753   enum SequenceKind SequenceKind;
754 
755   /// \brief Steps taken by this initialization.
756   SmallVector<Step, 4> Steps;
757 
758 public:
759   /// \brief Describes why initialization failed.
760   enum FailureKind {
761     /// \brief Too many initializers provided for a reference.
762     FK_TooManyInitsForReference,
763     /// \brief Array must be initialized with an initializer list.
764     FK_ArrayNeedsInitList,
765     /// \brief Array must be initialized with an initializer list or a
766     /// string literal.
767     FK_ArrayNeedsInitListOrStringLiteral,
768     /// \brief Array must be initialized with an initializer list or a
769     /// wide string literal.
770     FK_ArrayNeedsInitListOrWideStringLiteral,
771     /// \brief Initializing a wide char array with narrow string literal.
772     FK_NarrowStringIntoWideCharArray,
773     /// \brief Initializing char array with wide string literal.
774     FK_WideStringIntoCharArray,
775     /// \brief Initializing wide char array with incompatible wide string
776     /// literal.
777     FK_IncompatWideStringIntoWideChar,
778     /// \brief Array type mismatch.
779     FK_ArrayTypeMismatch,
780     /// \brief Non-constant array initializer
781     FK_NonConstantArrayInit,
782     /// \brief Cannot resolve the address of an overloaded function.
783     FK_AddressOfOverloadFailed,
784     /// \brief Overloading due to reference initialization failed.
785     FK_ReferenceInitOverloadFailed,
786     /// \brief Non-const lvalue reference binding to a temporary.
787     FK_NonConstLValueReferenceBindingToTemporary,
788     /// \brief Non-const lvalue reference binding to an lvalue of unrelated
789     /// type.
790     FK_NonConstLValueReferenceBindingToUnrelated,
791     /// \brief Rvalue reference binding to an lvalue.
792     FK_RValueReferenceBindingToLValue,
793     /// \brief Reference binding drops qualifiers.
794     FK_ReferenceInitDropsQualifiers,
795     /// \brief Reference binding failed.
796     FK_ReferenceInitFailed,
797     /// \brief Implicit conversion failed.
798     FK_ConversionFailed,
799     /// \brief Implicit conversion failed.
800     FK_ConversionFromPropertyFailed,
801     /// \brief Too many initializers for scalar
802     FK_TooManyInitsForScalar,
803     /// \brief Reference initialization from an initializer list
804     FK_ReferenceBindingToInitList,
805     /// \brief Initialization of some unused destination type with an
806     /// initializer list.
807     FK_InitListBadDestinationType,
808     /// \brief Overloading for a user-defined conversion failed.
809     FK_UserConversionOverloadFailed,
810     /// \brief Overloading for initialization by constructor failed.
811     FK_ConstructorOverloadFailed,
812     /// \brief Overloading for list-initialization by constructor failed.
813     FK_ListConstructorOverloadFailed,
814     /// \brief Default-initialization of a 'const' object.
815     FK_DefaultInitOfConst,
816     /// \brief Initialization of an incomplete type.
817     FK_Incomplete,
818     /// \brief Variable-length array must not have an initializer.
819     FK_VariableLengthArrayHasInitializer,
820     /// \brief List initialization failed at some point.
821     FK_ListInitializationFailed,
822     /// \brief Initializer has a placeholder type which cannot be
823     /// resolved by initialization.
824     FK_PlaceholderType,
825     /// \brief List-copy-initialization chose an explicit constructor.
826     FK_ExplicitConstructor
827   };
828 
829 private:
830   /// \brief The reason why initialization failed.
831   FailureKind Failure;
832 
833   /// \brief The failed result of overload resolution.
834   OverloadingResult FailedOverloadResult;
835 
836   /// \brief The candidate set created when initialization failed.
837   OverloadCandidateSet FailedCandidateSet;
838 
839   /// \brief The incomplete type that caused a failure.
840   QualType FailedIncompleteType;
841 
842   /// \brief Prints a follow-up note that highlights the location of
843   /// the initialized entity, if it's remote.
844   void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
845 
846 public:
847   /// \brief Try to perform initialization of the given entity, creating a
848   /// record of the steps required to perform the initialization.
849   ///
850   /// The generated initialization sequence will either contain enough
851   /// information to diagnose
852   ///
853   /// \param S the semantic analysis object.
854   ///
855   /// \param Entity the entity being initialized.
856   ///
857   /// \param Kind the kind of initialization being performed.
858   ///
859   /// \param Args the argument(s) provided for initialization.
860   ///
861   /// \param TopLevelOfInitList true if we are initializing from an expression
862   ///        at the top level inside an initializer list. This disallows
863   ///        narrowing conversions in C++11 onwards.
864   InitializationSequence(Sema &S,
865                          const InitializedEntity &Entity,
866                          const InitializationKind &Kind,
867                          MultiExprArg Args,
868                          bool TopLevelOfInitList = false);
869   void InitializeFrom(Sema &S, const InitializedEntity &Entity,
870                       const InitializationKind &Kind, MultiExprArg Args,
871                       bool TopLevelOfInitList);
872 
873   ~InitializationSequence();
874 
875   /// \brief Perform the actual initialization of the given entity based on
876   /// the computed initialization sequence.
877   ///
878   /// \param S the semantic analysis object.
879   ///
880   /// \param Entity the entity being initialized.
881   ///
882   /// \param Kind the kind of initialization being performed.
883   ///
884   /// \param Args the argument(s) provided for initialization, ownership of
885   /// which is transferred into the routine.
886   ///
887   /// \param ResultType if non-NULL, will be set to the type of the
888   /// initialized object, which is the type of the declaration in most
889   /// cases. However, when the initialized object is a variable of
890   /// incomplete array type and the initializer is an initializer
891   /// list, this type will be set to the completed array type.
892   ///
893   /// \returns an expression that performs the actual object initialization, if
894   /// the initialization is well-formed. Otherwise, emits diagnostics
895   /// and returns an invalid expression.
896   ExprResult Perform(Sema &S,
897                      const InitializedEntity &Entity,
898                      const InitializationKind &Kind,
899                      MultiExprArg Args,
900                      QualType *ResultType = nullptr);
901 
902   /// \brief Diagnose an potentially-invalid initialization sequence.
903   ///
904   /// \returns true if the initialization sequence was ill-formed,
905   /// false otherwise.
906   bool Diagnose(Sema &S,
907                 const InitializedEntity &Entity,
908                 const InitializationKind &Kind,
909                 ArrayRef<Expr *> Args);
910 
911   /// \brief Determine the kind of initialization sequence computed.
getKind()912   enum SequenceKind getKind() const { return SequenceKind; }
913 
914   /// \brief Set the kind of sequence computed.
setSequenceKind(enum SequenceKind SK)915   void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
916 
917   /// \brief Determine whether the initialization sequence is valid.
918   LLVM_EXPLICIT operator bool() const { return !Failed(); }
919 
920   /// \brief Determine whether the initialization sequence is invalid.
Failed()921   bool Failed() const { return SequenceKind == FailedSequence; }
922 
923   typedef SmallVectorImpl<Step>::const_iterator step_iterator;
step_begin()924   step_iterator step_begin() const { return Steps.begin(); }
step_end()925   step_iterator step_end()   const { return Steps.end(); }
926 
927   /// \brief Determine whether this initialization is a direct reference
928   /// binding (C++ [dcl.init.ref]).
929   bool isDirectReferenceBinding() const;
930 
931   /// \brief Determine whether this initialization failed due to an ambiguity.
932   bool isAmbiguous() const;
933 
934   /// \brief Determine whether this initialization is direct call to a
935   /// constructor.
936   bool isConstructorInitialization() const;
937 
938   /// \brief Returns whether the last step in this initialization sequence is a
939   /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
940   ///
941   /// If this function returns true, *isInitializerConstant will be set to
942   /// describe whether *Initializer was a constant expression.  If
943   /// *isInitializerConstant is set to true, *ConstantValue will be set to the
944   /// evaluated value of *Initializer.
945   bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
946                          bool *isInitializerConstant,
947                          APValue *ConstantValue) const;
948 
949   /// \brief Add a new step in the initialization that resolves the address
950   /// of an overloaded function to a specific function declaration.
951   ///
952   /// \param Function the function to which the overloaded function reference
953   /// resolves.
954   void AddAddressOverloadResolutionStep(FunctionDecl *Function,
955                                         DeclAccessPair Found,
956                                         bool HadMultipleCandidates);
957 
958   /// \brief Add a new step in the initialization that performs a derived-to-
959   /// base cast.
960   ///
961   /// \param BaseType the base type to which we will be casting.
962   ///
963   /// \param Category Indicates whether the result will be treated as an
964   /// rvalue, an xvalue, or an lvalue.
965   void AddDerivedToBaseCastStep(QualType BaseType,
966                                 ExprValueKind Category);
967 
968   /// \brief Add a new step binding a reference to an object.
969   ///
970   /// \param BindingTemporary True if we are binding a reference to a temporary
971   /// object (thereby extending its lifetime); false if we are binding to an
972   /// lvalue or an lvalue treated as an rvalue.
973   void AddReferenceBindingStep(QualType T, bool BindingTemporary);
974 
975   /// \brief Add a new step that makes an extraneous copy of the input
976   /// to a temporary of the same class type.
977   ///
978   /// This extraneous copy only occurs during reference binding in
979   /// C++98/03, where we are permitted (but not required) to introduce
980   /// an extra copy. At a bare minimum, we must check that we could
981   /// call the copy constructor, and produce a diagnostic if the copy
982   /// constructor is inaccessible or no copy constructor matches.
983   //
984   /// \param T The type of the temporary being created.
985   void AddExtraneousCopyToTemporary(QualType T);
986 
987   /// \brief Add a new step invoking a conversion function, which is either
988   /// a constructor or a conversion function.
989   void AddUserConversionStep(FunctionDecl *Function,
990                              DeclAccessPair FoundDecl,
991                              QualType T,
992                              bool HadMultipleCandidates);
993 
994   /// \brief Add a new step that performs a qualification conversion to the
995   /// given type.
996   void AddQualificationConversionStep(QualType Ty,
997                                      ExprValueKind Category);
998 
999   /// \brief Add a new step that performs a load of the given type.
1000   ///
1001   /// Although the term "LValueToRValue" is conventional, this applies to both
1002   /// lvalues and xvalues.
1003   void AddLValueToRValueStep(QualType Ty);
1004 
1005   /// \brief Add a new step that applies an implicit conversion sequence.
1006   void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
1007                                  QualType T, bool TopLevelOfInitList = false);
1008 
1009   /// \brief Add a list-initialization step.
1010   void AddListInitializationStep(QualType T);
1011 
1012   /// \brief Add a constructor-initialization step.
1013   ///
1014   /// \param FromInitList The constructor call is syntactically an initializer
1015   /// list.
1016   /// \param AsInitList The constructor is called as an init list constructor.
1017   void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
1018                                         AccessSpecifier Access,
1019                                         QualType T,
1020                                         bool HadMultipleCandidates,
1021                                         bool FromInitList, bool AsInitList);
1022 
1023   /// \brief Add a zero-initialization step.
1024   void AddZeroInitializationStep(QualType T);
1025 
1026   /// \brief Add a C assignment step.
1027   //
1028   // FIXME: It isn't clear whether this should ever be needed;
1029   // ideally, we would handle everything needed in C in the common
1030   // path. However, that isn't the case yet.
1031   void AddCAssignmentStep(QualType T);
1032 
1033   /// \brief Add a string init step.
1034   void AddStringInitStep(QualType T);
1035 
1036   /// \brief Add an Objective-C object conversion step, which is
1037   /// always a no-op.
1038   void AddObjCObjectConversionStep(QualType T);
1039 
1040   /// \brief Add an array initialization step.
1041   void AddArrayInitStep(QualType T);
1042 
1043   /// \brief Add a parenthesized array initialization step.
1044   void AddParenthesizedArrayInitStep(QualType T);
1045 
1046   /// \brief Add a step to pass an object by indirect copy-restore.
1047   void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1048 
1049   /// \brief Add a step to "produce" an Objective-C object (by
1050   /// retaining it).
1051   void AddProduceObjCObjectStep(QualType T);
1052 
1053   /// \brief Add a step to construct a std::initializer_list object from an
1054   /// initializer list.
1055   void AddStdInitializerListConstructionStep(QualType T);
1056 
1057   /// \brief Add a step to initialize an OpenCL sampler from an integer
1058   /// constant.
1059   void AddOCLSamplerInitStep(QualType T);
1060 
1061   /// \brief Add a step to initialize an OpenCL event_t from a NULL
1062   /// constant.
1063   void AddOCLZeroEventStep(QualType T);
1064 
1065   /// \brief Add steps to unwrap a initializer list for a reference around a
1066   /// single element and rewrap it at the end.
1067   void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1068 
1069   /// \brief Note that this initialization sequence failed.
SetFailed(FailureKind Failure)1070   void SetFailed(FailureKind Failure) {
1071     SequenceKind = FailedSequence;
1072     this->Failure = Failure;
1073     assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1074            "Incomplete type failure requires a type!");
1075   }
1076 
1077   /// \brief Note that this initialization sequence failed due to failed
1078   /// overload resolution.
1079   void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1080 
1081   /// \brief Retrieve a reference to the candidate set when overload
1082   /// resolution fails.
getFailedCandidateSet()1083   OverloadCandidateSet &getFailedCandidateSet() {
1084     return FailedCandidateSet;
1085   }
1086 
1087   /// \brief Get the overloading result, for when the initialization
1088   /// sequence failed due to a bad overload.
getFailedOverloadResult()1089   OverloadingResult getFailedOverloadResult() const {
1090     return FailedOverloadResult;
1091   }
1092 
1093   /// \brief Note that this initialization sequence failed due to an
1094   /// incomplete type.
setIncompleteTypeFailure(QualType IncompleteType)1095   void setIncompleteTypeFailure(QualType IncompleteType) {
1096     FailedIncompleteType = IncompleteType;
1097     SetFailed(FK_Incomplete);
1098   }
1099 
1100   /// \brief Determine why initialization failed.
getFailureKind()1101   FailureKind getFailureKind() const {
1102     assert(Failed() && "Not an initialization failure!");
1103     return Failure;
1104   }
1105 
1106   /// \brief Dump a representation of this initialization sequence to
1107   /// the given stream, for debugging purposes.
1108   void dump(raw_ostream &OS) const;
1109 
1110   /// \brief Dump a representation of this initialization sequence to
1111   /// standard error, for debugging purposes.
1112   void dump() const;
1113 };
1114 
1115 } // end namespace clang
1116 
1117 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H
1118