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