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