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