clang  6.0.0svn
SemaInit.cpp
Go to the documentation of this file.
1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for initializers.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Sema/Designator.h"
22 #include "clang/Sema/Lookup.h"
24 #include "llvm/ADT/APInt.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 
29 using namespace clang;
30 
31 //===----------------------------------------------------------------------===//
32 // Sema Initialization Checking
33 //===----------------------------------------------------------------------===//
34 
35 /// \brief Check whether T is compatible with a wide character type (wchar_t,
36 /// char16_t or char32_t).
37 static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38  if (Context.typesAreCompatible(Context.getWideCharType(), T))
39  return true;
40  if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41  return Context.typesAreCompatible(Context.Char16Ty, T) ||
42  Context.typesAreCompatible(Context.Char32Ty, T);
43  }
44  return false;
45 }
46 
53 };
54 
55 /// \brief Check whether the array of type AT can be initialized by the Init
56 /// expression by means of string initialization. Returns SIF_None if so,
57 /// otherwise returns a StringInitFailureKind that describes why the
58 /// initialization would not work.
60  ASTContext &Context) {
61  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
62  return SIF_Other;
63 
64  // See if this is a string literal or @encode.
65  Init = Init->IgnoreParens();
66 
67  // Handle @encode, which is a narrow string.
68  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
69  return SIF_None;
70 
71  // Otherwise we can only handle string literals.
72  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
73  if (!SL)
74  return SIF_Other;
75 
76  const QualType ElemTy =
77  Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
78 
79  switch (SL->getKind()) {
82  // char array can be initialized with a narrow string.
83  // Only allow char x[] = "foo"; not char x[] = L"foo";
84  if (ElemTy->isCharType())
85  return SIF_None;
86  if (IsWideCharCompatible(ElemTy, Context))
88  return SIF_Other;
89  // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90  // "An array with element type compatible with a qualified or unqualified
91  // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92  // string literal with the corresponding encoding prefix (L, u, or U,
93  // respectively), optionally enclosed in braces.
95  if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96  return SIF_None;
97  if (ElemTy->isCharType())
99  if (IsWideCharCompatible(ElemTy, Context))
101  return SIF_Other;
103  if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104  return SIF_None;
105  if (ElemTy->isCharType())
106  return SIF_WideStringIntoChar;
107  if (IsWideCharCompatible(ElemTy, Context))
109  return SIF_Other;
110  case StringLiteral::Wide:
111  if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112  return SIF_None;
113  if (ElemTy->isCharType())
114  return SIF_WideStringIntoChar;
115  if (IsWideCharCompatible(ElemTy, Context))
117  return SIF_Other;
118  }
119 
120  llvm_unreachable("missed a StringLiteral kind?");
121 }
122 
124  ASTContext &Context) {
125  const ArrayType *arrayType = Context.getAsArrayType(declType);
126  if (!arrayType)
127  return SIF_Other;
128  return IsStringInit(init, arrayType, Context);
129 }
130 
131 /// Update the type of a string literal, including any surrounding parentheses,
132 /// to match the type of the object which it is initializing.
133 static void updateStringLiteralType(Expr *E, QualType Ty) {
134  while (true) {
135  E->setType(Ty);
136  if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137  break;
138  else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139  E = PE->getSubExpr();
140  else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141  E = UO->getSubExpr();
142  else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143  E = GSE->getResultExpr();
144  else
145  llvm_unreachable("unexpected expr in string literal init");
146  }
147 }
148 
149 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150  Sema &S) {
151  // Get the length of the string as parsed.
152  auto *ConstantArrayTy =
153  cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
154  uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
155 
156  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
157  // C99 6.7.8p14. We have an array of character type with unknown size
158  // being initialized to a string literal.
159  llvm::APInt ConstVal(32, StrLength);
160  // Return a new array type (C99 6.7.8p22).
161  DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162  ConstVal,
163  ArrayType::Normal, 0);
164  updateStringLiteralType(Str, DeclT);
165  return;
166  }
167 
168  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
169 
170  // We have an array of character type with known size. However,
171  // the size may be smaller or larger than the string we are initializing.
172  // FIXME: Avoid truncation for 64-bit length strings.
173  if (S.getLangOpts().CPlusPlus) {
174  if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
175  // For Pascal strings it's OK to strip off the terminating null character,
176  // so the example below is valid:
177  //
178  // unsigned char a[2] = "\pa";
179  if (SL->isPascal())
180  StrLength--;
181  }
182 
183  // [dcl.init.string]p2
184  if (StrLength > CAT->getSize().getZExtValue())
185  S.Diag(Str->getLocStart(),
186  diag::err_initializer_string_for_char_array_too_long)
187  << Str->getSourceRange();
188  } else {
189  // C99 6.7.8p14.
190  if (StrLength-1 > CAT->getSize().getZExtValue())
191  S.Diag(Str->getLocStart(),
192  diag::ext_initializer_string_for_char_array_too_long)
193  << Str->getSourceRange();
194  }
195 
196  // Set the type to the actual size that we are initializing. If we have
197  // something like:
198  // char x[1] = "foo";
199  // then this will set the string literal's type to char[1].
200  updateStringLiteralType(Str, DeclT);
201 }
202 
203 //===----------------------------------------------------------------------===//
204 // Semantic checking for initializer lists.
205 //===----------------------------------------------------------------------===//
206 
207 namespace {
208 
209 /// @brief Semantic checking for initializer lists.
210 ///
211 /// The InitListChecker class contains a set of routines that each
212 /// handle the initialization of a certain kind of entity, e.g.,
213 /// arrays, vectors, struct/union types, scalars, etc. The
214 /// InitListChecker itself performs a recursive walk of the subobject
215 /// structure of the type to be initialized, while stepping through
216 /// the initializer list one element at a time. The IList and Index
217 /// parameters to each of the Check* routines contain the active
218 /// (syntactic) initializer list and the index into that initializer
219 /// list that represents the current initializer. Each routine is
220 /// responsible for moving that Index forward as it consumes elements.
221 ///
222 /// Each Check* routine also has a StructuredList/StructuredIndex
223 /// arguments, which contains the current "structured" (semantic)
224 /// initializer list and the index into that initializer list where we
225 /// are copying initializers as we map them over to the semantic
226 /// list. Once we have completed our recursive walk of the subobject
227 /// structure, we will have constructed a full semantic initializer
228 /// list.
229 ///
230 /// C99 designators cause changes in the initializer list traversal,
231 /// because they make the initialization "jump" into a specific
232 /// subobject and then continue the initialization from that
233 /// point. CheckDesignatedInitializer() recursively steps into the
234 /// designated subobject and manages backing out the recursion to
235 /// initialize the subobjects after the one designated.
236 class InitListChecker {
237  Sema &SemaRef;
238  bool hadError;
239  bool VerifyOnly; // no diagnostics, no structure building
240  bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
241  llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
242  InitListExpr *FullyStructuredList;
243 
244  void CheckImplicitInitList(const InitializedEntity &Entity,
245  InitListExpr *ParentIList, QualType T,
246  unsigned &Index, InitListExpr *StructuredList,
247  unsigned &StructuredIndex);
248  void CheckExplicitInitList(const InitializedEntity &Entity,
249  InitListExpr *IList, QualType &T,
250  InitListExpr *StructuredList,
251  bool TopLevelObject = false);
252  void CheckListElementTypes(const InitializedEntity &Entity,
253  InitListExpr *IList, QualType &DeclType,
254  bool SubobjectIsDesignatorContext,
255  unsigned &Index,
256  InitListExpr *StructuredList,
257  unsigned &StructuredIndex,
258  bool TopLevelObject = false);
259  void CheckSubElementType(const InitializedEntity &Entity,
260  InitListExpr *IList, QualType ElemType,
261  unsigned &Index,
262  InitListExpr *StructuredList,
263  unsigned &StructuredIndex);
264  void CheckComplexType(const InitializedEntity &Entity,
265  InitListExpr *IList, QualType DeclType,
266  unsigned &Index,
267  InitListExpr *StructuredList,
268  unsigned &StructuredIndex);
269  void CheckScalarType(const InitializedEntity &Entity,
270  InitListExpr *IList, QualType DeclType,
271  unsigned &Index,
272  InitListExpr *StructuredList,
273  unsigned &StructuredIndex);
274  void CheckReferenceType(const InitializedEntity &Entity,
275  InitListExpr *IList, QualType DeclType,
276  unsigned &Index,
277  InitListExpr *StructuredList,
278  unsigned &StructuredIndex);
279  void CheckVectorType(const InitializedEntity &Entity,
280  InitListExpr *IList, QualType DeclType, unsigned &Index,
281  InitListExpr *StructuredList,
282  unsigned &StructuredIndex);
283  void CheckStructUnionTypes(const InitializedEntity &Entity,
284  InitListExpr *IList, QualType DeclType,
287  bool SubobjectIsDesignatorContext, unsigned &Index,
288  InitListExpr *StructuredList,
289  unsigned &StructuredIndex,
290  bool TopLevelObject = false);
291  void CheckArrayType(const InitializedEntity &Entity,
292  InitListExpr *IList, QualType &DeclType,
293  llvm::APSInt elementIndex,
294  bool SubobjectIsDesignatorContext, unsigned &Index,
295  InitListExpr *StructuredList,
296  unsigned &StructuredIndex);
297  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
298  InitListExpr *IList, DesignatedInitExpr *DIE,
299  unsigned DesigIdx,
300  QualType &CurrentObjectType,
301  RecordDecl::field_iterator *NextField,
302  llvm::APSInt *NextElementIndex,
303  unsigned &Index,
304  InitListExpr *StructuredList,
305  unsigned &StructuredIndex,
306  bool FinishSubobjectInit,
307  bool TopLevelObject);
308  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
309  QualType CurrentObjectType,
310  InitListExpr *StructuredList,
311  unsigned StructuredIndex,
312  SourceRange InitRange,
313  bool IsFullyOverwritten = false);
314  void UpdateStructuredListElement(InitListExpr *StructuredList,
315  unsigned &StructuredIndex,
316  Expr *expr);
317  int numArrayElements(QualType DeclType);
318  int numStructUnionElements(QualType DeclType);
319 
320  static ExprResult PerformEmptyInit(Sema &SemaRef,
321  SourceLocation Loc,
322  const InitializedEntity &Entity,
323  bool VerifyOnly,
324  bool TreatUnavailableAsInvalid);
325 
326  // Explanation on the "FillWithNoInit" mode:
327  //
328  // Assume we have the following definitions (Case#1):
329  // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
330  // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
331  //
332  // l.lp.x[1][0..1] should not be filled with implicit initializers because the
333  // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
334  //
335  // But if we have (Case#2):
336  // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
337  //
338  // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
339  // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
340  //
341  // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
342  // in the InitListExpr, the "holes" in Case#1 are filled not with empty
343  // initializers but with special "NoInitExpr" place holders, which tells the
344  // CodeGen not to generate any initializers for these parts.
345  void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
346  const InitializedEntity &ParentEntity,
347  InitListExpr *ILE, bool &RequiresSecondPass,
348  bool FillWithNoInit);
349  void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
350  const InitializedEntity &ParentEntity,
351  InitListExpr *ILE, bool &RequiresSecondPass,
352  bool FillWithNoInit = false);
353  void FillInEmptyInitializations(const InitializedEntity &Entity,
354  InitListExpr *ILE, bool &RequiresSecondPass,
355  bool FillWithNoInit = false);
356  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
357  Expr *InitExpr, FieldDecl *Field,
358  bool TopLevelObject);
359  void CheckEmptyInitializable(const InitializedEntity &Entity,
360  SourceLocation Loc);
361 
362 public:
363  InitListChecker(Sema &S, const InitializedEntity &Entity,
364  InitListExpr *IL, QualType &T, bool VerifyOnly,
365  bool TreatUnavailableAsInvalid);
366  bool HadError() { return hadError; }
367 
368  // @brief Retrieves the fully-structured initializer list used for
369  // semantic analysis and code generation.
370  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
371 };
372 
373 } // end anonymous namespace
374 
375 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
376  SourceLocation Loc,
377  const InitializedEntity &Entity,
378  bool VerifyOnly,
379  bool TreatUnavailableAsInvalid) {
381  true);
382  MultiExprArg SubInit;
383  Expr *InitExpr;
384  InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
385 
386  // C++ [dcl.init.aggr]p7:
387  // If there are fewer initializer-clauses in the list than there are
388  // members in the aggregate, then each member not explicitly initialized
389  // ...
390  bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
392  if (EmptyInitList) {
393  // C++1y / DR1070:
394  // shall be initialized [...] from an empty initializer list.
395  //
396  // We apply the resolution of this DR to C++11 but not C++98, since C++98
397  // does not have useful semantics for initialization from an init list.
398  // We treat this as copy-initialization, because aggregate initialization
399  // always performs copy-initialization on its elements.
400  //
401  // Only do this if we're initializing a class type, to avoid filling in
402  // the initializer list where possible.
403  InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
404  InitListExpr(SemaRef.Context, Loc, None, Loc);
405  InitExpr->setType(SemaRef.Context.VoidTy);
406  SubInit = InitExpr;
407  Kind = InitializationKind::CreateCopy(Loc, Loc);
408  } else {
409  // C++03:
410  // shall be value-initialized.
411  }
412 
413  InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
414  // libstdc++4.6 marks the vector default constructor as explicit in
415  // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
416  // stlport does so too. Look for std::__debug for libstdc++, and for
417  // std:: for stlport. This is effectively a compiler-side implementation of
418  // LWG2193.
419  if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
423  InitSeq.getFailedCandidateSet()
424  .BestViableFunction(SemaRef, Kind.getLocation(), Best);
425  (void)O;
426  assert(O == OR_Success && "Inconsistent overload resolution");
427  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
428  CXXRecordDecl *R = CtorDecl->getParent();
429 
430  if (CtorDecl->getMinRequiredArguments() == 0 &&
431  CtorDecl->isExplicit() && R->getDeclName() &&
432  SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
433  bool IsInStd = false;
434  for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
435  ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
436  if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
437  IsInStd = true;
438  }
439 
440  if (IsInStd && llvm::StringSwitch<bool>(R->getName())
441  .Cases("basic_string", "deque", "forward_list", true)
442  .Cases("list", "map", "multimap", "multiset", true)
443  .Cases("priority_queue", "queue", "set", "stack", true)
444  .Cases("unordered_map", "unordered_set", "vector", true)
445  .Default(false)) {
446  InitSeq.InitializeFrom(
447  SemaRef, Entity,
448  InitializationKind::CreateValue(Loc, Loc, Loc, true),
449  MultiExprArg(), /*TopLevelOfInitList=*/false,
450  TreatUnavailableAsInvalid);
451  // Emit a warning for this. System header warnings aren't shown
452  // by default, but people working on system headers should see it.
453  if (!VerifyOnly) {
454  SemaRef.Diag(CtorDecl->getLocation(),
455  diag::warn_invalid_initializer_from_system_header);
456  if (Entity.getKind() == InitializedEntity::EK_Member)
457  SemaRef.Diag(Entity.getDecl()->getLocation(),
458  diag::note_used_in_initialization_here);
459  else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
460  SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
461  }
462  }
463  }
464  }
465  if (!InitSeq) {
466  if (!VerifyOnly) {
467  InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
468  if (Entity.getKind() == InitializedEntity::EK_Member)
469  SemaRef.Diag(Entity.getDecl()->getLocation(),
470  diag::note_in_omitted_aggregate_initializer)
471  << /*field*/1 << Entity.getDecl();
472  else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
473  bool IsTrailingArrayNewMember =
474  Entity.getParent() &&
476  SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
477  << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
478  << Entity.getElementIndex();
479  }
480  }
481  return ExprError();
482  }
483 
484  return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
485  : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
486 }
487 
488 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
489  SourceLocation Loc) {
490  assert(VerifyOnly &&
491  "CheckEmptyInitializable is only inteded for verification mode.");
492  if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
493  TreatUnavailableAsInvalid).isInvalid())
494  hadError = true;
495 }
496 
497 void InitListChecker::FillInEmptyInitForBase(
498  unsigned Init, const CXXBaseSpecifier &Base,
499  const InitializedEntity &ParentEntity, InitListExpr *ILE,
500  bool &RequiresSecondPass, bool FillWithNoInit) {
501  assert(Init < ILE->getNumInits() && "should have been expanded");
502 
504  SemaRef.Context, &Base, false, &ParentEntity);
505 
506  if (!ILE->getInit(Init)) {
507  ExprResult BaseInit =
508  FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
509  : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
510  /*VerifyOnly*/ false,
511  TreatUnavailableAsInvalid);
512  if (BaseInit.isInvalid()) {
513  hadError = true;
514  return;
515  }
516 
517  ILE->setInit(Init, BaseInit.getAs<Expr>());
518  } else if (InitListExpr *InnerILE =
519  dyn_cast<InitListExpr>(ILE->getInit(Init))) {
520  FillInEmptyInitializations(BaseEntity, InnerILE,
521  RequiresSecondPass, FillWithNoInit);
522  } else if (DesignatedInitUpdateExpr *InnerDIUE =
523  dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
524  FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
525  RequiresSecondPass, /*FillWithNoInit =*/true);
526  }
527 }
528 
529 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
530  const InitializedEntity &ParentEntity,
531  InitListExpr *ILE,
532  bool &RequiresSecondPass,
533  bool FillWithNoInit) {
534  SourceLocation Loc = ILE->getLocEnd();
535  unsigned NumInits = ILE->getNumInits();
536  InitializedEntity MemberEntity
537  = InitializedEntity::InitializeMember(Field, &ParentEntity);
538 
539  if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
540  if (!RType->getDecl()->isUnion())
541  assert(Init < NumInits && "This ILE should have been expanded");
542 
543  if (Init >= NumInits || !ILE->getInit(Init)) {
544  if (FillWithNoInit) {
545  Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
546  if (Init < NumInits)
547  ILE->setInit(Init, Filler);
548  else
549  ILE->updateInit(SemaRef.Context, Init, Filler);
550  return;
551  }
552  // C++1y [dcl.init.aggr]p7:
553  // If there are fewer initializer-clauses in the list than there are
554  // members in the aggregate, then each member not explicitly initialized
555  // shall be initialized from its brace-or-equal-initializer [...]
556  if (Field->hasInClassInitializer()) {
557  ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
558  if (DIE.isInvalid()) {
559  hadError = true;
560  return;
561  }
562  if (Init < NumInits)
563  ILE->setInit(Init, DIE.get());
564  else {
565  ILE->updateInit(SemaRef.Context, Init, DIE.get());
566  RequiresSecondPass = true;
567  }
568  return;
569  }
570 
571  if (Field->getType()->isReferenceType()) {
572  // C++ [dcl.init.aggr]p9:
573  // If an incomplete or empty initializer-list leaves a
574  // member of reference type uninitialized, the program is
575  // ill-formed.
576  SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
577  << Field->getType()
578  << ILE->getSyntacticForm()->getSourceRange();
579  SemaRef.Diag(Field->getLocation(),
580  diag::note_uninit_reference_member);
581  hadError = true;
582  return;
583  }
584 
585  ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
586  /*VerifyOnly*/false,
587  TreatUnavailableAsInvalid);
588  if (MemberInit.isInvalid()) {
589  hadError = true;
590  return;
591  }
592 
593  if (hadError) {
594  // Do nothing
595  } else if (Init < NumInits) {
596  ILE->setInit(Init, MemberInit.getAs<Expr>());
597  } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
598  // Empty initialization requires a constructor call, so
599  // extend the initializer list to include the constructor
600  // call and make a note that we'll need to take another pass
601  // through the initializer list.
602  ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
603  RequiresSecondPass = true;
604  }
605  } else if (InitListExpr *InnerILE
606  = dyn_cast<InitListExpr>(ILE->getInit(Init)))
607  FillInEmptyInitializations(MemberEntity, InnerILE,
608  RequiresSecondPass, FillWithNoInit);
609  else if (DesignatedInitUpdateExpr *InnerDIUE
610  = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
611  FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
612  RequiresSecondPass, /*FillWithNoInit =*/ true);
613 }
614 
615 /// Recursively replaces NULL values within the given initializer list
616 /// with expressions that perform value-initialization of the
617 /// appropriate type.
618 void
619 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
620  InitListExpr *ILE,
621  bool &RequiresSecondPass,
622  bool FillWithNoInit) {
623  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
624  "Should not have void type");
625 
626  // A transparent ILE is not performing aggregate initialization and should
627  // not be filled in.
628  if (ILE->isTransparent())
629  return;
630 
631  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
632  const RecordDecl *RDecl = RType->getDecl();
633  if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
634  FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
635  Entity, ILE, RequiresSecondPass, FillWithNoInit);
636  else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
637  cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
638  for (auto *Field : RDecl->fields()) {
639  if (Field->hasInClassInitializer()) {
640  FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
641  FillWithNoInit);
642  break;
643  }
644  }
645  } else {
646  // The fields beyond ILE->getNumInits() are default initialized, so in
647  // order to leave them uninitialized, the ILE is expanded and the extra
648  // fields are then filled with NoInitExpr.
649  unsigned NumElems = numStructUnionElements(ILE->getType());
650  if (RDecl->hasFlexibleArrayMember())
651  ++NumElems;
652  if (ILE->getNumInits() < NumElems)
653  ILE->resizeInits(SemaRef.Context, NumElems);
654 
655  unsigned Init = 0;
656 
657  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
658  for (auto &Base : CXXRD->bases()) {
659  if (hadError)
660  return;
661 
662  FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
663  FillWithNoInit);
664  ++Init;
665  }
666  }
667 
668  for (auto *Field : RDecl->fields()) {
669  if (Field->isUnnamedBitfield())
670  continue;
671 
672  if (hadError)
673  return;
674 
675  FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
676  FillWithNoInit);
677  if (hadError)
678  return;
679 
680  ++Init;
681 
682  // Only look at the first initialization of a union.
683  if (RDecl->isUnion())
684  break;
685  }
686  }
687 
688  return;
689  }
690 
691  QualType ElementType;
692 
693  InitializedEntity ElementEntity = Entity;
694  unsigned NumInits = ILE->getNumInits();
695  unsigned NumElements = NumInits;
696  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
697  ElementType = AType->getElementType();
698  if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
699  NumElements = CAType->getSize().getZExtValue();
700  // For an array new with an unknown bound, ask for one additional element
701  // in order to populate the array filler.
702  if (Entity.isVariableLengthArrayNew())
703  ++NumElements;
704  ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
705  0, Entity);
706  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
707  ElementType = VType->getElementType();
708  NumElements = VType->getNumElements();
709  ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
710  0, Entity);
711  } else
712  ElementType = ILE->getType();
713 
714  for (unsigned Init = 0; Init != NumElements; ++Init) {
715  if (hadError)
716  return;
717 
718  if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
719  ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
720  ElementEntity.setElementIndex(Init);
721 
722  Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
723  if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
724  ILE->setInit(Init, ILE->getArrayFiller());
725  else if (!InitExpr && !ILE->hasArrayFiller()) {
726  Expr *Filler = nullptr;
727 
728  if (FillWithNoInit)
729  Filler = new (SemaRef.Context) NoInitExpr(ElementType);
730  else {
731  ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
732  ElementEntity,
733  /*VerifyOnly*/false,
734  TreatUnavailableAsInvalid);
735  if (ElementInit.isInvalid()) {
736  hadError = true;
737  return;
738  }
739 
740  Filler = ElementInit.getAs<Expr>();
741  }
742 
743  if (hadError) {
744  // Do nothing
745  } else if (Init < NumInits) {
746  // For arrays, just set the expression used for value-initialization
747  // of the "holes" in the array.
748  if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
749  ILE->setArrayFiller(Filler);
750  else
751  ILE->setInit(Init, Filler);
752  } else {
753  // For arrays, just set the expression used for value-initialization
754  // of the rest of elements and exit.
755  if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
756  ILE->setArrayFiller(Filler);
757  return;
758  }
759 
760  if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
761  // Empty initialization requires a constructor call, so
762  // extend the initializer list to include the constructor
763  // call and make a note that we'll need to take another pass
764  // through the initializer list.
765  ILE->updateInit(SemaRef.Context, Init, Filler);
766  RequiresSecondPass = true;
767  }
768  }
769  } else if (InitListExpr *InnerILE
770  = dyn_cast_or_null<InitListExpr>(InitExpr))
771  FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
772  FillWithNoInit);
773  else if (DesignatedInitUpdateExpr *InnerDIUE
774  = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
775  FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
776  RequiresSecondPass, /*FillWithNoInit =*/ true);
777  }
778 }
779 
780 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
781  InitListExpr *IL, QualType &T,
782  bool VerifyOnly,
783  bool TreatUnavailableAsInvalid)
784  : SemaRef(S), VerifyOnly(VerifyOnly),
785  TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
786  // FIXME: Check that IL isn't already the semantic form of some other
787  // InitListExpr. If it is, we'd create a broken AST.
788 
789  hadError = false;
790 
791  FullyStructuredList =
792  getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
793  CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
794  /*TopLevelObject=*/true);
795 
796  if (!hadError && !VerifyOnly) {
797  bool RequiresSecondPass = false;
798  FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
799  if (RequiresSecondPass && !hadError)
800  FillInEmptyInitializations(Entity, FullyStructuredList,
801  RequiresSecondPass);
802  }
803 }
804 
805 int InitListChecker::numArrayElements(QualType DeclType) {
806  // FIXME: use a proper constant
807  int maxElements = 0x7FFFFFFF;
808  if (const ConstantArrayType *CAT =
809  SemaRef.Context.getAsConstantArrayType(DeclType)) {
810  maxElements = static_cast<int>(CAT->getSize().getZExtValue());
811  }
812  return maxElements;
813 }
814 
815 int InitListChecker::numStructUnionElements(QualType DeclType) {
816  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
817  int InitializableMembers = 0;
818  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
819  InitializableMembers += CXXRD->getNumBases();
820  for (const auto *Field : structDecl->fields())
821  if (!Field->isUnnamedBitfield())
822  ++InitializableMembers;
823 
824  if (structDecl->isUnion())
825  return std::min(InitializableMembers, 1);
826  return InitializableMembers - structDecl->hasFlexibleArrayMember();
827 }
828 
829 /// Determine whether Entity is an entity for which it is idiomatic to elide
830 /// the braces in aggregate initialization.
832  // Recursive initialization of the one and only field within an aggregate
833  // class is considered idiomatic. This case arises in particular for
834  // initialization of std::array, where the C++ standard suggests the idiom of
835  //
836  // std::array<T, N> arr = {1, 2, 3};
837  //
838  // (where std::array is an aggregate struct containing a single array field.
839 
840  // FIXME: Should aggregate initialization of a struct with a single
841  // base class and no members also suppress the warning?
842  if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
843  return false;
844 
845  auto *ParentRD =
846  Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
847  if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
848  if (CXXRD->getNumBases())
849  return false;
850 
851  auto FieldIt = ParentRD->field_begin();
852  assert(FieldIt != ParentRD->field_end() &&
853  "no fields but have initializer for member?");
854  return ++FieldIt == ParentRD->field_end();
855 }
856 
857 /// Check whether the range of the initializer \p ParentIList from element
858 /// \p Index onwards can be used to initialize an object of type \p T. Update
859 /// \p Index to indicate how many elements of the list were consumed.
860 ///
861 /// This also fills in \p StructuredList, from element \p StructuredIndex
862 /// onwards, with the fully-braced, desugared form of the initialization.
863 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
864  InitListExpr *ParentIList,
865  QualType T, unsigned &Index,
866  InitListExpr *StructuredList,
867  unsigned &StructuredIndex) {
868  int maxElements = 0;
869 
870  if (T->isArrayType())
871  maxElements = numArrayElements(T);
872  else if (T->isRecordType())
873  maxElements = numStructUnionElements(T);
874  else if (T->isVectorType())
875  maxElements = T->getAs<VectorType>()->getNumElements();
876  else
877  llvm_unreachable("CheckImplicitInitList(): Illegal type");
878 
879  if (maxElements == 0) {
880  if (!VerifyOnly)
881  SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
882  diag::err_implicit_empty_initializer);
883  ++Index;
884  hadError = true;
885  return;
886  }
887 
888  // Build a structured initializer list corresponding to this subobject.
889  InitListExpr *StructuredSubobjectInitList
890  = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
891  StructuredIndex,
892  SourceRange(ParentIList->getInit(Index)->getLocStart(),
893  ParentIList->getSourceRange().getEnd()));
894  unsigned StructuredSubobjectInitIndex = 0;
895 
896  // Check the element types and build the structural subobject.
897  unsigned StartIndex = Index;
898  CheckListElementTypes(Entity, ParentIList, T,
899  /*SubobjectIsDesignatorContext=*/false, Index,
900  StructuredSubobjectInitList,
901  StructuredSubobjectInitIndex);
902 
903  if (!VerifyOnly) {
904  StructuredSubobjectInitList->setType(T);
905 
906  unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
907  // Update the structured sub-object initializer so that it's ending
908  // range corresponds with the end of the last initializer it used.
909  if (EndIndex < ParentIList->getNumInits() &&
910  ParentIList->getInit(EndIndex)) {
911  SourceLocation EndLoc
912  = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
913  StructuredSubobjectInitList->setRBraceLoc(EndLoc);
914  }
915 
916  // Complain about missing braces.
917  if ((T->isArrayType() || T->isRecordType()) &&
918  !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
920  SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
921  diag::warn_missing_braces)
922  << StructuredSubobjectInitList->getSourceRange()
924  StructuredSubobjectInitList->getLocStart(), "{")
926  SemaRef.getLocForEndOfToken(
927  StructuredSubobjectInitList->getLocEnd()),
928  "}");
929  }
930  }
931 }
932 
933 /// Warn that \p Entity was of scalar type and was initialized by a
934 /// single-element braced initializer list.
935 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
936  SourceRange Braces) {
937  // Don't warn during template instantiation. If the initialization was
938  // non-dependent, we warned during the initial parse; otherwise, the
939  // type might not be scalar in some uses of the template.
940  if (S.inTemplateInstantiation())
941  return;
942 
943  unsigned DiagID = 0;
944 
945  switch (Entity.getKind()) {
952  // Extra braces here are suspicious.
953  DiagID = diag::warn_braces_around_scalar_init;
954  break;
955 
957  // Warn on aggregate initialization but not on ctor init list or
958  // default member initializer.
959  if (Entity.getParent())
960  DiagID = diag::warn_braces_around_scalar_init;
961  break;
962 
965  // No warning, might be direct-list-initialization.
966  // FIXME: Should we warn for copy-list-initialization in these cases?
967  break;
968 
972  // No warning, braces are part of the syntax of the underlying construct.
973  break;
974 
976  // No warning, we already warned when initializing the result.
977  break;
978 
985  llvm_unreachable("unexpected braced scalar init");
986  }
987 
988  if (DiagID) {
989  S.Diag(Braces.getBegin(), DiagID)
990  << Braces
992  << FixItHint::CreateRemoval(Braces.getEnd());
993  }
994 }
995 
996 /// Check whether the initializer \p IList (that was written with explicit
997 /// braces) can be used to initialize an object of type \p T.
998 ///
999 /// This also fills in \p StructuredList with the fully-braced, desugared
1000 /// form of the initialization.
1001 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1002  InitListExpr *IList, QualType &T,
1003  InitListExpr *StructuredList,
1004  bool TopLevelObject) {
1005  if (!VerifyOnly) {
1006  SyntacticToSemantic[IList] = StructuredList;
1007  StructuredList->setSyntacticForm(IList);
1008  }
1009 
1010  unsigned Index = 0, StructuredIndex = 0;
1011  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1012  Index, StructuredList, StructuredIndex, TopLevelObject);
1013  if (!VerifyOnly) {
1014  QualType ExprTy = T;
1015  if (!ExprTy->isArrayType())
1016  ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1017  IList->setType(ExprTy);
1018  StructuredList->setType(ExprTy);
1019  }
1020  if (hadError)
1021  return;
1022 
1023  if (Index < IList->getNumInits()) {
1024  // We have leftover initializers
1025  if (VerifyOnly) {
1026  if (SemaRef.getLangOpts().CPlusPlus ||
1027  (SemaRef.getLangOpts().OpenCL &&
1028  IList->getType()->isVectorType())) {
1029  hadError = true;
1030  }
1031  return;
1032  }
1033 
1034  if (StructuredIndex == 1 &&
1035  IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1036  SIF_None) {
1037  unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1038  if (SemaRef.getLangOpts().CPlusPlus) {
1039  DK = diag::err_excess_initializers_in_char_array_initializer;
1040  hadError = true;
1041  }
1042  // Special-case
1043  SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1044  << IList->getInit(Index)->getSourceRange();
1045  } else if (!T->isIncompleteType()) {
1046  // Don't complain for incomplete types, since we'll get an error
1047  // elsewhere
1048  QualType CurrentObjectType = StructuredList->getType();
1049  int initKind =
1050  CurrentObjectType->isArrayType()? 0 :
1051  CurrentObjectType->isVectorType()? 1 :
1052  CurrentObjectType->isScalarType()? 2 :
1053  CurrentObjectType->isUnionType()? 3 :
1054  4;
1055 
1056  unsigned DK = diag::ext_excess_initializers;
1057  if (SemaRef.getLangOpts().CPlusPlus) {
1058  DK = diag::err_excess_initializers;
1059  hadError = true;
1060  }
1061  if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1062  DK = diag::err_excess_initializers;
1063  hadError = true;
1064  }
1065 
1066  SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1067  << initKind << IList->getInit(Index)->getSourceRange();
1068  }
1069  }
1070 
1071  if (!VerifyOnly && T->isScalarType() &&
1072  IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1073  warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1074 }
1075 
1076 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1077  InitListExpr *IList,
1078  QualType &DeclType,
1079  bool SubobjectIsDesignatorContext,
1080  unsigned &Index,
1081  InitListExpr *StructuredList,
1082  unsigned &StructuredIndex,
1083  bool TopLevelObject) {
1084  if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1085  // Explicitly braced initializer for complex type can be real+imaginary
1086  // parts.
1087  CheckComplexType(Entity, IList, DeclType, Index,
1088  StructuredList, StructuredIndex);
1089  } else if (DeclType->isScalarType()) {
1090  CheckScalarType(Entity, IList, DeclType, Index,
1091  StructuredList, StructuredIndex);
1092  } else if (DeclType->isVectorType()) {
1093  CheckVectorType(Entity, IList, DeclType, Index,
1094  StructuredList, StructuredIndex);
1095  } else if (DeclType->isRecordType()) {
1096  assert(DeclType->isAggregateType() &&
1097  "non-aggregate records should be handed in CheckSubElementType");
1098  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1099  auto Bases =
1102  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1103  Bases = CXXRD->bases();
1104  CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1105  SubobjectIsDesignatorContext, Index, StructuredList,
1106  StructuredIndex, TopLevelObject);
1107  } else if (DeclType->isArrayType()) {
1108  llvm::APSInt Zero(
1109  SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1110  false);
1111  CheckArrayType(Entity, IList, DeclType, Zero,
1112  SubobjectIsDesignatorContext, Index,
1113  StructuredList, StructuredIndex);
1114  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1115  // This type is invalid, issue a diagnostic.
1116  ++Index;
1117  if (!VerifyOnly)
1118  SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1119  << DeclType;
1120  hadError = true;
1121  } else if (DeclType->isReferenceType()) {
1122  CheckReferenceType(Entity, IList, DeclType, Index,
1123  StructuredList, StructuredIndex);
1124  } else if (DeclType->isObjCObjectType()) {
1125  if (!VerifyOnly)
1126  SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1127  << DeclType;
1128  hadError = true;
1129  } else {
1130  if (!VerifyOnly)
1131  SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1132  << DeclType;
1133  hadError = true;
1134  }
1135 }
1136 
1137 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1138  InitListExpr *IList,
1139  QualType ElemType,
1140  unsigned &Index,
1141  InitListExpr *StructuredList,
1142  unsigned &StructuredIndex) {
1143  Expr *expr = IList->getInit(Index);
1144 
1145  if (ElemType->isReferenceType())
1146  return CheckReferenceType(Entity, IList, ElemType, Index,
1147  StructuredList, StructuredIndex);
1148 
1149  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1150  if (SubInitList->getNumInits() == 1 &&
1151  IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1152  SIF_None) {
1153  expr = SubInitList->getInit(0);
1154  } else if (!SemaRef.getLangOpts().CPlusPlus) {
1155  InitListExpr *InnerStructuredList
1156  = getStructuredSubobjectInit(IList, Index, ElemType,
1157  StructuredList, StructuredIndex,
1158  SubInitList->getSourceRange(), true);
1159  CheckExplicitInitList(Entity, SubInitList, ElemType,
1160  InnerStructuredList);
1161 
1162  if (!hadError && !VerifyOnly) {
1163  bool RequiresSecondPass = false;
1164  FillInEmptyInitializations(Entity, InnerStructuredList,
1165  RequiresSecondPass);
1166  if (RequiresSecondPass && !hadError)
1167  FillInEmptyInitializations(Entity, InnerStructuredList,
1168  RequiresSecondPass);
1169  }
1170  ++StructuredIndex;
1171  ++Index;
1172  return;
1173  }
1174  // C++ initialization is handled later.
1175  } else if (isa<ImplicitValueInitExpr>(expr)) {
1176  // This happens during template instantiation when we see an InitListExpr
1177  // that we've already checked once.
1178  assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1179  "found implicit initialization for the wrong type");
1180  if (!VerifyOnly)
1181  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1182  ++Index;
1183  return;
1184  }
1185 
1186  if (SemaRef.getLangOpts().CPlusPlus) {
1187  // C++ [dcl.init.aggr]p2:
1188  // Each member is copy-initialized from the corresponding
1189  // initializer-clause.
1190 
1191  // FIXME: Better EqualLoc?
1194  InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1195  /*TopLevelOfInitList*/ true);
1196 
1197  // C++14 [dcl.init.aggr]p13:
1198  // If the assignment-expression can initialize a member, the member is
1199  // initialized. Otherwise [...] brace elision is assumed
1200  //
1201  // Brace elision is never performed if the element is not an
1202  // assignment-expression.
1203  if (Seq || isa<InitListExpr>(expr)) {
1204  if (!VerifyOnly) {
1205  ExprResult Result =
1206  Seq.Perform(SemaRef, Entity, Kind, expr);
1207  if (Result.isInvalid())
1208  hadError = true;
1209 
1210  UpdateStructuredListElement(StructuredList, StructuredIndex,
1211  Result.getAs<Expr>());
1212  } else if (!Seq)
1213  hadError = true;
1214  ++Index;
1215  return;
1216  }
1217 
1218  // Fall through for subaggregate initialization
1219  } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1220  // FIXME: Need to handle atomic aggregate types with implicit init lists.
1221  return CheckScalarType(Entity, IList, ElemType, Index,
1222  StructuredList, StructuredIndex);
1223  } else if (const ArrayType *arrayType =
1224  SemaRef.Context.getAsArrayType(ElemType)) {
1225  // arrayType can be incomplete if we're initializing a flexible
1226  // array member. There's nothing we can do with the completed
1227  // type here, though.
1228 
1229  if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1230  if (!VerifyOnly) {
1231  CheckStringInit(expr, ElemType, arrayType, SemaRef);
1232  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1233  }
1234  ++Index;
1235  return;
1236  }
1237 
1238  // Fall through for subaggregate initialization.
1239 
1240  } else {
1241  assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1242  ElemType->isOpenCLSpecificType()) && "Unexpected type");
1243 
1244  // C99 6.7.8p13:
1245  //
1246  // The initializer for a structure or union object that has
1247  // automatic storage duration shall be either an initializer
1248  // list as described below, or a single expression that has
1249  // compatible structure or union type. In the latter case, the
1250  // initial value of the object, including unnamed members, is
1251  // that of the expression.
1252  ExprResult ExprRes = expr;
1254  ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1255  if (ExprRes.isInvalid())
1256  hadError = true;
1257  else {
1258  ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1259  if (ExprRes.isInvalid())
1260  hadError = true;
1261  }
1262  UpdateStructuredListElement(StructuredList, StructuredIndex,
1263  ExprRes.getAs<Expr>());
1264  ++Index;
1265  return;
1266  }
1267  ExprRes.get();
1268  // Fall through for subaggregate initialization
1269  }
1270 
1271  // C++ [dcl.init.aggr]p12:
1272  //
1273  // [...] Otherwise, if the member is itself a non-empty
1274  // subaggregate, brace elision is assumed and the initializer is
1275  // considered for the initialization of the first member of
1276  // the subaggregate.
1277  // OpenCL vector initializer is handled elsewhere.
1278  if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1279  ElemType->isAggregateType()) {
1280  CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1281  StructuredIndex);
1282  ++StructuredIndex;
1283  } else {
1284  if (!VerifyOnly) {
1285  // We cannot initialize this element, so let
1286  // PerformCopyInitialization produce the appropriate diagnostic.
1287  SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1288  /*TopLevelOfInitList=*/true);
1289  }
1290  hadError = true;
1291  ++Index;
1292  ++StructuredIndex;
1293  }
1294 }
1295 
1296 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1297  InitListExpr *IList, QualType DeclType,
1298  unsigned &Index,
1299  InitListExpr *StructuredList,
1300  unsigned &StructuredIndex) {
1301  assert(Index == 0 && "Index in explicit init list must be zero");
1302 
1303  // As an extension, clang supports complex initializers, which initialize
1304  // a complex number component-wise. When an explicit initializer list for
1305  // a complex number contains two two initializers, this extension kicks in:
1306  // it exepcts the initializer list to contain two elements convertible to
1307  // the element type of the complex type. The first element initializes
1308  // the real part, and the second element intitializes the imaginary part.
1309 
1310  if (IList->getNumInits() != 2)
1311  return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1312  StructuredIndex);
1313 
1314  // This is an extension in C. (The builtin _Complex type does not exist
1315  // in the C++ standard.)
1316  if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1317  SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1318  << IList->getSourceRange();
1319 
1320  // Initialize the complex number.
1321  QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1322  InitializedEntity ElementEntity =
1323  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1324 
1325  for (unsigned i = 0; i < 2; ++i) {
1326  ElementEntity.setElementIndex(Index);
1327  CheckSubElementType(ElementEntity, IList, elementType, Index,
1328  StructuredList, StructuredIndex);
1329  }
1330 }
1331 
1332 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1333  InitListExpr *IList, QualType DeclType,
1334  unsigned &Index,
1335  InitListExpr *StructuredList,
1336  unsigned &StructuredIndex) {
1337  if (Index >= IList->getNumInits()) {
1338  if (!VerifyOnly)
1339  SemaRef.Diag(IList->getLocStart(),
1340  SemaRef.getLangOpts().CPlusPlus11 ?
1341  diag::warn_cxx98_compat_empty_scalar_initializer :
1342  diag::err_empty_scalar_initializer)
1343  << IList->getSourceRange();
1344  hadError = !SemaRef.getLangOpts().CPlusPlus11;
1345  ++Index;
1346  ++StructuredIndex;
1347  return;
1348  }
1349 
1350  Expr *expr = IList->getInit(Index);
1351  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1352  // FIXME: This is invalid, and accepting it causes overload resolution
1353  // to pick the wrong overload in some corner cases.
1354  if (!VerifyOnly)
1355  SemaRef.Diag(SubIList->getLocStart(),
1356  diag::ext_many_braces_around_scalar_init)
1357  << SubIList->getSourceRange();
1358 
1359  CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1360  StructuredIndex);
1361  return;
1362  } else if (isa<DesignatedInitExpr>(expr)) {
1363  if (!VerifyOnly)
1364  SemaRef.Diag(expr->getLocStart(),
1365  diag::err_designator_for_scalar_init)
1366  << DeclType << expr->getSourceRange();
1367  hadError = true;
1368  ++Index;
1369  ++StructuredIndex;
1370  return;
1371  }
1372 
1373  if (VerifyOnly) {
1374  if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1375  hadError = true;
1376  ++Index;
1377  return;
1378  }
1379 
1380  ExprResult Result =
1381  SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1382  /*TopLevelOfInitList=*/true);
1383 
1384  Expr *ResultExpr = nullptr;
1385 
1386  if (Result.isInvalid())
1387  hadError = true; // types weren't compatible.
1388  else {
1389  ResultExpr = Result.getAs<Expr>();
1390 
1391  if (ResultExpr != expr) {
1392  // The type was promoted, update initializer list.
1393  IList->setInit(Index, ResultExpr);
1394  }
1395  }
1396  if (hadError)
1397  ++StructuredIndex;
1398  else
1399  UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1400  ++Index;
1401 }
1402 
1403 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1404  InitListExpr *IList, QualType DeclType,
1405  unsigned &Index,
1406  InitListExpr *StructuredList,
1407  unsigned &StructuredIndex) {
1408  if (Index >= IList->getNumInits()) {
1409  // FIXME: It would be wonderful if we could point at the actual member. In
1410  // general, it would be useful to pass location information down the stack,
1411  // so that we know the location (or decl) of the "current object" being
1412  // initialized.
1413  if (!VerifyOnly)
1414  SemaRef.Diag(IList->getLocStart(),
1415  diag::err_init_reference_member_uninitialized)
1416  << DeclType
1417  << IList->getSourceRange();
1418  hadError = true;
1419  ++Index;
1420  ++StructuredIndex;
1421  return;
1422  }
1423 
1424  Expr *expr = IList->getInit(Index);
1425  if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1426  if (!VerifyOnly)
1427  SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1428  << DeclType << IList->getSourceRange();
1429  hadError = true;
1430  ++Index;
1431  ++StructuredIndex;
1432  return;
1433  }
1434 
1435  if (VerifyOnly) {
1436  if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1437  hadError = true;
1438  ++Index;
1439  return;
1440  }
1441 
1442  ExprResult Result =
1443  SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1444  /*TopLevelOfInitList=*/true);
1445 
1446  if (Result.isInvalid())
1447  hadError = true;
1448 
1449  expr = Result.getAs<Expr>();
1450  IList->setInit(Index, expr);
1451 
1452  if (hadError)
1453  ++StructuredIndex;
1454  else
1455  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1456  ++Index;
1457 }
1458 
1459 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1460  InitListExpr *IList, QualType DeclType,
1461  unsigned &Index,
1462  InitListExpr *StructuredList,
1463  unsigned &StructuredIndex) {
1464  const VectorType *VT = DeclType->getAs<VectorType>();
1465  unsigned maxElements = VT->getNumElements();
1466  unsigned numEltsInit = 0;
1467  QualType elementType = VT->getElementType();
1468 
1469  if (Index >= IList->getNumInits()) {
1470  // Make sure the element type can be value-initialized.
1471  if (VerifyOnly)
1472  CheckEmptyInitializable(
1473  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1474  IList->getLocEnd());
1475  return;
1476  }
1477 
1478  if (!SemaRef.getLangOpts().OpenCL) {
1479  // If the initializing element is a vector, try to copy-initialize
1480  // instead of breaking it apart (which is doomed to failure anyway).
1481  Expr *Init = IList->getInit(Index);
1482  if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1483  if (VerifyOnly) {
1484  if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1485  hadError = true;
1486  ++Index;
1487  return;
1488  }
1489 
1490  ExprResult Result =
1491  SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1492  /*TopLevelOfInitList=*/true);
1493 
1494  Expr *ResultExpr = nullptr;
1495  if (Result.isInvalid())
1496  hadError = true; // types weren't compatible.
1497  else {
1498  ResultExpr = Result.getAs<Expr>();
1499 
1500  if (ResultExpr != Init) {
1501  // The type was promoted, update initializer list.
1502  IList->setInit(Index, ResultExpr);
1503  }
1504  }
1505  if (hadError)
1506  ++StructuredIndex;
1507  else
1508  UpdateStructuredListElement(StructuredList, StructuredIndex,
1509  ResultExpr);
1510  ++Index;
1511  return;
1512  }
1513 
1514  InitializedEntity ElementEntity =
1515  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1516 
1517  for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1518  // Don't attempt to go past the end of the init list
1519  if (Index >= IList->getNumInits()) {
1520  if (VerifyOnly)
1521  CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
1522  break;
1523  }
1524 
1525  ElementEntity.setElementIndex(Index);
1526  CheckSubElementType(ElementEntity, IList, elementType, Index,
1527  StructuredList, StructuredIndex);
1528  }
1529 
1530  if (VerifyOnly)
1531  return;
1532 
1533  bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1534  const VectorType *T = Entity.getType()->getAs<VectorType>();
1535  if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1537  // The ability to use vector initializer lists is a GNU vector extension
1538  // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1539  // endian machines it works fine, however on big endian machines it
1540  // exhibits surprising behaviour:
1541  //
1542  // uint32x2_t x = {42, 64};
1543  // return vget_lane_u32(x, 0); // Will return 64.
1544  //
1545  // Because of this, explicitly call out that it is non-portable.
1546  //
1547  SemaRef.Diag(IList->getLocStart(),
1548  diag::warn_neon_vector_initializer_non_portable);
1549 
1550  const char *typeCode;
1551  unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1552 
1553  if (elementType->isFloatingType())
1554  typeCode = "f";
1555  else if (elementType->isSignedIntegerType())
1556  typeCode = "s";
1557  else if (elementType->isUnsignedIntegerType())
1558  typeCode = "u";
1559  else
1560  llvm_unreachable("Invalid element type!");
1561 
1562  SemaRef.Diag(IList->getLocStart(),
1563  SemaRef.Context.getTypeSize(VT) > 64 ?
1564  diag::note_neon_vector_initializer_non_portable_q :
1565  diag::note_neon_vector_initializer_non_portable)
1566  << typeCode << typeSize;
1567  }
1568 
1569  return;
1570  }
1571 
1572  InitializedEntity ElementEntity =
1573  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1574 
1575  // OpenCL initializers allows vectors to be constructed from vectors.
1576  for (unsigned i = 0; i < maxElements; ++i) {
1577  // Don't attempt to go past the end of the init list
1578  if (Index >= IList->getNumInits())
1579  break;
1580 
1581  ElementEntity.setElementIndex(Index);
1582 
1583  QualType IType = IList->getInit(Index)->getType();
1584  if (!IType->isVectorType()) {
1585  CheckSubElementType(ElementEntity, IList, elementType, Index,
1586  StructuredList, StructuredIndex);
1587  ++numEltsInit;
1588  } else {
1589  QualType VecType;
1590  const VectorType *IVT = IType->getAs<VectorType>();
1591  unsigned numIElts = IVT->getNumElements();
1592 
1593  if (IType->isExtVectorType())
1594  VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1595  else
1596  VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1597  IVT->getVectorKind());
1598  CheckSubElementType(ElementEntity, IList, VecType, Index,
1599  StructuredList, StructuredIndex);
1600  numEltsInit += numIElts;
1601  }
1602  }
1603 
1604  // OpenCL requires all elements to be initialized.
1605  if (numEltsInit != maxElements) {
1606  if (!VerifyOnly)
1607  SemaRef.Diag(IList->getLocStart(),
1608  diag::err_vector_incorrect_num_initializers)
1609  << (numEltsInit < maxElements) << maxElements << numEltsInit;
1610  hadError = true;
1611  }
1612 }
1613 
1614 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1615  InitListExpr *IList, QualType &DeclType,
1616  llvm::APSInt elementIndex,
1617  bool SubobjectIsDesignatorContext,
1618  unsigned &Index,
1619  InitListExpr *StructuredList,
1620  unsigned &StructuredIndex) {
1621  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1622 
1623  // Check for the special-case of initializing an array with a string.
1624  if (Index < IList->getNumInits()) {
1625  if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1626  SIF_None) {
1627  // We place the string literal directly into the resulting
1628  // initializer list. This is the only place where the structure
1629  // of the structured initializer list doesn't match exactly,
1630  // because doing so would involve allocating one character
1631  // constant for each string.
1632  if (!VerifyOnly) {
1633  CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1634  UpdateStructuredListElement(StructuredList, StructuredIndex,
1635  IList->getInit(Index));
1636  StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1637  }
1638  ++Index;
1639  return;
1640  }
1641  }
1642  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1643  // Check for VLAs; in standard C it would be possible to check this
1644  // earlier, but I don't know where clang accepts VLAs (gcc accepts
1645  // them in all sorts of strange places).
1646  if (!VerifyOnly)
1647  SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1648  diag::err_variable_object_no_init)
1649  << VAT->getSizeExpr()->getSourceRange();
1650  hadError = true;
1651  ++Index;
1652  ++StructuredIndex;
1653  return;
1654  }
1655 
1656  // We might know the maximum number of elements in advance.
1657  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1658  elementIndex.isUnsigned());
1659  bool maxElementsKnown = false;
1660  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1661  maxElements = CAT->getSize();
1662  elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1663  elementIndex.setIsUnsigned(maxElements.isUnsigned());
1664  maxElementsKnown = true;
1665  }
1666 
1667  QualType elementType = arrayType->getElementType();
1668  while (Index < IList->getNumInits()) {
1669  Expr *Init = IList->getInit(Index);
1670  if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1671  // If we're not the subobject that matches up with the '{' for
1672  // the designator, we shouldn't be handling the
1673  // designator. Return immediately.
1674  if (!SubobjectIsDesignatorContext)
1675  return;
1676 
1677  // Handle this designated initializer. elementIndex will be
1678  // updated to be the next array element we'll initialize.
1679  if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1680  DeclType, nullptr, &elementIndex, Index,
1681  StructuredList, StructuredIndex, true,
1682  false)) {
1683  hadError = true;
1684  continue;
1685  }
1686 
1687  if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1688  maxElements = maxElements.extend(elementIndex.getBitWidth());
1689  else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1690  elementIndex = elementIndex.extend(maxElements.getBitWidth());
1691  elementIndex.setIsUnsigned(maxElements.isUnsigned());
1692 
1693  // If the array is of incomplete type, keep track of the number of
1694  // elements in the initializer.
1695  if (!maxElementsKnown && elementIndex > maxElements)
1696  maxElements = elementIndex;
1697 
1698  continue;
1699  }
1700 
1701  // If we know the maximum number of elements, and we've already
1702  // hit it, stop consuming elements in the initializer list.
1703  if (maxElementsKnown && elementIndex == maxElements)
1704  break;
1705 
1706  InitializedEntity ElementEntity =
1707  InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1708  Entity);
1709  // Check this element.
1710  CheckSubElementType(ElementEntity, IList, elementType, Index,
1711  StructuredList, StructuredIndex);
1712  ++elementIndex;
1713 
1714  // If the array is of incomplete type, keep track of the number of
1715  // elements in the initializer.
1716  if (!maxElementsKnown && elementIndex > maxElements)
1717  maxElements = elementIndex;
1718  }
1719  if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1720  // If this is an incomplete array type, the actual type needs to
1721  // be calculated here.
1722  llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1723  if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1724  // Sizing an array implicitly to zero is not allowed by ISO C,
1725  // but is supported by GNU.
1726  SemaRef.Diag(IList->getLocStart(),
1727  diag::ext_typecheck_zero_array_size);
1728  }
1729 
1730  DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1731  ArrayType::Normal, 0);
1732  }
1733  if (!hadError && VerifyOnly) {
1734  // If there are any members of the array that get value-initialized, check
1735  // that is possible. That happens if we know the bound and don't have
1736  // enough elements, or if we're performing an array new with an unknown
1737  // bound.
1738  // FIXME: This needs to detect holes left by designated initializers too.
1739  if ((maxElementsKnown && elementIndex < maxElements) ||
1740  Entity.isVariableLengthArrayNew())
1741  CheckEmptyInitializable(InitializedEntity::InitializeElement(
1742  SemaRef.Context, 0, Entity),
1743  IList->getLocEnd());
1744  }
1745 }
1746 
1747 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1748  Expr *InitExpr,
1749  FieldDecl *Field,
1750  bool TopLevelObject) {
1751  // Handle GNU flexible array initializers.
1752  unsigned FlexArrayDiag;
1753  if (isa<InitListExpr>(InitExpr) &&
1754  cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1755  // Empty flexible array init always allowed as an extension
1756  FlexArrayDiag = diag::ext_flexible_array_init;
1757  } else if (SemaRef.getLangOpts().CPlusPlus) {
1758  // Disallow flexible array init in C++; it is not required for gcc
1759  // compatibility, and it needs work to IRGen correctly in general.
1760  FlexArrayDiag = diag::err_flexible_array_init;
1761  } else if (!TopLevelObject) {
1762  // Disallow flexible array init on non-top-level object
1763  FlexArrayDiag = diag::err_flexible_array_init;
1764  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1765  // Disallow flexible array init on anything which is not a variable.
1766  FlexArrayDiag = diag::err_flexible_array_init;
1767  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1768  // Disallow flexible array init on local variables.
1769  FlexArrayDiag = diag::err_flexible_array_init;
1770  } else {
1771  // Allow other cases.
1772  FlexArrayDiag = diag::ext_flexible_array_init;
1773  }
1774 
1775  if (!VerifyOnly) {
1776  SemaRef.Diag(InitExpr->getLocStart(),
1777  FlexArrayDiag)
1778  << InitExpr->getLocStart();
1779  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1780  << Field;
1781  }
1782 
1783  return FlexArrayDiag != diag::ext_flexible_array_init;
1784 }
1785 
1786 void InitListChecker::CheckStructUnionTypes(
1787  const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1789  bool SubobjectIsDesignatorContext, unsigned &Index,
1790  InitListExpr *StructuredList, unsigned &StructuredIndex,
1791  bool TopLevelObject) {
1792  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1793 
1794  // If the record is invalid, some of it's members are invalid. To avoid
1795  // confusion, we forgo checking the intializer for the entire record.
1796  if (structDecl->isInvalidDecl()) {
1797  // Assume it was supposed to consume a single initializer.
1798  ++Index;
1799  hadError = true;
1800  return;
1801  }
1802 
1803  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1804  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1805 
1806  // If there's a default initializer, use it.
1807  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1808  if (VerifyOnly)
1809  return;
1810  for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1811  Field != FieldEnd; ++Field) {
1812  if (Field->hasInClassInitializer()) {
1813  StructuredList->setInitializedFieldInUnion(*Field);
1814  // FIXME: Actually build a CXXDefaultInitExpr?
1815  return;
1816  }
1817  }
1818  }
1819 
1820  // Value-initialize the first member of the union that isn't an unnamed
1821  // bitfield.
1822  for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1823  Field != FieldEnd; ++Field) {
1824  if (!Field->isUnnamedBitfield()) {
1825  if (VerifyOnly)
1826  CheckEmptyInitializable(
1827  InitializedEntity::InitializeMember(*Field, &Entity),
1828  IList->getLocEnd());
1829  else
1830  StructuredList->setInitializedFieldInUnion(*Field);
1831  break;
1832  }
1833  }
1834  return;
1835  }
1836 
1837  bool InitializedSomething = false;
1838 
1839  // If we have any base classes, they are initialized prior to the fields.
1840  for (auto &Base : Bases) {
1841  Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1842  SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1843 
1844  // Designated inits always initialize fields, so if we see one, all
1845  // remaining base classes have no explicit initializer.
1846  if (Init && isa<DesignatedInitExpr>(Init))
1847  Init = nullptr;
1848 
1850  SemaRef.Context, &Base, false, &Entity);
1851  if (Init) {
1852  CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1853  StructuredList, StructuredIndex);
1854  InitializedSomething = true;
1855  } else if (VerifyOnly) {
1856  CheckEmptyInitializable(BaseEntity, InitLoc);
1857  }
1858  }
1859 
1860  // If structDecl is a forward declaration, this loop won't do
1861  // anything except look at designated initializers; That's okay,
1862  // because an error should get printed out elsewhere. It might be
1863  // worthwhile to skip over the rest of the initializer, though.
1864  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1865  RecordDecl::field_iterator FieldEnd = RD->field_end();
1866  bool CheckForMissingFields =
1867  !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1868 
1869  while (Index < IList->getNumInits()) {
1870  Expr *Init = IList->getInit(Index);
1871 
1872  if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1873  // If we're not the subobject that matches up with the '{' for
1874  // the designator, we shouldn't be handling the
1875  // designator. Return immediately.
1876  if (!SubobjectIsDesignatorContext)
1877  return;
1878 
1879  // Handle this designated initializer. Field will be updated to
1880  // the next field that we'll be initializing.
1881  if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1882  DeclType, &Field, nullptr, Index,
1883  StructuredList, StructuredIndex,
1884  true, TopLevelObject))
1885  hadError = true;
1886 
1887  InitializedSomething = true;
1888 
1889  // Disable check for missing fields when designators are used.
1890  // This matches gcc behaviour.
1891  CheckForMissingFields = false;
1892  continue;
1893  }
1894 
1895  if (Field == FieldEnd) {
1896  // We've run out of fields. We're done.
1897  break;
1898  }
1899 
1900  // We've already initialized a member of a union. We're done.
1901  if (InitializedSomething && DeclType->isUnionType())
1902  break;
1903 
1904  // If we've hit the flexible array member at the end, we're done.
1905  if (Field->getType()->isIncompleteArrayType())
1906  break;
1907 
1908  if (Field->isUnnamedBitfield()) {
1909  // Don't initialize unnamed bitfields, e.g. "int : 20;"
1910  ++Field;
1911  continue;
1912  }
1913 
1914  // Make sure we can use this declaration.
1915  bool InvalidUse;
1916  if (VerifyOnly)
1917  InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
1918  else
1919  InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1920  IList->getInit(Index)->getLocStart());
1921  if (InvalidUse) {
1922  ++Index;
1923  ++Field;
1924  hadError = true;
1925  continue;
1926  }
1927 
1928  InitializedEntity MemberEntity =
1929  InitializedEntity::InitializeMember(*Field, &Entity);
1930  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1931  StructuredList, StructuredIndex);
1932  InitializedSomething = true;
1933 
1934  if (DeclType->isUnionType() && !VerifyOnly) {
1935  // Initialize the first field within the union.
1936  StructuredList->setInitializedFieldInUnion(*Field);
1937  }
1938 
1939  ++Field;
1940  }
1941 
1942  // Emit warnings for missing struct field initializers.
1943  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1944  Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1945  !DeclType->isUnionType()) {
1946  // It is possible we have one or more unnamed bitfields remaining.
1947  // Find first (if any) named field and emit warning.
1948  for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1949  it != end; ++it) {
1950  if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1951  SemaRef.Diag(IList->getSourceRange().getEnd(),
1952  diag::warn_missing_field_initializers) << *it;
1953  break;
1954  }
1955  }
1956  }
1957 
1958  // Check that any remaining fields can be value-initialized.
1959  if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1960  !Field->getType()->isIncompleteArrayType()) {
1961  // FIXME: Should check for holes left by designated initializers too.
1962  for (; Field != FieldEnd && !hadError; ++Field) {
1963  if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1964  CheckEmptyInitializable(
1965  InitializedEntity::InitializeMember(*Field, &Entity),
1966  IList->getLocEnd());
1967  }
1968  }
1969 
1970  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1971  Index >= IList->getNumInits())
1972  return;
1973 
1974  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1975  TopLevelObject)) {
1976  hadError = true;
1977  ++Index;
1978  return;
1979  }
1980 
1981  InitializedEntity MemberEntity =
1982  InitializedEntity::InitializeMember(*Field, &Entity);
1983 
1984  if (isa<InitListExpr>(IList->getInit(Index)))
1985  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1986  StructuredList, StructuredIndex);
1987  else
1988  CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1989  StructuredList, StructuredIndex);
1990 }
1991 
1992 /// \brief Expand a field designator that refers to a member of an
1993 /// anonymous struct or union into a series of field designators that
1994 /// refers to the field within the appropriate subobject.
1995 ///
1997  DesignatedInitExpr *DIE,
1998  unsigned DesigIdx,
1999  IndirectFieldDecl *IndirectField) {
2001 
2002  // Build the replacement designators.
2003  SmallVector<Designator, 4> Replacements;
2004  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2005  PE = IndirectField->chain_end(); PI != PE; ++PI) {
2006  if (PI + 1 == PE)
2007  Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2008  DIE->getDesignator(DesigIdx)->getDotLoc(),
2009  DIE->getDesignator(DesigIdx)->getFieldLoc()));
2010  else
2011  Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2013  assert(isa<FieldDecl>(*PI));
2014  Replacements.back().setField(cast<FieldDecl>(*PI));
2015  }
2016 
2017  // Expand the current designator into the set of replacement
2018  // designators, so we have a full subobject path down to where the
2019  // member of the anonymous struct/union is actually stored.
2020  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2021  &Replacements[0] + Replacements.size());
2022 }
2023 
2025  DesignatedInitExpr *DIE) {
2026  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2027  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2028  for (unsigned I = 0; I < NumIndexExprs; ++I)
2029  IndexExprs[I] = DIE->getSubExpr(I + 1);
2030  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2031  IndexExprs,
2032  DIE->getEqualOrColonLoc(),
2033  DIE->usesGNUSyntax(), DIE->getInit());
2034 }
2035 
2036 namespace {
2037 
2038 // Callback to only accept typo corrections that are for field members of
2039 // the given struct or union.
2040 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2041  public:
2042  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2043  : Record(RD) {}
2044 
2045  bool ValidateCandidate(const TypoCorrection &candidate) override {
2046  FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2047  return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2048  }
2049 
2050  private:
2051  RecordDecl *Record;
2052 };
2053 
2054 } // end anonymous namespace
2055 
2056 /// @brief Check the well-formedness of a C99 designated initializer.
2057 ///
2058 /// Determines whether the designated initializer @p DIE, which
2059 /// resides at the given @p Index within the initializer list @p
2060 /// IList, is well-formed for a current object of type @p DeclType
2061 /// (C99 6.7.8). The actual subobject that this designator refers to
2062 /// within the current subobject is returned in either
2063 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2064 ///
2065 /// @param IList The initializer list in which this designated
2066 /// initializer occurs.
2067 ///
2068 /// @param DIE The designated initializer expression.
2069 ///
2070 /// @param DesigIdx The index of the current designator.
2071 ///
2072 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2073 /// into which the designation in @p DIE should refer.
2074 ///
2075 /// @param NextField If non-NULL and the first designator in @p DIE is
2076 /// a field, this will be set to the field declaration corresponding
2077 /// to the field named by the designator.
2078 ///
2079 /// @param NextElementIndex If non-NULL and the first designator in @p
2080 /// DIE is an array designator or GNU array-range designator, this
2081 /// will be set to the last index initialized by this designator.
2082 ///
2083 /// @param Index Index into @p IList where the designated initializer
2084 /// @p DIE occurs.
2085 ///
2086 /// @param StructuredList The initializer list expression that
2087 /// describes all of the subobject initializers in the order they'll
2088 /// actually be initialized.
2089 ///
2090 /// @returns true if there was an error, false otherwise.
2091 bool
2092 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2093  InitListExpr *IList,
2094  DesignatedInitExpr *DIE,
2095  unsigned DesigIdx,
2096  QualType &CurrentObjectType,
2097  RecordDecl::field_iterator *NextField,
2098  llvm::APSInt *NextElementIndex,
2099  unsigned &Index,
2100  InitListExpr *StructuredList,
2101  unsigned &StructuredIndex,
2102  bool FinishSubobjectInit,
2103  bool TopLevelObject) {
2104  if (DesigIdx == DIE->size()) {
2105  // Check the actual initialization for the designated object type.
2106  bool prevHadError = hadError;
2107 
2108  // Temporarily remove the designator expression from the
2109  // initializer list that the child calls see, so that we don't try
2110  // to re-process the designator.
2111  unsigned OldIndex = Index;
2112  IList->setInit(OldIndex, DIE->getInit());
2113 
2114  CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2115  StructuredList, StructuredIndex);
2116 
2117  // Restore the designated initializer expression in the syntactic
2118  // form of the initializer list.
2119  if (IList->getInit(OldIndex) != DIE->getInit())
2120  DIE->setInit(IList->getInit(OldIndex));
2121  IList->setInit(OldIndex, DIE);
2122 
2123  return hadError && !prevHadError;
2124  }
2125 
2126  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2127  bool IsFirstDesignator = (DesigIdx == 0);
2128  if (!VerifyOnly) {
2129  assert((IsFirstDesignator || StructuredList) &&
2130  "Need a non-designated initializer list to start from");
2131 
2132  // Determine the structural initializer list that corresponds to the
2133  // current subobject.
2134  if (IsFirstDesignator)
2135  StructuredList = SyntacticToSemantic.lookup(IList);
2136  else {
2137  Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2138  StructuredList->getInit(StructuredIndex) : nullptr;
2139  if (!ExistingInit && StructuredList->hasArrayFiller())
2140  ExistingInit = StructuredList->getArrayFiller();
2141 
2142  if (!ExistingInit)
2143  StructuredList =
2144  getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2145  StructuredList, StructuredIndex,
2146  SourceRange(D->getLocStart(),
2147  DIE->getLocEnd()));
2148  else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2149  StructuredList = Result;
2150  else {
2151  if (DesignatedInitUpdateExpr *E =
2152  dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2153  StructuredList = E->getUpdater();
2154  else {
2155  DesignatedInitUpdateExpr *DIUE =
2156  new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2157  D->getLocStart(), ExistingInit,
2158  DIE->getLocEnd());
2159  StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2160  StructuredList = DIUE->getUpdater();
2161  }
2162 
2163  // We need to check on source range validity because the previous
2164  // initializer does not have to be an explicit initializer. e.g.,
2165  //
2166  // struct P { int a, b; };
2167  // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2168  //
2169  // There is an overwrite taking place because the first braced initializer
2170  // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2171  if (ExistingInit->getSourceRange().isValid()) {
2172  // We are creating an initializer list that initializes the
2173  // subobjects of the current object, but there was already an
2174  // initialization that completely initialized the current
2175  // subobject, e.g., by a compound literal:
2176  //
2177  // struct X { int a, b; };
2178  // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2179  //
2180  // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2181  // designated initializer re-initializes the whole
2182  // subobject [0], overwriting previous initializers.
2183  SemaRef.Diag(D->getLocStart(),
2184  diag::warn_subobject_initializer_overrides)
2185  << SourceRange(D->getLocStart(), DIE->getLocEnd());
2186 
2187  SemaRef.Diag(ExistingInit->getLocStart(),
2188  diag::note_previous_initializer)
2189  << /*FIXME:has side effects=*/0
2190  << ExistingInit->getSourceRange();
2191  }
2192  }
2193  }
2194  assert(StructuredList && "Expected a structured initializer list");
2195  }
2196 
2197  if (D->isFieldDesignator()) {
2198  // C99 6.7.8p7:
2199  //
2200  // If a designator has the form
2201  //
2202  // . identifier
2203  //
2204  // then the current object (defined below) shall have
2205  // structure or union type and the identifier shall be the
2206  // name of a member of that type.
2207  const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2208  if (!RT) {
2209  SourceLocation Loc = D->getDotLoc();
2210  if (Loc.isInvalid())
2211  Loc = D->getFieldLoc();
2212  if (!VerifyOnly)
2213  SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2214  << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2215  ++Index;
2216  return true;
2217  }
2218 
2219  FieldDecl *KnownField = D->getField();
2220  if (!KnownField) {
2221  IdentifierInfo *FieldName = D->getFieldName();
2222  DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2223  for (NamedDecl *ND : Lookup) {
2224  if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2225  KnownField = FD;
2226  break;
2227  }
2228  if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2229  // In verify mode, don't modify the original.
2230  if (VerifyOnly)
2231  DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2232  ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2233  D = DIE->getDesignator(DesigIdx);
2234  KnownField = cast<FieldDecl>(*IFD->chain_begin());
2235  break;
2236  }
2237  }
2238  if (!KnownField) {
2239  if (VerifyOnly) {
2240  ++Index;
2241  return true; // No typo correction when just trying this out.
2242  }
2243 
2244  // Name lookup found something, but it wasn't a field.
2245  if (!Lookup.empty()) {
2246  SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2247  << FieldName;
2248  SemaRef.Diag(Lookup.front()->getLocation(),
2249  diag::note_field_designator_found);
2250  ++Index;
2251  return true;
2252  }
2253 
2254  // Name lookup didn't find anything.
2255  // Determine whether this was a typo for another field name.
2256  if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2257  DeclarationNameInfo(FieldName, D->getFieldLoc()),
2258  Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
2259  llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2260  Sema::CTK_ErrorRecovery, RT->getDecl())) {
2261  SemaRef.diagnoseTypo(
2262  Corrected,
2263  SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2264  << FieldName << CurrentObjectType);
2265  KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2266  hadError = true;
2267  } else {
2268  // Typo correction didn't find anything.
2269  SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2270  << FieldName << CurrentObjectType;
2271  ++Index;
2272  return true;
2273  }
2274  }
2275  }
2276 
2277  unsigned FieldIndex = 0;
2278 
2279  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2280  FieldIndex = CXXRD->getNumBases();
2281 
2282  for (auto *FI : RT->getDecl()->fields()) {
2283  if (FI->isUnnamedBitfield())
2284  continue;
2285  if (declaresSameEntity(KnownField, FI)) {
2286  KnownField = FI;
2287  break;
2288  }
2289  ++FieldIndex;
2290  }
2291 
2294 
2295  // All of the fields of a union are located at the same place in
2296  // the initializer list.
2297  if (RT->getDecl()->isUnion()) {
2298  FieldIndex = 0;
2299  if (!VerifyOnly) {
2300  FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2301  if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2302  assert(StructuredList->getNumInits() == 1
2303  && "A union should never have more than one initializer!");
2304 
2305  Expr *ExistingInit = StructuredList->getInit(0);
2306  if (ExistingInit) {
2307  // We're about to throw away an initializer, emit warning.
2308  SemaRef.Diag(D->getFieldLoc(),
2309  diag::warn_initializer_overrides)
2310  << D->getSourceRange();
2311  SemaRef.Diag(ExistingInit->getLocStart(),
2312  diag::note_previous_initializer)
2313  << /*FIXME:has side effects=*/0
2314  << ExistingInit->getSourceRange();
2315  }
2316 
2317  // remove existing initializer
2318  StructuredList->resizeInits(SemaRef.Context, 0);
2319  StructuredList->setInitializedFieldInUnion(nullptr);
2320  }
2321 
2322  StructuredList->setInitializedFieldInUnion(*Field);
2323  }
2324  }
2325 
2326  // Make sure we can use this declaration.
2327  bool InvalidUse;
2328  if (VerifyOnly)
2329  InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2330  else
2331  InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2332  if (InvalidUse) {
2333  ++Index;
2334  return true;
2335  }
2336 
2337  if (!VerifyOnly) {
2338  // Update the designator with the field declaration.
2339  D->setField(*Field);
2340 
2341  // Make sure that our non-designated initializer list has space
2342  // for a subobject corresponding to this field.
2343  if (FieldIndex >= StructuredList->getNumInits())
2344  StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2345  }
2346 
2347  // This designator names a flexible array member.
2348  if (Field->getType()->isIncompleteArrayType()) {
2349  bool Invalid = false;
2350  if ((DesigIdx + 1) != DIE->size()) {
2351  // We can't designate an object within the flexible array
2352  // member (because GCC doesn't allow it).
2353  if (!VerifyOnly) {
2355  = DIE->getDesignator(DesigIdx + 1);
2356  SemaRef.Diag(NextD->getLocStart(),
2357  diag::err_designator_into_flexible_array_member)
2358  << SourceRange(NextD->getLocStart(),
2359  DIE->getLocEnd());
2360  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2361  << *Field;
2362  }
2363  Invalid = true;
2364  }
2365 
2366  if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2367  !isa<StringLiteral>(DIE->getInit())) {
2368  // The initializer is not an initializer list.
2369  if (!VerifyOnly) {
2370  SemaRef.Diag(DIE->getInit()->getLocStart(),
2371  diag::err_flexible_array_init_needs_braces)
2372  << DIE->getInit()->getSourceRange();
2373  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2374  << *Field;
2375  }
2376  Invalid = true;
2377  }
2378 
2379  // Check GNU flexible array initializer.
2380  if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2381  TopLevelObject))
2382  Invalid = true;
2383 
2384  if (Invalid) {
2385  ++Index;
2386  return true;
2387  }
2388 
2389  // Initialize the array.
2390  bool prevHadError = hadError;
2391  unsigned newStructuredIndex = FieldIndex;
2392  unsigned OldIndex = Index;
2393  IList->setInit(Index, DIE->getInit());
2394 
2395  InitializedEntity MemberEntity =
2396  InitializedEntity::InitializeMember(*Field, &Entity);
2397  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2398  StructuredList, newStructuredIndex);
2399 
2400  IList->setInit(OldIndex, DIE);
2401  if (hadError && !prevHadError) {
2402  ++Field;
2403  ++FieldIndex;
2404  if (NextField)
2405  *NextField = Field;
2406  StructuredIndex = FieldIndex;
2407  return true;
2408  }
2409  } else {
2410  // Recurse to check later designated subobjects.
2411  QualType FieldType = Field->getType();
2412  unsigned newStructuredIndex = FieldIndex;
2413 
2414  InitializedEntity MemberEntity =
2415  InitializedEntity::InitializeMember(*Field, &Entity);
2416  if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2417  FieldType, nullptr, nullptr, Index,
2418  StructuredList, newStructuredIndex,
2419  FinishSubobjectInit, false))
2420  return true;
2421  }
2422 
2423  // Find the position of the next field to be initialized in this
2424  // subobject.
2425  ++Field;
2426  ++FieldIndex;
2427 
2428  // If this the first designator, our caller will continue checking
2429  // the rest of this struct/class/union subobject.
2430  if (IsFirstDesignator) {
2431  if (NextField)
2432  *NextField = Field;
2433  StructuredIndex = FieldIndex;
2434  return false;
2435  }
2436 
2437  if (!FinishSubobjectInit)
2438  return false;
2439 
2440  // We've already initialized something in the union; we're done.
2441  if (RT->getDecl()->isUnion())
2442  return hadError;
2443 
2444  // Check the remaining fields within this class/struct/union subobject.
2445  bool prevHadError = hadError;
2446 
2447  auto NoBases =
2450  CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2451  false, Index, StructuredList, FieldIndex);
2452  return hadError && !prevHadError;
2453  }
2454 
2455  // C99 6.7.8p6:
2456  //
2457  // If a designator has the form
2458  //
2459  // [ constant-expression ]
2460  //
2461  // then the current object (defined below) shall have array
2462  // type and the expression shall be an integer constant
2463  // expression. If the array is of unknown size, any
2464  // nonnegative value is valid.
2465  //
2466  // Additionally, cope with the GNU extension that permits
2467  // designators of the form
2468  //
2469  // [ constant-expression ... constant-expression ]
2470  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2471  if (!AT) {
2472  if (!VerifyOnly)
2473  SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2474  << CurrentObjectType;
2475  ++Index;
2476  return true;
2477  }
2478 
2479  Expr *IndexExpr = nullptr;
2480  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2481  if (D->isArrayDesignator()) {
2482  IndexExpr = DIE->getArrayIndex(*D);
2483  DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2484  DesignatedEndIndex = DesignatedStartIndex;
2485  } else {
2486  assert(D->isArrayRangeDesignator() && "Need array-range designator");
2487 
2488  DesignatedStartIndex =
2490  DesignatedEndIndex =
2491  DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2492  IndexExpr = DIE->getArrayRangeEnd(*D);
2493 
2494  // Codegen can't handle evaluating array range designators that have side
2495  // effects, because we replicate the AST value for each initialized element.
2496  // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2497  // elements with something that has a side effect, so codegen can emit an
2498  // "error unsupported" error instead of miscompiling the app.
2499  if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2500  DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2501  FullyStructuredList->sawArrayRangeDesignator();
2502  }
2503 
2504  if (isa<ConstantArrayType>(AT)) {
2505  llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2506  DesignatedStartIndex
2507  = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2508  DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2509  DesignatedEndIndex
2510  = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2511  DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2512  if (DesignatedEndIndex >= MaxElements) {
2513  if (!VerifyOnly)
2514  SemaRef.Diag(IndexExpr->getLocStart(),
2515  diag::err_array_designator_too_large)
2516  << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2517  << IndexExpr->getSourceRange();
2518  ++Index;
2519  return true;
2520  }
2521  } else {
2522  unsigned DesignatedIndexBitWidth =
2524  DesignatedStartIndex =
2525  DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2526  DesignatedEndIndex =
2527  DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2528  DesignatedStartIndex.setIsUnsigned(true);
2529  DesignatedEndIndex.setIsUnsigned(true);
2530  }
2531 
2532  if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2533  // We're modifying a string literal init; we have to decompose the string
2534  // so we can modify the individual characters.
2535  ASTContext &Context = SemaRef.Context;
2536  Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2537 
2538  // Compute the character type
2539  QualType CharTy = AT->getElementType();
2540 
2541  // Compute the type of the integer literals.
2542  QualType PromotedCharTy = CharTy;
2543  if (CharTy->isPromotableIntegerType())
2544  PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2545  unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2546 
2547  if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2548  // Get the length of the string.
2549  uint64_t StrLen = SL->getLength();
2550  if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2551  StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2552  StructuredList->resizeInits(Context, StrLen);
2553 
2554  // Build a literal for each character in the string, and put them into
2555  // the init list.
2556  for (unsigned i = 0, e = StrLen; i != e; ++i) {
2557  llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2558  Expr *Init = new (Context) IntegerLiteral(
2559  Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2560  if (CharTy != PromotedCharTy)
2561  Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2562  Init, nullptr, VK_RValue);
2563  StructuredList->updateInit(Context, i, Init);
2564  }
2565  } else {
2566  ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2567  std::string Str;
2568  Context.getObjCEncodingForType(E->getEncodedType(), Str);
2569 
2570  // Get the length of the string.
2571  uint64_t StrLen = Str.size();
2572  if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2573  StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2574  StructuredList->resizeInits(Context, StrLen);
2575 
2576  // Build a literal for each character in the string, and put them into
2577  // the init list.
2578  for (unsigned i = 0, e = StrLen; i != e; ++i) {
2579  llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2580  Expr *Init = new (Context) IntegerLiteral(
2581  Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2582  if (CharTy != PromotedCharTy)
2583  Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2584  Init, nullptr, VK_RValue);
2585  StructuredList->updateInit(Context, i, Init);
2586  }
2587  }
2588  }
2589 
2590  // Make sure that our non-designated initializer list has space
2591  // for a subobject corresponding to this array element.
2592  if (!VerifyOnly &&
2593  DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2594  StructuredList->resizeInits(SemaRef.Context,
2595  DesignatedEndIndex.getZExtValue() + 1);
2596 
2597  // Repeatedly perform subobject initializations in the range
2598  // [DesignatedStartIndex, DesignatedEndIndex].
2599 
2600  // Move to the next designator
2601  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2602  unsigned OldIndex = Index;
2603 
2604  InitializedEntity ElementEntity =
2605  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2606 
2607  while (DesignatedStartIndex <= DesignatedEndIndex) {
2608  // Recurse to check later designated subobjects.
2609  QualType ElementType = AT->getElementType();
2610  Index = OldIndex;
2611 
2612  ElementEntity.setElementIndex(ElementIndex);
2613  if (CheckDesignatedInitializer(
2614  ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2615  nullptr, Index, StructuredList, ElementIndex,
2616  FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2617  false))
2618  return true;
2619 
2620  // Move to the next index in the array that we'll be initializing.
2621  ++DesignatedStartIndex;
2622  ElementIndex = DesignatedStartIndex.getZExtValue();
2623  }
2624 
2625  // If this the first designator, our caller will continue checking
2626  // the rest of this array subobject.
2627  if (IsFirstDesignator) {
2628  if (NextElementIndex)
2629  *NextElementIndex = DesignatedStartIndex;
2630  StructuredIndex = ElementIndex;
2631  return false;
2632  }
2633 
2634  if (!FinishSubobjectInit)
2635  return false;
2636 
2637  // Check the remaining elements within this array subobject.
2638  bool prevHadError = hadError;
2639  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2640  /*SubobjectIsDesignatorContext=*/false, Index,
2641  StructuredList, ElementIndex);
2642  return hadError && !prevHadError;
2643 }
2644 
2645 // Get the structured initializer list for a subobject of type
2646 // @p CurrentObjectType.
2647 InitListExpr *
2648 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2649  QualType CurrentObjectType,
2650  InitListExpr *StructuredList,
2651  unsigned StructuredIndex,
2652  SourceRange InitRange,
2653  bool IsFullyOverwritten) {
2654  if (VerifyOnly)
2655  return nullptr; // No structured list in verification-only mode.
2656  Expr *ExistingInit = nullptr;
2657  if (!StructuredList)
2658  ExistingInit = SyntacticToSemantic.lookup(IList);
2659  else if (StructuredIndex < StructuredList->getNumInits())
2660  ExistingInit = StructuredList->getInit(StructuredIndex);
2661 
2662  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2663  // There might have already been initializers for subobjects of the current
2664  // object, but a subsequent initializer list will overwrite the entirety
2665  // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2666  //
2667  // struct P { char x[6]; };
2668  // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2669  //
2670  // The first designated initializer is ignored, and l.x is just "f".
2671  if (!IsFullyOverwritten)
2672  return Result;
2673 
2674  if (ExistingInit) {
2675  // We are creating an initializer list that initializes the
2676  // subobjects of the current object, but there was already an
2677  // initialization that completely initialized the current
2678  // subobject, e.g., by a compound literal:
2679  //
2680  // struct X { int a, b; };
2681  // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2682  //
2683  // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2684  // designated initializer re-initializes the whole
2685  // subobject [0], overwriting previous initializers.
2686  SemaRef.Diag(InitRange.getBegin(),
2687  diag::warn_subobject_initializer_overrides)
2688  << InitRange;
2689  SemaRef.Diag(ExistingInit->getLocStart(),
2690  diag::note_previous_initializer)
2691  << /*FIXME:has side effects=*/0
2692  << ExistingInit->getSourceRange();
2693  }
2694 
2696  = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2697  InitRange.getBegin(), None,
2698  InitRange.getEnd());
2699 
2700  QualType ResultType = CurrentObjectType;
2701  if (!ResultType->isArrayType())
2702  ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2703  Result->setType(ResultType);
2704 
2705  // Pre-allocate storage for the structured initializer list.
2706  unsigned NumElements = 0;
2707  unsigned NumInits = 0;
2708  bool GotNumInits = false;
2709  if (!StructuredList) {
2710  NumInits = IList->getNumInits();
2711  GotNumInits = true;
2712  } else if (Index < IList->getNumInits()) {
2713  if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2714  NumInits = SubList->getNumInits();
2715  GotNumInits = true;
2716  }
2717  }
2718 
2719  if (const ArrayType *AType
2720  = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2721  if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2722  NumElements = CAType->getSize().getZExtValue();
2723  // Simple heuristic so that we don't allocate a very large
2724  // initializer with many empty entries at the end.
2725  if (GotNumInits && NumElements > NumInits)
2726  NumElements = 0;
2727  }
2728  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2729  NumElements = VType->getNumElements();
2730  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2731  RecordDecl *RDecl = RType->getDecl();
2732  if (RDecl->isUnion())
2733  NumElements = 1;
2734  else
2735  NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2736  }
2737 
2738  Result->reserveInits(SemaRef.Context, NumElements);
2739 
2740  // Link this new initializer list into the structured initializer
2741  // lists.
2742  if (StructuredList)
2743  StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2744  else {
2745  Result->setSyntacticForm(IList);
2746  SyntacticToSemantic[IList] = Result;
2747  }
2748 
2749  return Result;
2750 }
2751 
2752 /// Update the initializer at index @p StructuredIndex within the
2753 /// structured initializer list to the value @p expr.
2754 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2755  unsigned &StructuredIndex,
2756  Expr *expr) {
2757  // No structured initializer list to update
2758  if (!StructuredList)
2759  return;
2760 
2761  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2762  StructuredIndex, expr)) {
2763  // This initializer overwrites a previous initializer. Warn.
2764  // We need to check on source range validity because the previous
2765  // initializer does not have to be an explicit initializer.
2766  // struct P { int a, b; };
2767  // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2768  // There is an overwrite taking place because the first braced initializer
2769  // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2770  if (PrevInit->getSourceRange().isValid()) {
2771  SemaRef.Diag(expr->getLocStart(),
2772  diag::warn_initializer_overrides)
2773  << expr->getSourceRange();
2774 
2775  SemaRef.Diag(PrevInit->getLocStart(),
2776  diag::note_previous_initializer)
2777  << /*FIXME:has side effects=*/0
2778  << PrevInit->getSourceRange();
2779  }
2780  }
2781 
2782  ++StructuredIndex;
2783 }
2784 
2785 /// Check that the given Index expression is a valid array designator
2786 /// value. This is essentially just a wrapper around
2787 /// VerifyIntegerConstantExpression that also checks for negative values
2788 /// and produces a reasonable diagnostic if there is a
2789 /// failure. Returns the index expression, possibly with an implicit cast
2790 /// added, on success. If everything went okay, Value will receive the
2791 /// value of the constant expression.
2792 static ExprResult
2793 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2794  SourceLocation Loc = Index->getLocStart();
2795 
2796  // Make sure this is an integer constant expression.
2798  if (Result.isInvalid())
2799  return Result;
2800 
2801  if (Value.isSigned() && Value.isNegative())
2802  return S.Diag(Loc, diag::err_array_designator_negative)
2803  << Value.toString(10) << Index->getSourceRange();
2804 
2805  Value.setIsUnsigned(true);
2806  return Result;
2807 }
2808 
2810  SourceLocation Loc,
2811  bool GNUSyntax,
2812  ExprResult Init) {
2813  typedef DesignatedInitExpr::Designator ASTDesignator;
2814 
2815  bool Invalid = false;
2816  SmallVector<ASTDesignator, 32> Designators;
2817  SmallVector<Expr *, 32> InitExpressions;
2818 
2819  // Build designators and check array designator expressions.
2820  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2821  const Designator &D = Desig.getDesignator(Idx);
2822  switch (D.getKind()) {
2824  Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2825  D.getFieldLoc()));
2826  break;
2827 
2829  Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2830  llvm::APSInt IndexValue;
2831  if (!Index->isTypeDependent() && !Index->isValueDependent())
2832  Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2833  if (!Index)
2834  Invalid = true;
2835  else {
2836  Designators.push_back(ASTDesignator(InitExpressions.size(),
2837  D.getLBracketLoc(),
2838  D.getRBracketLoc()));
2839  InitExpressions.push_back(Index);
2840  }
2841  break;
2842  }
2843 
2845  Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2846  Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2847  llvm::APSInt StartValue;
2848  llvm::APSInt EndValue;
2849  bool StartDependent = StartIndex->isTypeDependent() ||
2850  StartIndex->isValueDependent();
2851  bool EndDependent = EndIndex->isTypeDependent() ||
2852  EndIndex->isValueDependent();
2853  if (!StartDependent)
2854  StartIndex =
2855  CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2856  if (!EndDependent)
2857  EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2858 
2859  if (!StartIndex || !EndIndex)
2860  Invalid = true;
2861  else {
2862  // Make sure we're comparing values with the same bit width.
2863  if (StartDependent || EndDependent) {
2864  // Nothing to compute.
2865  } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2866  EndValue = EndValue.extend(StartValue.getBitWidth());
2867  else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2868  StartValue = StartValue.extend(EndValue.getBitWidth());
2869 
2870  if (!StartDependent && !EndDependent && EndValue < StartValue) {
2871  Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2872  << StartValue.toString(10) << EndValue.toString(10)
2873  << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2874  Invalid = true;
2875  } else {
2876  Designators.push_back(ASTDesignator(InitExpressions.size(),
2877  D.getLBracketLoc(),
2878  D.getEllipsisLoc(),
2879  D.getRBracketLoc()));
2880  InitExpressions.push_back(StartIndex);
2881  InitExpressions.push_back(EndIndex);
2882  }
2883  }
2884  break;
2885  }
2886  }
2887  }
2888 
2889  if (Invalid || Init.isInvalid())
2890  return ExprError();
2891 
2892  // Clear out the expressions within the designation.
2893  Desig.ClearExprs(*this);
2894 
2895  DesignatedInitExpr *DIE
2896  = DesignatedInitExpr::Create(Context,
2897  Designators,
2898  InitExpressions, Loc, GNUSyntax,
2899  Init.getAs<Expr>());
2900 
2901  if (!getLangOpts().C99)
2902  Diag(DIE->getLocStart(), diag::ext_designated_init)
2903  << DIE->getSourceRange();
2904 
2905  return DIE;
2906 }
2907 
2908 //===----------------------------------------------------------------------===//
2909 // Initialization entity
2910 //===----------------------------------------------------------------------===//
2911 
2912 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2913  const InitializedEntity &Parent)
2914  : Parent(&Parent), Index(Index)
2915 {
2916  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2917  Kind = EK_ArrayElement;
2918  Type = AT->getElementType();
2919  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2920  Kind = EK_VectorElement;
2921  Type = VT->getElementType();
2922  } else {
2923  const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2924  assert(CT && "Unexpected type");
2925  Kind = EK_ComplexElement;
2926  Type = CT->getElementType();
2927  }
2928 }
2929 
2932  const CXXBaseSpecifier *Base,
2933  bool IsInheritedVirtualBase,
2934  const InitializedEntity *Parent) {
2936  Result.Kind = EK_Base;
2937  Result.Parent = Parent;
2938  Result.Base = reinterpret_cast<uintptr_t>(Base);
2939  if (IsInheritedVirtualBase)
2940  Result.Base |= 0x01;
2941 
2942  Result.Type = Base->getType();
2943  return Result;
2944 }
2945 
2947  switch (getKind()) {
2948  case EK_Parameter:
2949  case EK_Parameter_CF_Audited: {
2950  ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2951  return (D ? D->getDeclName() : DeclarationName());
2952  }
2953 
2954  case EK_Variable:
2955  case EK_Member:
2956  case EK_Binding:
2957  return Variable.VariableOrMember->getDeclName();
2958 
2959  case EK_LambdaCapture:
2960  return DeclarationName(Capture.VarID);
2961 
2962  case EK_Result:
2963  case EK_Exception:
2964  case EK_New:
2965  case EK_Temporary:
2966  case EK_Base:
2967  case EK_Delegating:
2968  case EK_ArrayElement:
2969  case EK_VectorElement:
2970  case EK_ComplexElement:
2971  case EK_BlockElement:
2972  case EK_LambdaToBlockConversionBlockElement:
2973  case EK_CompoundLiteralInit:
2974  case EK_RelatedResult:
2975  return DeclarationName();
2976  }
2977 
2978  llvm_unreachable("Invalid EntityKind!");
2979 }
2980 
2982  switch (getKind()) {
2983  case EK_Variable:
2984  case EK_Member:
2985  case EK_Binding:
2986  return Variable.VariableOrMember;
2987 
2988  case EK_Parameter:
2989  case EK_Parameter_CF_Audited:
2990  return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2991 
2992  case EK_Result:
2993  case EK_Exception:
2994  case EK_New:
2995  case EK_Temporary:
2996  case EK_Base:
2997  case EK_Delegating:
2998  case EK_ArrayElement:
2999  case EK_VectorElement:
3000  case EK_ComplexElement:
3001  case EK_BlockElement:
3002  case EK_LambdaToBlockConversionBlockElement:
3003  case EK_LambdaCapture:
3004  case EK_CompoundLiteralInit:
3005  case EK_RelatedResult:
3006  return nullptr;
3007  }
3008 
3009  llvm_unreachable("Invalid EntityKind!");
3010 }
3011 
3013  switch (getKind()) {
3014  case EK_Result:
3015  case EK_Exception:
3016  return LocAndNRVO.NRVO;
3017 
3018  case EK_Variable:
3019  case EK_Parameter:
3020  case EK_Parameter_CF_Audited:
3021  case EK_Member:
3022  case EK_Binding:
3023  case EK_New:
3024  case EK_Temporary:
3025  case EK_CompoundLiteralInit:
3026  case EK_Base:
3027  case EK_Delegating:
3028  case EK_ArrayElement:
3029  case EK_VectorElement:
3030  case EK_ComplexElement:
3031  case EK_BlockElement:
3032  case EK_LambdaToBlockConversionBlockElement:
3033  case EK_LambdaCapture:
3034  case EK_RelatedResult:
3035  break;
3036  }
3037 
3038  return false;
3039 }
3040 
3041 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3042  assert(getParent() != this);
3043  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3044  for (unsigned I = 0; I != Depth; ++I)
3045  OS << "`-";
3046 
3047  switch (getKind()) {
3048  case EK_Variable: OS << "Variable"; break;
3049  case EK_Parameter: OS << "Parameter"; break;
3050  case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3051  break;
3052  case EK_Result: OS << "Result"; break;
3053  case EK_Exception: OS << "Exception"; break;
3054  case EK_Member: OS << "Member"; break;
3055  case EK_Binding: OS << "Binding"; break;
3056  case EK_New: OS << "New"; break;
3057  case EK_Temporary: OS << "Temporary"; break;
3058  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3059  case EK_RelatedResult: OS << "RelatedResult"; break;
3060  case EK_Base: OS << "Base"; break;
3061  case EK_Delegating: OS << "Delegating"; break;
3062  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3063  case EK_VectorElement: OS << "VectorElement " << Index; break;
3064  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3065  case EK_BlockElement: OS << "Block"; break;
3066  case EK_LambdaToBlockConversionBlockElement:
3067  OS << "Block (lambda)";
3068  break;
3069  case EK_LambdaCapture:
3070  OS << "LambdaCapture ";
3071  OS << DeclarationName(Capture.VarID);
3072  break;
3073  }
3074 
3075  if (auto *D = getDecl()) {
3076  OS << " ";
3077  D->printQualifiedName(OS);
3078  }
3079 
3080  OS << " '" << getType().getAsString() << "'\n";
3081 
3082  return Depth + 1;
3083 }
3084 
3085 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3086  dumpImpl(llvm::errs());
3087 }
3088 
3089 //===----------------------------------------------------------------------===//
3090 // Initialization sequence
3091 //===----------------------------------------------------------------------===//
3092 
3094  switch (Kind) {
3095  case SK_ResolveAddressOfOverloadedFunction:
3096  case SK_CastDerivedToBaseRValue:
3097  case SK_CastDerivedToBaseXValue:
3098  case SK_CastDerivedToBaseLValue:
3099  case SK_BindReference:
3100  case SK_BindReferenceToTemporary:
3101  case SK_FinalCopy:
3102  case SK_ExtraneousCopyToTemporary:
3103  case SK_UserConversion:
3104  case SK_QualificationConversionRValue:
3105  case SK_QualificationConversionXValue:
3106  case SK_QualificationConversionLValue:
3107  case SK_AtomicConversion:
3108  case SK_LValueToRValue:
3109  case SK_ListInitialization:
3110  case SK_UnwrapInitList:
3111  case SK_RewrapInitList:
3112  case SK_ConstructorInitialization:
3113  case SK_ConstructorInitializationFromList:
3114  case SK_ZeroInitialization:
3115  case SK_CAssignment:
3116  case SK_StringInit:
3117  case SK_ObjCObjectConversion:
3118  case SK_ArrayLoopIndex:
3119  case SK_ArrayLoopInit:
3120  case SK_ArrayInit:
3121  case SK_GNUArrayInit:
3122  case SK_ParenthesizedArrayInit:
3123  case SK_PassByIndirectCopyRestore:
3124  case SK_PassByIndirectRestore:
3125  case SK_ProduceObjCObject:
3126  case SK_StdInitializerList:
3127  case SK_StdInitializerListConstructorCall:
3128  case SK_OCLSamplerInit:
3129  case SK_OCLZeroEvent:
3130  case SK_OCLZeroQueue:
3131  break;
3132 
3133  case SK_ConversionSequence:
3134  case SK_ConversionSequenceNoNarrowing:
3135  delete ICS;
3136  }
3137 }
3138 
3140  // There can be some lvalue adjustments after the SK_BindReference step.
3141  for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3142  if (I->Kind == SK_BindReference)
3143  return true;
3144  if (I->Kind == SK_BindReferenceToTemporary)
3145  return false;
3146  }
3147  return false;
3148 }
3149 
3151  if (!Failed())
3152  return false;
3153 
3154  switch (getFailureKind()) {
3155  case FK_TooManyInitsForReference:
3156  case FK_ParenthesizedListInitForReference:
3157  case FK_ArrayNeedsInitList:
3158  case FK_ArrayNeedsInitListOrStringLiteral:
3159  case FK_ArrayNeedsInitListOrWideStringLiteral:
3160  case FK_NarrowStringIntoWideCharArray:
3161  case FK_WideStringIntoCharArray:
3162  case FK_IncompatWideStringIntoWideChar:
3163  case FK_AddressOfOverloadFailed: // FIXME: Could do better
3164  case FK_NonConstLValueReferenceBindingToTemporary:
3165  case FK_NonConstLValueReferenceBindingToBitfield:
3166  case FK_NonConstLValueReferenceBindingToVectorElement:
3167  case FK_NonConstLValueReferenceBindingToUnrelated:
3168  case FK_RValueReferenceBindingToLValue:
3169  case FK_ReferenceInitDropsQualifiers:
3170  case FK_ReferenceInitFailed:
3171  case FK_ConversionFailed:
3172  case FK_ConversionFromPropertyFailed:
3173  case FK_TooManyInitsForScalar:
3174  case FK_ParenthesizedListInitForScalar:
3175  case FK_ReferenceBindingToInitList:
3176  case FK_InitListBadDestinationType:
3177  case FK_DefaultInitOfConst:
3178  case FK_Incomplete:
3179  case FK_ArrayTypeMismatch:
3180  case FK_NonConstantArrayInit:
3181  case FK_ListInitializationFailed:
3182  case FK_VariableLengthArrayHasInitializer:
3183  case FK_PlaceholderType:
3184  case FK_ExplicitConstructor:
3185  case FK_AddressOfUnaddressableFunction:
3186  return false;
3187 
3188  case FK_ReferenceInitOverloadFailed:
3189  case FK_UserConversionOverloadFailed:
3190  case FK_ConstructorOverloadFailed:
3191  case FK_ListConstructorOverloadFailed:
3192  return FailedOverloadResult == OR_Ambiguous;
3193  }
3194 
3195  llvm_unreachable("Invalid EntityKind!");
3196 }
3197 
3199  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3200 }
3201 
3202 void
3205  DeclAccessPair Found,
3206  bool HadMultipleCandidates) {
3207  Step S;
3208  S.Kind = SK_ResolveAddressOfOverloadedFunction;
3209  S.Type = Function->getType();
3210  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3211  S.Function.Function = Function;
3212  S.Function.FoundDecl = Found;
3213  Steps.push_back(S);
3214 }
3215 
3217  ExprValueKind VK) {
3218  Step S;
3219  switch (VK) {
3220  case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3221  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3222  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3223  }
3224  S.Type = BaseType;
3225  Steps.push_back(S);
3226 }
3227 
3229  bool BindingTemporary) {
3230  Step S;
3231  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3232  S.Type = T;
3233  Steps.push_back(S);
3234 }
3235 
3237  Step S;
3238  S.Kind = SK_FinalCopy;
3239  S.Type = T;
3240  Steps.push_back(S);
3241 }
3242 
3244  Step S;
3245  S.Kind = SK_ExtraneousCopyToTemporary;
3246  S.Type = T;
3247  Steps.push_back(S);
3248 }
3249 
3250 void
3252  DeclAccessPair FoundDecl,
3253  QualType T,
3254  bool HadMultipleCandidates) {
3255  Step S;
3256  S.Kind = SK_UserConversion;
3257  S.Type = T;
3258  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3259  S.Function.Function = Function;
3260  S.Function.FoundDecl = FoundDecl;
3261  Steps.push_back(S);
3262 }
3263 
3265  ExprValueKind VK) {
3266  Step S;
3267  S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3268  switch (VK) {
3269  case VK_RValue:
3270  S.Kind = SK_QualificationConversionRValue;
3271  break;
3272  case VK_XValue:
3273  S.Kind = SK_QualificationConversionXValue;
3274  break;
3275  case VK_LValue:
3276  S.Kind = SK_QualificationConversionLValue;
3277  break;
3278  }
3279  S.Type = Ty;
3280  Steps.push_back(S);
3281 }
3282 
3284  Step S;
3285  S.Kind = SK_AtomicConversion;
3286  S.Type = Ty;
3287  Steps.push_back(S);
3288 }
3289 
3291  assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3292 
3293  Step S;
3294  S.Kind = SK_LValueToRValue;
3295  S.Type = Ty;
3296  Steps.push_back(S);
3297 }
3298 
3300  const ImplicitConversionSequence &ICS, QualType T,
3301  bool TopLevelOfInitList) {
3302  Step S;
3303  S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3304  : SK_ConversionSequence;
3305  S.Type = T;
3306  S.ICS = new ImplicitConversionSequence(ICS);
3307  Steps.push_back(S);
3308 }
3309 
3311  Step S;
3312  S.Kind = SK_ListInitialization;
3313  S.Type = T;
3314  Steps.push_back(S);
3315 }
3316 
3318  DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3319  bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3320  Step S;
3321  S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3322  : SK_ConstructorInitializationFromList
3323  : SK_ConstructorInitialization;
3324  S.Type = T;
3325  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3326  S.Function.Function = Constructor;
3327  S.Function.FoundDecl = FoundDecl;
3328  Steps.push_back(S);
3329 }
3330 
3332  Step S;
3333  S.Kind = SK_ZeroInitialization;
3334  S.Type = T;
3335  Steps.push_back(S);
3336 }
3337 
3339  Step S;
3340  S.Kind = SK_CAssignment;
3341  S.Type = T;
3342  Steps.push_back(S);
3343 }
3344 
3346  Step S;
3347  S.Kind = SK_StringInit;
3348  S.Type = T;
3349  Steps.push_back(S);
3350 }
3351 
3353  Step S;
3354  S.Kind = SK_ObjCObjectConversion;
3355  S.Type = T;
3356  Steps.push_back(S);
3357 }
3358 
3360  Step S;
3361  S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3362  S.Type = T;
3363  Steps.push_back(S);
3364 }
3365 
3367  Step S;
3368  S.Kind = SK_ArrayLoopIndex;
3369  S.Type = EltT;
3370  Steps.insert(Steps.begin(), S);
3371 
3372  S.Kind = SK_ArrayLoopInit;
3373  S.Type = T;
3374  Steps.push_back(S);
3375 }
3376 
3378  Step S;
3379  S.Kind = SK_ParenthesizedArrayInit;
3380  S.Type = T;
3381  Steps.push_back(S);
3382 }
3383 
3385  bool shouldCopy) {
3386  Step s;
3387  s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3388  : SK_PassByIndirectRestore);
3389  s.Type = type;
3390  Steps.push_back(s);
3391 }
3392 
3394  Step S;
3395  S.Kind = SK_ProduceObjCObject;
3396  S.Type = T;
3397  Steps.push_back(S);
3398 }
3399 
3401  Step S;
3402  S.Kind = SK_StdInitializerList;
3403  S.Type = T;
3404  Steps.push_back(S);
3405 }
3406 
3408  Step S;
3409  S.Kind = SK_OCLSamplerInit;
3410  S.Type = T;
3411  Steps.push_back(S);
3412 }
3413 
3415  Step S;
3416  S.Kind = SK_OCLZeroEvent;
3417  S.Type = T;
3418  Steps.push_back(S);
3419 }
3420 
3422  Step S;
3423  S.Kind = SK_OCLZeroQueue;
3424  S.Type = T;
3425  Steps.push_back(S);
3426 }
3427 
3429  InitListExpr *Syntactic) {
3430  assert(Syntactic->getNumInits() == 1 &&
3431  "Can only rewrap trivial init lists.");
3432  Step S;
3433  S.Kind = SK_UnwrapInitList;
3434  S.Type = Syntactic->getInit(0)->getType();
3435  Steps.insert(Steps.begin(), S);
3436 
3437  S.Kind = SK_RewrapInitList;
3438  S.Type = T;
3439  S.WrappingSyntacticList = Syntactic;
3440  Steps.push_back(S);
3441 }
3442 
3445  setSequenceKind(FailedSequence);
3446  this->Failure = Failure;
3447  this->FailedOverloadResult = Result;
3448 }
3449 
3450 //===----------------------------------------------------------------------===//
3451 // Attempt initialization
3452 //===----------------------------------------------------------------------===//
3453 
3454 /// Tries to add a zero initializer. Returns true if that worked.
3455 static bool
3457  const InitializedEntity &Entity) {
3458  if (Entity.getKind() != InitializedEntity::EK_Variable)
3459  return false;
3460 
3461  VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3462  if (VD->getInit() || VD->getLocEnd().isMacroID())
3463  return false;
3464 
3465  QualType VariableTy = VD->getType().getCanonicalType();
3467  std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3468  if (!Init.empty()) {
3469  Sequence.AddZeroInitializationStep(Entity.getType());
3470  Sequence.SetZeroInitializationFixit(Init, Loc);
3471  return true;
3472  }
3473  return false;
3474 }
3475 
3477  InitializationSequence &Sequence,
3478  const InitializedEntity &Entity) {
3479  if (!S.getLangOpts().ObjCAutoRefCount) return;
3480 
3481  /// When initializing a parameter, produce the value if it's marked
3482  /// __attribute__((ns_consumed)).
3483  if (Entity.isParameterKind()) {
3484  if (!Entity.isParameterConsumed())
3485  return;
3486 
3487  assert(Entity.getType()->isObjCRetainableType() &&
3488  "consuming an object of unretainable type?");
3489  Sequence.AddProduceObjCObjectStep(Entity.getType());
3490 
3491  /// When initializing a return value, if the return type is a
3492  /// retainable type, then returns need to immediately retain the
3493  /// object. If an autorelease is required, it will be done at the
3494  /// last instant.
3495  } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3496  if (!Entity.getType()->isObjCRetainableType())
3497  return;
3498 
3499  Sequence.AddProduceObjCObjectStep(Entity.getType());
3500  }
3501 }
3502 
3503 static void TryListInitialization(Sema &S,
3504  const InitializedEntity &Entity,
3505  const InitializationKind &Kind,
3506  InitListExpr *InitList,
3507  InitializationSequence &Sequence,
3508  bool TreatUnavailableAsInvalid);
3509 
3510 /// \brief When initializing from init list via constructor, handle
3511 /// initialization of an object of type std::initializer_list<T>.
3512 ///
3513 /// \return true if we have handled initialization of an object of type
3514 /// std::initializer_list<T>, false otherwise.
3516  InitListExpr *List,
3517  QualType DestType,
3518  InitializationSequence &Sequence,
3519  bool TreatUnavailableAsInvalid) {
3520  QualType E;
3521  if (!S.isStdInitializerList(DestType, &E))
3522  return false;
3523 
3524  if (!S.isCompleteType(List->getExprLoc(), E)) {
3525  Sequence.setIncompleteTypeFailure(E);
3526  return true;
3527  }
3528 
3529  // Try initializing a temporary array from the init list.
3531  E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3532  List->getNumInits()),
3534  InitializedEntity HiddenArray =
3536  InitializationKind Kind =
3538  TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3539  TreatUnavailableAsInvalid);
3540  if (Sequence)
3541  Sequence.AddStdInitializerListConstructionStep(DestType);
3542  return true;
3543 }
3544 
3545 /// Determine if the constructor has the signature of a copy or move
3546 /// constructor for the type T of the class in which it was found. That is,
3547 /// determine if its first parameter is of type T or reference to (possibly
3548 /// cv-qualified) T.
3550  const ConstructorInfo &Info) {
3551  if (Info.Constructor->getNumParams() == 0)
3552  return false;
3553 
3554  QualType ParmT =
3556  QualType ClassT =
3557  Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3558 
3559  return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3560 }
3561 
3562 static OverloadingResult
3564  MultiExprArg Args,
3565  OverloadCandidateSet &CandidateSet,
3566  QualType DestType,
3569  bool CopyInitializing, bool AllowExplicit,
3570  bool OnlyListConstructors, bool IsListInit,
3571  bool SecondStepOfCopyInit = false) {
3573 
3574  for (NamedDecl *D : Ctors) {
3575  auto Info = getConstructorInfo(D);
3576  if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3577  continue;
3578 
3579  if (!AllowExplicit && Info.Constructor->isExplicit())
3580  continue;
3581 
3582  if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3583  continue;
3584 
3585  // C++11 [over.best.ics]p4:
3586  // ... and the constructor or user-defined conversion function is a
3587  // candidate by
3588  // - 13.3.1.3, when the argument is the temporary in the second step
3589  // of a class copy-initialization, or
3590  // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3591  // - the second phase of 13.3.1.7 when the initializer list has exactly
3592  // one element that is itself an initializer list, and the target is
3593  // the first parameter of a constructor of class X, and the conversion
3594  // is to X or reference to (possibly cv-qualified X),
3595  // user-defined conversion sequences are not considered.
3596  bool SuppressUserConversions =
3597  SecondStepOfCopyInit ||
3598  (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3599  hasCopyOrMoveCtorParam(S.Context, Info));
3600 
3601  if (Info.ConstructorTmpl)
3602  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3603  /*ExplicitArgs*/ nullptr, Args,
3604  CandidateSet, SuppressUserConversions);
3605  else {
3606  // C++ [over.match.copy]p1:
3607  // - When initializing a temporary to be bound to the first parameter
3608  // of a constructor [for type T] that takes a reference to possibly
3609  // cv-qualified T as its first argument, called with a single
3610  // argument in the context of direct-initialization, explicit
3611  // conversion functions are also considered.
3612  // FIXME: What if a constructor template instantiates to such a signature?
3613  bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3614  Args.size() == 1 &&
3616  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3617  CandidateSet, SuppressUserConversions,
3618  /*PartialOverloading=*/false,
3619  /*AllowExplicit=*/AllowExplicitConv);
3620  }
3621  }
3622 
3623  // FIXME: Work around a bug in C++17 guaranteed copy elision.
3624  //
3625  // When initializing an object of class type T by constructor
3626  // ([over.match.ctor]) or by list-initialization ([over.match.list])
3627  // from a single expression of class type U, conversion functions of
3628  // U that convert to the non-reference type cv T are candidates.
3629  // Explicit conversion functions are only candidates during
3630  // direct-initialization.
3631  //
3632  // Note: SecondStepOfCopyInit is only ever true in this case when
3633  // evaluating whether to produce a C++98 compatibility warning.
3634  if (S.getLangOpts().CPlusPlus1z && Args.size() == 1 &&
3635  !SecondStepOfCopyInit) {
3636  Expr *Initializer = Args[0];
3637  auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3638  if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3639  const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3640  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3641  NamedDecl *D = *I;
3642  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3643  D = D->getUnderlyingDecl();
3644 
3645  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3646  CXXConversionDecl *Conv;
3647  if (ConvTemplate)
3648  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3649  else
3650  Conv = cast<CXXConversionDecl>(D);
3651 
3652  if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3653  if (ConvTemplate)
3654  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3655  ActingDC, Initializer, DestType,
3656  CandidateSet, AllowExplicit,
3657  /*AllowResultConversion*/false);
3658  else
3659  S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3660  DestType, CandidateSet, AllowExplicit,
3661  /*AllowResultConversion*/false);
3662  }
3663  }
3664  }
3665  }
3666 
3667  // Perform overload resolution and return the result.
3668  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3669 }
3670 
3671 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3672 /// enumerates the constructors of the initialized entity and performs overload
3673 /// resolution to select the best.
3674 /// \param DestType The destination class type.
3675 /// \param DestArrayType The destination type, which is either DestType or
3676 /// a (possibly multidimensional) array of DestType.
3677 /// \param IsListInit Is this list-initialization?
3678 /// \param IsInitListCopy Is this non-list-initialization resulting from a
3679 /// list-initialization from {x} where x is the same
3680 /// type as the entity?
3682  const InitializedEntity &Entity,
3683  const InitializationKind &Kind,
3684  MultiExprArg Args, QualType DestType,
3685  QualType DestArrayType,
3686  InitializationSequence &Sequence,
3687  bool IsListInit = false,
3688  bool IsInitListCopy = false) {
3689  assert(((!IsListInit && !IsInitListCopy) ||
3690  (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3691  "IsListInit/IsInitListCopy must come with a single initializer list "
3692  "argument.");
3693  InitListExpr *ILE =
3694  (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3695  MultiExprArg UnwrappedArgs =
3696  ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
3697 
3698  // The type we're constructing needs to be complete.
3699  if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3700  Sequence.setIncompleteTypeFailure(DestType);
3701  return;
3702  }
3703 
3704  // C++1z [dcl.init]p17:
3705  // - If the initializer expression is a prvalue and the cv-unqualified
3706  // version of the source type is the same class as the class of the
3707  // destination, the initializer expression is used to initialize the
3708  // destination object.
3709  // Per DR (no number yet), this does not apply when initializing a base
3710  // class or delegating to another constructor from a mem-initializer.
3711  // ObjC++: Lambda captured by the block in the lambda to block conversion
3712  // should avoid copy elision.
3713  if (S.getLangOpts().CPlusPlus1z &&
3714  Entity.getKind() != InitializedEntity::EK_Base &&
3716  Entity.getKind() !=
3718  UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3719  S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3720  // Convert qualifications if necessary.
3721  Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3722  if (ILE)
3723  Sequence.RewrapReferenceInitList(DestType, ILE);
3724  return;
3725  }
3726 
3727  const RecordType *DestRecordType = DestType->getAs<RecordType>();
3728  assert(DestRecordType && "Constructor initialization requires record type");
3729  CXXRecordDecl *DestRecordDecl
3730  = cast<CXXRecordDecl>(DestRecordType->getDecl());
3731 
3732  // Build the candidate set directly in the initialization sequence
3733  // structure, so that it will persist if we fail.
3734  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3735 
3736  // Determine whether we are allowed to call explicit constructors or
3737  // explicit conversion operators.
3738  bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3739  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3740 
3741  // - Otherwise, if T is a class type, constructors are considered. The
3742  // applicable constructors are enumerated, and the best one is chosen
3743  // through overload resolution.
3744  DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3745 
3748  bool AsInitializerList = false;
3749 
3750  // C++11 [over.match.list]p1, per DR1467:
3751  // When objects of non-aggregate type T are list-initialized, such that
3752  // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3753  // according to the rules in this section, overload resolution selects
3754  // the constructor in two phases:
3755  //
3756  // - Initially, the candidate functions are the initializer-list
3757  // constructors of the class T and the argument list consists of the
3758  // initializer list as a single argument.
3759  if (IsListInit) {
3760  AsInitializerList = true;
3761 
3762  // If the initializer list has no elements and T has a default constructor,
3763  // the first phase is omitted.
3764  if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
3765  Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3766  CandidateSet, DestType, Ctors, Best,
3767  CopyInitialization, AllowExplicit,
3768  /*OnlyListConstructor=*/true,
3769  IsListInit);
3770  }
3771 
3772  // C++11 [over.match.list]p1:
3773  // - If no viable initializer-list constructor is found, overload resolution
3774  // is performed again, where the candidate functions are all the
3775  // constructors of the class T and the argument list consists of the
3776  // elements of the initializer list.
3777  if (Result == OR_No_Viable_Function) {
3778  AsInitializerList = false;
3779  Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3780  CandidateSet, DestType, Ctors, Best,
3781  CopyInitialization, AllowExplicit,
3782  /*OnlyListConstructors=*/false,
3783  IsListInit);
3784  }
3785  if (Result) {
3786  Sequence.SetOverloadFailure(IsListInit ?
3789  Result);
3790  return;
3791  }
3792 
3793  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3794 
3795  // In C++17, ResolveConstructorOverload can select a conversion function
3796  // instead of a constructor.
3797  if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3798  // Add the user-defined conversion step that calls the conversion function.
3799  QualType ConvType = CD->getConversionType();
3800  assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3801  "should not have selected this conversion function");
3802  Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3803  HadMultipleCandidates);
3804  if (!S.Context.hasSameType(ConvType, DestType))
3805  Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3806  if (IsListInit)
3807  Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3808  return;
3809  }
3810 
3811  // C++11 [dcl.init]p6:
3812  // If a program calls for the default initialization of an object
3813  // of a const-qualified type T, T shall be a class type with a
3814  // user-provided default constructor.
3815  // C++ core issue 253 proposal:
3816  // If the implicit default constructor initializes all subobjects, no
3817  // initializer should be required.
3818  // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3819  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3820  if (Kind.getKind() == InitializationKind::IK_Default &&
3821  Entity.getType().isConstQualified()) {
3822  if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3823  if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3825  return;
3826  }
3827  }
3828 
3829  // C++11 [over.match.list]p1:
3830  // In copy-list-initialization, if an explicit constructor is chosen, the
3831  // initializer is ill-formed.
3832  if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3834  return;
3835  }
3836 
3837  // Add the constructor initialization step. Any cv-qualification conversion is
3838  // subsumed by the initialization.
3840  Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
3841  IsListInit | IsInitListCopy, AsInitializerList);
3842 }
3843 
3844 static bool
3846  Expr *Initializer,
3847  QualType &SourceType,
3848  QualType &UnqualifiedSourceType,
3849  QualType UnqualifiedTargetType,
3850  InitializationSequence &Sequence) {
3851  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3852  S.Context.OverloadTy) {
3853  DeclAccessPair Found;
3854  bool HadMultipleCandidates = false;
3855  if (FunctionDecl *Fn
3856  = S.ResolveAddressOfOverloadedFunction(Initializer,
3857  UnqualifiedTargetType,
3858  false, Found,
3859  &HadMultipleCandidates)) {
3860  Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3861  HadMultipleCandidates);
3862  SourceType = Fn->getType();
3863  UnqualifiedSourceType = SourceType.getUnqualifiedType();
3864  } else if (!UnqualifiedTargetType->isRecordType()) {
3866  return true;
3867  }
3868  }
3869  return false;
3870 }
3871 
3872 static void TryReferenceInitializationCore(Sema &S,
3873  const InitializedEntity &Entity,
3874  const InitializationKind &Kind,
3875  Expr *Initializer,
3876  QualType cv1T1, QualType T1,
3877  Qualifiers T1Quals,
3878  QualType cv2T2, QualType T2,
3879  Qualifiers T2Quals,
3880  InitializationSequence &Sequence);
3881 
3882 static void TryValueInitialization(Sema &S,
3883  const InitializedEntity &Entity,
3884  const InitializationKind &Kind,
3885  InitializationSequence &Sequence,
3886  InitListExpr *InitList = nullptr);
3887 
3888 /// \brief Attempt list initialization of a reference.
3890  const InitializedEntity &Entity,
3891  const InitializationKind &Kind,
3892  InitListExpr *InitList,
3893  InitializationSequence &Sequence,
3894  bool TreatUnavailableAsInvalid) {
3895  // First, catch C++03 where this isn't possible.
3896  if (!S.getLangOpts().CPlusPlus11) {
3898  return;
3899  }
3900  // Can't reference initialize a compound literal.
3903  return;
3904  }
3905 
3906  QualType DestType = Entity.getType();
3907  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3908  Qualifiers T1Quals;
3909  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3910 
3911  // Reference initialization via an initializer list works thus:
3912  // If the initializer list consists of a single element that is
3913  // reference-related to the referenced type, bind directly to that element
3914  // (possibly creating temporaries).
3915  // Otherwise, initialize a temporary with the initializer list and
3916  // bind to that.
3917  if (InitList->getNumInits() == 1) {
3918  Expr *Initializer = InitList->getInit(0);
3919  QualType cv2T2 = Initializer->getType();
3920  Qualifiers T2Quals;
3921  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3922 
3923  // If this fails, creating a temporary wouldn't work either.
3924  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3925  T1, Sequence))
3926  return;
3927 
3928  SourceLocation DeclLoc = Initializer->getLocStart();
3929  bool dummy1, dummy2, dummy3;
3930  Sema::ReferenceCompareResult RefRelationship
3931  = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3932  dummy2, dummy3);
3933  if (RefRelationship >= Sema::Ref_Related) {
3934  // Try to bind the reference here.
3935  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3936  T1Quals, cv2T2, T2, T2Quals, Sequence);
3937  if (Sequence)
3938  Sequence.RewrapReferenceInitList(cv1T1, InitList);
3939  return;
3940  }
3941 
3942  // Update the initializer if we've resolved an overloaded function.
3943  if (Sequence.step_begin() != Sequence.step_end())
3944  Sequence.RewrapReferenceInitList(cv1T1, InitList);
3945  }
3946 
3947  // Not reference-related. Create a temporary and bind to that.
3949 
3950  TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3951  TreatUnavailableAsInvalid);
3952  if (Sequence) {
3953  if (DestType->isRValueReferenceType() ||
3954  (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3955  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3956  else
3957  Sequence.SetFailed(
3959  }
3960 }
3961 
3962 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3964  const InitializedEntity &Entity,
3965  const InitializationKind &Kind,
3966  InitListExpr *InitList,
3967  InitializationSequence &Sequence,
3968  bool TreatUnavailableAsInvalid) {
3969  QualType DestType = Entity.getType();
3970 
3971  // C++ doesn't allow scalar initialization with more than one argument.
3972  // But C99 complex numbers are scalars and it makes sense there.
3973  if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3974  !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3976  return;
3977  }
3978  if (DestType->isReferenceType()) {
3979  TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
3980  TreatUnavailableAsInvalid);
3981  return;
3982  }
3983 
3984  if (DestType->isRecordType() &&
3985  !S.isCompleteType(InitList->getLocStart(), DestType)) {
3986  Sequence.setIncompleteTypeFailure(DestType);
3987  return;
3988  }
3989 
3990  // C++11 [dcl.init.list]p3, per DR1467:
3991  // - If T is a class type and the initializer list has a single element of
3992  // type cv U, where U is T or a class derived from T, the object is
3993  // initialized from that element (by copy-initialization for
3994  // copy-list-initialization, or by direct-initialization for
3995  // direct-list-initialization).
3996  // - Otherwise, if T is a character array and the initializer list has a
3997  // single element that is an appropriately-typed string literal
3998  // (8.5.2 [dcl.init.string]), initialization is performed as described
3999  // in that section.
4000  // - Otherwise, if T is an aggregate, [...] (continue below).
4001  if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4002  if (DestType->isRecordType()) {
4003  QualType InitType = InitList->getInit(0)->getType();
4004  if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4005  S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
4006  Expr *InitListAsExpr = InitList;
4007  TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4008  DestType, Sequence,
4009  /*InitListSyntax*/false,
4010  /*IsInitListCopy*/true);
4011  return;
4012  }
4013  }
4014  if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4015  Expr *SubInit[1] = {InitList->getInit(0)};
4016  if (!isa<VariableArrayType>(DestAT) &&
4017  IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4018  InitializationKind SubKind =
4021  InitList->getLBraceLoc(),
4022  InitList->getRBraceLoc())
4023  : Kind;
4024  Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4025  /*TopLevelOfInitList*/ true,
4026  TreatUnavailableAsInvalid);
4027 
4028  // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4029  // the element is not an appropriately-typed string literal, in which
4030  // case we should proceed as in C++11 (below).
4031  if (Sequence) {
4032  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4033  return;
4034  }
4035  }
4036  }
4037  }
4038 
4039  // C++11 [dcl.init.list]p3:
4040  // - If T is an aggregate, aggregate initialization is performed.
4041  if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4042  (S.getLangOpts().CPlusPlus11 &&
4043  S.isStdInitializerList(DestType, nullptr))) {
4044  if (S.getLangOpts().CPlusPlus11) {
4045  // - Otherwise, if the initializer list has no elements and T is a
4046  // class type with a default constructor, the object is
4047  // value-initialized.
4048  if (InitList->getNumInits() == 0) {
4049  CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4050  if (RD->hasDefaultConstructor()) {
4051  TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4052  return;
4053  }
4054  }
4055 
4056  // - Otherwise, if T is a specialization of std::initializer_list<E>,
4057  // an initializer_list object constructed [...]
4058  if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4059  TreatUnavailableAsInvalid))
4060  return;
4061 
4062  // - Otherwise, if T is a class type, constructors are considered.
4063  Expr *InitListAsExpr = InitList;
4064  TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4065  DestType, Sequence, /*InitListSyntax*/true);
4066  } else
4068  return;
4069  }
4070 
4071  if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4072  InitList->getNumInits() == 1) {
4073  Expr *E = InitList->getInit(0);
4074 
4075  // - Otherwise, if T is an enumeration with a fixed underlying type,
4076  // the initializer-list has a single element v, and the initialization
4077  // is direct-list-initialization, the object is initialized with the
4078  // value T(v); if a narrowing conversion is required to convert v to
4079  // the underlying type of T, the program is ill-formed.
4080  auto *ET = DestType->getAs<EnumType>();
4081  if (S.getLangOpts().CPlusPlus1z &&
4083  ET && ET->getDecl()->isFixed() &&
4084  !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4086  E->getType()->isFloatingType())) {
4087  // There are two ways that T(v) can work when T is an enumeration type.
4088  // If there is either an implicit conversion sequence from v to T or
4089  // a conversion function that can convert from v to T, then we use that.
4090  // Otherwise, if v is of integral, enumeration, or floating-point type,
4091  // it is converted to the enumeration type via its underlying type.
4092  // There is no overlap possible between these two cases (except when the
4093  // source value is already of the destination type), and the first
4094  // case is handled by the general case for single-element lists below.
4096  ICS.setStandard();
4098  if (!E->isRValue())
4100  // If E is of a floating-point type, then the conversion is ill-formed
4101  // due to narrowing, but go through the motions in order to produce the
4102  // right diagnostic.
4103  ICS.Standard.Second = E->getType()->isFloatingType()
4106  ICS.Standard.setFromType(E->getType());
4107  ICS.Standard.setToType(0, E->getType());
4108  ICS.Standard.setToType(1, DestType);
4109  ICS.Standard.setToType(2, DestType);
4110  Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4111  /*TopLevelOfInitList*/true);
4112  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4113  return;
4114  }
4115 
4116  // - Otherwise, if the initializer list has a single element of type E
4117  // [...references are handled above...], the object or reference is
4118  // initialized from that element (by copy-initialization for
4119  // copy-list-initialization, or by direct-initialization for
4120  // direct-list-initialization); if a narrowing conversion is required
4121  // to convert the element to T, the program is ill-formed.
4122  //
4123  // Per core-24034, this is direct-initialization if we were performing
4124  // direct-list-initialization and copy-initialization otherwise.
4125  // We can't use InitListChecker for this, because it always performs
4126  // copy-initialization. This only matters if we might use an 'explicit'
4127  // conversion operator, so we only need to handle the cases where the source
4128  // is of record type.
4129  if (InitList->getInit(0)->getType()->isRecordType()) {
4130  InitializationKind SubKind =
4133  InitList->getLBraceLoc(),
4134  InitList->getRBraceLoc())
4135  : Kind;
4136  Expr *SubInit[1] = { InitList->getInit(0) };
4137  Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4138  /*TopLevelOfInitList*/true,
4139  TreatUnavailableAsInvalid);
4140  if (Sequence)
4141  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4142  return;
4143  }
4144  }
4145 
4146  InitListChecker CheckInitList(S, Entity, InitList,
4147  DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4148  if (CheckInitList.HadError()) {
4150  return;
4151  }
4152 
4153  // Add the list initialization step with the built init list.
4154  Sequence.AddListInitializationStep(DestType);
4155 }
4156 
4157 /// \brief Try a reference initialization that involves calling a conversion
4158 /// function.
4160  Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4161  Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4162  InitializationSequence &Sequence) {
4163  QualType DestType = Entity.getType();
4164  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4165  QualType T1 = cv1T1.getUnqualifiedType();
4166  QualType cv2T2 = Initializer->getType();
4167  QualType T2 = cv2T2.getUnqualifiedType();
4168 
4169  bool DerivedToBase;
4170  bool ObjCConversion;
4171  bool ObjCLifetimeConversion;
4172  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
4173  T1, T2, DerivedToBase,
4174  ObjCConversion,
4175  ObjCLifetimeConversion) &&
4176  "Must have incompatible references when binding via conversion");
4177  (void)DerivedToBase;
4178  (void)ObjCConversion;
4179  (void)ObjCLifetimeConversion;
4180 
4181  // Build the candidate set directly in the initialization sequence
4182  // structure, so that it will persist if we fail.
4183  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4185 
4186  // Determine whether we are allowed to call explicit constructors or
4187  // explicit conversion operators.
4188  bool AllowExplicit = Kind.AllowExplicit();
4189  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4190 
4191  const RecordType *T1RecordType = nullptr;
4192  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4193  S.isCompleteType(Kind.getLocation(), T1)) {
4194  // The type we're converting to is a class type. Enumerate its constructors
4195  // to see if there is a suitable conversion.
4196  CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4197 
4198  for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4199  auto Info = getConstructorInfo(D);
4200  if (!Info.Constructor)
4201  continue;
4202 
4203  if (!Info.Constructor->isInvalidDecl() &&
4204  Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4205  if (Info.ConstructorTmpl)
4206  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4207  /*ExplicitArgs*/ nullptr,
4208  Initializer, CandidateSet,
4209  /*SuppressUserConversions=*/true);
4210  else
4211  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4212  Initializer, CandidateSet,
4213  /*SuppressUserConversions=*/true);
4214  }
4215  }
4216  }
4217  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4218  return OR_No_Viable_Function;
4219 
4220  const RecordType *T2RecordType = nullptr;
4221  if ((T2RecordType = T2->getAs<RecordType>()) &&
4222  S.isCompleteType(Kind.getLocation(), T2)) {
4223  // The type we're converting from is a class type, enumerate its conversion
4224  // functions.
4225  CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4226 
4227  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4228  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4229  NamedDecl *D = *I;
4230  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4231  if (isa<UsingShadowDecl>(D))
4232  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4233 
4234  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4235  CXXConversionDecl *Conv;
4236  if (ConvTemplate)
4237  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4238  else
4239  Conv = cast<CXXConversionDecl>(D);
4240 
4241  // If the conversion function doesn't return a reference type,
4242  // it can't be considered for this conversion unless we're allowed to
4243  // consider rvalues.
4244  // FIXME: Do we need to make sure that we only consider conversion
4245  // candidates with reference-compatible results? That might be needed to
4246  // break recursion.
4247  if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4248  (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4249  if (ConvTemplate)
4250  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4251  ActingDC, Initializer,
4252  DestType, CandidateSet,
4253  /*AllowObjCConversionOnExplicit=*/
4254  false);
4255  else
4256  S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4257  Initializer, DestType, CandidateSet,
4258  /*AllowObjCConversionOnExplicit=*/false);
4259  }
4260  }
4261  }
4262  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4263  return OR_No_Viable_Function;
4264 
4265  SourceLocation DeclLoc = Initializer->getLocStart();
4266 
4267  // Perform overload resolution. If it fails, return the failed result.
4270  = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4271  return Result;
4272 
4273  FunctionDecl *Function = Best->Function;
4274  // This is the overload that will be used for this initialization step if we
4275  // use this initialization. Mark it as referenced.
4276  Function->setReferenced();
4277 
4278  // Compute the returned type and value kind of the conversion.
4279  QualType cv3T3;
4280  if (isa<CXXConversionDecl>(Function))
4281  cv3T3 = Function->getReturnType();
4282  else
4283  cv3T3 = T1;
4284 
4285  ExprValueKind VK = VK_RValue;
4286  if (cv3T3->isLValueReferenceType())
4287  VK = VK_LValue;
4288  else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4289  VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4290  cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4291 
4292  // Add the user-defined conversion step.
4293  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4294  Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4295  HadMultipleCandidates);
4296 
4297  // Determine whether we'll need to perform derived-to-base adjustments or
4298  // other conversions.
4299  bool NewDerivedToBase = false;
4300  bool NewObjCConversion = false;
4301  bool NewObjCLifetimeConversion = false;
4302  Sema::ReferenceCompareResult NewRefRelationship
4303  = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4304  NewDerivedToBase, NewObjCConversion,
4305  NewObjCLifetimeConversion);
4306 
4307  // Add the final conversion sequence, if necessary.
4308  if (NewRefRelationship == Sema::Ref_Incompatible) {
4309  assert(!isa<CXXConstructorDecl>(Function) &&
4310  "should not have conversion after constructor");
4311 
4313  ICS.setStandard();
4314  ICS.Standard = Best->FinalConversion;
4315  Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4316 
4317  // Every implicit conversion results in a prvalue, except for a glvalue
4318  // derived-to-base conversion, which we handle below.
4319  cv3T3 = ICS.Standard.getToType(2);
4320  VK = VK_RValue;
4321  }
4322 
4323  // If the converted initializer is a prvalue, its type T4 is adjusted to
4324  // type "cv1 T4" and the temporary materialization conversion is applied.
4325  //
4326  // We adjust the cv-qualifications to match the reference regardless of
4327  // whether we have a prvalue so that the AST records the change. In this
4328  // case, T4 is "cv3 T3".
4329  QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4330  if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4331  Sequence.AddQualificationConversionStep(cv1T4, VK);
4332  Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4333  VK = IsLValueRef ? VK_LValue : VK_XValue;
4334 
4335  if (NewDerivedToBase)
4336  Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4337  else if (NewObjCConversion)
4338  Sequence.AddObjCObjectConversionStep(cv1T1);
4339 
4340  return OR_Success;
4341 }
4342 
4343 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4344  const InitializedEntity &Entity,
4345  Expr *CurInitExpr);
4346 
4347 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4349  const InitializedEntity &Entity,
4350  const InitializationKind &Kind,
4351  Expr *Initializer,
4352  InitializationSequence &Sequence) {
4353  QualType DestType = Entity.getType();
4354  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4355  Qualifiers T1Quals;
4356  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4357  QualType cv2T2 = Initializer->getType();
4358  Qualifiers T2Quals;
4359  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4360 
4361  // If the initializer is the address of an overloaded function, try
4362  // to resolve the overloaded function. If all goes well, T2 is the
4363  // type of the resulting function.
4364  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4365  T1, Sequence))
4366  return;
4367 
4368  // Delegate everything else to a subfunction.
4369  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4370  T1Quals, cv2T2, T2, T2Quals, Sequence);
4371 }
4372 
4373 /// Determine whether an expression is a non-referenceable glvalue (one to
4374 /// which a reference can never bind). Attemting to bind a reference to
4375 /// such a glvalue will always create a temporary.
4377  return E->refersToBitField() || E->refersToVectorElement();
4378 }
4379 
4380 /// \brief Reference initialization without resolving overloaded functions.
4382  const InitializedEntity &Entity,
4383  const InitializationKind &Kind,
4384  Expr *Initializer,
4385  QualType cv1T1, QualType T1,
4386  Qualifiers T1Quals,
4387  QualType cv2T2, QualType T2,
4388  Qualifiers T2Quals,
4389  InitializationSequence &Sequence) {
4390  QualType DestType = Entity.getType();
4391  SourceLocation DeclLoc = Initializer->getLocStart();
4392  // Compute some basic properties of the types and the initializer.
4393  bool isLValueRef = DestType->isLValueReferenceType();
4394  bool isRValueRef = !isLValueRef;
4395  bool DerivedToBase = false;
4396  bool ObjCConversion = false;
4397  bool ObjCLifetimeConversion = false;
4398  Expr::Classification InitCategory = Initializer->Classify(S.Context);
4399  Sema::ReferenceCompareResult RefRelationship
4400  = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4401  ObjCConversion, ObjCLifetimeConversion);
4402 
4403  // C++0x [dcl.init.ref]p5:
4404  // A reference to type "cv1 T1" is initialized by an expression of type
4405  // "cv2 T2" as follows:
4406  //
4407  // - If the reference is an lvalue reference and the initializer
4408  // expression
4409  // Note the analogous bullet points for rvalue refs to functions. Because
4410  // there are no function rvalues in C++, rvalue refs to functions are treated
4411  // like lvalue refs.
4412  OverloadingResult ConvOvlResult = OR_Success;
4413  bool T1Function = T1->isFunctionType();
4414  if (isLValueRef || T1Function) {
4415  if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4416  (RefRelationship == Sema::Ref_Compatible ||
4417  (Kind.isCStyleOrFunctionalCast() &&
4418  RefRelationship == Sema::Ref_Related))) {
4419  // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4420  // reference-compatible with "cv2 T2," or
4421  if (T1Quals != T2Quals)
4422  // Convert to cv1 T2. This should only add qualifiers unless this is a
4423  // c-style cast. The removal of qualifiers in that case notionally
4424  // happens after the reference binding, but that doesn't matter.
4426  S.Context.getQualifiedType(T2, T1Quals),
4427  Initializer->getValueKind());
4428  if (DerivedToBase)
4429  Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4430  else if (ObjCConversion)
4431  Sequence.AddObjCObjectConversionStep(cv1T1);
4432 
4433  // We only create a temporary here when binding a reference to a
4434  // bit-field or vector element. Those cases are't supposed to be
4435  // handled by this bullet, but the outcome is the same either way.
4436  Sequence.AddReferenceBindingStep(cv1T1, false);
4437  return;
4438  }
4439 
4440  // - has a class type (i.e., T2 is a class type), where T1 is not
4441  // reference-related to T2, and can be implicitly converted to an
4442  // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4443  // with "cv3 T3" (this conversion is selected by enumerating the
4444  // applicable conversion functions (13.3.1.6) and choosing the best
4445  // one through overload resolution (13.3)),
4446  // If we have an rvalue ref to function type here, the rhs must be
4447  // an rvalue. DR1287 removed the "implicitly" here.
4448  if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4449  (isLValueRef || InitCategory.isRValue())) {
4450  ConvOvlResult = TryRefInitWithConversionFunction(
4451  S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4452  /*IsLValueRef*/ isLValueRef, Sequence);
4453  if (ConvOvlResult == OR_Success)
4454  return;
4455  if (ConvOvlResult != OR_No_Viable_Function)
4456  Sequence.SetOverloadFailure(
4458  ConvOvlResult);
4459  }
4460  }
4461 
4462  // - Otherwise, the reference shall be an lvalue reference to a
4463  // non-volatile const type (i.e., cv1 shall be const), or the reference
4464  // shall be an rvalue reference.
4465  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4466  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4468  else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4469  Sequence.SetOverloadFailure(
4471  ConvOvlResult);
4472  else if (!InitCategory.isLValue())
4473  Sequence.SetFailed(
4475  else {
4477  switch (RefRelationship) {
4478  case Sema::Ref_Compatible:
4479  if (Initializer->refersToBitField())
4480  FK = InitializationSequence::
4481  FK_NonConstLValueReferenceBindingToBitfield;
4482  else if (Initializer->refersToVectorElement())
4483  FK = InitializationSequence::
4484  FK_NonConstLValueReferenceBindingToVectorElement;
4485  else
4486  llvm_unreachable("unexpected kind of compatible initializer");
4487  break;
4488  case Sema::Ref_Related:
4490  break;
4494  break;
4495  }
4496  Sequence.SetFailed(FK);
4497  }
4498  return;
4499  }
4500 
4501  // - If the initializer expression
4502  // - is an
4503  // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4504  // [1z] rvalue (but not a bit-field) or
4505  // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4506  //
4507  // Note: functions are handled above and below rather than here...
4508  if (!T1Function &&
4509  (RefRelationship == Sema::Ref_Compatible ||
4510  (Kind.isCStyleOrFunctionalCast() &&
4511  RefRelationship == Sema::Ref_Related)) &&
4512  ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4513  (InitCategory.isPRValue() &&
4514  (S.getLangOpts().CPlusPlus1z || T2->isRecordType() ||
4515  T2->isArrayType())))) {
4516  ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
4517  if (InitCategory.isPRValue() && T2->isRecordType()) {
4518  // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4519  // compiler the freedom to perform a copy here or bind to the
4520  // object, while C++0x requires that we bind directly to the
4521  // object. Hence, we always bind to the object without making an
4522  // extra copy. However, in C++03 requires that we check for the
4523  // presence of a suitable copy constructor:
4524  //
4525  // The constructor that would be used to make the copy shall
4526  // be callable whether or not the copy is actually done.
4527  if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4528  Sequence.AddExtraneousCopyToTemporary(cv2T2);
4529  else if (S.getLangOpts().CPlusPlus11)
4530  CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4531  }
4532 
4533  // C++1z [dcl.init.ref]/5.2.1.2:
4534  // If the converted initializer is a prvalue, its type T4 is adjusted
4535  // to type "cv1 T4" and the temporary materialization conversion is
4536  // applied.
4537  QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4538  if (T1Quals != T2Quals)
4539  Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4540  Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4541  ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4542 
4543  // In any case, the reference is bound to the resulting glvalue (or to
4544  // an appropriate base class subobject).
4545  if (DerivedToBase)
4546  Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4547  else if (ObjCConversion)
4548  Sequence.AddObjCObjectConversionStep(cv1T1);
4549  return;
4550  }
4551 
4552  // - has a class type (i.e., T2 is a class type), where T1 is not
4553  // reference-related to T2, and can be implicitly converted to an
4554  // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4555  // where "cv1 T1" is reference-compatible with "cv3 T3",
4556  //
4557  // DR1287 removes the "implicitly" here.
4558  if (T2->isRecordType()) {
4559  if (RefRelationship == Sema::Ref_Incompatible) {
4560  ConvOvlResult = TryRefInitWithConversionFunction(
4561  S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4562  /*IsLValueRef*/ isLValueRef, Sequence);
4563  if (ConvOvlResult)
4564  Sequence.SetOverloadFailure(
4566  ConvOvlResult);
4567 
4568  return;
4569  }
4570 
4571  if (RefRelationship == Sema::Ref_Compatible &&
4572  isRValueRef && InitCategory.isLValue()) {
4573  Sequence.SetFailed(
4575  return;
4576  }
4577 
4579  return;
4580  }
4581 
4582  // - Otherwise, a temporary of type "cv1 T1" is created and initialized
4583  // from the initializer expression using the rules for a non-reference
4584  // copy-initialization (8.5). The reference is then bound to the
4585  // temporary. [...]
4586 
4588 
4589  // FIXME: Why do we use an implicit conversion here rather than trying
4590  // copy-initialization?
4592  = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4593  /*SuppressUserConversions=*/false,
4594  /*AllowExplicit=*/false,
4595  /*FIXME:InOverloadResolution=*/false,
4596  /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4597  /*AllowObjCWritebackConversion=*/false);
4598 
4599  if (ICS.isBad()) {
4600  // FIXME: Use the conversion function set stored in ICS to turn
4601  // this into an overloading ambiguity diagnostic. However, we need
4602  // to keep that set as an OverloadCandidateSet rather than as some
4603  // other kind of set.
4604  if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4605  Sequence.SetOverloadFailure(
4607  ConvOvlResult);
4608  else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4610  else
4612  return;
4613  } else {
4614  Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4615  }
4616 
4617  // [...] If T1 is reference-related to T2, cv1 must be the
4618  // same cv-qualification as, or greater cv-qualification
4619  // than, cv2; otherwise, the program is ill-formed.
4620  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4621  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4622  if (RefRelationship == Sema::Ref_Related &&
4623  (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4625  return;
4626  }
4627 
4628  // [...] If T1 is reference-related to T2 and the reference is an rvalue
4629  // reference, the initializer expression shall not be an lvalue.
4630  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4631  InitCategory.isLValue()) {
4632  Sequence.SetFailed(
4634  return;
4635  }
4636 
4637  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4638 }
4639 
4640 /// \brief Attempt character array initialization from a string literal
4641 /// (C++ [dcl.init.string], C99 6.7.8).
4643  const InitializedEntity &Entity,
4644  const InitializationKind &Kind,
4645  Expr *Initializer,
4646  InitializationSequence &Sequence) {
4647  Sequence.AddStringInitStep(Entity.getType());
4648 }
4649 
4650 /// \brief Attempt value initialization (C++ [dcl.init]p7).
4652  const InitializedEntity &Entity,
4653  const InitializationKind &Kind,
4654  InitializationSequence &Sequence,
4655  InitListExpr *InitList) {
4656  assert((!InitList || InitList->getNumInits() == 0) &&
4657  "Shouldn't use value-init for non-empty init lists");
4658 
4659  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4660  //
4661  // To value-initialize an object of type T means:
4662  QualType T = Entity.getType();
4663 
4664  // -- if T is an array type, then each element is value-initialized;
4665  T = S.Context.getBaseElementType(T);
4666 
4667  if (const RecordType *RT = T->getAs<RecordType>()) {
4668  if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4669  bool NeedZeroInitialization = true;
4670  // C++98:
4671  // -- if T is a class type (clause 9) with a user-declared constructor
4672  // (12.1), then the default constructor for T is called (and the
4673  // initialization is ill-formed if T has no accessible default
4674  // constructor);
4675  // C++11:
4676  // -- if T is a class type (clause 9) with either no default constructor
4677  // (12.1 [class.ctor]) or a default constructor that is user-provided
4678  // or deleted, then the object is default-initialized;
4679  //
4680  // Note that the C++11 rule is the same as the C++98 rule if there are no
4681  // defaulted or deleted constructors, so we just use it unconditionally.
4682  CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4683  if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4684  NeedZeroInitialization = false;
4685 
4686  // -- if T is a (possibly cv-qualified) non-union class type without a
4687  // user-provided or deleted default constructor, then the object is
4688  // zero-initialized and, if T has a non-trivial default constructor,
4689  // default-initialized;
4690  // The 'non-union' here was removed by DR1502. The 'non-trivial default
4691  // constructor' part was removed by DR1507.
4692  if (NeedZeroInitialization)
4693  Sequence.AddZeroInitializationStep(Entity.getType());
4694 
4695  // C++03:
4696  // -- if T is a non-union class type without a user-declared constructor,
4697  // then every non-static data member and base class component of T is
4698  // value-initialized;
4699  // [...] A program that calls for [...] value-initialization of an
4700  // entity of reference type is ill-formed.
4701  //
4702  // C++11 doesn't need this handling, because value-initialization does not
4703  // occur recursively there, and the implicit default constructor is
4704  // defined as deleted in the problematic cases.
4705  if (!S.getLangOpts().CPlusPlus11 &&
4706  ClassDecl->hasUninitializedReferenceMember()) {
4708  return;
4709  }
4710 
4711  // If this is list-value-initialization, pass the empty init list on when
4712  // building the constructor call. This affects the semantics of a few
4713  // things (such as whether an explicit default constructor can be called).
4714  Expr *InitListAsExpr = InitList;
4715  MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4716  bool InitListSyntax = InitList;
4717 
4718  // FIXME: Instead of creating a CXXConstructExpr of array type here,
4719  // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4721  S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4722  }
4723  }
4724 
4725  Sequence.AddZeroInitializationStep(Entity.getType());
4726 }
4727 
4728 /// \brief Attempt default initialization (C++ [dcl.init]p6).
4730  const InitializedEntity &Entity,
4731  const InitializationKind &Kind,
4732  InitializationSequence &Sequence) {
4733  assert(Kind.getKind() == InitializationKind::IK_Default);
4734 
4735  // C++ [dcl.init]p6:
4736  // To default-initialize an object of type T means:
4737  // - if T is an array type, each element is default-initialized;
4738  QualType DestType = S.Context.getBaseElementType(Entity.getType());
4739 
4740  // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4741  // constructor for T is called (and the initialization is ill-formed if
4742  // T has no accessible default constructor);
4743  if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4744  TryConstructorInitialization(S, Entity, Kind, None, DestType,
4745  Entity.getType(), Sequence);
4746  return;
4747  }
4748 
4749  // - otherwise, no initialization is performed.
4750 
4751  // If a program calls for the default initialization of an object of
4752  // a const-qualified type T, T shall be a class type with a user-provided
4753  // default constructor.
4754  if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4755  if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4757  return;
4758  }
4759 
4760  // If the destination type has a lifetime property, zero-initialize it.
4761  if (DestType.getQualifiers().hasObjCLifetime()) {
4762  Sequence.AddZeroInitializationStep(Entity.getType());
4763  return;
4764  }
4765 }
4766 
4767 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4768 /// which enumerates all conversion functions and performs overload resolution
4769 /// to select the best.
4771  QualType DestType,
4772  const InitializationKind &Kind,
4773  Expr *Initializer,
4774  InitializationSequence &Sequence,
4775  bool TopLevelOfInitList) {
4776  assert(!DestType->isReferenceType() && "References are handled elsewhere");
4777  QualType SourceType = Initializer->getType();
4778  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4779  "Must have a class type to perform a user-defined conversion");
4780 
4781  // Build the candidate set directly in the initialization sequence
4782  // structure, so that it will persist if we fail.
4783  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4785 
4786  // Determine whether we are allowed to call explicit constructors or
4787  // explicit conversion operators.
4788  bool AllowExplicit = Kind.AllowExplicit();
4789 
4790  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4791  // The type we're converting to is a class type. Enumerate its constructors
4792  // to see if there is a suitable conversion.
4793  CXXRecordDecl *DestRecordDecl
4794  = cast<CXXRecordDecl>(DestRecordType->getDecl());
4795 
4796  // Try to complete the type we're converting to.
4797  if (S.isCompleteType(Kind.getLocation(), DestType)) {
4798  for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
4799  auto Info = getConstructorInfo(D);
4800  if (!Info.Constructor)
4801  continue;
4802 
4803  if (!Info.Constructor->isInvalidDecl() &&
4804  Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4805  if (Info.ConstructorTmpl)
4806  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4807  /*ExplicitArgs*/ nullptr,
4808  Initializer, CandidateSet,
4809  /*SuppressUserConversions=*/true);
4810  else
4811  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4812  Initializer, CandidateSet,
4813  /*SuppressUserConversions=*/true);
4814  }
4815  }
4816  }
4817  }
4818 
4819  SourceLocation DeclLoc = Initializer->getLocStart();
4820 
4821  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4822  // The type we're converting from is a class type, enumerate its conversion
4823  // functions.
4824 
4825  // We can only enumerate the conversion functions for a complete type; if
4826  // the type isn't complete, simply skip this step.
4827  if (S.isCompleteType(DeclLoc, SourceType)) {
4828  CXXRecordDecl *SourceRecordDecl
4829  = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4830 
4831  const auto &Conversions =
4832  SourceRecordDecl->getVisibleConversionFunctions();
4833  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4834  NamedDecl *D = *I;
4835  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4836  if (isa<UsingShadowDecl>(D))
4837  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4838 
4839  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4840  CXXConversionDecl *Conv;
4841  if (ConvTemplate)
4842  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4843  else
4844  Conv = cast<CXXConversionDecl>(D);
4845 
4846  if (AllowExplicit || !Conv->isExplicit()) {
4847  if (ConvTemplate)
4848  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4849  ActingDC, Initializer, DestType,
4850  CandidateSet, AllowExplicit);
4851  else
4852  S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4853  Initializer, DestType, CandidateSet,
4854  AllowExplicit);
4855  }
4856  }
4857  }
4858  }
4859 
4860  // Perform overload resolution. If it fails, return the failed result.
4863  = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4864  Sequence.SetOverloadFailure(
4866  Result);
4867  return;
4868  }
4869 
4870  FunctionDecl *Function = Best->Function;
4871  Function->setReferenced();
4872  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4873 
4874  if (isa<CXXConstructorDecl>(Function)) {
4875  // Add the user-defined conversion step. Any cv-qualification conversion is
4876  // subsumed by the initialization. Per DR5, the created temporary is of the
4877  // cv-unqualified type of the destination.
4878  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4879  DestType.getUnqualifiedType(),
4880  HadMultipleCandidates);
4881 
4882  // C++14 and before:
4883  // - if the function is a constructor, the call initializes a temporary
4884  // of the cv-unqualified version of the destination type. The [...]
4885  // temporary [...] is then used to direct-initialize, according to the
4886  // rules above, the object that is the destination of the
4887  // copy-initialization.
4888  // Note that this just performs a simple object copy from the temporary.
4889  //
4890  // C++1z:
4891  // - if the function is a constructor, the call is a prvalue of the
4892  // cv-unqualified version of the destination type whose return object
4893  // is initialized by the constructor. The call is used to
4894  // direct-initialize, according to the rules above, the object that
4895  // is the destination of the copy-initialization.
4896  // Therefore we need to do nothing further.
4897  //
4898  // FIXME: Mark this copy as extraneous.
4899  if (!S.getLangOpts().CPlusPlus1z)
4900  Sequence.AddFinalCopy(DestType);
4901  else if (DestType.hasQualifiers())
4902  Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4903  return;
4904  }
4905 
4906  // Add the user-defined conversion step that calls the conversion function.
4907  QualType ConvType = Function->getCallResultType();
4908  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4909  HadMultipleCandidates);
4910 
4911  if (ConvType->getAs<RecordType>()) {
4912  // The call is used to direct-initialize [...] the object that is the
4913  // destination of the copy-initialization.
4914  //
4915  // In C++1z, this does not call a constructor if we enter /17.6.1:
4916  // - If the initializer expression is a prvalue and the cv-unqualified
4917  // version of the source type is the same as the class of the
4918  // destination [... do not make an extra copy]
4919  //
4920  // FIXME: Mark this copy as extraneous.
4921  if (!S.getLangOpts().CPlusPlus1z ||
4922  Function->getReturnType()->isReferenceType() ||
4923  !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4924  Sequence.AddFinalCopy(DestType);
4925  else if (!S.Context.hasSameType(ConvType, DestType))
4926  Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4927  return;
4928  }
4929 
4930  // If the conversion following the call to the conversion function
4931  // is interesting, add it as a separate step.
4932  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4933  Best->FinalConversion.Third) {
4935  ICS.setStandard();
4936  ICS.Standard = Best->FinalConversion;
4937  Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4938  }
4939 }
4940 
4941 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4942 /// a function with a pointer return type contains a 'return false;' statement.
4943 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
4944 /// code using that header.
4945 ///
4946 /// Work around this by treating 'return false;' as zero-initializing the result
4947 /// if it's used in a pointer-returning function in a system header.
4949  const InitializedEntity &Entity,
4950  const Expr *Init) {
4951  return S.getLangOpts().CPlusPlus11 &&
4952  Entity.getKind() == InitializedEntity::EK_Result &&
4953  Entity.getType()->isPointerType() &&
4954  isa<CXXBoolLiteralExpr>(Init) &&
4955  !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4957 }
4958 
4959 /// The non-zero enum values here are indexes into diagnostic alternatives.
4961 
4962 /// Determines whether this expression is an acceptable ICR source.
4964  bool isAddressOf, bool &isWeakAccess) {
4965  // Skip parens.
4966  e = e->IgnoreParens();
4967 
4968  // Skip address-of nodes.
4969  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4970  if (op->getOpcode() == UO_AddrOf)
4971  return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4972  isWeakAccess);
4973 
4974  // Skip certain casts.
4975  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4976  switch (ce->getCastKind()) {
4977  case CK_Dependent:
4978  case CK_BitCast:
4979  case CK_LValueBitCast:
4980  case CK_NoOp:
4981  return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4982 
4983  case CK_ArrayToPointerDecay:
4984  return IIK_nonscalar;
4985 
4986  case CK_NullToPointer:
4987  return IIK_okay;
4988 
4989  default:
4990  break;
4991  }
4992 
4993  // If we have a declaration reference, it had better be a local variable.
4994  } else if (isa<DeclRefExpr>(e)) {
4995  // set isWeakAccess to true, to mean that there will be an implicit
4996  // load which requires a cleanup.
4998  isWeakAccess = true;
4999 
5000  if (!isAddressOf) return IIK_nonlocal;
5001 
5002  VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5003  if (!var) return IIK_nonlocal;
5004 
5005  return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5006 
5007  // If we have a conditional operator, check both sides.
5008  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5009  if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5010  isWeakAccess))
5011  return iik;
5012 
5013  return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5014 
5015  // These are never scalar.
5016  } else if (isa<ArraySubscriptExpr>(e)) {
5017  return IIK_nonscalar;
5018 
5019  // Otherwise, it needs to be a null pointer constant.
5020  } else {
5022  ? IIK_okay : IIK_nonlocal);
5023  }
5024 
5025  return IIK_nonlocal;
5026 }
5027 
5028 /// Check whether the given expression is a valid operand for an
5029 /// indirect copy/restore.
5031  assert(src->isRValue());
5032  bool isWeakAccess = false;
5033  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5034  // If isWeakAccess to true, there will be an implicit
5035  // load which requires a cleanup.
5036  if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5037  S.Cleanup.setExprNeedsCleanups(true);
5038 
5039  if (iik == IIK_okay) return;
5040 
5041  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5042  << ((unsigned) iik - 1) // shift index into diagnostic explanations
5043  << src->getSourceRange();
5044 }
5045 
5046 /// \brief Determine whether we have compatible array types for the
5047 /// purposes of GNU by-copy array initialization.
5048 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5049  const ArrayType *Source) {
5050  // If the source and destination array types are equivalent, we're
5051  // done.
5052  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5053  return true;
5054 
5055  // Make sure that the element types are the same.
5056  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5057  return false;
5058 
5059  // The only mismatch we allow is when the destination is an
5060  // incomplete array type and the source is a constant array type.
5061  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5062 }
5063 
5065  InitializationSequence &Sequence,
5066  const InitializedEntity &Entity,
5067  Expr *Initializer) {
5068  bool ArrayDecay = false;
5069  QualType ArgType = Initializer->getType();
5070  QualType ArgPointee;
5071  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5072  ArrayDecay = true;
5073  ArgPointee = ArgArrayType->getElementType();
5074  ArgType = S.Context.getPointerType(ArgPointee);
5075  }
5076 
5077  // Handle write-back conversion.
5078  QualType ConvertedArgType;
5079  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5080  ConvertedArgType))
5081  return false;
5082 
5083  // We should copy unless we're passing to an argument explicitly
5084  // marked 'out'.
5085  bool ShouldCopy = true;
5086  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5087  ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5088 
5089  // Do we need an lvalue conversion?
5090  if (ArrayDecay || Initializer->isGLValue()) {
5092  ICS.setStandard();
5094 
5095  QualType ResultType;
5096  if (ArrayDecay) {
5098  ResultType = S.Context.getPointerType(ArgPointee);
5099  } else {
5101  ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5102  }
5103 
5104  Sequence.AddConversionSequenceStep(ICS, ResultType);
5105  }
5106 
5107  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5108  return true;
5109 }
5110 
5112  InitializationSequence &Sequence,
5113  QualType DestType,
5114  Expr *Initializer) {
5115  if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5116  (!Initializer->isIntegerConstantExpr(S.Context) &&
5117  !Initializer->getType()->isSamplerT()))
5118  return false;
5119 
5120  Sequence.AddOCLSamplerInitStep(DestType);
5121  return true;
5122 }
5123 
5124 //
5125 // OpenCL 1.2 spec, s6.12.10
5126 //
5127 // The event argument can also be used to associate the
5128 // async_work_group_copy with a previous async copy allowing
5129 // an event to be shared by multiple async copies; otherwise
5130 // event should be zero.
5131 //
5133  InitializationSequence &Sequence,
5134  QualType DestType,
5135  Expr *Initializer) {
5136  if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5137  !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5138  (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5139  return false;
5140 
5141  Sequence.AddOCLZeroEventStep(DestType);
5142  return true;
5143 }
5144 
5146  InitializationSequence &Sequence,
5147  QualType DestType,
5148  Expr *Initializer) {
5149  if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5150  !DestType->isQueueT() ||
5151  !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5152  (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5153  return false;
5154 
5155  Sequence.AddOCLZeroQueueStep(DestType);
5156  return true;
5157 }
5158 
5160  const InitializedEntity &Entity,
5161  const InitializationKind &Kind,
5162  MultiExprArg Args,
5163  bool TopLevelOfInitList,
5164  bool TreatUnavailableAsInvalid)
5165  : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5166  InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5167  TreatUnavailableAsInvalid);
5168 }
5169 
5170 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5171 /// address of that function, this returns true. Otherwise, it returns false.
5172 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5173  auto *DRE = dyn_cast<DeclRefExpr>(E);
5174  if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5175  return false;
5176 
5178  cast<FunctionDecl>(DRE->getDecl()));
5179 }
5180 
5181 /// Determine whether we can perform an elementwise array copy for this kind
5182 /// of entity.
5183 static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5184  switch (Entity.getKind()) {
5186  // C++ [expr.prim.lambda]p24:
5187  // For array members, the array elements are direct-initialized in
5188  // increasing subscript order.
5189  return true;
5190 
5192  // C++ [dcl.decomp]p1:
5193  // [...] each element is copy-initialized or direct-initialized from the
5194  // corresponding element of the assignment-expression [...]
5195  return isa<DecompositionDecl>(Entity.getDecl());
5196 
5198  // C++ [class.copy.ctor]p14:
5199  // - if the member is an array, each element is direct-initialized with
5200  // the corresponding subobject of x
5201  return Entity.isImplicitMemberInitializer();
5202 
5204  // All the above cases are intended to apply recursively, even though none
5205  // of them actually say that.
5206  if (auto *E = Entity.getParent())
5207  return canPerformArrayCopy(*E);
5208  break;
5209 
5210  default:
5211  break;
5212  }
5213 
5214  return false;
5215 }
5216 
5218  const InitializedEntity &Entity,
5219  const InitializationKind &Kind,
5220  MultiExprArg Args,
5221  bool TopLevelOfInitList,
5222  bool TreatUnavailableAsInvalid) {
5223  ASTContext &Context = S.Context;
5224 
5225  // Eliminate non-overload placeholder types in the arguments. We
5226  // need to do this before checking whether types are dependent
5227  // because lowering a pseudo-object expression might well give us
5228  // something of dependent type.
5229  for (unsigned I = 0, E = Args.size(); I != E; ++I)
5230  if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5231  // FIXME: should we be doing this here?
5232  ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5233  if (result.isInvalid()) {
5235  return;
5236  }
5237  Args[I] = result.get();
5238  }
5239 
5240  // C++0x [dcl.init]p16:
5241  // The semantics of initializers are as follows. The destination type is
5242  // the type of the object or reference being initialized and the source
5243  // type is the type of the initializer expression. The source type is not
5244  // defined when the initializer is a braced-init-list or when it is a
5245  // parenthesized list of expressions.
5246  QualType DestType = Entity.getType();
5247 
5248  if (DestType->isDependentType() ||
5251  return;
5252  }
5253 
5254  // Almost everything is a normal sequence.
5256 
5257  QualType SourceType;
5258  Expr *Initializer = nullptr;
5259  if (Args.size() == 1) {
5260  Initializer = Args[0];
5261  if (S.getLangOpts().ObjC1) {
5262  if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5263  DestType, Initializer->getType(),
5264  Initializer) ||
5265  S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5266  Args[0] = Initializer;
5267  }
5268  if (!isa<InitListExpr>(Initializer))
5269  SourceType = Initializer->getType();
5270  }
5271 
5272  // - If the initializer is a (non-parenthesized) braced-init-list, the
5273  // object is list-initialized (8.5.4).
5274  if (Kind.getKind() != InitializationKind::IK_Direct) {
5275  if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5276  TryListInitialization(S, Entity, Kind, InitList, *this,
5277  TreatUnavailableAsInvalid);
5278  return;
5279  }
5280  }
5281 
5282  // - If the destination type is a reference type, see 8.5.3.
5283  if (DestType->isReferenceType()) {
5284  // C++0x [dcl.init.ref]p1:
5285  // A variable declared to be a T& or T&&, that is, "reference to type T"
5286  // (8.3.2), shall be initialized by an object, or function, of type T or
5287  // by an object that can be converted into a T.
5288  // (Therefore, multiple arguments are not permitted.)
5289  if (Args.size() != 1)
5291  // C++17 [dcl.init.ref]p5:
5292  // A reference [...] is initialized by an expression [...] as follows:
5293  // If the initializer is not an expression, presumably we should reject,
5294  // but the standard fails to actually say so.
5295  else if (isa<InitListExpr>(Args[0]))
5297  else
5298  TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5299  return;
5300  }
5301 
5302  // - If the initializer is (), the object is value-initialized.
5303  if (Kind.getKind() == InitializationKind::IK_Value ||
5304  (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
5305  TryValueInitialization(S, Entity, Kind, *this);
5306  return;
5307  }
5308 
5309  // Handle default initialization.
5310  if (Kind.getKind() == InitializationKind::IK_Default) {
5311  TryDefaultInitialization(S, Entity, Kind, *this);
5312  return;
5313  }
5314 
5315  // - If the destination type is an array of characters, an array of
5316  // char16_t, an array of char32_t, or an array of wchar_t, and the
5317  // initializer is a string literal, see 8.5.2.
5318  // - Otherwise, if the destination type is an array, the program is
5319  // ill-formed.
5320  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
5321  if (Initializer && isa<VariableArrayType>(DestAT)) {
5323  return;
5324  }
5325 
5326  if (Initializer) {
5327  switch (IsStringInit(Initializer, DestAT, Context)) {
5328  case SIF_None:
5329  TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5330  return;
5333  return;
5336  return;
5339  return;
5340  case SIF_Other:
5341  break;
5342  }
5343  }
5344 
5345  // Some kinds of initialization permit an array to be initialized from
5346  // another array of the same type, and perform elementwise initialization.
5347  if (Initializer && isa<ConstantArrayType>(DestAT) &&
5348  S.Context.hasSameUnqualifiedType(Initializer->getType(),
5349  Entity.getType()) &&
5350  canPerformArrayCopy(Entity)) {
5351  // If source is a prvalue, use it directly.
5352  if (Initializer->getValueKind() == VK_RValue) {
5353  AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5354  return;
5355  }
5356 
5357  // Emit element-at-a-time copy loop.
5358  InitializedEntity Element =
5360  QualType InitEltT =
5361  Context.getAsArrayType(Initializer->getType())->getElementType();
5362  OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5363  Initializer->getValueKind(),
5364  Initializer->getObjectKind());
5365  Expr *OVEAsExpr = &OVE;
5366  InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5367  TreatUnavailableAsInvalid);
5368  if (!Failed())
5369  AddArrayInitLoopStep(Entity.getType(), InitEltT);
5370  return;
5371  }
5372 
5373  // Note: as an GNU C extension, we allow initialization of an
5374  // array from a compound literal that creates an array of the same
5375  // type, so long as the initializer has no side effects.
5376  if (!S.getLangOpts().CPlusPlus && Initializer &&
5377  isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5378  Initializer->getType()->isArrayType()) {
5379  const ArrayType *SourceAT
5380  = Context.getAsArrayType(Initializer->getType());
5381  if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5383  else if (Initializer->HasSideEffects(S.Context))
5385  else {
5386  AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5387  }
5388  }
5389  // Note: as a GNU C++ extension, we allow list-initialization of a
5390  // class member of array type from a parenthesized initializer list.
5391  else if (S.getLangOpts().CPlusPlus &&
5392  Entity.getKind() == InitializedEntity::EK_Member &&
5393  Initializer && isa<InitListExpr>(Initializer)) {
5394  TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5395  *this, TreatUnavailableAsInvalid);
5397  } else if (DestAT->getElementType()->isCharType())
5399  else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5401  else
5403 
5404  return;
5405  }
5406 
5407  // Determine whether we should consider writeback conversions for
5408  // Objective-C ARC.
5409  bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
5410  Entity.isParameterKind();
5411 
5412  // We're at the end of the line for C: it's either a write-back conversion
5413  // or it's a C assignment. There's no need to check anything else.
5414  if (!S.getLangOpts().CPlusPlus) {
5415  // If allowed, check whether this is an Objective-C writeback conversion.
5416  if (allowObjCWritebackConversion &&
5417  tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5418  return;
5419  }
5420 
5421  if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5422  return;
5423 
5424  if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5425  return;
5426 
5427  if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5428  return;
5429 
5430  // Handle initialization in C
5431  AddCAssignmentStep(DestType);
5432  MaybeProduceObjCObject(S, *this, Entity);
5433  return;
5434  }
5435 
5436  assert(S.getLangOpts().CPlusPlus);
5437 
5438  // - If the destination type is a (possibly cv-qualified) class type:
5439  if (DestType->isRecordType()) {
5440  // - If the initialization is direct-initialization, or if it is
5441  // copy-initialization where the cv-unqualified version of the
5442  // source type is the same class as, or a derived class of, the
5443  // class of the destination, constructors are considered. [...]
5444  if (Kind.getKind() == InitializationKind::IK_Direct ||
5445  (Kind.getKind() == InitializationKind::IK_Copy &&
5446  (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5447  S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
5448  TryConstructorInitialization(S, Entity, Kind, Args,
5449  DestType, DestType, *this);
5450  // - Otherwise (i.e., for the remaining copy-initialization cases),
5451  // user-defined conversion sequences that can convert from the source
5452  // type to the destination type or (when a conversion function is
5453  // used) to a derived class thereof are enumerated as described in
5454  // 13.3.1.4, and the best one is chosen through overload resolution
5455  // (13.3).
5456  else
5457  TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5458  TopLevelOfInitList);
5459  return;
5460  }
5461 
5462  assert(Args.size() >= 1 && "Zero-argument case handled above");
5463 
5464  // The remaining cases all need a source type.
5465  if (Args.size() > 1) {
5467  return;
5468  } else if (isa<InitListExpr>(Args[0])) {
5470  return;
5471  }
5472 
5473  // - Otherwise, if the source type is a (possibly cv-qualified) class
5474  // type, conversion functions are considered.
5475  if (!SourceType.isNull() && SourceType->isRecordType()) {
5476  // For a conversion to _Atomic(T) from either T or a class type derived
5477  // from T, initialize the T object then convert to _Atomic type.
5478  bool NeedAtomicConversion = false;
5479  if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5480  if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5481  S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5482  Atomic->getValueType())) {
5483  DestType = Atomic->getValueType();
5484  NeedAtomicConversion = true;
5485  }
5486  }
5487 
5488  TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5489  TopLevelOfInitList);
5490  MaybeProduceObjCObject(S, *this, Entity);
5491  if (!Failed() && NeedAtomicConversion)
5492  AddAtomicConversionStep(Entity.getType());
5493  return;
5494  }
5495 
5496  // - Otherwise, the initial value of the object being initialized is the
5497  // (possibly converted) value of the initializer expression. Standard
5498  // conversions (Clause 4) will be used, if necessary, to convert the
5499  // initializer expression to the cv-unqualified version of the
5500  // destination type; no user-defined conversions are considered.
5501 
5503  = S.TryImplicitConversion(Initializer, DestType,
5504  /*SuppressUserConversions*/true,
5505  /*AllowExplicitConversions*/ false,
5506  /*InOverloadResolution*/ false,
5507  /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5508  allowObjCWritebackConversion);
5509 
5510  if (ICS.isStandard() &&
5512  // Objective-C ARC writeback conversion.
5513 
5514  // We should copy unless we're passing to an argument explicitly
5515  // marked 'out'.
5516  bool ShouldCopy = true;
5517  if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5518  ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5519 
5520  // If there was an lvalue adjustment, add it as a separate conversion.
5521  if (ICS.Standard.First == ICK_Array_To_Pointer ||
5523  ImplicitConversionSequence LvalueICS;
5524  LvalueICS.setStandard();
5525  LvalueICS.Standard.setAsIdentityConversion();
5526  LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5527  LvalueICS.Standard.First = ICS.Standard.First;
5528  AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
5529  }
5530 
5531  AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
5532  } else if (ICS.isBad()) {
5533  DeclAccessPair dap;
5534  if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5536  } else if (Initializer->getType() == Context.OverloadTy &&
5537  !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5538  false, dap))
5539  SetFailed(