1 //===- Initialization.h - Semantic Analysis for Initializers ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides supporting data types for initialization of objects.
10 //
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/Decl.h"
19 #include "clang/AST/DeclAccessPair.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/IdentifierTable.h"
24 #include "clang/Basic/LLVM.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Specifiers.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/Ownership.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/ADT/iterator_range.h"
34 #include "llvm/Support/Casting.h"
35 #include <cassert>
36 #include <cstdint>
37 #include <string>
38 
39 namespace clang {
40 
41 class APValue;
42 class CXXBaseSpecifier;
43 class CXXConstructorDecl;
44 class ObjCMethodDecl;
45 class Sema;
46 
47 /// Describes an entity that is being initialized.
48 class alignas(8) InitializedEntity {
49 public:
50   /// Specifies the kind of entity being initialized.
51   enum EntityKind {
52     /// The entity being initialized is a variable.
53     EK_Variable,
54 
55     /// The entity being initialized is a function parameter.
56     EK_Parameter,
57 
58     /// The entity being initialized is a non-type template parameter.
59     EK_TemplateParameter,
60 
61     /// The entity being initialized is the result of a function call.
62     EK_Result,
63 
64     /// The entity being initialized is the result of a statement expression.
65     EK_StmtExprResult,
66 
67     /// The entity being initialized is an exception object that
68     /// is being thrown.
69     EK_Exception,
70 
71     /// The entity being initialized is a non-static data member
72     /// subobject.
73     EK_Member,
74 
75     /// The entity being initialized is an element of an array.
76     EK_ArrayElement,
77 
78     /// The entity being initialized is an object (or array of
79     /// objects) allocated via new.
80     EK_New,
81 
82     /// The entity being initialized is a temporary object.
83     EK_Temporary,
84 
85     /// The entity being initialized is a base member subobject.
86     EK_Base,
87 
88     /// The initialization is being done by a delegating constructor.
89     EK_Delegating,
90 
91     /// The entity being initialized is an element of a vector.
92     /// or vector.
93     EK_VectorElement,
94 
95     /// The entity being initialized is a field of block descriptor for
96     /// the copied-in c++ object.
97     EK_BlockElement,
98 
99     /// The entity being initialized is a field of block descriptor for the
100     /// copied-in lambda object that's used in the lambda to block conversion.
101     EK_LambdaToBlockConversionBlockElement,
102 
103     /// The entity being initialized is the real or imaginary part of a
104     /// complex number.
105     EK_ComplexElement,
106 
107     /// The entity being initialized is the field that captures a
108     /// variable in a lambda.
109     EK_LambdaCapture,
110 
111     /// The entity being initialized is the initializer for a compound
112     /// literal.
113     EK_CompoundLiteralInit,
114 
115     /// The entity being implicitly initialized back to the formal
116     /// result type.
117     EK_RelatedResult,
118 
119     /// The entity being initialized is a function parameter; function
120     /// is member of group of audited CF APIs.
121     EK_Parameter_CF_Audited,
122 
123     /// The entity being initialized is a structured binding of a
124     /// decomposition declaration.
125     EK_Binding,
126 
127     // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
128     // enum as an index for its first %select.  When modifying this list,
129     // that diagnostic text needs to be updated as well.
130   };
131 
132 private:
133   /// The kind of entity being initialized.
134   EntityKind Kind;
135 
136   /// If non-NULL, the parent entity in which this
137   /// initialization occurs.
138   const InitializedEntity *Parent = nullptr;
139 
140   /// The type of the object or reference being initialized.
141   QualType Type;
142 
143   /// The mangling number for the next reference temporary to be created.
144   mutable unsigned ManglingNumber = 0;
145 
146   struct LN {
147     /// When Kind == EK_Result, EK_Exception, EK_New, the
148     /// location of the 'return', 'throw', or 'new' keyword,
149     /// respectively. When Kind == EK_Temporary, the location where
150     /// the temporary is being created.
151     SourceLocation Location;
152 
153     /// Whether the entity being initialized may end up using the
154     /// named return value optimization (NRVO).
155     bool NRVO;
156   };
157 
158   struct VD {
159     /// The VarDecl, FieldDecl, or BindingDecl being initialized.
160     ValueDecl *VariableOrMember;
161 
162     /// When Kind == EK_Member, whether this is an implicit member
163     /// initialization in a copy or move constructor. These can perform array
164     /// copies.
165     bool IsImplicitFieldInit;
166 
167     /// When Kind == EK_Member, whether this is the initial initialization
168     /// check for a default member initializer.
169     bool IsDefaultMemberInit;
170   };
171 
172   struct C {
173     /// The name of the variable being captured by an EK_LambdaCapture.
174     IdentifierInfo *VarID;
175 
176     /// The source location at which the capture occurs.
177     SourceLocation Location;
178   };
179 
180   union {
181     /// When Kind == EK_Variable, EK_Member, EK_Binding, or
182     /// EK_TemplateParameter, the variable, binding, or template parameter.
183     VD Variable;
184 
185     /// When Kind == EK_RelatedResult, the ObjectiveC method where
186     /// result type was implicitly changed to accommodate ARC semantics.
187     ObjCMethodDecl *MethodDecl;
188 
189     /// When Kind == EK_Parameter, the ParmVarDecl, with the
190     /// low bit indicating whether the parameter is "consumed".
191     uintptr_t Parameter;
192 
193     /// When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
194     /// source information for the temporary.
195     TypeSourceInfo *TypeInfo;
196 
197     struct LN LocAndNRVO;
198 
199     /// When Kind == EK_Base, the base specifier that provides the
200     /// base class. The lower bit specifies whether the base is an inherited
201     /// virtual base.
202     uintptr_t Base;
203 
204     /// When Kind == EK_ArrayElement, EK_VectorElement, or
205     /// EK_ComplexElement, the index of the array or vector element being
206     /// initialized.
207     unsigned Index;
208 
209     struct C Capture;
210   };
211 
InitializedEntity()212   InitializedEntity() {};
213 
214   /// Create the initialization entity for a variable.
215   InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable)
Kind(EK)216       : Kind(EK), Type(Var->getType()), Variable{Var, false, false} {}
217 
218   /// Create the initialization entity for the result of a
219   /// function, throwing an object, performing an explicit cast, or
220   /// initializing a parameter for which there is no declaration.
221   InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
222                     bool NRVO = false)
Kind(Kind)223       : Kind(Kind), Type(Type) {
224     new (&LocAndNRVO) LN;
225     LocAndNRVO.Location = Loc;
226     LocAndNRVO.NRVO = NRVO;
227   }
228 
229   /// Create the initialization entity for a member subobject.
InitializedEntity(FieldDecl * Member,const InitializedEntity * Parent,bool Implicit,bool DefaultMemberInit)230   InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent,
231                     bool Implicit, bool DefaultMemberInit)
232       : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
233         Variable{Member, Implicit, DefaultMemberInit} {}
234 
235   /// Create the initialization entity for an array element.
236   InitializedEntity(ASTContext &Context, unsigned Index,
237                     const InitializedEntity &Parent);
238 
239   /// Create the initialization entity for a lambda capture.
InitializedEntity(IdentifierInfo * VarID,QualType FieldType,SourceLocation Loc)240   InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
241       : Kind(EK_LambdaCapture), Type(FieldType) {
242     new (&Capture) C;
243     Capture.VarID = VarID;
244     Capture.Location = Loc;
245   }
246 
247 public:
248   /// Create the initialization entity for a variable.
InitializeVariable(VarDecl * Var)249   static InitializedEntity InitializeVariable(VarDecl *Var) {
250     return InitializedEntity(Var);
251   }
252 
253   /// Create the initialization entity for a parameter.
InitializeParameter(ASTContext & Context,const ParmVarDecl * Parm)254   static InitializedEntity InitializeParameter(ASTContext &Context,
255                                                const ParmVarDecl *Parm) {
256     return InitializeParameter(Context, Parm, Parm->getType());
257   }
258 
259   /// Create the initialization entity for a parameter, but use
260   /// another type.
InitializeParameter(ASTContext & Context,const ParmVarDecl * Parm,QualType Type)261   static InitializedEntity InitializeParameter(ASTContext &Context,
262                                                const ParmVarDecl *Parm,
263                                                QualType Type) {
264     bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
265                      Parm->hasAttr<NSConsumedAttr>());
266 
267     InitializedEntity Entity;
268     Entity.Kind = EK_Parameter;
269     Entity.Type =
270       Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
271     Entity.Parent = nullptr;
272     Entity.Parameter
273       = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
274     return Entity;
275   }
276 
277   /// Create the initialization entity for a parameter that is
278   /// only known by its type.
InitializeParameter(ASTContext & Context,QualType Type,bool Consumed)279   static InitializedEntity InitializeParameter(ASTContext &Context,
280                                                QualType Type,
281                                                bool Consumed) {
282     InitializedEntity Entity;
283     Entity.Kind = EK_Parameter;
284     Entity.Type = Context.getVariableArrayDecayedType(Type);
285     Entity.Parent = nullptr;
286     Entity.Parameter = (Consumed);
287     return Entity;
288   }
289 
290   /// Create the initialization entity for a template parameter.
291   static InitializedEntity
InitializeTemplateParameter(QualType T,NonTypeTemplateParmDecl * Param)292   InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param) {
293     InitializedEntity Entity;
294     Entity.Kind = EK_TemplateParameter;
295     Entity.Type = T;
296     Entity.Parent = nullptr;
297     Entity.Variable = {Param, false, false};
298     return Entity;
299   }
300 
301   /// Create the initialization entity for the result of a function.
InitializeResult(SourceLocation ReturnLoc,QualType Type,bool NRVO)302   static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
303                                             QualType Type, bool NRVO) {
304     return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
305   }
306 
InitializeStmtExprResult(SourceLocation ReturnLoc,QualType Type)307   static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc,
308                                             QualType Type) {
309     return InitializedEntity(EK_StmtExprResult, ReturnLoc, Type);
310   }
311 
InitializeBlock(SourceLocation BlockVarLoc,QualType Type,bool NRVO)312   static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
313                                            QualType Type, bool NRVO) {
314     return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
315   }
316 
InitializeLambdaToBlock(SourceLocation BlockVarLoc,QualType Type,bool NRVO)317   static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc,
318                                                    QualType Type, bool NRVO) {
319     return InitializedEntity(EK_LambdaToBlockConversionBlockElement,
320                              BlockVarLoc, Type, NRVO);
321   }
322 
323   /// Create the initialization entity for an exception object.
InitializeException(SourceLocation ThrowLoc,QualType Type,bool NRVO)324   static InitializedEntity InitializeException(SourceLocation ThrowLoc,
325                                                QualType Type, bool NRVO) {
326     return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
327   }
328 
329   /// Create the initialization entity for an object allocated via new.
InitializeNew(SourceLocation NewLoc,QualType Type)330   static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
331     return InitializedEntity(EK_New, NewLoc, Type);
332   }
333 
334   /// Create the initialization entity for a temporary.
InitializeTemporary(QualType Type)335   static InitializedEntity InitializeTemporary(QualType Type) {
336     return InitializeTemporary(nullptr, Type);
337   }
338 
339   /// Create the initialization entity for a temporary.
InitializeTemporary(TypeSourceInfo * TypeInfo)340   static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
341     return InitializeTemporary(TypeInfo, TypeInfo->getType());
342   }
343 
344   /// Create the initialization entity for a temporary.
InitializeTemporary(TypeSourceInfo * TypeInfo,QualType Type)345   static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo,
346                                                QualType Type) {
347     InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
348     Result.TypeInfo = TypeInfo;
349     return Result;
350   }
351 
352   /// Create the initialization entity for a related result.
InitializeRelatedResult(ObjCMethodDecl * MD,QualType Type)353   static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
354                                                    QualType Type) {
355     InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
356     Result.MethodDecl = MD;
357     return Result;
358   }
359 
360   /// Create the initialization entity for a base class subobject.
361   static InitializedEntity
362   InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base,
363                  bool IsInheritedVirtualBase,
364                  const InitializedEntity *Parent = nullptr);
365 
366   /// Create the initialization entity for a delegated constructor.
InitializeDelegation(QualType Type)367   static InitializedEntity InitializeDelegation(QualType Type) {
368     return InitializedEntity(EK_Delegating, SourceLocation(), Type);
369   }
370 
371   /// Create the initialization entity for a member subobject.
372   static InitializedEntity
373   InitializeMember(FieldDecl *Member,
374                    const InitializedEntity *Parent = nullptr,
375                    bool Implicit = false) {
376     return InitializedEntity(Member, Parent, Implicit, false);
377   }
378 
379   /// Create the initialization entity for a member subobject.
380   static InitializedEntity
381   InitializeMember(IndirectFieldDecl *Member,
382                    const InitializedEntity *Parent = nullptr,
383                    bool Implicit = false) {
384     return InitializedEntity(Member->getAnonField(), Parent, Implicit, false);
385   }
386 
387   /// Create the initialization entity for a default member initializer.
388   static InitializedEntity
InitializeMemberFromDefaultMemberInitializer(FieldDecl * Member)389   InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member) {
390     return InitializedEntity(Member, nullptr, false, true);
391   }
392 
393   /// Create the initialization entity for an array element.
InitializeElement(ASTContext & Context,unsigned Index,const InitializedEntity & Parent)394   static InitializedEntity InitializeElement(ASTContext &Context,
395                                              unsigned Index,
396                                              const InitializedEntity &Parent) {
397     return InitializedEntity(Context, Index, Parent);
398   }
399 
400   /// Create the initialization entity for a structured binding.
InitializeBinding(VarDecl * Binding)401   static InitializedEntity InitializeBinding(VarDecl *Binding) {
402     return InitializedEntity(Binding, EK_Binding);
403   }
404 
405   /// Create the initialization entity for a lambda capture.
406   ///
407   /// \p VarID The name of the entity being captured, or nullptr for 'this'.
InitializeLambdaCapture(IdentifierInfo * VarID,QualType FieldType,SourceLocation Loc)408   static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
409                                                    QualType FieldType,
410                                                    SourceLocation Loc) {
411     return InitializedEntity(VarID, FieldType, Loc);
412   }
413 
414   /// Create the entity for a compound literal initializer.
InitializeCompoundLiteralInit(TypeSourceInfo * TSI)415   static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
416     InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
417                              TSI->getType());
418     Result.TypeInfo = TSI;
419     return Result;
420   }
421 
422   /// Determine the kind of initialization.
getKind()423   EntityKind getKind() const { return Kind; }
424 
425   /// Retrieve the parent of the entity being initialized, when
426   /// the initialization itself is occurring within the context of a
427   /// larger initialization.
getParent()428   const InitializedEntity *getParent() const { return Parent; }
429 
430   /// Retrieve type being initialized.
getType()431   QualType getType() const { return Type; }
432 
433   /// Retrieve complete type-source information for the object being
434   /// constructed, if known.
getTypeSourceInfo()435   TypeSourceInfo *getTypeSourceInfo() const {
436     if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
437       return TypeInfo;
438 
439     return nullptr;
440   }
441 
442   /// Retrieve the name of the entity being initialized.
443   DeclarationName getName() const;
444 
445   /// Retrieve the variable, parameter, or field being
446   /// initialized.
447   ValueDecl *getDecl() const;
448 
449   /// Retrieve the ObjectiveC method being initialized.
getMethodDecl()450   ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
451 
452   /// Determine whether this initialization allows the named return
453   /// value optimization, which also applies to thrown objects.
454   bool allowsNRVO() const;
455 
isParameterKind()456   bool isParameterKind() const {
457     return (getKind() == EK_Parameter  ||
458             getKind() == EK_Parameter_CF_Audited);
459   }
460 
isParamOrTemplateParamKind()461   bool isParamOrTemplateParamKind() const {
462     return isParameterKind() || getKind() == EK_TemplateParameter;
463   }
464 
465   /// Determine whether this initialization consumes the
466   /// parameter.
isParameterConsumed()467   bool isParameterConsumed() const {
468     assert(isParameterKind() && "Not a parameter");
469     return (Parameter & 1);
470   }
471 
472   /// Retrieve the base specifier.
getBaseSpecifier()473   const CXXBaseSpecifier *getBaseSpecifier() const {
474     assert(getKind() == EK_Base && "Not a base specifier");
475     return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
476   }
477 
478   /// Return whether the base is an inherited virtual base.
isInheritedVirtualBase()479   bool isInheritedVirtualBase() const {
480     assert(getKind() == EK_Base && "Not a base specifier");
481     return Base & 0x1;
482   }
483 
484   /// Determine whether this is an array new with an unknown bound.
isVariableLengthArrayNew()485   bool isVariableLengthArrayNew() const {
486     return getKind() == EK_New && dyn_cast_or_null<IncompleteArrayType>(
487                                       getType()->getAsArrayTypeUnsafe());
488   }
489 
490   /// Is this the implicit initialization of a member of a class from
491   /// a defaulted constructor?
isImplicitMemberInitializer()492   bool isImplicitMemberInitializer() const {
493     return getKind() == EK_Member && Variable.IsImplicitFieldInit;
494   }
495 
496   /// Is this the default member initializer of a member (specified inside
497   /// the class definition)?
isDefaultMemberInitializer()498   bool isDefaultMemberInitializer() const {
499     return getKind() == EK_Member && Variable.IsDefaultMemberInit;
500   }
501 
502   /// Determine the location of the 'return' keyword when initializing
503   /// the result of a function call.
getReturnLoc()504   SourceLocation getReturnLoc() const {
505     assert(getKind() == EK_Result && "No 'return' location!");
506     return LocAndNRVO.Location;
507   }
508 
509   /// Determine the location of the 'throw' keyword when initializing
510   /// an exception object.
getThrowLoc()511   SourceLocation getThrowLoc() const {
512     assert(getKind() == EK_Exception && "No 'throw' location!");
513     return LocAndNRVO.Location;
514   }
515 
516   /// If this is an array, vector, or complex number element, get the
517   /// element's index.
getElementIndex()518   unsigned getElementIndex() const {
519     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
520            getKind() == EK_ComplexElement);
521     return Index;
522   }
523 
524   /// If this is already the initializer for an array or vector
525   /// element, sets the element index.
setElementIndex(unsigned Index)526   void setElementIndex(unsigned Index) {
527     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
528            getKind() == EK_ComplexElement);
529     this->Index = Index;
530   }
531 
532   /// For a lambda capture, return the capture's name.
getCapturedVarName()533   StringRef getCapturedVarName() const {
534     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
535     return Capture.VarID ? Capture.VarID->getName() : "this";
536   }
537 
538   /// Determine the location of the capture when initializing
539   /// field from a captured variable in a lambda.
getCaptureLoc()540   SourceLocation getCaptureLoc() const {
541     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
542     return Capture.Location;
543   }
544 
setParameterCFAudited()545   void setParameterCFAudited() {
546     Kind = EK_Parameter_CF_Audited;
547   }
548 
allocateManglingNumber()549   unsigned allocateManglingNumber() const { return ++ManglingNumber; }
550 
551   /// Dump a representation of the initialized entity to standard error,
552   /// for debugging purposes.
553   void dump() const;
554 
555 private:
556   unsigned dumpImpl(raw_ostream &OS) const;
557 };
558 
559 /// Describes the kind of initialization being performed, along with
560 /// location information for tokens related to the initialization (equal sign,
561 /// parentheses).
562 class InitializationKind {
563 public:
564   /// The kind of initialization being performed.
565   enum InitKind {
566     /// Direct initialization
567     IK_Direct,
568 
569     /// Direct list-initialization
570     IK_DirectList,
571 
572     /// Copy initialization
573     IK_Copy,
574 
575     /// Default initialization
576     IK_Default,
577 
578     /// Value initialization
579     IK_Value
580   };
581 
582 private:
583   /// The context of the initialization.
584   enum InitContext {
585     /// Normal context
586     IC_Normal,
587 
588     /// Normal context, but allows explicit conversion functionss
589     IC_ExplicitConvs,
590 
591     /// Implicit context (value initialization)
592     IC_Implicit,
593 
594     /// Static cast context
595     IC_StaticCast,
596 
597     /// C-style cast context
598     IC_CStyleCast,
599 
600     /// Functional cast context
601     IC_FunctionalCast
602   };
603 
604   /// The kind of initialization being performed.
605   InitKind Kind : 8;
606 
607   /// The context of the initialization.
608   InitContext Context : 8;
609 
610   /// The source locations involved in the initialization.
611   SourceLocation Locations[3];
612 
InitializationKind(InitKind Kind,InitContext Context,SourceLocation Loc1,SourceLocation Loc2,SourceLocation Loc3)613   InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
614                      SourceLocation Loc2, SourceLocation Loc3)
615       : Kind(Kind), Context(Context) {
616     Locations[0] = Loc1;
617     Locations[1] = Loc2;
618     Locations[2] = Loc3;
619   }
620 
621 public:
622   /// Create a direct initialization.
CreateDirect(SourceLocation InitLoc,SourceLocation LParenLoc,SourceLocation RParenLoc)623   static InitializationKind CreateDirect(SourceLocation InitLoc,
624                                          SourceLocation LParenLoc,
625                                          SourceLocation RParenLoc) {
626     return InitializationKind(IK_Direct, IC_Normal,
627                               InitLoc, LParenLoc, RParenLoc);
628   }
629 
CreateDirectList(SourceLocation InitLoc)630   static InitializationKind CreateDirectList(SourceLocation InitLoc) {
631     return InitializationKind(IK_DirectList, IC_Normal, InitLoc, InitLoc,
632                               InitLoc);
633   }
634 
CreateDirectList(SourceLocation InitLoc,SourceLocation LBraceLoc,SourceLocation RBraceLoc)635   static InitializationKind CreateDirectList(SourceLocation InitLoc,
636                                              SourceLocation LBraceLoc,
637                                              SourceLocation RBraceLoc) {
638     return InitializationKind(IK_DirectList, IC_Normal, InitLoc, LBraceLoc,
639                               RBraceLoc);
640   }
641 
642   /// Create a direct initialization due to a cast that isn't a C-style
643   /// or functional cast.
CreateCast(SourceRange TypeRange)644   static InitializationKind CreateCast(SourceRange TypeRange) {
645     return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
646                               TypeRange.getBegin(), TypeRange.getEnd());
647   }
648 
649   /// Create a direct initialization for a C-style cast.
CreateCStyleCast(SourceLocation StartLoc,SourceRange TypeRange,bool InitList)650   static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
651                                              SourceRange TypeRange,
652                                              bool InitList) {
653     // C++ cast syntax doesn't permit init lists, but C compound literals are
654     // exactly that.
655     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
656                               IC_CStyleCast, StartLoc, TypeRange.getBegin(),
657                               TypeRange.getEnd());
658   }
659 
660   /// Create a direct initialization for a functional cast.
CreateFunctionalCast(SourceRange TypeRange,bool InitList)661   static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
662                                                  bool InitList) {
663     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
664                               IC_FunctionalCast, TypeRange.getBegin(),
665                               TypeRange.getBegin(), TypeRange.getEnd());
666   }
667 
668   /// Create a copy initialization.
669   static InitializationKind CreateCopy(SourceLocation InitLoc,
670                                        SourceLocation EqualLoc,
671                                        bool AllowExplicitConvs = false) {
672     return InitializationKind(IK_Copy,
673                               AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
674                               InitLoc, EqualLoc, EqualLoc);
675   }
676 
677   /// Create a default initialization.
CreateDefault(SourceLocation InitLoc)678   static InitializationKind CreateDefault(SourceLocation InitLoc) {
679     return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
680   }
681 
682   /// Create a value initialization.
683   static InitializationKind CreateValue(SourceLocation InitLoc,
684                                         SourceLocation LParenLoc,
685                                         SourceLocation RParenLoc,
686                                         bool isImplicit = false) {
687     return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
688                               InitLoc, LParenLoc, RParenLoc);
689   }
690 
691   /// Create an initialization from an initializer (which, for direct
692   /// initialization from a parenthesized list, will be a ParenListExpr).
CreateForInit(SourceLocation Loc,bool DirectInit,Expr * Init)693   static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit,
694                                           Expr *Init) {
695     if (!Init) return CreateDefault(Loc);
696     if (!DirectInit)
697       return CreateCopy(Loc, Init->getBeginLoc());
698     if (isa<InitListExpr>(Init))
699       return CreateDirectList(Loc, Init->getBeginLoc(), Init->getEndLoc());
700     return CreateDirect(Loc, Init->getBeginLoc(), Init->getEndLoc());
701   }
702 
703   /// Determine the initialization kind.
getKind()704   InitKind getKind() const {
705     return Kind;
706   }
707 
708   /// Determine whether this initialization is an explicit cast.
isExplicitCast()709   bool isExplicitCast() const {
710     return Context >= IC_StaticCast;
711   }
712 
713   /// Determine whether this initialization is a static cast.
isStaticCast()714   bool isStaticCast() const { return Context == IC_StaticCast; }
715 
716   /// Determine whether this initialization is a C-style cast.
isCStyleOrFunctionalCast()717   bool isCStyleOrFunctionalCast() const {
718     return Context >= IC_CStyleCast;
719   }
720 
721   /// Determine whether this is a C-style cast.
isCStyleCast()722   bool isCStyleCast() const {
723     return Context == IC_CStyleCast;
724   }
725 
726   /// Determine whether this is a functional-style cast.
isFunctionalCast()727   bool isFunctionalCast() const {
728     return Context == IC_FunctionalCast;
729   }
730 
731   /// Determine whether this initialization is an implicit
732   /// value-initialization, e.g., as occurs during aggregate
733   /// initialization.
isImplicitValueInit()734   bool isImplicitValueInit() const { return Context == IC_Implicit; }
735 
736   /// Retrieve the location at which initialization is occurring.
getLocation()737   SourceLocation getLocation() const { return Locations[0]; }
738 
739   /// Retrieve the source range that covers the initialization.
getRange()740   SourceRange getRange() const {
741     return SourceRange(Locations[0], Locations[2]);
742   }
743 
744   /// Retrieve the location of the equal sign for copy initialization
745   /// (if present).
getEqualLoc()746   SourceLocation getEqualLoc() const {
747     assert(Kind == IK_Copy && "Only copy initialization has an '='");
748     return Locations[1];
749   }
750 
isCopyInit()751   bool isCopyInit() const { return Kind == IK_Copy; }
752 
753   /// Retrieve whether this initialization allows the use of explicit
754   ///        constructors.
AllowExplicit()755   bool AllowExplicit() const { return !isCopyInit(); }
756 
757   /// Retrieve whether this initialization allows the use of explicit
758   /// conversion functions when binding a reference. If the reference is the
759   /// first parameter in a copy or move constructor, such conversions are
760   /// permitted even though we are performing copy-initialization.
allowExplicitConversionFunctionsInRefBinding()761   bool allowExplicitConversionFunctionsInRefBinding() const {
762     return !isCopyInit() || Context == IC_ExplicitConvs;
763   }
764 
765   /// Determine whether this initialization has a source range containing the
766   /// locations of open and closing parentheses or braces.
hasParenOrBraceRange()767   bool hasParenOrBraceRange() const {
768     return Kind == IK_Direct || Kind == IK_Value || Kind == IK_DirectList;
769   }
770 
771   /// Retrieve the source range containing the locations of the open
772   /// and closing parentheses or braces for value, direct, and direct list
773   /// initializations.
getParenOrBraceRange()774   SourceRange getParenOrBraceRange() const {
775     assert(hasParenOrBraceRange() && "Only direct, value, and direct-list "
776                                      "initialization have parentheses or "
777                                      "braces");
778     return SourceRange(Locations[1], Locations[2]);
779   }
780 };
781 
782 /// Describes the sequence of initializations required to initialize
783 /// a given object or reference with a set of arguments.
784 class InitializationSequence {
785 public:
786   /// Describes the kind of initialization sequence computed.
787   enum SequenceKind {
788     /// A failed initialization sequence. The failure kind tells what
789     /// happened.
790     FailedSequence = 0,
791 
792     /// A dependent initialization, which could not be
793     /// type-checked due to the presence of dependent types or
794     /// dependently-typed expressions.
795     DependentSequence,
796 
797     /// A normal sequence.
798     NormalSequence
799   };
800 
801   /// Describes the kind of a particular step in an initialization
802   /// sequence.
803   enum StepKind {
804     /// Resolve the address of an overloaded function to a specific
805     /// function declaration.
806     SK_ResolveAddressOfOverloadedFunction,
807 
808     /// Perform a derived-to-base cast, producing an rvalue.
809     SK_CastDerivedToBaseRValue,
810 
811     /// Perform a derived-to-base cast, producing an xvalue.
812     SK_CastDerivedToBaseXValue,
813 
814     /// Perform a derived-to-base cast, producing an lvalue.
815     SK_CastDerivedToBaseLValue,
816 
817     /// Reference binding to an lvalue.
818     SK_BindReference,
819 
820     /// Reference binding to a temporary.
821     SK_BindReferenceToTemporary,
822 
823     /// An optional copy of a temporary object to another
824     /// temporary object, which is permitted (but not required) by
825     /// C++98/03 but not C++0x.
826     SK_ExtraneousCopyToTemporary,
827 
828     /// Direct-initialization from a reference-related object in the
829     /// final stage of class copy-initialization.
830     SK_FinalCopy,
831 
832     /// Perform a user-defined conversion, either via a conversion
833     /// function or via a constructor.
834     SK_UserConversion,
835 
836     /// Perform a qualification conversion, producing an rvalue.
837     SK_QualificationConversionRValue,
838 
839     /// Perform a qualification conversion, producing an xvalue.
840     SK_QualificationConversionXValue,
841 
842     /// Perform a qualification conversion, producing an lvalue.
843     SK_QualificationConversionLValue,
844 
845     /// Perform a function reference conversion, see [dcl.init.ref]p4.
846     SK_FunctionReferenceConversion,
847 
848     /// Perform a conversion adding _Atomic to a type.
849     SK_AtomicConversion,
850 
851     /// Perform an implicit conversion sequence.
852     SK_ConversionSequence,
853 
854     /// Perform an implicit conversion sequence without narrowing.
855     SK_ConversionSequenceNoNarrowing,
856 
857     /// Perform list-initialization without a constructor.
858     SK_ListInitialization,
859 
860     /// Unwrap the single-element initializer list for a reference.
861     SK_UnwrapInitList,
862 
863     /// Rewrap the single-element initializer list for a reference.
864     SK_RewrapInitList,
865 
866     /// Perform initialization via a constructor.
867     SK_ConstructorInitialization,
868 
869     /// Perform initialization via a constructor, taking arguments from
870     /// a single InitListExpr.
871     SK_ConstructorInitializationFromList,
872 
873     /// Zero-initialize the object
874     SK_ZeroInitialization,
875 
876     /// C assignment
877     SK_CAssignment,
878 
879     /// Initialization by string
880     SK_StringInit,
881 
882     /// An initialization that "converts" an Objective-C object
883     /// (not a point to an object) to another Objective-C object type.
884     SK_ObjCObjectConversion,
885 
886     /// Array indexing for initialization by elementwise copy.
887     SK_ArrayLoopIndex,
888 
889     /// Array initialization by elementwise copy.
890     SK_ArrayLoopInit,
891 
892     /// Array initialization (from an array rvalue).
893     SK_ArrayInit,
894 
895     /// Array initialization (from an array rvalue) as a GNU extension.
896     SK_GNUArrayInit,
897 
898     /// Array initialization from a parenthesized initializer list.
899     /// This is a GNU C++ extension.
900     SK_ParenthesizedArrayInit,
901 
902     /// Pass an object by indirect copy-and-restore.
903     SK_PassByIndirectCopyRestore,
904 
905     /// Pass an object by indirect restore.
906     SK_PassByIndirectRestore,
907 
908     /// Produce an Objective-C object pointer.
909     SK_ProduceObjCObject,
910 
911     /// Construct a std::initializer_list from an initializer list.
912     SK_StdInitializerList,
913 
914     /// Perform initialization via a constructor taking a single
915     /// std::initializer_list argument.
916     SK_StdInitializerListConstructorCall,
917 
918     /// Initialize an OpenCL sampler from an integer.
919     SK_OCLSamplerInit,
920 
921     /// Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero
922     SK_OCLZeroOpaqueType
923   };
924 
925   /// A single step in the initialization sequence.
926   class Step {
927   public:
928     /// The kind of conversion or initialization step we are taking.
929     StepKind Kind;
930 
931     // The type that results from this initialization.
932     QualType Type;
933 
934     struct F {
935       bool HadMultipleCandidates;
936       FunctionDecl *Function;
937       DeclAccessPair FoundDecl;
938     };
939 
940     union {
941       /// When Kind == SK_ResolvedOverloadedFunction or Kind ==
942       /// SK_UserConversion, the function that the expression should be
943       /// resolved to or the conversion function to call, respectively.
944       /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
945       /// the constructor to be called.
946       ///
947       /// Always a FunctionDecl, plus a Boolean flag telling if it was
948       /// selected from an overloaded set having size greater than 1.
949       /// For conversion decls, the naming class is the source type.
950       /// For construct decls, the naming class is the target type.
951       struct F Function;
952 
953       /// When Kind = SK_ConversionSequence, the implicit conversion
954       /// sequence.
955       ImplicitConversionSequence *ICS;
956 
957       /// When Kind = SK_RewrapInitList, the syntactic form of the
958       /// wrapping list.
959       InitListExpr *WrappingSyntacticList;
960     };
961 
962     void Destroy();
963   };
964 
965 private:
966   /// The kind of initialization sequence computed.
967   enum SequenceKind SequenceKind;
968 
969   /// Steps taken by this initialization.
970   SmallVector<Step, 4> Steps;
971 
972 public:
973   /// Describes why initialization failed.
974   enum FailureKind {
975     /// Too many initializers provided for a reference.
976     FK_TooManyInitsForReference,
977 
978     /// Reference initialized from a parenthesized initializer list.
979     FK_ParenthesizedListInitForReference,
980 
981     /// Array must be initialized with an initializer list.
982     FK_ArrayNeedsInitList,
983 
984     /// Array must be initialized with an initializer list or a
985     /// string literal.
986     FK_ArrayNeedsInitListOrStringLiteral,
987 
988     /// Array must be initialized with an initializer list or a
989     /// wide string literal.
990     FK_ArrayNeedsInitListOrWideStringLiteral,
991 
992     /// Initializing a wide char array with narrow string literal.
993     FK_NarrowStringIntoWideCharArray,
994 
995     /// Initializing char array with wide string literal.
996     FK_WideStringIntoCharArray,
997 
998     /// Initializing wide char array with incompatible wide string
999     /// literal.
1000     FK_IncompatWideStringIntoWideChar,
1001 
1002     /// Initializing char8_t array with plain string literal.
1003     FK_PlainStringIntoUTF8Char,
1004 
1005     /// Initializing char array with UTF-8 string literal.
1006     FK_UTF8StringIntoPlainChar,
1007 
1008     /// Array type mismatch.
1009     FK_ArrayTypeMismatch,
1010 
1011     /// Non-constant array initializer
1012     FK_NonConstantArrayInit,
1013 
1014     /// Cannot resolve the address of an overloaded function.
1015     FK_AddressOfOverloadFailed,
1016 
1017     /// Overloading due to reference initialization failed.
1018     FK_ReferenceInitOverloadFailed,
1019 
1020     /// Non-const lvalue reference binding to a temporary.
1021     FK_NonConstLValueReferenceBindingToTemporary,
1022 
1023     /// Non-const lvalue reference binding to a bit-field.
1024     FK_NonConstLValueReferenceBindingToBitfield,
1025 
1026     /// Non-const lvalue reference binding to a vector element.
1027     FK_NonConstLValueReferenceBindingToVectorElement,
1028 
1029     /// Non-const lvalue reference binding to a matrix element.
1030     FK_NonConstLValueReferenceBindingToMatrixElement,
1031 
1032     /// Non-const lvalue reference binding to an lvalue of unrelated
1033     /// type.
1034     FK_NonConstLValueReferenceBindingToUnrelated,
1035 
1036     /// Rvalue reference binding to an lvalue.
1037     FK_RValueReferenceBindingToLValue,
1038 
1039     /// Reference binding drops qualifiers.
1040     FK_ReferenceInitDropsQualifiers,
1041 
1042     /// Reference with mismatching address space binding to temporary.
1043     FK_ReferenceAddrspaceMismatchTemporary,
1044 
1045     /// Reference binding failed.
1046     FK_ReferenceInitFailed,
1047 
1048     /// Implicit conversion failed.
1049     FK_ConversionFailed,
1050 
1051     /// Implicit conversion failed.
1052     FK_ConversionFromPropertyFailed,
1053 
1054     /// Too many initializers for scalar
1055     FK_TooManyInitsForScalar,
1056 
1057     /// Scalar initialized from a parenthesized initializer list.
1058     FK_ParenthesizedListInitForScalar,
1059 
1060     /// Reference initialization from an initializer list
1061     FK_ReferenceBindingToInitList,
1062 
1063     /// Initialization of some unused destination type with an
1064     /// initializer list.
1065     FK_InitListBadDestinationType,
1066 
1067     /// Overloading for a user-defined conversion failed.
1068     FK_UserConversionOverloadFailed,
1069 
1070     /// Overloading for initialization by constructor failed.
1071     FK_ConstructorOverloadFailed,
1072 
1073     /// Overloading for list-initialization by constructor failed.
1074     FK_ListConstructorOverloadFailed,
1075 
1076     /// Default-initialization of a 'const' object.
1077     FK_DefaultInitOfConst,
1078 
1079     /// Initialization of an incomplete type.
1080     FK_Incomplete,
1081 
1082     /// Variable-length array must not have an initializer.
1083     FK_VariableLengthArrayHasInitializer,
1084 
1085     /// List initialization failed at some point.
1086     FK_ListInitializationFailed,
1087 
1088     /// Initializer has a placeholder type which cannot be
1089     /// resolved by initialization.
1090     FK_PlaceholderType,
1091 
1092     /// Trying to take the address of a function that doesn't support
1093     /// having its address taken.
1094     FK_AddressOfUnaddressableFunction,
1095 
1096     /// List-copy-initialization chose an explicit constructor.
1097     FK_ExplicitConstructor,
1098   };
1099 
1100 private:
1101   /// The reason why initialization failed.
1102   FailureKind Failure;
1103 
1104   /// The failed result of overload resolution.
1105   OverloadingResult FailedOverloadResult;
1106 
1107   /// The candidate set created when initialization failed.
1108   OverloadCandidateSet FailedCandidateSet;
1109 
1110   /// The incomplete type that caused a failure.
1111   QualType FailedIncompleteType;
1112 
1113   /// The fixit that needs to be applied to make this initialization
1114   /// succeed.
1115   std::string ZeroInitializationFixit;
1116   SourceLocation ZeroInitializationFixitLoc;
1117 
1118 public:
1119   /// Call for initializations are invalid but that would be valid
1120   /// zero initialzations if Fixit was applied.
SetZeroInitializationFixit(const std::string & Fixit,SourceLocation L)1121   void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
1122     ZeroInitializationFixit = Fixit;
1123     ZeroInitializationFixitLoc = L;
1124   }
1125 
1126 private:
1127   /// Prints a follow-up note that highlights the location of
1128   /// the initialized entity, if it's remote.
1129   void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
1130 
1131 public:
1132   /// Try to perform initialization of the given entity, creating a
1133   /// record of the steps required to perform the initialization.
1134   ///
1135   /// The generated initialization sequence will either contain enough
1136   /// information to diagnose
1137   ///
1138   /// \param S the semantic analysis object.
1139   ///
1140   /// \param Entity the entity being initialized.
1141   ///
1142   /// \param Kind the kind of initialization being performed.
1143   ///
1144   /// \param Args the argument(s) provided for initialization.
1145   ///
1146   /// \param TopLevelOfInitList true if we are initializing from an expression
1147   ///        at the top level inside an initializer list. This disallows
1148   ///        narrowing conversions in C++11 onwards.
1149   /// \param TreatUnavailableAsInvalid true if we want to treat unavailable
1150   ///        as invalid.
1151   InitializationSequence(Sema &S,
1152                          const InitializedEntity &Entity,
1153                          const InitializationKind &Kind,
1154                          MultiExprArg Args,
1155                          bool TopLevelOfInitList = false,
1156                          bool TreatUnavailableAsInvalid = true);
1157   void InitializeFrom(Sema &S, const InitializedEntity &Entity,
1158                       const InitializationKind &Kind, MultiExprArg Args,
1159                       bool TopLevelOfInitList, bool TreatUnavailableAsInvalid);
1160 
1161   ~InitializationSequence();
1162 
1163   /// Perform the actual initialization of the given entity based on
1164   /// the computed initialization sequence.
1165   ///
1166   /// \param S the semantic analysis object.
1167   ///
1168   /// \param Entity the entity being initialized.
1169   ///
1170   /// \param Kind the kind of initialization being performed.
1171   ///
1172   /// \param Args the argument(s) provided for initialization, ownership of
1173   /// which is transferred into the routine.
1174   ///
1175   /// \param ResultType if non-NULL, will be set to the type of the
1176   /// initialized object, which is the type of the declaration in most
1177   /// cases. However, when the initialized object is a variable of
1178   /// incomplete array type and the initializer is an initializer
1179   /// list, this type will be set to the completed array type.
1180   ///
1181   /// \returns an expression that performs the actual object initialization, if
1182   /// the initialization is well-formed. Otherwise, emits diagnostics
1183   /// and returns an invalid expression.
1184   ExprResult Perform(Sema &S,
1185                      const InitializedEntity &Entity,
1186                      const InitializationKind &Kind,
1187                      MultiExprArg Args,
1188                      QualType *ResultType = nullptr);
1189 
1190   /// Diagnose an potentially-invalid initialization sequence.
1191   ///
1192   /// \returns true if the initialization sequence was ill-formed,
1193   /// false otherwise.
1194   bool Diagnose(Sema &S,
1195                 const InitializedEntity &Entity,
1196                 const InitializationKind &Kind,
1197                 ArrayRef<Expr *> Args);
1198 
1199   /// Determine the kind of initialization sequence computed.
getKind()1200   enum SequenceKind getKind() const { return SequenceKind; }
1201 
1202   /// Set the kind of sequence computed.
setSequenceKind(enum SequenceKind SK)1203   void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
1204 
1205   /// Determine whether the initialization sequence is valid.
1206   explicit operator bool() const { return !Failed(); }
1207 
1208   /// Determine whether the initialization sequence is invalid.
Failed()1209   bool Failed() const { return SequenceKind == FailedSequence; }
1210 
1211   using step_iterator = SmallVectorImpl<Step>::const_iterator;
1212 
step_begin()1213   step_iterator step_begin() const { return Steps.begin(); }
step_end()1214   step_iterator step_end()   const { return Steps.end(); }
1215 
1216   using step_range = llvm::iterator_range<step_iterator>;
1217 
steps()1218   step_range steps() const { return {step_begin(), step_end()}; }
1219 
1220   /// Determine whether this initialization is a direct reference
1221   /// binding (C++ [dcl.init.ref]).
1222   bool isDirectReferenceBinding() const;
1223 
1224   /// Determine whether this initialization failed due to an ambiguity.
1225   bool isAmbiguous() const;
1226 
1227   /// Determine whether this initialization is direct call to a
1228   /// constructor.
1229   bool isConstructorInitialization() const;
1230 
1231   /// Add a new step in the initialization that resolves the address
1232   /// of an overloaded function to a specific function declaration.
1233   ///
1234   /// \param Function the function to which the overloaded function reference
1235   /// resolves.
1236   void AddAddressOverloadResolutionStep(FunctionDecl *Function,
1237                                         DeclAccessPair Found,
1238                                         bool HadMultipleCandidates);
1239 
1240   /// Add a new step in the initialization that performs a derived-to-
1241   /// base cast.
1242   ///
1243   /// \param BaseType the base type to which we will be casting.
1244   ///
1245   /// \param Category Indicates whether the result will be treated as an
1246   /// rvalue, an xvalue, or an lvalue.
1247   void AddDerivedToBaseCastStep(QualType BaseType,
1248                                 ExprValueKind Category);
1249 
1250   /// Add a new step binding a reference to an object.
1251   ///
1252   /// \param BindingTemporary True if we are binding a reference to a temporary
1253   /// object (thereby extending its lifetime); false if we are binding to an
1254   /// lvalue or an lvalue treated as an rvalue.
1255   void AddReferenceBindingStep(QualType T, bool BindingTemporary);
1256 
1257   /// Add a new step that makes an extraneous copy of the input
1258   /// to a temporary of the same class type.
1259   ///
1260   /// This extraneous copy only occurs during reference binding in
1261   /// C++98/03, where we are permitted (but not required) to introduce
1262   /// an extra copy. At a bare minimum, we must check that we could
1263   /// call the copy constructor, and produce a diagnostic if the copy
1264   /// constructor is inaccessible or no copy constructor matches.
1265   //
1266   /// \param T The type of the temporary being created.
1267   void AddExtraneousCopyToTemporary(QualType T);
1268 
1269   /// Add a new step that makes a copy of the input to an object of
1270   /// the given type, as the final step in class copy-initialization.
1271   void AddFinalCopy(QualType T);
1272 
1273   /// Add a new step invoking a conversion function, which is either
1274   /// a constructor or a conversion function.
1275   void AddUserConversionStep(FunctionDecl *Function,
1276                              DeclAccessPair FoundDecl,
1277                              QualType T,
1278                              bool HadMultipleCandidates);
1279 
1280   /// Add a new step that performs a qualification conversion to the
1281   /// given type.
1282   void AddQualificationConversionStep(QualType Ty,
1283                                      ExprValueKind Category);
1284 
1285   /// Add a new step that performs a function reference conversion to the
1286   /// given type.
1287   void AddFunctionReferenceConversionStep(QualType Ty);
1288 
1289   /// Add a new step that performs conversion from non-atomic to atomic
1290   /// type.
1291   void AddAtomicConversionStep(QualType Ty);
1292 
1293   /// Add a new step that applies an implicit conversion sequence.
1294   void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
1295                                  QualType T, bool TopLevelOfInitList = false);
1296 
1297   /// Add a list-initialization step.
1298   void AddListInitializationStep(QualType T);
1299 
1300   /// Add a constructor-initialization step.
1301   ///
1302   /// \param FromInitList The constructor call is syntactically an initializer
1303   /// list.
1304   /// \param AsInitList The constructor is called as an init list constructor.
1305   void AddConstructorInitializationStep(DeclAccessPair FoundDecl,
1306                                         CXXConstructorDecl *Constructor,
1307                                         QualType T,
1308                                         bool HadMultipleCandidates,
1309                                         bool FromInitList, bool AsInitList);
1310 
1311   /// Add a zero-initialization step.
1312   void AddZeroInitializationStep(QualType T);
1313 
1314   /// Add a C assignment step.
1315   //
1316   // FIXME: It isn't clear whether this should ever be needed;
1317   // ideally, we would handle everything needed in C in the common
1318   // path. However, that isn't the case yet.
1319   void AddCAssignmentStep(QualType T);
1320 
1321   /// Add a string init step.
1322   void AddStringInitStep(QualType T);
1323 
1324   /// Add an Objective-C object conversion step, which is
1325   /// always a no-op.
1326   void AddObjCObjectConversionStep(QualType T);
1327 
1328   /// Add an array initialization loop step.
1329   void AddArrayInitLoopStep(QualType T, QualType EltTy);
1330 
1331   /// Add an array initialization step.
1332   void AddArrayInitStep(QualType T, bool IsGNUExtension);
1333 
1334   /// Add a parenthesized array initialization step.
1335   void AddParenthesizedArrayInitStep(QualType T);
1336 
1337   /// Add a step to pass an object by indirect copy-restore.
1338   void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1339 
1340   /// Add a step to "produce" an Objective-C object (by
1341   /// retaining it).
1342   void AddProduceObjCObjectStep(QualType T);
1343 
1344   /// Add a step to construct a std::initializer_list object from an
1345   /// initializer list.
1346   void AddStdInitializerListConstructionStep(QualType T);
1347 
1348   /// Add a step to initialize an OpenCL sampler from an integer
1349   /// constant.
1350   void AddOCLSamplerInitStep(QualType T);
1351 
1352   /// Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.)
1353   /// from a zero constant.
1354   void AddOCLZeroOpaqueTypeStep(QualType T);
1355 
1356   /// Add steps to unwrap a initializer list for a reference around a
1357   /// single element and rewrap it at the end.
1358   void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1359 
1360   /// Note that this initialization sequence failed.
SetFailed(FailureKind Failure)1361   void SetFailed(FailureKind Failure) {
1362     SequenceKind = FailedSequence;
1363     this->Failure = Failure;
1364     assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1365            "Incomplete type failure requires a type!");
1366   }
1367 
1368   /// Note that this initialization sequence failed due to failed
1369   /// overload resolution.
1370   void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1371 
1372   /// Retrieve a reference to the candidate set when overload
1373   /// resolution fails.
getFailedCandidateSet()1374   OverloadCandidateSet &getFailedCandidateSet() {
1375     return FailedCandidateSet;
1376   }
1377 
1378   /// Get the overloading result, for when the initialization
1379   /// sequence failed due to a bad overload.
getFailedOverloadResult()1380   OverloadingResult getFailedOverloadResult() const {
1381     return FailedOverloadResult;
1382   }
1383 
1384   /// Note that this initialization sequence failed due to an
1385   /// incomplete type.
setIncompleteTypeFailure(QualType IncompleteType)1386   void setIncompleteTypeFailure(QualType IncompleteType) {
1387     FailedIncompleteType = IncompleteType;
1388     SetFailed(FK_Incomplete);
1389   }
1390 
1391   /// Determine why initialization failed.
getFailureKind()1392   FailureKind getFailureKind() const {
1393     assert(Failed() && "Not an initialization failure!");
1394     return Failure;
1395   }
1396 
1397   /// Dump a representation of this initialization sequence to
1398   /// the given stream, for debugging purposes.
1399   void dump(raw_ostream &OS) const;
1400 
1401   /// Dump a representation of this initialization sequence to
1402   /// standard error, for debugging purposes.
1403   void dump() const;
1404 };
1405 
1406 } // namespace clang
1407 
1408 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H
1409