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