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  // Warn if this type won't be an aggregate in future versions of C++.
969  auto *CXXRD = T->getAsCXXRecordDecl();
970  if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
971  SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
972  diag::warn_cxx2a_compat_aggregate_init_with_ctors)
973  << StructuredSubobjectInitList->getSourceRange() << T;
974  }
975  }
976 }
977 
978 /// Warn that \p Entity was of scalar type and was initialized by a
979 /// single-element braced initializer list.
980 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
981  SourceRange Braces) {
982  // Don't warn during template instantiation. If the initialization was
983  // non-dependent, we warned during the initial parse; otherwise, the
984  // type might not be scalar in some uses of the template.
985  if (S.inTemplateInstantiation())
986  return;
987 
988  unsigned DiagID = 0;
989 
990  switch (Entity.getKind()) {
997  // Extra braces here are suspicious.
998  DiagID = diag::warn_braces_around_scalar_init;
999  break;
1000 
1002  // Warn on aggregate initialization but not on ctor init list or
1003  // default member initializer.
1004  if (Entity.getParent())
1005  DiagID = diag::warn_braces_around_scalar_init;
1006  break;
1007 
1010  // No warning, might be direct-list-initialization.
1011  // FIXME: Should we warn for copy-list-initialization in these cases?
1012  break;
1013 
1017  // No warning, braces are part of the syntax of the underlying construct.
1018  break;
1019 
1021  // No warning, we already warned when initializing the result.
1022  break;
1023 
1031  llvm_unreachable("unexpected braced scalar init");
1032  }
1033 
1034  if (DiagID) {
1035  S.Diag(Braces.getBegin(), DiagID)
1036  << Braces
1037  << FixItHint::CreateRemoval(Braces.getBegin())
1038  << FixItHint::CreateRemoval(Braces.getEnd());
1039  }
1040 }
1041 
1042 /// Check whether the initializer \p IList (that was written with explicit
1043 /// braces) can be used to initialize an object of type \p T.
1044 ///
1045 /// This also fills in \p StructuredList with the fully-braced, desugared
1046 /// form of the initialization.
1047 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1048  InitListExpr *IList, QualType &T,
1049  InitListExpr *StructuredList,
1050  bool TopLevelObject) {
1051  if (!VerifyOnly) {
1052  SyntacticToSemantic[IList] = StructuredList;
1053  StructuredList->setSyntacticForm(IList);
1054  }
1055 
1056  unsigned Index = 0, StructuredIndex = 0;
1057  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1058  Index, StructuredList, StructuredIndex, TopLevelObject);
1059  if (!VerifyOnly) {
1060  QualType ExprTy = T;
1061  if (!ExprTy->isArrayType())
1062  ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1063  IList->setType(ExprTy);
1064  StructuredList->setType(ExprTy);
1065  }
1066  if (hadError)
1067  return;
1068 
1069  if (Index < IList->getNumInits()) {
1070  // We have leftover initializers
1071  if (VerifyOnly) {
1072  if (SemaRef.getLangOpts().CPlusPlus ||
1073  (SemaRef.getLangOpts().OpenCL &&
1074  IList->getType()->isVectorType())) {
1075  hadError = true;
1076  }
1077  return;
1078  }
1079 
1080  if (StructuredIndex == 1 &&
1081  IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1082  SIF_None) {
1083  unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1084  if (SemaRef.getLangOpts().CPlusPlus) {
1085  DK = diag::err_excess_initializers_in_char_array_initializer;
1086  hadError = true;
1087  }
1088  // Special-case
1089  SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1090  << IList->getInit(Index)->getSourceRange();
1091  } else if (!T->isIncompleteType()) {
1092  // Don't complain for incomplete types, since we'll get an error
1093  // elsewhere
1094  QualType CurrentObjectType = StructuredList->getType();
1095  int initKind =
1096  CurrentObjectType->isArrayType()? 0 :
1097  CurrentObjectType->isVectorType()? 1 :
1098  CurrentObjectType->isScalarType()? 2 :
1099  CurrentObjectType->isUnionType()? 3 :
1100  4;
1101 
1102  unsigned DK = diag::ext_excess_initializers;
1103  if (SemaRef.getLangOpts().CPlusPlus) {
1104  DK = diag::err_excess_initializers;
1105  hadError = true;
1106  }
1107  if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1108  DK = diag::err_excess_initializers;
1109  hadError = true;
1110  }
1111 
1112  SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1113  << initKind << IList->getInit(Index)->getSourceRange();
1114  }
1115  }
1116 
1117  if (!VerifyOnly) {
1118  if (T->isScalarType() && IList->getNumInits() == 1 &&
1119  !isa<InitListExpr>(IList->getInit(0)))
1120  warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1121 
1122  // Warn if this is a class type that won't be an aggregate in future
1123  // versions of C++.
1124  auto *CXXRD = T->getAsCXXRecordDecl();
1125  if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1126  // Don't warn if there's an equivalent default constructor that would be
1127  // used instead.
1128  bool HasEquivCtor = false;
1129  if (IList->getNumInits() == 0) {
1130  auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1131  HasEquivCtor = CD && !CD->isDeleted();
1132  }
1133 
1134  if (!HasEquivCtor) {
1135  SemaRef.Diag(IList->getBeginLoc(),
1136  diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1137  << IList->getSourceRange() << T;
1138  }
1139  }
1140  }
1141 }
1142 
1143 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1144  InitListExpr *IList,
1145  QualType &DeclType,
1146  bool SubobjectIsDesignatorContext,
1147  unsigned &Index,
1148  InitListExpr *StructuredList,
1149  unsigned &StructuredIndex,
1150  bool TopLevelObject) {
1151  if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1152  // Explicitly braced initializer for complex type can be real+imaginary
1153  // parts.
1154  CheckComplexType(Entity, IList, DeclType, Index,
1155  StructuredList, StructuredIndex);
1156  } else if (DeclType->isScalarType()) {
1157  CheckScalarType(Entity, IList, DeclType, Index,
1158  StructuredList, StructuredIndex);
1159  } else if (DeclType->isVectorType()) {
1160  CheckVectorType(Entity, IList, DeclType, Index,
1161  StructuredList, StructuredIndex);
1162  } else if (DeclType->isRecordType()) {
1163  assert(DeclType->isAggregateType() &&
1164  "non-aggregate records should be handed in CheckSubElementType");
1165  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1166  auto Bases =
1169  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1170  Bases = CXXRD->bases();
1171  CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1172  SubobjectIsDesignatorContext, Index, StructuredList,
1173  StructuredIndex, TopLevelObject);
1174  } else if (DeclType->isArrayType()) {
1175  llvm::APSInt Zero(
1176  SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1177  false);
1178  CheckArrayType(Entity, IList, DeclType, Zero,
1179  SubobjectIsDesignatorContext, Index,
1180  StructuredList, StructuredIndex);
1181  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1182  // This type is invalid, issue a diagnostic.
1183  ++Index;
1184  if (!VerifyOnly)
1185  SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1186  << DeclType;
1187  hadError = true;
1188  } else if (DeclType->isReferenceType()) {
1189  CheckReferenceType(Entity, IList, DeclType, Index,
1190  StructuredList, StructuredIndex);
1191  } else if (DeclType->isObjCObjectType()) {
1192  if (!VerifyOnly)
1193  SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1194  hadError = true;
1195  } else {
1196  if (!VerifyOnly)
1197  SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1198  << DeclType;
1199  hadError = true;
1200  }
1201 }
1202 
1203 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1204  InitListExpr *IList,
1205  QualType ElemType,
1206  unsigned &Index,
1207  InitListExpr *StructuredList,
1208  unsigned &StructuredIndex) {
1209  Expr *expr = IList->getInit(Index);
1210 
1211  if (ElemType->isReferenceType())
1212  return CheckReferenceType(Entity, IList, ElemType, Index,
1213  StructuredList, StructuredIndex);
1214 
1215  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1216  if (SubInitList->getNumInits() == 1 &&
1217  IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1218  SIF_None) {
1219  expr = SubInitList->getInit(0);
1220  } else if (!SemaRef.getLangOpts().CPlusPlus) {
1221  InitListExpr *InnerStructuredList
1222  = getStructuredSubobjectInit(IList, Index, ElemType,
1223  StructuredList, StructuredIndex,
1224  SubInitList->getSourceRange(), true);
1225  CheckExplicitInitList(Entity, SubInitList, ElemType,
1226  InnerStructuredList);
1227 
1228  if (!hadError && !VerifyOnly) {
1229  bool RequiresSecondPass = false;
1230  FillInEmptyInitializations(Entity, InnerStructuredList,
1231  RequiresSecondPass, StructuredList,
1232  StructuredIndex);
1233  if (RequiresSecondPass && !hadError)
1234  FillInEmptyInitializations(Entity, InnerStructuredList,
1235  RequiresSecondPass, StructuredList,
1236  StructuredIndex);
1237  }
1238  ++StructuredIndex;
1239  ++Index;
1240  return;
1241  }
1242  // C++ initialization is handled later.
1243  } else if (isa<ImplicitValueInitExpr>(expr)) {
1244  // This happens during template instantiation when we see an InitListExpr
1245  // that we've already checked once.
1246  assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1247  "found implicit initialization for the wrong type");
1248  if (!VerifyOnly)
1249  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1250  ++Index;
1251  return;
1252  }
1253 
1254  if (SemaRef.getLangOpts().CPlusPlus) {
1255  // C++ [dcl.init.aggr]p2:
1256  // Each member is copy-initialized from the corresponding
1257  // initializer-clause.
1258 
1259  // FIXME: Better EqualLoc?
1262  InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1263  /*TopLevelOfInitList*/ true);
1264 
1265  // C++14 [dcl.init.aggr]p13:
1266  // If the assignment-expression can initialize a member, the member is
1267  // initialized. Otherwise [...] brace elision is assumed
1268  //
1269  // Brace elision is never performed if the element is not an
1270  // assignment-expression.
1271  if (Seq || isa<InitListExpr>(expr)) {
1272  if (!VerifyOnly) {
1273  ExprResult Result =
1274  Seq.Perform(SemaRef, Entity, Kind, expr);
1275  if (Result.isInvalid())
1276  hadError = true;
1277 
1278  UpdateStructuredListElement(StructuredList, StructuredIndex,
1279  Result.getAs<Expr>());
1280  } else if (!Seq)
1281  hadError = true;
1282  ++Index;
1283  return;
1284  }
1285 
1286  // Fall through for subaggregate initialization
1287  } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1288  // FIXME: Need to handle atomic aggregate types with implicit init lists.
1289  return CheckScalarType(Entity, IList, ElemType, Index,
1290  StructuredList, StructuredIndex);
1291  } else if (const ArrayType *arrayType =
1292  SemaRef.Context.getAsArrayType(ElemType)) {
1293  // arrayType can be incomplete if we're initializing a flexible
1294  // array member. There's nothing we can do with the completed
1295  // type here, though.
1296 
1297  if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1298  if (!VerifyOnly) {
1299  CheckStringInit(expr, ElemType, arrayType, SemaRef);
1300  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1301  }
1302  ++Index;
1303  return;
1304  }
1305 
1306  // Fall through for subaggregate initialization.
1307 
1308  } else {
1309  assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1310  ElemType->isOpenCLSpecificType()) && "Unexpected type");
1311 
1312  // C99 6.7.8p13:
1313  //
1314  // The initializer for a structure or union object that has
1315  // automatic storage duration shall be either an initializer
1316  // list as described below, or a single expression that has
1317  // compatible structure or union type. In the latter case, the
1318  // initial value of the object, including unnamed members, is
1319  // that of the expression.
1320  ExprResult ExprRes = expr;
1322  ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1323  if (ExprRes.isInvalid())
1324  hadError = true;
1325  else {
1326  ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1327  if (ExprRes.isInvalid())
1328  hadError = true;
1329  }
1330  UpdateStructuredListElement(StructuredList, StructuredIndex,
1331  ExprRes.getAs<Expr>());
1332  ++Index;
1333  return;
1334  }
1335  ExprRes.get();
1336  // Fall through for subaggregate initialization
1337  }
1338 
1339  // C++ [dcl.init.aggr]p12:
1340  //
1341  // [...] Otherwise, if the member is itself a non-empty
1342  // subaggregate, brace elision is assumed and the initializer is
1343  // considered for the initialization of the first member of
1344  // the subaggregate.
1345  // OpenCL vector initializer is handled elsewhere.
1346  if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1347  ElemType->isAggregateType()) {
1348  CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1349  StructuredIndex);
1350  ++StructuredIndex;
1351  } else {
1352  if (!VerifyOnly) {
1353  // We cannot initialize this element, so let
1354  // PerformCopyInitialization produce the appropriate diagnostic.
1355  SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1356  /*TopLevelOfInitList=*/true);
1357  }
1358  hadError = true;
1359  ++Index;
1360  ++StructuredIndex;
1361  }
1362 }
1363 
1364 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1365  InitListExpr *IList, QualType DeclType,
1366  unsigned &Index,
1367  InitListExpr *StructuredList,
1368  unsigned &StructuredIndex) {
1369  assert(Index == 0 && "Index in explicit init list must be zero");
1370 
1371  // As an extension, clang supports complex initializers, which initialize
1372  // a complex number component-wise. When an explicit initializer list for
1373  // a complex number contains two two initializers, this extension kicks in:
1374  // it exepcts the initializer list to contain two elements convertible to
1375  // the element type of the complex type. The first element initializes
1376  // the real part, and the second element intitializes the imaginary part.
1377 
1378  if (IList->getNumInits() != 2)
1379  return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1380  StructuredIndex);
1381 
1382  // This is an extension in C. (The builtin _Complex type does not exist
1383  // in the C++ standard.)
1384  if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1385  SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1386  << IList->getSourceRange();
1387 
1388  // Initialize the complex number.
1389  QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1390  InitializedEntity ElementEntity =
1391  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1392 
1393  for (unsigned i = 0; i < 2; ++i) {
1394  ElementEntity.setElementIndex(Index);
1395  CheckSubElementType(ElementEntity, IList, elementType, Index,
1396  StructuredList, StructuredIndex);
1397  }
1398 }
1399 
1400 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1401  InitListExpr *IList, QualType DeclType,
1402  unsigned &Index,
1403  InitListExpr *StructuredList,
1404  unsigned &StructuredIndex) {
1405  if (Index >= IList->getNumInits()) {
1406  if (!VerifyOnly)
1407  SemaRef.Diag(IList->getBeginLoc(),
1408  SemaRef.getLangOpts().CPlusPlus11
1409  ? diag::warn_cxx98_compat_empty_scalar_initializer
1410  : diag::err_empty_scalar_initializer)
1411  << IList->getSourceRange();
1412  hadError = !SemaRef.getLangOpts().CPlusPlus11;
1413  ++Index;
1414  ++StructuredIndex;
1415  return;
1416  }
1417 
1418  Expr *expr = IList->getInit(Index);
1419  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1420  // FIXME: This is invalid, and accepting it causes overload resolution
1421  // to pick the wrong overload in some corner cases.
1422  if (!VerifyOnly)
1423  SemaRef.Diag(SubIList->getBeginLoc(),
1424  diag::ext_many_braces_around_scalar_init)
1425  << SubIList->getSourceRange();
1426 
1427  CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1428  StructuredIndex);
1429  return;
1430  } else if (isa<DesignatedInitExpr>(expr)) {
1431  if (!VerifyOnly)
1432  SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
1433  << DeclType << expr->getSourceRange();
1434  hadError = true;
1435  ++Index;
1436  ++StructuredIndex;
1437  return;
1438  }
1439 
1440  if (VerifyOnly) {
1441  if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1442  hadError = true;
1443  ++Index;
1444  return;
1445  }
1446 
1447  ExprResult Result =
1448  SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1449  /*TopLevelOfInitList=*/true);
1450 
1451  Expr *ResultExpr = nullptr;
1452 
1453  if (Result.isInvalid())
1454  hadError = true; // types weren't compatible.
1455  else {
1456  ResultExpr = Result.getAs<Expr>();
1457 
1458  if (ResultExpr != expr) {
1459  // The type was promoted, update initializer list.
1460  IList->setInit(Index, ResultExpr);
1461  }
1462  }
1463  if (hadError)
1464  ++StructuredIndex;
1465  else
1466  UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1467  ++Index;
1468 }
1469 
1470 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1471  InitListExpr *IList, QualType DeclType,
1472  unsigned &Index,
1473  InitListExpr *StructuredList,
1474  unsigned &StructuredIndex) {
1475  if (Index >= IList->getNumInits()) {
1476  // FIXME: It would be wonderful if we could point at the actual member. In
1477  // general, it would be useful to pass location information down the stack,
1478  // so that we know the location (or decl) of the "current object" being
1479  // initialized.
1480  if (!VerifyOnly)
1481  SemaRef.Diag(IList->getBeginLoc(),
1482  diag::err_init_reference_member_uninitialized)
1483  << DeclType << IList->getSourceRange();
1484  hadError = true;
1485  ++Index;
1486  ++StructuredIndex;
1487  return;
1488  }
1489 
1490  Expr *expr = IList->getInit(Index);
1491  if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1492  if (!VerifyOnly)
1493  SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1494  << DeclType << IList->getSourceRange();
1495  hadError = true;
1496  ++Index;
1497  ++StructuredIndex;
1498  return;
1499  }
1500 
1501  if (VerifyOnly) {
1502  if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1503  hadError = true;
1504  ++Index;
1505  return;
1506  }
1507 
1508  ExprResult Result =
1509  SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1510  /*TopLevelOfInitList=*/true);
1511 
1512  if (Result.isInvalid())
1513  hadError = true;
1514 
1515  expr = Result.getAs<Expr>();
1516  IList->setInit(Index, expr);
1517 
1518  if (hadError)
1519  ++StructuredIndex;
1520  else
1521  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1522  ++Index;
1523 }
1524 
1525 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1526  InitListExpr *IList, QualType DeclType,
1527  unsigned &Index,
1528  InitListExpr *StructuredList,
1529  unsigned &StructuredIndex) {
1530  const VectorType *VT = DeclType->getAs<VectorType>();
1531  unsigned maxElements = VT->getNumElements();
1532  unsigned numEltsInit = 0;
1533  QualType elementType = VT->getElementType();
1534 
1535  if (Index >= IList->getNumInits()) {
1536  // Make sure the element type can be value-initialized.
1537  if (VerifyOnly)
1538  CheckEmptyInitializable(
1539  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1540  IList->getEndLoc());
1541  return;
1542  }
1543 
1544  if (!SemaRef.getLangOpts().OpenCL) {
1545  // If the initializing element is a vector, try to copy-initialize
1546  // instead of breaking it apart (which is doomed to failure anyway).
1547  Expr *Init = IList->getInit(Index);
1548  if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1549  if (VerifyOnly) {
1550  if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1551  hadError = true;
1552  ++Index;
1553  return;
1554  }
1555 
1556  ExprResult Result =
1557  SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1558  /*TopLevelOfInitList=*/true);
1559 
1560  Expr *ResultExpr = nullptr;
1561  if (Result.isInvalid())
1562  hadError = true; // types weren't compatible.
1563  else {
1564  ResultExpr = Result.getAs<Expr>();
1565 
1566  if (ResultExpr != Init) {
1567  // The type was promoted, update initializer list.
1568  IList->setInit(Index, ResultExpr);
1569  }
1570  }
1571  if (hadError)
1572  ++StructuredIndex;
1573  else
1574  UpdateStructuredListElement(StructuredList, StructuredIndex,
1575  ResultExpr);
1576  ++Index;
1577  return;
1578  }
1579 
1580  InitializedEntity ElementEntity =
1581  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1582 
1583  for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1584  // Don't attempt to go past the end of the init list
1585  if (Index >= IList->getNumInits()) {
1586  if (VerifyOnly)
1587  CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1588  break;
1589  }
1590 
1591  ElementEntity.setElementIndex(Index);
1592  CheckSubElementType(ElementEntity, IList, elementType, Index,
1593  StructuredList, StructuredIndex);
1594  }
1595 
1596  if (VerifyOnly)
1597  return;
1598 
1599  bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1600  const VectorType *T = Entity.getType()->getAs<VectorType>();
1601  if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1603  // The ability to use vector initializer lists is a GNU vector extension
1604  // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1605  // endian machines it works fine, however on big endian machines it
1606  // exhibits surprising behaviour:
1607  //
1608  // uint32x2_t x = {42, 64};
1609  // return vget_lane_u32(x, 0); // Will return 64.
1610  //
1611  // Because of this, explicitly call out that it is non-portable.
1612  //
1613  SemaRef.Diag(IList->getBeginLoc(),
1614  diag::warn_neon_vector_initializer_non_portable);
1615 
1616  const char *typeCode;
1617  unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1618 
1619  if (elementType->isFloatingType())
1620  typeCode = "f";
1621  else if (elementType->isSignedIntegerType())
1622  typeCode = "s";
1623  else if (elementType->isUnsignedIntegerType())
1624  typeCode = "u";
1625  else
1626  llvm_unreachable("Invalid element type!");
1627 
1628  SemaRef.Diag(IList->getBeginLoc(),
1629  SemaRef.Context.getTypeSize(VT) > 64
1630  ? diag::note_neon_vector_initializer_non_portable_q
1631  : diag::note_neon_vector_initializer_non_portable)
1632  << typeCode << typeSize;
1633  }
1634 
1635  return;
1636  }
1637 
1638  InitializedEntity ElementEntity =
1639  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1640 
1641  // OpenCL initializers allows vectors to be constructed from vectors.
1642  for (unsigned i = 0; i < maxElements; ++i) {
1643  // Don't attempt to go past the end of the init list
1644  if (Index >= IList->getNumInits())
1645  break;
1646 
1647  ElementEntity.setElementIndex(Index);
1648 
1649  QualType IType = IList->getInit(Index)->getType();
1650  if (!IType->isVectorType()) {
1651  CheckSubElementType(ElementEntity, IList, elementType, Index,
1652  StructuredList, StructuredIndex);
1653  ++numEltsInit;
1654  } else {
1655  QualType VecType;
1656  const VectorType *IVT = IType->getAs<VectorType>();
1657  unsigned numIElts = IVT->getNumElements();
1658 
1659  if (IType->isExtVectorType())
1660  VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1661  else
1662  VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1663  IVT->getVectorKind());
1664  CheckSubElementType(ElementEntity, IList, VecType, Index,
1665  StructuredList, StructuredIndex);
1666  numEltsInit += numIElts;
1667  }
1668  }
1669 
1670  // OpenCL requires all elements to be initialized.
1671  if (numEltsInit != maxElements) {
1672  if (!VerifyOnly)
1673  SemaRef.Diag(IList->getBeginLoc(),
1674  diag::err_vector_incorrect_num_initializers)
1675  << (numEltsInit < maxElements) << maxElements << numEltsInit;
1676  hadError = true;
1677  }
1678 }
1679 
1680 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1681  InitListExpr *IList, QualType &DeclType,
1682  llvm::APSInt elementIndex,
1683  bool SubobjectIsDesignatorContext,
1684  unsigned &Index,
1685  InitListExpr *StructuredList,
1686  unsigned &StructuredIndex) {
1687  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1688 
1689  // Check for the special-case of initializing an array with a string.
1690  if (Index < IList->getNumInits()) {
1691  if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1692  SIF_None) {
1693  // We place the string literal directly into the resulting
1694  // initializer list. This is the only place where the structure
1695  // of the structured initializer list doesn't match exactly,
1696  // because doing so would involve allocating one character
1697  // constant for each string.
1698  if (!VerifyOnly) {
1699  CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1700  UpdateStructuredListElement(StructuredList, StructuredIndex,
1701  IList->getInit(Index));
1702  StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1703  }
1704  ++Index;
1705  return;
1706  }
1707  }
1708  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1709  // Check for VLAs; in standard C it would be possible to check this
1710  // earlier, but I don't know where clang accepts VLAs (gcc accepts
1711  // them in all sorts of strange places).
1712  if (!VerifyOnly)
1713  SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1714  diag::err_variable_object_no_init)
1715  << VAT->getSizeExpr()->getSourceRange();
1716  hadError = true;
1717  ++Index;
1718  ++StructuredIndex;
1719  return;
1720  }
1721 
1722  // We might know the maximum number of elements in advance.
1723  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1724  elementIndex.isUnsigned());
1725  bool maxElementsKnown = false;
1726  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1727  maxElements = CAT->getSize();
1728  elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1729  elementIndex.setIsUnsigned(maxElements.isUnsigned());
1730  maxElementsKnown = true;
1731  }
1732 
1733  QualType elementType = arrayType->getElementType();
1734  while (Index < IList->getNumInits()) {
1735  Expr *Init = IList->getInit(Index);
1736  if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1737  // If we're not the subobject that matches up with the '{' for
1738  // the designator, we shouldn't be handling the
1739  // designator. Return immediately.
1740  if (!SubobjectIsDesignatorContext)
1741  return;
1742 
1743  // Handle this designated initializer. elementIndex will be
1744  // updated to be the next array element we'll initialize.
1745  if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1746  DeclType, nullptr, &elementIndex, Index,
1747  StructuredList, StructuredIndex, true,
1748  false)) {
1749  hadError = true;
1750  continue;
1751  }
1752 
1753  if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1754  maxElements = maxElements.extend(elementIndex.getBitWidth());
1755  else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1756  elementIndex = elementIndex.extend(maxElements.getBitWidth());
1757  elementIndex.setIsUnsigned(maxElements.isUnsigned());
1758 
1759  // If the array is of incomplete type, keep track of the number of
1760  // elements in the initializer.
1761  if (!maxElementsKnown && elementIndex > maxElements)
1762  maxElements = elementIndex;
1763 
1764  continue;
1765  }
1766 
1767  // If we know the maximum number of elements, and we've already
1768  // hit it, stop consuming elements in the initializer list.
1769  if (maxElementsKnown && elementIndex == maxElements)
1770  break;
1771 
1772  InitializedEntity ElementEntity =
1773  InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1774  Entity);
1775  // Check this element.
1776  CheckSubElementType(ElementEntity, IList, elementType, Index,
1777  StructuredList, StructuredIndex);
1778  ++elementIndex;
1779 
1780  // If the array is of incomplete type, keep track of the number of
1781  // elements in the initializer.
1782  if (!maxElementsKnown && elementIndex > maxElements)
1783  maxElements = elementIndex;
1784  }
1785  if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1786  // If this is an incomplete array type, the actual type needs to
1787  // be calculated here.
1788  llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1789  if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1790  // Sizing an array implicitly to zero is not allowed by ISO C,
1791  // but is supported by GNU.
1792  SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
1793  }
1794 
1795  DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1796  ArrayType::Normal, 0);
1797  }
1798  if (!hadError && VerifyOnly) {
1799  // If there are any members of the array that get value-initialized, check
1800  // that is possible. That happens if we know the bound and don't have
1801  // enough elements, or if we're performing an array new with an unknown
1802  // bound.
1803  // FIXME: This needs to detect holes left by designated initializers too.
1804  if ((maxElementsKnown && elementIndex < maxElements) ||
1805  Entity.isVariableLengthArrayNew())
1806  CheckEmptyInitializable(
1807  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1808  IList->getEndLoc());
1809  }
1810 }
1811 
1812 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1813  Expr *InitExpr,
1814  FieldDecl *Field,
1815  bool TopLevelObject) {
1816  // Handle GNU flexible array initializers.
1817  unsigned FlexArrayDiag;
1818  if (isa<InitListExpr>(InitExpr) &&
1819  cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1820  // Empty flexible array init always allowed as an extension
1821  FlexArrayDiag = diag::ext_flexible_array_init;
1822  } else if (SemaRef.getLangOpts().CPlusPlus) {
1823  // Disallow flexible array init in C++; it is not required for gcc
1824  // compatibility, and it needs work to IRGen correctly in general.
1825  FlexArrayDiag = diag::err_flexible_array_init;
1826  } else if (!TopLevelObject) {
1827  // Disallow flexible array init on non-top-level object
1828  FlexArrayDiag = diag::err_flexible_array_init;
1829  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1830  // Disallow flexible array init on anything which is not a variable.
1831  FlexArrayDiag = diag::err_flexible_array_init;
1832  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1833  // Disallow flexible array init on local variables.
1834  FlexArrayDiag = diag::err_flexible_array_init;
1835  } else {
1836  // Allow other cases.
1837  FlexArrayDiag = diag::ext_flexible_array_init;
1838  }
1839 
1840  if (!VerifyOnly) {
1841  SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
1842  << InitExpr->getBeginLoc();
1843  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1844  << Field;
1845  }
1846 
1847  return FlexArrayDiag != diag::ext_flexible_array_init;
1848 }
1849 
1850 /// Check if the type of a class element has an accessible destructor.
1851 ///
1852 /// Aggregate initialization requires a class element's destructor be
1853 /// accessible per 11.6.1 [dcl.init.aggr]:
1854 ///
1855 /// The destructor for each element of class type is potentially invoked
1856 /// (15.4 [class.dtor]) from the context where the aggregate initialization
1857 /// occurs.
1858 static bool hasAccessibleDestructor(QualType ElementType, SourceLocation Loc,
1859  Sema &SemaRef) {
1860  auto *CXXRD = ElementType->getAsCXXRecordDecl();
1861  if (!CXXRD)
1862  return false;
1863 
1864  CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1865  SemaRef.CheckDestructorAccess(Loc, Destructor,
1866  SemaRef.PDiag(diag::err_access_dtor_temp)
1867  << ElementType);
1868  SemaRef.MarkFunctionReferenced(Loc, Destructor);
1869  if (SemaRef.DiagnoseUseOfDecl(Destructor, Loc))
1870  return true;
1871  return false;
1872 }
1873 
1874 void InitListChecker::CheckStructUnionTypes(
1875  const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1877  bool SubobjectIsDesignatorContext, unsigned &Index,
1878  InitListExpr *StructuredList, unsigned &StructuredIndex,
1879  bool TopLevelObject) {
1880  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1881 
1882  // If the record is invalid, some of it's members are invalid. To avoid
1883  // confusion, we forgo checking the intializer for the entire record.
1884  if (structDecl->isInvalidDecl()) {
1885  // Assume it was supposed to consume a single initializer.
1886  ++Index;
1887  hadError = true;
1888  return;
1889  }
1890 
1891  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1892  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1893 
1894  if (!VerifyOnly)
1895  for (FieldDecl *FD : RD->fields()) {
1896  QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
1897  if (hasAccessibleDestructor(ET, IList->getEndLoc(), SemaRef)) {
1898  hadError = true;
1899  return;
1900  }
1901  }
1902 
1903  // If there's a default initializer, use it.
1904  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1905  if (VerifyOnly)
1906  return;
1907  for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1908  Field != FieldEnd; ++Field) {
1909  if (Field->hasInClassInitializer()) {
1910  StructuredList->setInitializedFieldInUnion(*Field);
1911  // FIXME: Actually build a CXXDefaultInitExpr?
1912  return;
1913  }
1914  }
1915  }
1916 
1917  // Value-initialize the first member of the union that isn't an unnamed
1918  // bitfield.
1919  for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1920  Field != FieldEnd; ++Field) {
1921  if (!Field->isUnnamedBitfield()) {
1922  if (VerifyOnly)
1923  CheckEmptyInitializable(
1924  InitializedEntity::InitializeMember(*Field, &Entity),
1925  IList->getEndLoc());
1926  else
1927  StructuredList->setInitializedFieldInUnion(*Field);
1928  break;
1929  }
1930  }
1931  return;
1932  }
1933 
1934  bool InitializedSomething = false;
1935 
1936  // If we have any base classes, they are initialized prior to the fields.
1937  for (auto &Base : Bases) {
1938  Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1939 
1940  // Designated inits always initialize fields, so if we see one, all
1941  // remaining base classes have no explicit initializer.
1942  if (Init && isa<DesignatedInitExpr>(Init))
1943  Init = nullptr;
1944 
1945  SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
1947  SemaRef.Context, &Base, false, &Entity);
1948  if (Init) {
1949  CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1950  StructuredList, StructuredIndex);
1951  InitializedSomething = true;
1952  } else if (VerifyOnly) {
1953  CheckEmptyInitializable(BaseEntity, InitLoc);
1954  }
1955 
1956  if (!VerifyOnly)
1957  if (hasAccessibleDestructor(Base.getType(), InitLoc, SemaRef)) {
1958  hadError = true;
1959  return;
1960  }
1961  }
1962 
1963  // If structDecl is a forward declaration, this loop won't do
1964  // anything except look at designated initializers; That's okay,
1965  // because an error should get printed out elsewhere. It might be
1966  // worthwhile to skip over the rest of the initializer, though.
1967  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1968  RecordDecl::field_iterator FieldEnd = RD->field_end();
1969  bool CheckForMissingFields =
1970  !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1971  bool HasDesignatedInit = false;
1972 
1973  while (Index < IList->getNumInits()) {
1974  Expr *Init = IList->getInit(Index);
1975  SourceLocation InitLoc = Init->getBeginLoc();
1976 
1977  if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1978  // If we're not the subobject that matches up with the '{' for
1979  // the designator, we shouldn't be handling the
1980  // designator. Return immediately.
1981  if (!SubobjectIsDesignatorContext)
1982  return;
1983 
1984  HasDesignatedInit = true;
1985 
1986  // Handle this designated initializer. Field will be updated to
1987  // the next field that we'll be initializing.
1988  if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1989  DeclType, &Field, nullptr, Index,
1990  StructuredList, StructuredIndex,
1991  true, TopLevelObject))
1992  hadError = true;
1993  else if (!VerifyOnly) {
1994  // Find the field named by the designated initializer.
1996  while (std::next(F) != Field)
1997  ++F;
1998  QualType ET = SemaRef.Context.getBaseElementType(F->getType());
1999  if (hasAccessibleDestructor(ET, InitLoc, SemaRef)) {
2000  hadError = true;
2001  return;
2002  }
2003  }
2004 
2005  InitializedSomething = true;
2006 
2007  // Disable check for missing fields when designators are used.
2008  // This matches gcc behaviour.
2009  CheckForMissingFields = false;
2010  continue;
2011  }
2012 
2013  if (Field == FieldEnd) {
2014  // We've run out of fields. We're done.
2015  break;
2016  }
2017 
2018  // We've already initialized a member of a union. We're done.
2019  if (InitializedSomething && DeclType->isUnionType())
2020  break;
2021 
2022  // If we've hit the flexible array member at the end, we're done.
2023  if (Field->getType()->isIncompleteArrayType())
2024  break;
2025 
2026  if (Field->isUnnamedBitfield()) {
2027  // Don't initialize unnamed bitfields, e.g. "int : 20;"
2028  ++Field;
2029  continue;
2030  }
2031 
2032  // Make sure we can use this declaration.
2033  bool InvalidUse;
2034  if (VerifyOnly)
2035  InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2036  else
2037  InvalidUse = SemaRef.DiagnoseUseOfDecl(
2038  *Field, IList->getInit(Index)->getBeginLoc());
2039  if (InvalidUse) {
2040  ++Index;
2041  ++Field;
2042  hadError = true;
2043  continue;
2044  }
2045 
2046  if (!VerifyOnly) {
2047  QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2048  if (hasAccessibleDestructor(ET, InitLoc, SemaRef)) {
2049  hadError = true;
2050  return;
2051  }
2052  }
2053 
2054  InitializedEntity MemberEntity =
2055  InitializedEntity::InitializeMember(*Field, &Entity);
2056  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2057  StructuredList, StructuredIndex);
2058  InitializedSomething = true;
2059 
2060  if (DeclType->isUnionType() && !VerifyOnly) {
2061  // Initialize the first field within the union.
2062  StructuredList->setInitializedFieldInUnion(*Field);
2063  }
2064 
2065  ++Field;
2066  }
2067 
2068  // Emit warnings for missing struct field initializers.
2069  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2070  Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2071  !DeclType->isUnionType()) {
2072  // It is possible we have one or more unnamed bitfields remaining.
2073  // Find first (if any) named field and emit warning.
2074  for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2075  it != end; ++it) {
2076  if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
2077  SemaRef.Diag(IList->getSourceRange().getEnd(),
2078  diag::warn_missing_field_initializers) << *it;
2079  break;
2080  }
2081  }
2082  }
2083 
2084  // Check that any remaining fields can be value-initialized.
2085  if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2086  !Field->getType()->isIncompleteArrayType()) {
2087  // FIXME: Should check for holes left by designated initializers too.
2088  for (; Field != FieldEnd && !hadError; ++Field) {
2089  if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2090  CheckEmptyInitializable(
2091  InitializedEntity::InitializeMember(*Field, &Entity),
2092  IList->getEndLoc());
2093  }
2094  }
2095 
2096  // Check that the types of the remaining fields have accessible destructors.
2097  if (!VerifyOnly) {
2098  // If the initializer expression has a designated initializer, check the
2099  // elements for which a designated initializer is not provided too.
2100  RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2101  : Field;
2102  for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2103  QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2104  if (hasAccessibleDestructor(ET, IList->getEndLoc(), SemaRef)) {
2105  hadError = true;
2106  return;
2107  }
2108  }
2109  }
2110 
2111  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2112  Index >= IList->getNumInits())
2113  return;
2114 
2115  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2116  TopLevelObject)) {
2117  hadError = true;
2118  ++Index;
2119  return;
2120  }
2121 
2122  InitializedEntity MemberEntity =
2123  InitializedEntity::InitializeMember(*Field, &Entity);
2124 
2125  if (isa<InitListExpr>(IList->getInit(Index)))
2126  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2127  StructuredList, StructuredIndex);
2128  else
2129  CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2130  StructuredList, StructuredIndex);
2131 }
2132 
2133 /// Expand a field designator that refers to a member of an
2134 /// anonymous struct or union into a series of field designators that
2135 /// refers to the field within the appropriate subobject.
2136 ///
2138  DesignatedInitExpr *DIE,
2139  unsigned DesigIdx,
2140  IndirectFieldDecl *IndirectField) {
2142 
2143  // Build the replacement designators.
2144  SmallVector<Designator, 4> Replacements;
2145  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2146  PE = IndirectField->chain_end(); PI != PE; ++PI) {
2147  if (PI + 1 == PE)
2148  Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2149  DIE->getDesignator(DesigIdx)->getDotLoc(),
2150  DIE->getDesignator(DesigIdx)->getFieldLoc()));
2151  else
2152  Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2154  assert(isa<FieldDecl>(*PI));
2155  Replacements.back().setField(cast<FieldDecl>(*PI));
2156  }
2157 
2158  // Expand the current designator into the set of replacement
2159  // designators, so we have a full subobject path down to where the
2160  // member of the anonymous struct/union is actually stored.
2161  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2162  &Replacements[0] + Replacements.size());
2163 }
2164 
2166  DesignatedInitExpr *DIE) {
2167  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2168  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2169  for (unsigned I = 0; I < NumIndexExprs; ++I)
2170  IndexExprs[I] = DIE->getSubExpr(I + 1);
2171  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2172  IndexExprs,
2173  DIE->getEqualOrColonLoc(),
2174  DIE->usesGNUSyntax(), DIE->getInit());
2175 }
2176 
2177 namespace {
2178 
2179 // Callback to only accept typo corrections that are for field members of
2180 // the given struct or union.
2181 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2182  public:
2183  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2184  : Record(RD) {}
2185 
2186  bool ValidateCandidate(const TypoCorrection &candidate) override {
2187  FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2188  return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2189  }
2190 
2191  private:
2192  RecordDecl *Record;
2193 };
2194 
2195 } // end anonymous namespace
2196 
2197 /// Check the well-formedness of a C99 designated initializer.
2198 ///
2199 /// Determines whether the designated initializer @p DIE, which
2200 /// resides at the given @p Index within the initializer list @p
2201 /// IList, is well-formed for a current object of type @p DeclType
2202 /// (C99 6.7.8). The actual subobject that this designator refers to
2203 /// within the current subobject is returned in either
2204 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2205 ///
2206 /// @param IList The initializer list in which this designated
2207 /// initializer occurs.
2208 ///
2209 /// @param DIE The designated initializer expression.
2210 ///
2211 /// @param DesigIdx The index of the current designator.
2212 ///
2213 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2214 /// into which the designation in @p DIE should refer.
2215 ///
2216 /// @param NextField If non-NULL and the first designator in @p DIE is
2217 /// a field, this will be set to the field declaration corresponding
2218 /// to the field named by the designator.
2219 ///
2220 /// @param NextElementIndex If non-NULL and the first designator in @p
2221 /// DIE is an array designator or GNU array-range designator, this
2222 /// will be set to the last index initialized by this designator.
2223 ///
2224 /// @param Index Index into @p IList where the designated initializer
2225 /// @p DIE occurs.
2226 ///
2227 /// @param StructuredList The initializer list expression that
2228 /// describes all of the subobject initializers in the order they'll
2229 /// actually be initialized.
2230 ///
2231 /// @returns true if there was an error, false otherwise.
2232 bool
2233 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2234  InitListExpr *IList,
2235  DesignatedInitExpr *DIE,
2236  unsigned DesigIdx,
2237  QualType &CurrentObjectType,
2238  RecordDecl::field_iterator *NextField,
2239  llvm::APSInt *NextElementIndex,
2240  unsigned &Index,
2241  InitListExpr *StructuredList,
2242  unsigned &StructuredIndex,
2243  bool FinishSubobjectInit,
2244  bool TopLevelObject) {
2245  if (DesigIdx == DIE->size()) {
2246  // Check the actual initialization for the designated object type.
2247  bool prevHadError = hadError;
2248 
2249  // Temporarily remove the designator expression from the
2250  // initializer list that the child calls see, so that we don't try
2251  // to re-process the designator.
2252  unsigned OldIndex = Index;
2253  IList->setInit(OldIndex, DIE->getInit());
2254 
2255  CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2256  StructuredList, StructuredIndex);
2257 
2258  // Restore the designated initializer expression in the syntactic
2259  // form of the initializer list.
2260  if (IList->getInit(OldIndex) != DIE->getInit())
2261  DIE->setInit(IList->getInit(OldIndex));
2262  IList->setInit(OldIndex, DIE);
2263 
2264  return hadError && !prevHadError;
2265  }
2266 
2267  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2268  bool IsFirstDesignator = (DesigIdx == 0);
2269  if (!VerifyOnly) {
2270  assert((IsFirstDesignator || StructuredList) &&
2271  "Need a non-designated initializer list to start from");
2272 
2273  // Determine the structural initializer list that corresponds to the
2274  // current subobject.
2275  if (IsFirstDesignator)
2276  StructuredList = SyntacticToSemantic.lookup(IList);
2277  else {
2278  Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2279  StructuredList->getInit(StructuredIndex) : nullptr;
2280  if (!ExistingInit && StructuredList->hasArrayFiller())
2281  ExistingInit = StructuredList->getArrayFiller();
2282 
2283  if (!ExistingInit)
2284  StructuredList = getStructuredSubobjectInit(
2285  IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2286  SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2287  else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2288  StructuredList = Result;
2289  else {
2290  if (DesignatedInitUpdateExpr *E =
2291  dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2292  StructuredList = E->getUpdater();
2293  else {
2294  DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2296  ExistingInit, DIE->getEndLoc());
2297  StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2298  StructuredList = DIUE->getUpdater();
2299  }
2300 
2301  // We need to check on source range validity because the previous
2302  // initializer does not have to be an explicit initializer. e.g.,
2303  //
2304  // struct P { int a, b; };
2305  // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2306  //
2307  // There is an overwrite taking place because the first braced initializer
2308  // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2309  if (ExistingInit->getSourceRange().isValid()) {
2310  // We are creating an initializer list that initializes the
2311  // subobjects of the current object, but there was already an
2312  // initialization that completely initialized the current
2313  // subobject, e.g., by a compound literal:
2314  //
2315  // struct X { int a, b; };
2316  // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2317  //
2318  // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2319  // designated initializer re-initializes the whole
2320  // subobject [0], overwriting previous initializers.
2321  SemaRef.Diag(D->getBeginLoc(),
2322  diag::warn_subobject_initializer_overrides)
2323  << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
2324 
2325  SemaRef.Diag(ExistingInit->getBeginLoc(),
2326  diag::note_previous_initializer)
2327  << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
2328  }
2329  }
2330  }
2331  assert(StructuredList && "Expected a structured initializer list");
2332  }
2333 
2334  if (D->isFieldDesignator()) {
2335  // C99 6.7.8p7:
2336  //
2337  // If a designator has the form
2338  //
2339  // . identifier
2340  //
2341  // then the current object (defined below) shall have
2342  // structure or union type and the identifier shall be the
2343  // name of a member of that type.
2344  const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2345  if (!RT) {
2346  SourceLocation Loc = D->getDotLoc();
2347  if (Loc.isInvalid())
2348  Loc = D->getFieldLoc();
2349  if (!VerifyOnly)
2350  SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2351  << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2352  ++Index;
2353  return true;
2354  }
2355 
2356  FieldDecl *KnownField = D->getField();
2357  if (!KnownField) {
2358  IdentifierInfo *FieldName = D->getFieldName();
2359  DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2360  for (NamedDecl *ND : Lookup) {
2361  if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2362  KnownField = FD;
2363  break;
2364  }
2365  if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2366  // In verify mode, don't modify the original.
2367  if (VerifyOnly)
2368  DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2369  ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2370  D = DIE->getDesignator(DesigIdx);
2371  KnownField = cast<FieldDecl>(*IFD->chain_begin());
2372  break;
2373  }
2374  }
2375  if (!KnownField) {
2376  if (VerifyOnly) {
2377  ++Index;
2378  return true; // No typo correction when just trying this out.
2379  }
2380 
2381  // Name lookup found something, but it wasn't a field.
2382  if (!Lookup.empty()) {
2383  SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2384  << FieldName;
2385  SemaRef.Diag(Lookup.front()->getLocation(),
2386  diag::note_field_designator_found);
2387  ++Index;
2388  return true;
2389  }
2390 
2391  // Name lookup didn't find anything.
2392  // Determine whether this was a typo for another field name.
2393  if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2394  DeclarationNameInfo(FieldName, D->getFieldLoc()),
2395  Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
2396  llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2397  Sema::CTK_ErrorRecovery, RT->getDecl())) {
2398  SemaRef.diagnoseTypo(
2399  Corrected,
2400  SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2401  << FieldName << CurrentObjectType);
2402  KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2403  hadError = true;
2404  } else {
2405  // Typo correction didn't find anything.
2406  SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2407  << FieldName << CurrentObjectType;
2408  ++Index;
2409  return true;
2410  }
2411  }
2412  }
2413 
2414  unsigned FieldIndex = 0;
2415 
2416  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2417  FieldIndex = CXXRD->getNumBases();
2418 
2419  for (auto *FI : RT->getDecl()->fields()) {
2420  if (FI->isUnnamedBitfield())
2421  continue;
2422  if (declaresSameEntity(KnownField, FI)) {
2423  KnownField = FI;
2424  break;
2425  }
2426  ++FieldIndex;
2427  }
2428 
2431 
2432  // All of the fields of a union are located at the same place in
2433  // the initializer list.
2434  if (RT->getDecl()->isUnion()) {
2435  FieldIndex = 0;
2436  if (!VerifyOnly) {
2437  FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2438  if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2439  assert(StructuredList->getNumInits() == 1
2440  && "A union should never have more than one initializer!");
2441 
2442  Expr *ExistingInit = StructuredList->getInit(0);
2443  if (ExistingInit) {
2444  // We're about to throw away an initializer, emit warning.
2445  SemaRef.Diag(D->getFieldLoc(),
2446  diag::warn_initializer_overrides)
2447  << D->getSourceRange();
2448  SemaRef.Diag(ExistingInit->getBeginLoc(),
2449  diag::note_previous_initializer)
2450  << /*FIXME:has side effects=*/0
2451  << ExistingInit->getSourceRange();
2452  }
2453 
2454  // remove existing initializer
2455  StructuredList->resizeInits(SemaRef.Context, 0);
2456  StructuredList->setInitializedFieldInUnion(nullptr);
2457  }
2458 
2459  StructuredList->setInitializedFieldInUnion(*Field);
2460  }
2461  }
2462 
2463  // Make sure we can use this declaration.
2464  bool InvalidUse;
2465  if (VerifyOnly)
2466  InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2467  else
2468  InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2469  if (InvalidUse) {
2470  ++Index;
2471  return true;
2472  }
2473 
2474  if (!VerifyOnly) {
2475  // Update the designator with the field declaration.
2476  D->setField(*Field);
2477 
2478  // Make sure that our non-designated initializer list has space
2479  // for a subobject corresponding to this field.
2480  if (FieldIndex >= StructuredList->getNumInits())
2481  StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2482  }
2483 
2484  // This designator names a flexible array member.
2485  if (Field->getType()->isIncompleteArrayType()) {
2486  bool Invalid = false;
2487  if ((DesigIdx + 1) != DIE->size()) {
2488  // We can't designate an object within the flexible array
2489  // member (because GCC doesn't allow it).
2490  if (!VerifyOnly) {
2492  = DIE->getDesignator(DesigIdx + 1);
2493  SemaRef.Diag(NextD->getBeginLoc(),
2494  diag::err_designator_into_flexible_array_member)
2495  << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2496  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2497  << *Field;
2498  }
2499  Invalid = true;
2500  }
2501 
2502  if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2503  !isa<StringLiteral>(DIE->getInit())) {
2504  // The initializer is not an initializer list.
2505  if (!VerifyOnly) {
2506  SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2507  diag::err_flexible_array_init_needs_braces)
2508  << DIE->getInit()->getSourceRange();
2509  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2510  << *Field;
2511  }
2512  Invalid = true;
2513  }
2514 
2515  // Check GNU flexible array initializer.
2516  if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2517  TopLevelObject))
2518  Invalid = true;
2519 
2520  if (Invalid) {
2521  ++Index;
2522  return true;
2523  }
2524 
2525  // Initialize the array.
2526  bool prevHadError = hadError;
2527  unsigned newStructuredIndex = FieldIndex;
2528  unsigned OldIndex = Index;
2529  IList->setInit(Index, DIE->getInit());
2530 
2531  InitializedEntity MemberEntity =
2532  InitializedEntity::InitializeMember(*Field, &Entity);
2533  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2534  StructuredList, newStructuredIndex);
2535 
2536  IList->setInit(OldIndex, DIE);
2537  if (hadError && !prevHadError) {
2538  ++Field;
2539  ++FieldIndex;
2540  if (NextField)
2541  *NextField = Field;
2542  StructuredIndex = FieldIndex;
2543  return true;
2544  }
2545  } else {
2546  // Recurse to check later designated subobjects.
2547  QualType FieldType = Field->getType();
2548  unsigned newStructuredIndex = FieldIndex;
2549 
2550  InitializedEntity MemberEntity =
2551  InitializedEntity::InitializeMember(*Field, &Entity);
2552  if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2553  FieldType, nullptr, nullptr, Index,
2554  StructuredList, newStructuredIndex,
2555  FinishSubobjectInit, false))
2556  return true;
2557  }
2558 
2559  // Find the position of the next field to be initialized in this
2560  // subobject.
2561  ++Field;
2562  ++FieldIndex;
2563 
2564  // If this the first designator, our caller will continue checking
2565  // the rest of this struct/class/union subobject.
2566  if (IsFirstDesignator) {
2567  if (NextField)
2568  *NextField = Field;
2569  StructuredIndex = FieldIndex;
2570  return false;
2571  }
2572 
2573  if (!FinishSubobjectInit)
2574  return false;
2575 
2576  // We've already initialized something in the union; we're done.
2577  if (RT->getDecl()->isUnion())
2578  return hadError;
2579 
2580  // Check the remaining fields within this class/struct/union subobject.
2581  bool prevHadError = hadError;
2582 
2583  auto NoBases =
2586  CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2587  false, Index, StructuredList, FieldIndex);
2588  return hadError && !prevHadError;
2589  }
2590 
2591  // C99 6.7.8p6:
2592  //
2593  // If a designator has the form
2594  //
2595  // [ constant-expression ]
2596  //
2597  // then the current object (defined below) shall have array
2598  // type and the expression shall be an integer constant
2599  // expression. If the array is of unknown size, any
2600  // nonnegative value is valid.
2601  //
2602  // Additionally, cope with the GNU extension that permits
2603  // designators of the form
2604  //
2605  // [ constant-expression ... constant-expression ]
2606  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2607  if (!AT) {
2608  if (!VerifyOnly)
2609  SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2610  << CurrentObjectType;
2611  ++Index;
2612  return true;
2613  }
2614 
2615  Expr *IndexExpr = nullptr;
2616  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2617  if (D->isArrayDesignator()) {
2618  IndexExpr = DIE->getArrayIndex(*D);
2619  DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2620  DesignatedEndIndex = DesignatedStartIndex;
2621  } else {
2622  assert(D->isArrayRangeDesignator() && "Need array-range designator");
2623 
2624  DesignatedStartIndex =
2626  DesignatedEndIndex =
2627  DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2628  IndexExpr = DIE->getArrayRangeEnd(*D);
2629 
2630  // Codegen can't handle evaluating array range designators that have side
2631  // effects, because we replicate the AST value for each initialized element.
2632  // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2633  // elements with something that has a side effect, so codegen can emit an
2634  // "error unsupported" error instead of miscompiling the app.
2635  if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2636  DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2637  FullyStructuredList->sawArrayRangeDesignator();
2638  }
2639 
2640  if (isa<ConstantArrayType>(AT)) {
2641  llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2642  DesignatedStartIndex
2643  = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2644  DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2645  DesignatedEndIndex
2646  = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2647  DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2648  if (DesignatedEndIndex >= MaxElements) {
2649  if (!VerifyOnly)
2650  SemaRef.Diag(IndexExpr->getBeginLoc(),
2651  diag::err_array_designator_too_large)
2652  << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2653  << IndexExpr->getSourceRange();
2654  ++Index;
2655  return true;
2656  }
2657  } else {
2658  unsigned DesignatedIndexBitWidth =
2660  DesignatedStartIndex =
2661  DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2662  DesignatedEndIndex =
2663  DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2664  DesignatedStartIndex.setIsUnsigned(true);
2665  DesignatedEndIndex.setIsUnsigned(true);
2666  }
2667 
2668  if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2669  // We're modifying a string literal init; we have to decompose the string
2670  // so we can modify the individual characters.
2671  ASTContext &Context = SemaRef.Context;
2672  Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2673 
2674  // Compute the character type
2675  QualType CharTy = AT->getElementType();
2676 
2677  // Compute the type of the integer literals.
2678  QualType PromotedCharTy = CharTy;
2679  if (CharTy->isPromotableIntegerType())
2680  PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2681  unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2682 
2683  if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2684  // Get the length of the string.
2685  uint64_t StrLen = SL->getLength();
2686  if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2687  StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2688  StructuredList->resizeInits(Context, StrLen);
2689 
2690  // Build a literal for each character in the string, and put them into
2691  // the init list.
2692  for (unsigned i = 0, e = StrLen; i != e; ++i) {
2693  llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2694  Expr *Init = new (Context) IntegerLiteral(
2695  Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2696  if (CharTy != PromotedCharTy)
2697  Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2698  Init, nullptr, VK_RValue);
2699  StructuredList->updateInit(Context, i, Init);
2700  }
2701  } else {
2702  ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2703  std::string Str;
2704  Context.getObjCEncodingForType(E->getEncodedType(), Str);
2705 
2706  // Get the length of the string.
2707  uint64_t StrLen = Str.size();
2708  if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2709  StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2710  StructuredList->resizeInits(Context, StrLen);
2711 
2712  // Build a literal for each character in the string, and put them into
2713  // the init list.
2714  for (unsigned i = 0, e = StrLen; i != e; ++i) {
2715  llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2716  Expr *Init = new (Context) IntegerLiteral(
2717  Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2718  if (CharTy != PromotedCharTy)
2719  Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2720  Init, nullptr, VK_RValue);
2721  StructuredList->updateInit(Context, i, Init);
2722  }
2723  }
2724  }
2725 
2726  // Make sure that our non-designated initializer list has space
2727  // for a subobject corresponding to this array element.
2728  if (!VerifyOnly &&
2729  DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2730  StructuredList->resizeInits(SemaRef.Context,
2731  DesignatedEndIndex.getZExtValue() + 1);
2732 
2733  // Repeatedly perform subobject initializations in the range
2734  // [DesignatedStartIndex, DesignatedEndIndex].
2735 
2736  // Move to the next designator
2737  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2738  unsigned OldIndex = Index;
2739 
2740  InitializedEntity ElementEntity =
2741  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2742 
2743  while (DesignatedStartIndex <= DesignatedEndIndex) {
2744  // Recurse to check later designated subobjects.
2745  QualType ElementType = AT->getElementType();
2746  Index = OldIndex;
2747 
2748  ElementEntity.setElementIndex(ElementIndex);
2749  if (CheckDesignatedInitializer(
2750  ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2751  nullptr, Index, StructuredList, ElementIndex,
2752  FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2753  false))
2754  return true;
2755 
2756  // Move to the next index in the array that we'll be initializing.
2757  ++DesignatedStartIndex;
2758  ElementIndex = DesignatedStartIndex.getZExtValue();
2759  }
2760 
2761  // If this the first designator, our caller will continue checking
2762  // the rest of this array subobject.
2763  if (IsFirstDesignator) {
2764  if (NextElementIndex)
2765  *NextElementIndex = DesignatedStartIndex;
2766  StructuredIndex = ElementIndex;
2767  return false;
2768  }
2769 
2770  if (!FinishSubobjectInit)
2771  return false;
2772 
2773  // Check the remaining elements within this array subobject.
2774  bool prevHadError = hadError;
2775  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2776  /*SubobjectIsDesignatorContext=*/false, Index,
2777  StructuredList, ElementIndex);
2778  return hadError && !prevHadError;
2779 }
2780 
2781 // Get the structured initializer list for a subobject of type
2782 // @p CurrentObjectType.
2783 InitListExpr *
2784 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2785  QualType CurrentObjectType,
2786  InitListExpr *StructuredList,
2787  unsigned StructuredIndex,
2788  SourceRange InitRange,
2789  bool IsFullyOverwritten) {
2790  if (VerifyOnly)
2791  return nullptr; // No structured list in verification-only mode.
2792  Expr *ExistingInit = nullptr;
2793  if (!StructuredList)
2794  ExistingInit = SyntacticToSemantic.lookup(IList);
2795  else if (StructuredIndex < StructuredList->getNumInits())
2796  ExistingInit = StructuredList->getInit(StructuredIndex);
2797 
2798  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2799  // There might have already been initializers for subobjects of the current
2800  // object, but a subsequent initializer list will overwrite the entirety
2801  // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2802  //
2803  // struct P { char x[6]; };
2804  // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2805  //
2806  // The first designated initializer is ignored, and l.x is just "f".
2807  if (!IsFullyOverwritten)
2808  return Result;
2809 
2810  if (ExistingInit) {
2811  // We are creating an initializer list that initializes the
2812  // subobjects of the current object, but there was already an
2813  // initialization that completely initialized the current
2814  // subobject, e.g., by a compound literal:
2815  //
2816  // struct X { int a, b; };
2817  // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2818  //
2819  // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2820  // designated initializer re-initializes the whole
2821  // subobject [0], overwriting previous initializers.
2822  SemaRef.Diag(InitRange.getBegin(),
2823  diag::warn_subobject_initializer_overrides)
2824  << InitRange;
2825  SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
2826  << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
2827  }
2828 
2830  = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2831  InitRange.getBegin(), None,
2832  InitRange.getEnd());
2833 
2834  QualType ResultType = CurrentObjectType;
2835  if (!ResultType->isArrayType())
2836  ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2837  Result->setType(ResultType);
2838 
2839  // Pre-allocate storage for the structured initializer list.
2840  unsigned NumElements = 0;
2841  unsigned NumInits = 0;
2842  bool GotNumInits = false;
2843  if (!StructuredList) {
2844  NumInits = IList->getNumInits();
2845  GotNumInits = true;
2846  } else if (Index < IList->getNumInits()) {
2847  if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2848  NumInits = SubList->getNumInits();
2849  GotNumInits = true;
2850  }
2851  }
2852 
2853  if (const ArrayType *AType
2854  = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2855  if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2856  NumElements = CAType->getSize().getZExtValue();
2857  // Simple heuristic so that we don't allocate a very large
2858  // initializer with many empty entries at the end.
2859  if (GotNumInits && NumElements > NumInits)
2860  NumElements = 0;
2861  }
2862  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2863  NumElements = VType->getNumElements();
2864  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2865  RecordDecl *RDecl = RType->getDecl();
2866  if (RDecl->isUnion())
2867  NumElements = 1;
2868  else
2869  NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2870  }
2871 
2872  Result->reserveInits(SemaRef.Context, NumElements);
2873 
2874  // Link this new initializer list into the structured initializer
2875  // lists.
2876  if (StructuredList)
2877  StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2878  else {
2879  Result->setSyntacticForm(IList);
2880  SyntacticToSemantic[IList] = Result;
2881  }
2882 
2883  return Result;
2884 }
2885 
2886 /// Update the initializer at index @p StructuredIndex within the
2887 /// structured initializer list to the value @p expr.
2888 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2889  unsigned &StructuredIndex,
2890  Expr *expr) {
2891  // No structured initializer list to update
2892  if (!StructuredList)
2893  return;
2894 
2895  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2896  StructuredIndex, expr)) {
2897  // This initializer overwrites a previous initializer. Warn.
2898  // We need to check on source range validity because the previous
2899  // initializer does not have to be an explicit initializer.
2900  // struct P { int a, b; };
2901  // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2902  // There is an overwrite taking place because the first braced initializer
2903  // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2904  if (PrevInit->getSourceRange().isValid()) {
2905  SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
2906  << expr->getSourceRange();
2907 
2908  SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
2909  << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
2910  }
2911  }
2912 
2913  ++StructuredIndex;
2914 }
2915 
2916 /// Check that the given Index expression is a valid array designator
2917 /// value. This is essentially just a wrapper around
2918 /// VerifyIntegerConstantExpression that also checks for negative values
2919 /// and produces a reasonable diagnostic if there is a
2920 /// failure. Returns the index expression, possibly with an implicit cast
2921 /// added, on success. If everything went okay, Value will receive the
2922 /// value of the constant expression.
2923 static ExprResult
2924 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2925  SourceLocation Loc = Index->getBeginLoc();
2926 
2927  // Make sure this is an integer constant expression.
2929  if (Result.isInvalid())
2930  return Result;
2931 
2932  if (Value.isSigned() && Value.isNegative())
2933  return S.Diag(Loc, diag::err_array_designator_negative)
2934  << Value.toString(10) << Index->getSourceRange();
2935 
2936  Value.setIsUnsigned(true);
2937  return Result;
2938 }
2939 
2941  SourceLocation Loc,
2942  bool GNUSyntax,
2943  ExprResult Init) {
2944  typedef DesignatedInitExpr::Designator ASTDesignator;
2945 
2946  bool Invalid = false;
2947  SmallVector<ASTDesignator, 32> Designators;
2948  SmallVector<Expr *, 32> InitExpressions;
2949 
2950  // Build designators and check array designator expressions.
2951  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2952  const Designator &D = Desig.getDesignator(Idx);
2953  switch (D.getKind()) {
2955  Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2956  D.getFieldLoc()));
2957  break;
2958 
2960  Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2961  llvm::APSInt IndexValue;
2962  if (!Index->isTypeDependent() && !Index->isValueDependent())
2963  Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2964  if (!Index)
2965  Invalid = true;
2966  else {
2967  Designators.push_back(ASTDesignator(InitExpressions.size(),
2968  D.getLBracketLoc(),
2969  D.getRBracketLoc()));
2970  InitExpressions.push_back(Index);
2971  }
2972  break;
2973  }
2974 
2976  Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2977  Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2978  llvm::APSInt StartValue;
2979  llvm::APSInt EndValue;
2980  bool StartDependent = StartIndex->isTypeDependent() ||
2981  StartIndex->isValueDependent();
2982  bool EndDependent = EndIndex->isTypeDependent() ||
2983  EndIndex->isValueDependent();
2984  if (!StartDependent)
2985  StartIndex =
2986  CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2987  if (!EndDependent)
2988  EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2989 
2990  if (!StartIndex || !EndIndex)
2991  Invalid = true;
2992  else {
2993  // Make sure we're comparing values with the same bit width.
2994  if (StartDependent || EndDependent) {
2995  // Nothing to compute.
2996  } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2997  EndValue = EndValue.extend(StartValue.getBitWidth());
2998  else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2999  StartValue = StartValue.extend(EndValue.getBitWidth());
3000 
3001  if (!StartDependent && !EndDependent && EndValue < StartValue) {
3002  Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3003  << StartValue.toString(10) << EndValue.toString(10)
3004  << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3005  Invalid = true;
3006  } else {
3007  Designators.push_back(ASTDesignator(InitExpressions.size(),
3008  D.getLBracketLoc(),
3009  D.getEllipsisLoc(),
3010  D.getRBracketLoc()));
3011  InitExpressions.push_back(StartIndex);
3012  InitExpressions.push_back(EndIndex);
3013  }
3014  }
3015  break;
3016  }
3017  }
3018  }
3019 
3020  if (Invalid || Init.isInvalid())
3021  return ExprError();
3022 
3023  // Clear out the expressions within the designation.
3024  Desig.ClearExprs(*this);
3025 
3026  DesignatedInitExpr *DIE
3027  = DesignatedInitExpr::Create(Context,
3028  Designators,
3029  InitExpressions, Loc, GNUSyntax,
3030  Init.getAs<Expr>());
3031 
3032  if (!getLangOpts().C99)
3033  Diag(DIE->getBeginLoc(), diag::ext_designated_init)
3034  << DIE->getSourceRange();
3035 
3036  return DIE;
3037 }
3038 
3039 //===----------------------------------------------------------------------===//
3040 // Initialization entity
3041 //===----------------------------------------------------------------------===//
3042 
3043 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3044  const InitializedEntity &Parent)
3045  : Parent(&Parent), Index(Index)
3046 {
3047  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3048  Kind = EK_ArrayElement;
3049  Type = AT->getElementType();
3050  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3051  Kind = EK_VectorElement;
3052  Type = VT->getElementType();
3053  } else {
3054  const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3055  assert(CT && "Unexpected type");
3056  Kind = EK_ComplexElement;
3057  Type = CT->getElementType();
3058  }
3059 }
3060 
3063  const CXXBaseSpecifier *Base,
3064  bool IsInheritedVirtualBase,
3065  const InitializedEntity *Parent) {
3067  Result.Kind = EK_Base;
3068  Result.Parent = Parent;
3069  Result.Base = reinterpret_cast<uintptr_t>(Base);
3070  if (IsInheritedVirtualBase)
3071  Result.Base |= 0x01;
3072 
3073  Result.Type = Base->getType();
3074  return Result;
3075 }
3076 
3078  switch (getKind()) {
3079  case EK_Parameter:
3080  case EK_Parameter_CF_Audited: {
3081  ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3082  return (D ? D->getDeclName() : DeclarationName());
3083  }
3084 
3085  case EK_Variable:
3086  case EK_Member:
3087  case EK_Binding:
3088  return Variable.VariableOrMember->getDeclName();
3089 
3090  case EK_LambdaCapture:
3091  return DeclarationName(Capture.VarID);
3092 
3093  case EK_Result:
3094  case EK_StmtExprResult:
3095  case EK_Exception:
3096  case EK_New:
3097  case EK_Temporary:
3098  case EK_Base:
3099  case EK_Delegating:
3100  case EK_ArrayElement:
3101  case EK_VectorElement:
3102  case EK_ComplexElement:
3103  case EK_BlockElement:
3104  case EK_LambdaToBlockConversionBlockElement:
3105  case EK_CompoundLiteralInit:
3106  case EK_RelatedResult:
3107  return DeclarationName();
3108  }
3109 
3110  llvm_unreachable("Invalid EntityKind!");
3111 }
3112 
3114  switch (getKind()) {
3115  case EK_Variable:
3116  case EK_Member:
3117  case EK_Binding:
3118  return Variable.VariableOrMember;
3119 
3120  case EK_Parameter:
3121  case EK_Parameter_CF_Audited:
3122  return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3123 
3124  case EK_Result:
3125  case EK_StmtExprResult:
3126  case EK_Exception:
3127  case EK_New:
3128  case EK_Temporary:
3129  case EK_Base:
3130  case EK_Delegating:
3131  case EK_ArrayElement:
3132  case EK_VectorElement:
3133  case EK_ComplexElement:
3134  case EK_BlockElement:
3135  case EK_LambdaToBlockConversionBlockElement:
3136  case EK_LambdaCapture:
3137  case EK_CompoundLiteralInit:
3138  case EK_RelatedResult:
3139  return nullptr;
3140  }
3141 
3142  llvm_unreachable("Invalid EntityKind!");
3143 }
3144 
3146  switch (getKind()) {
3147  case EK_Result:
3148  case EK_Exception:
3149  return LocAndNRVO.NRVO;
3150 
3151  case EK_StmtExprResult:
3152  case EK_Variable:
3153  case EK_Parameter:
3154  case EK_Parameter_CF_Audited:
3155  case EK_Member:
3156  case EK_Binding:
3157  case EK_New:
3158  case EK_Temporary:
3159  case EK_CompoundLiteralInit:
3160  case EK_Base:
3161  case EK_Delegating:
3162  case EK_ArrayElement:
3163  case EK_VectorElement:
3164  case EK_ComplexElement:
3165  case EK_BlockElement:
3166  case EK_LambdaToBlockConversionBlockElement:
3167  case EK_LambdaCapture:
3168  case EK_RelatedResult:
3169  break;
3170  }
3171 
3172  return false;
3173 }
3174 
3175 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3176  assert(getParent() != this);
3177  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3178  for (unsigned I = 0; I != Depth; ++I)
3179  OS << "`-";
3180 
3181  switch (getKind()) {
3182  case EK_Variable: OS << "Variable"; break;
3183  case EK_Parameter: OS << "Parameter"; break;
3184  case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3185  break;
3186  case EK_Result: OS << "Result"; break;
3187  case EK_StmtExprResult: OS << "StmtExprResult"; break;
3188  case EK_Exception: OS << "Exception"; break;
3189  case EK_Member: OS << "Member"; break;
3190  case EK_Binding: OS << "Binding"; break;
3191  case EK_New: OS << "New"; break;
3192  case EK_Temporary: OS << "Temporary"; break;
3193  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3194  case EK_RelatedResult: OS << "RelatedResult"; break;
3195  case EK_Base: OS << "Base"; break;
3196  case EK_Delegating: OS << "Delegating"; break;
3197  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3198  case EK_VectorElement: OS << "VectorElement " << Index; break;
3199  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3200  case EK_BlockElement: OS << "Block"; break;
3201  case EK_LambdaToBlockConversionBlockElement:
3202  OS << "Block (lambda)";
3203  break;
3204  case EK_LambdaCapture:
3205  OS << "LambdaCapture ";
3206  OS << DeclarationName(Capture.VarID);
3207  break;
3208  }
3209 
3210  if (auto *D = getDecl()) {
3211  OS << " ";
3212  D->printQualifiedName(OS);
3213  }
3214 
3215  OS << " '" << getType().getAsString() << "'\n";
3216 
3217  return Depth + 1;
3218 }
3219 
3220 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3221  dumpImpl(llvm::errs());
3222 }
3223 
3224 //===----------------------------------------------------------------------===//
3225 // Initialization sequence
3226 //===----------------------------------------------------------------------===//
3227 
3229  switch (Kind) {
3230  case SK_ResolveAddressOfOverloadedFunction:
3231  case SK_CastDerivedToBaseRValue:
3232  case SK_CastDerivedToBaseXValue:
3233  case SK_CastDerivedToBaseLValue:
3234  case SK_BindReference:
3235  case SK_BindReferenceToTemporary:
3236  case SK_FinalCopy:
3237  case SK_ExtraneousCopyToTemporary:
3238  case SK_UserConversion:
3239  case SK_QualificationConversionRValue:
3240  case SK_QualificationConversionXValue:
3241  case SK_QualificationConversionLValue:
3242  case SK_AtomicConversion:
3243  case SK_LValueToRValue:
3244  case SK_ListInitialization:
3245  case SK_UnwrapInitList:
3246  case SK_RewrapInitList:
3247  case SK_ConstructorInitialization:
3248  case SK_ConstructorInitializationFromList:
3249  case SK_ZeroInitialization:
3250  case SK_CAssignment:
3251  case SK_StringInit:
3252  case SK_ObjCObjectConversion:
3253  case SK_ArrayLoopIndex:
3254  case SK_ArrayLoopInit:
3255  case SK_ArrayInit:
3256  case SK_GNUArrayInit:
3257  case SK_ParenthesizedArrayInit:
3258  case SK_PassByIndirectCopyRestore:
3259  case SK_PassByIndirectRestore:
3260  case SK_ProduceObjCObject:
3261  case SK_StdInitializerList:
3262  case SK_StdInitializerListConstructorCall:
3263  case SK_OCLSamplerInit:
3264  case SK_OCLZeroEvent:
3265  case SK_OCLZeroQueue:
3266  break;
3267 
3268  case SK_ConversionSequence:
3269  case SK_ConversionSequenceNoNarrowing:
3270  delete ICS;
3271  }
3272 }
3273 
3275  // There can be some lvalue adjustments after the SK_BindReference step.
3276  for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3277  if (I->Kind == SK_BindReference)
3278  return true;
3279  if (I->Kind == SK_BindReferenceToTemporary)
3280  return false;
3281  }
3282  return false;
3283 }
3284 
3286  if (!Failed())
3287  return false;
3288 
3289  switch (getFailureKind()) {
3290  case FK_TooManyInitsForReference:
3291  case FK_ParenthesizedListInitForReference:
3292  case FK_ArrayNeedsInitList:
3293  case FK_ArrayNeedsInitListOrStringLiteral:
3294  case FK_ArrayNeedsInitListOrWideStringLiteral:
3295  case FK_NarrowStringIntoWideCharArray:
3296  case FK_WideStringIntoCharArray:
3297  case FK_IncompatWideStringIntoWideChar:
3298  case FK_PlainStringIntoUTF8Char:
3299  case FK_UTF8StringIntoPlainChar:
3300  case FK_AddressOfOverloadFailed: // FIXME: Could do better
3301  case FK_NonConstLValueReferenceBindingToTemporary:
3302  case FK_NonConstLValueReferenceBindingToBitfield:
3303  case FK_NonConstLValueReferenceBindingToVectorElement:
3304  case FK_NonConstLValueReferenceBindingToUnrelated:
3305  case FK_RValueReferenceBindingToLValue:
3306  case FK_ReferenceInitDropsQualifiers:
3307  case FK_ReferenceInitFailed:
3308  case FK_ConversionFailed:
3309  case FK_ConversionFromPropertyFailed:
3310  case FK_TooManyInitsForScalar:
3311  case FK_ParenthesizedListInitForScalar:
3312  case FK_ReferenceBindingToInitList:
3313  case FK_InitListBadDestinationType:
3314  case FK_DefaultInitOfConst:
3315  case FK_Incomplete:
3316  case FK_ArrayTypeMismatch:
3317  case FK_NonConstantArrayInit:
3318  case FK_ListInitializationFailed:
3319  case FK_VariableLengthArrayHasInitializer:
3320  case FK_PlaceholderType:
3321  case FK_ExplicitConstructor:
3322  case FK_AddressOfUnaddressableFunction:
3323  return false;
3324 
3325  case FK_ReferenceInitOverloadFailed:
3326  case FK_UserConversionOverloadFailed:
3327  case FK_ConstructorOverloadFailed:
3328  case FK_ListConstructorOverloadFailed:
3329  return FailedOverloadResult == OR_Ambiguous;
3330  }
3331 
3332  llvm_unreachable("Invalid EntityKind!");
3333 }
3334 
3336  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3337 }
3338 
3339 void
3342  DeclAccessPair Found,
3343  bool HadMultipleCandidates) {
3344  Step S;
3345  S.Kind = SK_ResolveAddressOfOverloadedFunction;
3346  S.Type = Function->getType();
3347  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3348  S.Function.Function = Function;
3349  S.Function.FoundDecl = Found;
3350  Steps.push_back(S);
3351 }
3352 
3354  ExprValueKind VK) {
3355  Step S;
3356  switch (VK) {
3357  case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3358  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3359  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3360  }
3361  S.Type = BaseType;
3362  Steps.push_back(S);
3363 }
3364 
3366  bool BindingTemporary) {
3367  Step S;
3368  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3369  S.Type = T;
3370  Steps.push_back(S);
3371 }
3372 
3374  Step S;
3375  S.Kind = SK_FinalCopy;
3376  S.Type = T;
3377  Steps.push_back(S);
3378 }
3379 
3381  Step S;
3382  S.Kind = SK_ExtraneousCopyToTemporary;
3383  S.Type = T;
3384  Steps.push_back(S);
3385 }
3386 
3387 void
3389  DeclAccessPair FoundDecl,
3390  QualType T,
3391  bool HadMultipleCandidates) {
3392  Step S;
3393  S.Kind = SK_UserConversion;
3394  S.Type = T;
3395  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3396  S.Function.Function = Function;
3397  S.Function.FoundDecl = FoundDecl;
3398  Steps.push_back(S);
3399 }
3400 
3402  ExprValueKind VK) {
3403  Step S;
3404  S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3405  switch (VK) {
3406  case VK_RValue:
3407  S.Kind = SK_QualificationConversionRValue;
3408  break;
3409  case VK_XValue:
3410  S.Kind = SK_QualificationConversionXValue;
3411  break;
3412  case VK_LValue:
3413  S.Kind = SK_QualificationConversionLValue;
3414  break;
3415  }
3416  S.Type = Ty;
3417  Steps.push_back(S);
3418 }
3419 
3421  Step S;
3422  S.Kind = SK_AtomicConversion;
3423  S.Type = Ty;
3424  Steps.push_back(S);
3425 }
3426 
3428  assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3429 
3430  Step S;
3431  S.Kind = SK_LValueToRValue;
3432  S.Type = Ty;
3433  Steps.push_back(S);
3434 }
3435 
3437  const ImplicitConversionSequence &ICS, QualType T,
3438  bool TopLevelOfInitList) {
3439  Step S;
3440  S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3441  : SK_ConversionSequence;
3442  S.Type = T;
3443  S.ICS = new ImplicitConversionSequence(ICS);
3444  Steps.push_back(S);
3445 }
3446 
3448  Step S;
3449  S.Kind = SK_ListInitialization;
3450  S.Type = T;
3451  Steps.push_back(S);
3452 }
3453 
3455  DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3456  bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3457  Step S;
3458  S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3459  : SK_ConstructorInitializationFromList
3460  : SK_ConstructorInitialization;
3461  S.Type = T;
3462  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3463  S.Function.Function = Constructor;
3464  S.Function.FoundDecl = FoundDecl;
3465  Steps.push_back(S);
3466 }
3467 
3469  Step S;
3470  S.Kind = SK_ZeroInitialization;
3471  S.Type = T;
3472  Steps.push_back(S);
3473 }
3474 
3476  Step S;
3477  S.Kind = SK_CAssignment;
3478  S.Type = T;
3479  Steps.push_back(S);
3480 }
3481 
3483  Step S;
3484  S.Kind = SK_StringInit;
3485  S.Type = T;
3486  Steps.push_back(S);
3487 }
3488 
3490  Step S;
3491  S.Kind = SK_ObjCObjectConversion;
3492  S.Type = T;
3493  Steps.push_back(S);
3494 }
3495 
3497  Step S;
3498  S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3499  S.Type = T;
3500  Steps.push_back(S);
3501 }
3502 
3504  Step S;
3505  S.Kind = SK_ArrayLoopIndex;
3506  S.Type = EltT;
3507  Steps.insert(Steps.begin(), S);
3508 
3509  S.Kind = SK_ArrayLoopInit;
3510  S.Type = T;
3511  Steps.push_back(S);
3512 }
3513 
3515  Step S;
3516  S.Kind = SK_ParenthesizedArrayInit;
3517  S.Type = T;
3518  Steps.push_back(S);
3519 }
3520 
3522  bool shouldCopy) {
3523  Step s;
3524  s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3525  : SK_PassByIndirectRestore);
3526  s.Type = type;
3527  Steps.push_back(s);
3528 }
3529 
3531  Step S;
3532  S.Kind = SK_ProduceObjCObject;
3533  S.Type = T;
3534  Steps.push_back(S);
3535 }
3536 
3538  Step S;
3539  S.Kind = SK_StdInitializerList;
3540  S.Type = T;
3541  Steps.push_back(S);
3542 }
3543 
3545  Step S;
3546  S.Kind = SK_OCLSamplerInit;
3547  S.Type = T;
3548  Steps.push_back(S);
3549 }
3550 
3552  Step S;
3553  S.Kind = SK_OCLZeroEvent;
3554  S.Type = T;
3555  Steps.push_back(S);
3556 }
3557 
3559  Step S;
3560  S.Kind = SK_OCLZeroQueue;
3561  S.Type = T;
3562  Steps.push_back(S);
3563 }
3564 
3566  InitListExpr *Syntactic) {
3567  assert(Syntactic->getNumInits() == 1 &&
3568  "Can only rewrap trivial init lists.");
3569  Step S;
3570  S.Kind = SK_UnwrapInitList;
3571  S.Type = Syntactic->getInit(0)->getType();
3572  Steps.insert(Steps.begin(), S);
3573 
3574  S.Kind = SK_RewrapInitList;
3575  S.Type = T;
3576  S.WrappingSyntacticList = Syntactic;
3577  Steps.push_back(S);
3578 }
3579 
3582  setSequenceKind(FailedSequence);
3583  this->Failure = Failure;
3584  this->FailedOverloadResult = Result;
3585 }
3586 
3587 //===----------------------------------------------------------------------===//
3588 // Attempt initialization
3589 //===----------------------------------------------------------------------===//
3590 
3591 /// Tries to add a zero initializer. Returns true if that worked.
3592 static bool
3594  const InitializedEntity &Entity) {
3595  if (Entity.getKind() != InitializedEntity::EK_Variable)
3596  return false;
3597 
3598  VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3599  if (VD->getInit() || VD->getEndLoc().isMacroID())
3600  return false;
3601 
3602  QualType VariableTy = VD->getType().getCanonicalType();
3604  std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3605  if (!Init.empty()) {
3606  Sequence.AddZeroInitializationStep(Entity.getType());
3607  Sequence.SetZeroInitializationFixit(Init, Loc);
3608  return true;
3609  }
3610  return false;
3611 }
3612 
3614  InitializationSequence &Sequence,
3615  const InitializedEntity &Entity) {
3616  if (!S.getLangOpts().ObjCAutoRefCount) return;
3617 
3618  /// When initializing a parameter, produce the value if it's marked
3619  /// __attribute__((ns_consumed)).
3620  if (Entity.isParameterKind()) {
3621  if (!Entity.isParameterConsumed())
3622  return;
3623 
3624  assert(Entity.getType()->isObjCRetainableType() &&
3625  "consuming an object of unretainable type?");
3626  Sequence.AddProduceObjCObjectStep(Entity.getType());
3627 
3628  /// When initializing a return value, if the return type is a
3629  /// retainable type, then returns need to immediately retain the
3630  /// object. If an autorelease is required, it will be done at the
3631  /// last instant.
3632  } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3634  if (!Entity.getType()->isObjCRetainableType())
3635  return;
3636 
3637  Sequence.AddProduceObjCObjectStep(Entity.getType());
3638  }
3639 }
3640 
3641 static void TryListInitialization(Sema &S,
3642  const InitializedEntity &Entity,
3643  const InitializationKind &Kind,
3644  InitListExpr *InitList,
3645  InitializationSequence &Sequence,
3646  bool TreatUnavailableAsInvalid);
3647 
3648 /// When initializing from init list via constructor, handle
3649 /// initialization of an object of type std::initializer_list<T>.
3650 ///
3651 /// \return true if we have handled initialization of an object of type
3652 /// std::initializer_list<T>, false otherwise.
3654  InitListExpr *List,
3655  QualType DestType,
3656  InitializationSequence &Sequence,
3657  bool TreatUnavailableAsInvalid) {
3658  QualType E;
3659  if (!S.isStdInitializerList(DestType, &E))
3660  return false;
3661 
3662  if (!S.isCompleteType(List->getExprLoc(), E)) {
3663  Sequence.setIncompleteTypeFailure(E);
3664  return true;
3665  }
3666 
3667  // Try initializing a temporary array from the init list.
3669  E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3670  List->getNumInits()),
3672  InitializedEntity HiddenArray =
3675  List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3676  TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3677  TreatUnavailableAsInvalid);
3678  if (Sequence)
3679  Sequence.AddStdInitializerListConstructionStep(DestType);
3680  return true;
3681 }
3682 
3683 /// Determine if the constructor has the signature of a copy or move
3684 /// constructor for the type T of the class in which it was found. That is,
3685 /// determine if its first parameter is of type T or reference to (possibly
3686 /// cv-qualified) T.
3688  const ConstructorInfo &Info) {
3689  if (Info.Constructor->getNumParams() == 0)
3690  return false;
3691 
3692  QualType ParmT =
3694  QualType ClassT =
3695  Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3696 
3697  return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3698 }
3699 
3700 static OverloadingResult
3702  MultiExprArg Args,
3703  OverloadCandidateSet &CandidateSet,
3704  QualType DestType,
3707  bool CopyInitializing, bool AllowExplicit,
3708  bool OnlyListConstructors, bool IsListInit,
3709  bool SecondStepOfCopyInit = false) {
3711 
3712  for (NamedDecl *D : Ctors) {
3713  auto Info = getConstructorInfo(D);
3714  if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3715  continue;
3716 
3717  if (!AllowExplicit && Info.Constructor->isExplicit())
3718  continue;
3719 
3720  if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3721  continue;
3722 
3723  // C++11 [over.best.ics]p4:
3724  // ... and the constructor or user-defined conversion function is a
3725  // candidate by
3726  // - 13.3.1.3, when the argument is the temporary in the second step
3727  // of a class copy-initialization, or
3728  // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3729  // - the second phase of 13.3.1.7 when the initializer list has exactly
3730  // one element that is itself an initializer list, and the target is
3731  // the first parameter of a constructor of class X, and the conversion
3732  // is to X or reference to (possibly cv-qualified X),
3733  // user-defined conversion sequences are not considered.
3734  bool SuppressUserConversions =
3735  SecondStepOfCopyInit ||
3736  (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3737  hasCopyOrMoveCtorParam(S.Context, Info));
3738 
3739  if (Info.ConstructorTmpl)
3740  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3741  /*ExplicitArgs*/ nullptr, Args,
3742  CandidateSet, SuppressUserConversions);
3743  else {
3744  // C++ [over.match.copy]p1:
3745  // - When initializing a temporary to be bound to the first parameter
3746  // of a constructor [for type T] that takes a reference to possibly
3747  // cv-qualified T as its first argument, called with a single
3748  // argument in the context of direct-initialization, explicit
3749  // conversion functions are also considered.
3750  // FIXME: What if a constructor template instantiates to such a signature?
3751  bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3752  Args.size() == 1 &&
3754  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3755  CandidateSet, SuppressUserConversions,
3756  /*PartialOverloading=*/false,
3757  /*AllowExplicit=*/AllowExplicitConv);
3758  }
3759  }
3760 
3761  // FIXME: Work around a bug in C++17 guaranteed copy elision.
3762  //
3763  // When initializing an object of class type T by constructor
3764  // ([over.match.ctor]) or by list-initialization ([over.match.list])
3765  // from a single expression of class type U, conversion functions of
3766  // U that convert to the non-reference type cv T are candidates.
3767  // Explicit conversion functions are only candidates during
3768  // direct-initialization.
3769  //
3770  // Note: SecondStepOfCopyInit is only ever true in this case when
3771  // evaluating whether to produce a C++98 compatibility warning.
3772  if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
3773  !SecondStepOfCopyInit) {
3774  Expr *Initializer = Args[0];
3775  auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3776  if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3777  const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3778  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3779  NamedDecl *D = *I;
3780  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3781  D = D->getUnderlyingDecl();
3782 
3783  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3784  CXXConversionDecl *Conv;
3785  if (ConvTemplate)
3786  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3787  else
3788  Conv = cast<CXXConversionDecl>(D);
3789 
3790  if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3791  if (ConvTemplate)
3792  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3793  ActingDC, Initializer, DestType,
3794  CandidateSet, AllowExplicit,
3795  /*AllowResultConversion*/false);
3796  else
3797  S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3798  DestType, CandidateSet, AllowExplicit,
3799  /*AllowResultConversion*/false);
3800  }
3801  }
3802  }
3803  }
3804 
3805  // Perform overload resolution and return the result.
3806  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3807 }
3808 
3809 /// Attempt initialization by constructor (C++ [dcl.init]), which
3810 /// enumerates the constructors of the initialized entity and performs overload
3811 /// resolution to select the best.
3812 /// \param DestType The destination class type.
3813 /// \param DestArrayType The destination type, which is either DestType or
3814 /// a (possibly multidimensional) array of DestType.
3815 /// \param IsListInit Is this list-initialization?
3816 /// \param IsInitListCopy Is this non-list-initialization resulting from a
3817 /// list-initialization from {x} where x is the same
3818 /// type as the entity?
3820  const InitializedEntity &Entity,
3821  const InitializationKind &Kind,
3822  MultiExprArg Args, QualType DestType,
3823  QualType DestArrayType,
3824  InitializationSequence &Sequence,
3825  bool IsListInit = false,
3826  bool IsInitListCopy = false) {
3827  assert(((!IsListInit && !IsInitListCopy) ||
3828  (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3829  "IsListInit/IsInitListCopy must come with a single initializer list "
3830  "argument.");
3831  InitListExpr *ILE =
3832  (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3833  MultiExprArg UnwrappedArgs =
3834  ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
3835 
3836  // The type we're constructing needs to be complete.
3837  if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3838  Sequence.setIncompleteTypeFailure(DestType);
3839  return;
3840  }
3841 
3842  // C++17 [dcl.init]p17:
3843  // - If the initializer expression is a prvalue and the cv-unqualified
3844  // version of the source type is the same class as the class of the
3845  // destination, the initializer expression is used to initialize the
3846  // destination object.
3847  // Per DR (no number yet), this does not apply when initializing a base
3848  // class or delegating to another constructor from a mem-initializer.
3849  // ObjC++: Lambda captured by the block in the lambda to block conversion
3850  // should avoid copy elision.
3851  if (S.getLangOpts().CPlusPlus17 &&
3852  Entity.getKind() != InitializedEntity::EK_Base &&
3854  Entity.getKind() !=
3856  UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3857  S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3858  // Convert qualifications if necessary.
3859  Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3860  if (ILE)
3861  Sequence.RewrapReferenceInitList(DestType, ILE);
3862  return;
3863  }
3864 
3865  const RecordType *DestRecordType = DestType->getAs<RecordType>();
3866  assert(DestRecordType && "Constructor initialization requires record type");
3867  CXXRecordDecl *DestRecordDecl
3868  = cast<CXXRecordDecl>(DestRecordType->getDecl());
3869 
3870  // Build the candidate set directly in the initialization sequence
3871  // structure, so that it will persist if we fail.
3872  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3873 
3874  // Determine whether we are allowed to call explicit constructors or
3875  // explicit conversion operators.
3876  bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3877  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3878 
3879  // - Otherwise, if T is a class type, constructors are considered. The
3880  // applicable constructors are enumerated, and the best one is chosen
3881  // through overload resolution.
3882  DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3883 
3886  bool AsInitializerList = false;
3887 
3888  // C++11 [over.match.list]p1, per DR1467:
3889  // When objects of non-aggregate type T are list-initialized, such that
3890  // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3891  // according to the rules in this section, overload resolution selects
3892  // the constructor in two phases:
3893  //
3894  // - Initially, the candidate functions are the initializer-list
3895  // constructors of the class T and the argument list consists of the
3896  // initializer list as a single argument.
3897  if (IsListInit) {
3898  AsInitializerList = true;
3899 
3900  // If the initializer list has no elements and T has a default constructor,
3901  // the first phase is omitted.
3902  if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
3903  Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3904  CandidateSet, DestType, Ctors, Best,
3905  CopyInitialization, AllowExplicit,
3906  /*OnlyListConstructor=*/true,
3907  IsListInit);
3908  }
3909 
3910  // C++11 [over.match.list]p1:
3911  // - If no viable initializer-list constructor is found, overload resolution
3912  // is performed again, where the candidate functions are all the
3913  // constructors of the class T and the argument list consists of the
3914  // elements of the initializer list.
3915  if (Result == OR_No_Viable_Function) {
3916  AsInitializerList = false;
3917  Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3918  CandidateSet, DestType, Ctors, Best,
3919  CopyInitialization, AllowExplicit,
3920  /*OnlyListConstructors=*/false,
3921  IsListInit);
3922  }
3923  if (Result) {
3924  Sequence.SetOverloadFailure(IsListInit ?
3927  Result);
3928  return;
3929  }
3930 
3931  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3932 
3933  // In C++17, ResolveConstructorOverload can select a conversion function
3934  // instead of a constructor.
3935  if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3936  // Add the user-defined conversion step that calls the conversion function.
3937  QualType ConvType = CD->getConversionType();
3938  assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3939  "should not have selected this conversion function");
3940  Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3941  HadMultipleCandidates);
3942  if (!S.Context.hasSameType(ConvType, DestType))
3943  Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3944  if (IsListInit)
3945  Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3946  return;
3947  }
3948 
3949  // C++11 [dcl.init]p6:
3950  // If a program calls for the default initialization of an object
3951  // of a const-qualified type T, T shall be a class type with a
3952  // user-provided default constructor.
3953  // C++ core issue 253 proposal:
3954  // If the implicit default constructor initializes all subobjects, no
3955  // initializer should be required.
3956  // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3957  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3958  if (Kind.getKind() == InitializationKind::IK_Default &&
3959  Entity.getType().isConstQualified()) {
3960  if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3961  if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3963  return;
3964  }
3965  }
3966 
3967  // C++11 [over.match.list]p1:
3968  // In copy-list-initialization, if an explicit constructor is chosen, the
3969  // initializer is ill-formed.
3970  if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3972  return;
3973  }
3974 
3975  // Add the constructor initialization step. Any cv-qualification conversion is
3976  // subsumed by the initialization.
3978  Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
3979  IsListInit | IsInitListCopy, AsInitializerList);
3980 }
3981 
3982 static bool
3984  Expr *Initializer,
3985  QualType &SourceType,
3986  QualType &UnqualifiedSourceType,
3987  QualType UnqualifiedTargetType,
3988  InitializationSequence &Sequence) {
3989  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3990  S.Context.OverloadTy) {
3991  DeclAccessPair Found;
3992  bool HadMultipleCandidates = false;
3993  if (FunctionDecl *Fn
3994  = S.ResolveAddressOfOverloadedFunction(Initializer,
3995  UnqualifiedTargetType,
3996  false, Found,
3997  &HadMultipleCandidates)) {
3998  Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3999  HadMultipleCandidates);
4000  SourceType = Fn->getType();
4001  UnqualifiedSourceType = SourceType.getUnqualifiedType();
4002  } else if (!UnqualifiedTargetType->isRecordType()) {
4004  return true;
4005  }
4006  }
4007  return false;
4008 }
4009 
4010 static void TryReferenceInitializationCore(Sema &S,
4011  const InitializedEntity &Entity,
4012  const InitializationKind &Kind,
4013  Expr *Initializer,
4014  QualType cv1T1, QualType T1,
4015  Qualifiers T1Quals,
4016  QualType cv2T2, QualType T2,
4017  Qualifiers T2Quals,
4018  InitializationSequence &Sequence);
4019 
4020 static void TryValueInitialization(Sema &S,
4021  const InitializedEntity &Entity,
4022  const InitializationKind &Kind,
4023  InitializationSequence &Sequence,
4024  InitListExpr *InitList = nullptr);
4025 
4026 /// Attempt list initialization of a reference.
4028  const InitializedEntity &Entity,
4029  const InitializationKind &Kind,
4030  InitListExpr *InitList,
4031  InitializationSequence &Sequence,
4032  bool TreatUnavailableAsInvalid) {
4033  // First, catch C++03 where this isn't possible.
4034  if (!S.getLangOpts().CPlusPlus11) {
4036  return;
4037  }
4038  // Can't reference initialize a compound literal.
4041  return;
4042  }
4043 
4044  QualType DestType = Entity.getType();
4045  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4046  Qualifiers T1Quals;
4047  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4048 
4049  // Reference initialization via an initializer list works thus:
4050  // If the initializer list consists of a single element that is
4051  // reference-related to the referenced type, bind directly to that element
4052  // (possibly creating temporaries).
4053  // Otherwise, initialize a temporary with the initializer list and
4054  // bind to that.
4055  if (InitList->getNumInits() == 1) {
4056  Expr *Initializer = InitList->getInit(0);
4057  QualType cv2T2 = Initializer->getType();
4058  Qualifiers T2Quals;
4059  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4060 
4061  // If this fails, creating a temporary wouldn't work either.
4062  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4063  T1, Sequence))
4064  return;
4065 
4066  SourceLocation DeclLoc = Initializer->getBeginLoc();
4067  bool dummy1, dummy2, dummy3;
4068  Sema::ReferenceCompareResult RefRelationship
4069  = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
4070  dummy2, dummy3);
4071  if (RefRelationship >= Sema::Ref_Related) {
4072  // Try to bind the reference here.
4073  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4074  T1Quals, cv2T2, T2, T2Quals, Sequence);
4075  if (Sequence)
4076  Sequence.RewrapReferenceInitList(cv1T1, InitList);
4077  return;
4078  }
4079 
4080  // Update the initializer if we've resolved an overloaded function.
4081  if (Sequence.step_begin() != Sequence.step_end())
4082  Sequence.RewrapReferenceInitList(cv1T1, InitList);
4083  }
4084 
4085  // Not reference-related. Create a temporary and bind to that.
4087 
4088  TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4089  TreatUnavailableAsInvalid);
4090  if (Sequence) {
4091  if (DestType->isRValueReferenceType() ||
4092  (T1Quals.hasConst() && !T1Quals.hasVolatile()))
4093  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4094  else
4095  Sequence.SetFailed(
4097  }
4098 }
4099 
4100 /// Attempt list initialization (C++0x [dcl.init.list])
4102  const InitializedEntity &Entity,
4103  const InitializationKind &Kind,
4104  InitListExpr *InitList,
4105  InitializationSequence &Sequence,
4106  bool TreatUnavailableAsInvalid) {
4107  QualType DestType = Entity.getType();
4108 
4109  // C++ doesn't allow scalar initialization with more than one argument.
4110  // But C99 complex numbers are scalars and it makes sense there.
4111  if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4112  !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4114  return;
4115  }
4116  if (DestType->isReferenceType()) {
4117  TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4118  TreatUnavailableAsInvalid);
4119  return;
4120  }
4121 
4122  if (DestType->isRecordType() &&
4123  !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4124  Sequence.setIncompleteTypeFailure(DestType);
4125  return;
4126  }
4127 
4128  // C++11 [dcl.init.list]p3, per DR1467:
4129  // - If T is a class type and the initializer list has a single element of
4130  // type cv U, where U is T or a class derived from T, the object is
4131  // initialized from that element (by copy-initialization for
4132  // copy-list-initialization, or by direct-initialization for
4133  // direct-list-initialization).
4134  // - Otherwise, if T is a character array and the initializer list has a
4135  // single element that is an appropriately-typed string literal
4136  // (8.5.2 [dcl.init.string]), initialization is performed as described
4137  // in that section.
4138  // - Otherwise, if T is an aggregate, [...] (continue below).
4139  if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4140  if (DestType->isRecordType()) {
4141  QualType InitType = InitList->getInit(0)->getType();
4142  if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4143  S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4144  Expr *InitListAsExpr = InitList;
4145  TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4146  DestType, Sequence,
4147  /*InitListSyntax*/false,
4148  /*IsInitListCopy*/true);
4149  return;
4150  }
4151  }
4152  if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4153  Expr *SubInit[1] = {InitList->getInit(0)};
4154  if (!isa<VariableArrayType>(DestAT) &&
4155  IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4156  InitializationKind SubKind =
4159  InitList->getLBraceLoc(),
4160  InitList->getRBraceLoc())
4161  : Kind;
4162  Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4163  /*TopLevelOfInitList*/ true,
4164  TreatUnavailableAsInvalid);
4165 
4166  // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4167  // the element is not an appropriately-typed string literal, in which
4168  // case we should proceed as in C++11 (below).
4169  if (Sequence) {
4170  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4171  return;
4172  }
4173  }
4174  }
4175  }
4176 
4177  // C++11 [dcl.init.list]p3:
4178  // - If T is an aggregate, aggregate initialization is performed.
4179  if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4180  (S.getLangOpts().CPlusPlus11 &&
4181  S.isStdInitializerList(DestType, nullptr))) {
4182  if (S.getLangOpts().CPlusPlus11) {
4183  // - Otherwise, if the initializer list has no elements and T is a
4184  // class type with a default constructor, the object is
4185  // value-initialized.
4186  if (InitList->getNumInits() == 0) {
4187  CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4188  if (RD->hasDefaultConstructor()) {
4189  TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4190  return;
4191  }
4192  }
4193 
4194  // - Otherwise, if T is a specialization of std::initializer_list<E>,
4195  // an initializer_list object constructed [...]
4196  if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4197  TreatUnavailableAsInvalid))
4198  return;
4199 
4200  // - Otherwise, if T is a class type, constructors are considered.
4201  Expr *InitListAsExpr = InitList;
4202  TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4203  DestType, Sequence, /*InitListSyntax*/true);
4204  } else
4206  return;
4207  }
4208 
4209  if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4210  InitList->getNumInits() == 1) {
4211  Expr *E = InitList->getInit(0);
4212 
4213  // - Otherwise, if T is an enumeration with a fixed underlying type,
4214  // the initializer-list has a single element v, and the initialization
4215  // is direct-list-initialization, the object is initialized with the
4216  // value T(v); if a narrowing conversion is required to convert v to
4217  // the underlying type of T, the program is ill-formed.
4218  auto *ET = DestType->getAs<EnumType>();
4219  if (S.getLangOpts().CPlusPlus17 &&
4221  ET && ET->getDecl()->isFixed() &&
4222  !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4224  E->getType()->isFloatingType())) {
4225  // There are two ways that T(v) can work when T is an enumeration type.
4226  // If there is either an implicit conversion sequence from v to T or
4227  // a conversion function that can convert from v to T, then we use that.
4228  // Otherwise, if v is of integral, enumeration, or floating-point type,
4229  // it is converted to the enumeration type via its underlying type.
4230  // There is no overlap possible between these two cases (except when the
4231  // source value is already of the destination type), and the first
4232  // case is handled by the general case for single-element lists below.
4234  ICS.setStandard();
4236  if (!E->isRValue())
4238  // If E is of a floating-point type, then the conversion is ill-formed
4239  // due to narrowing, but go through the motions in order to produce the
4240  // right diagnostic.
4241  ICS.Standard.Second = E->getType()->isFloatingType()
4244  ICS.Standard.setFromType(E->getType());
4245  ICS.Standard.setToType(0, E->getType());
4246  ICS.Standard.setToType(1, DestType);
4247  ICS.Standard.setToType(2, DestType);
4248  Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4249  /*TopLevelOfInitList*/true);
4250  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4251  return;
4252  }
4253 
4254  // - Otherwise, if the initializer list has a single element of type E
4255  // [...references are handled above...], the object or reference is
4256  // initialized from that element (by copy-initialization for
4257  // copy-list-initialization, or by direct-initialization for
4258  // direct-list-initialization); if a narrowing conversion is required
4259  // to convert the element to T, the program is ill-formed.
4260  //
4261  // Per core-24034, this is direct-initialization if we were performing
4262  // direct-list-initialization and copy-initialization otherwise.
4263  // We can't use InitListChecker for this, because it always performs
4264  // copy-initialization. This only matters if we might use an 'explicit'
4265  // conversion operator, so we only need to handle the cases where the source
4266  // is of record type.
4267  if (InitList->getInit(0)->getType()->isRecordType()) {
4268  InitializationKind SubKind =
4271  InitList->getLBraceLoc(),
4272  InitList->getRBraceLoc())
4273  : Kind;
4274  Expr *SubInit[1] = { InitList->getInit(0) };
4275  Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4276  /*TopLevelOfInitList*/true,
4277  TreatUnavailableAsInvalid);
4278  if (Sequence)
4279  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4280  return;
4281  }
4282  }
4283 
4284  InitListChecker CheckInitList(S, Entity, InitList,
4285  DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4286  if (CheckInitList.HadError()) {
4288  return;
4289  }
4290 
4291  // Add the list initialization step with the built init list.
4292  Sequence.AddListInitializationStep(DestType);
4293 }
4294 
4295 /// Try a reference initialization that involves calling a conversion
4296 /// function.
4298  Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4299  Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4300  InitializationSequence &Sequence) {
4301  QualType DestType = Entity.getType();
4302  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4303  QualType T1 = cv1T1.getUnqualifiedType();
4304  QualType cv2T2 = Initializer->getType();
4305  QualType T2 = cv2T2.getUnqualifiedType();
4306 
4307  bool DerivedToBase;
4308  bool ObjCConversion;
4309  bool ObjCLifetimeConversion;
4310  assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
4311  DerivedToBase, ObjCConversion,
4312  ObjCLifetimeConversion) &&
4313  "Must have incompatible references when binding via conversion");
4314  (void)DerivedToBase;
4315  (void)ObjCConversion;
4316  (void)ObjCLifetimeConversion;
4317 
4318  // Build the candidate set directly in the initialization sequence
4319  // structure, so that it will persist if we fail.
4320  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4322 
4323  // Determine whether we are allowed to call explicit conversion operators.
4324  // Note that none of [over.match.copy], [over.match.conv], nor
4325  // [over.match.ref] permit an explicit constructor to be chosen when
4326  // initializing a reference, not even for direct-initialization.
4327  bool AllowExplicitCtors = false;
4328  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4329 
4330  const RecordType *T1RecordType = nullptr;
4331  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4332  S.isCompleteType(Kind.getLocation(), T1)) {
4333  // The type we're converting to is a class type. Enumerate its constructors
4334  // to see if there is a suitable conversion.
4335  CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4336 
4337  for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4338  auto Info = getConstructorInfo(D);
4339  if (!Info.Constructor)
4340  continue;
4341 
4342  if (!Info.Constructor->isInvalidDecl() &&
4343  Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
4344  if (Info.ConstructorTmpl)
4345  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4346  /*ExplicitArgs*/ nullptr,
4347  Initializer, CandidateSet,
4348  /*SuppressUserConversions=*/true);
4349  else
4350  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4351  Initializer, CandidateSet,
4352  /*SuppressUserConversions=*/true);
4353  }
4354  }
4355  }
4356  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4357  return OR_No_Viable_Function;
4358 
4359  const RecordType *T2RecordType = nullptr;
4360  if ((T2RecordType = T2->getAs<RecordType>()) &&
4361  S.isCompleteType(Kind.getLocation(), T2)) {
4362  // The type we're converting from is a class type, enumerate its conversion
4363  // functions.
4364  CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4365 
4366  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4367  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4368  NamedDecl *D = *I;
4369  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4370  if (isa<UsingShadowDecl>(D))
4371  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4372 
4373  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4374  CXXConversionDecl *Conv;
4375  if (ConvTemplate)
4376  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4377  else
4378  Conv = cast<CXXConversionDecl>(D);
4379 
4380  // If the conversion function doesn't return a reference type,
4381  // it can't be considered for this conversion unless we're allowed to
4382  // consider rvalues.
4383  // FIXME: Do we need to make sure that we only consider conversion
4384  // candidates with reference-compatible results? That might be needed to
4385  // break recursion.
4386  if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4387  (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4388  if (ConvTemplate)
4389  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4390  ActingDC, Initializer,
4391  DestType, CandidateSet,
4392  /*AllowObjCConversionOnExplicit=*/
4393  false);
4394  else
4395  S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4396  Initializer, DestType, CandidateSet,
4397  /*AllowObjCConversionOnExplicit=*/false);
4398  }
4399  }
4400  }
4401  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4402  return OR_No_Viable_Function;
4403 
4404  SourceLocation DeclLoc = Initializer->getBeginLoc();
4405 
4406  // Perform overload resolution. If it fails, return the failed result.
4409  = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4410  return Result;
4411 
4412  FunctionDecl *Function = Best->Function;
4413  // This is the overload that will be used for this initialization step if we
4414  // use this initialization. Mark it as referenced.
4415  Function->setReferenced();
4416 
4417  // Compute the returned type and value kind of the conversion.
4418  QualType cv3T3;
4419  if (isa<CXXConversionDecl>(Function))
4420  cv3T3 = Function->getReturnType();
4421  else
4422  cv3T3 = T1;
4423 
4424  ExprValueKind VK = VK_RValue;
4425  if (cv3T3->isLValueReferenceType())
4426  VK = VK_LValue;
4427  else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4428  VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4429  cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4430 
4431  // Add the user-defined conversion step.
4432  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4433  Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4434  HadMultipleCandidates);
4435 
4436  // Determine whether we'll need to perform derived-to-base adjustments or
4437  // other conversions.
4438  bool NewDerivedToBase = false;
4439  bool NewObjCConversion = false;
4440  bool NewObjCLifetimeConversion = false;
4441  Sema::ReferenceCompareResult NewRefRelationship
4442  = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4443  NewDerivedToBase, NewObjCConversion,
4444  NewObjCLifetimeConversion);
4445 
4446  // Add the final conversion sequence, if necessary.
4447  if (NewRefRelationship == Sema::Ref_Incompatible) {
4448  assert(!isa<CXXConstructorDecl>(Function) &&
4449  "should not have conversion after constructor");
4450 
4452  ICS.setStandard();
4453  ICS.Standard = Best->FinalConversion;
4454  Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4455 
4456  // Every implicit conversion results in a prvalue, except for a glvalue
4457  // derived-to-base conversion, which we handle below.
4458  cv3T3 = ICS.Standard.getToType(2);
4459  VK = VK_RValue;
4460  }
4461 
4462  // If the converted initializer is a prvalue, its type T4 is adjusted to
4463  // type "cv1 T4" and the temporary materialization conversion is applied.
4464  //
4465  // We adjust the cv-qualifications to match the reference regardless of
4466  // whether we have a prvalue so that the AST records the change. In this
4467  // case, T4 is "cv3 T3".
4468  QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4469  if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4470  Sequence.AddQualificationConversionStep(cv1T4, VK);
4471  Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4472  VK = IsLValueRef ? VK_LValue : VK_XValue;
4473 
4474  if (NewDerivedToBase)
4475  Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4476  else if (NewObjCConversion)
4477  Sequence.AddObjCObjectConversionStep(cv1T1);
4478 
4479  return OR_Success;
4480 }
4481 
4482 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4483  const InitializedEntity &Entity,
4484  Expr *CurInitExpr);
4485 
4486 /// Attempt reference initialization (C++0x [dcl.init.ref])
4488  const InitializedEntity &Entity,
4489  const InitializationKind &Kind,
4490  Expr *Initializer,
4491  InitializationSequence &Sequence) {
4492  QualType DestType = Entity.getType();
4493  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4494  Qualifiers T1Quals;
4495  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4496  QualType cv2T2 = Initializer->getType();
4497  Qualifiers T2Quals;
4498  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4499 
4500  // If the initializer is the address of an overloaded function, try
4501  // to resolve the overloaded function. If all goes well, T2 is the
4502  // type of the resulting function.
4503  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4504  T1, Sequence))
4505  return;
4506 
4507  // Delegate everything else to a subfunction.
4508  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4509  T1Quals, cv2T2, T2, T2Quals, Sequence);
4510 }
4511 
4512 /// Determine whether an expression is a non-referenceable glvalue (one to
4513 /// which a reference can never bind). Attempting to bind a reference to
4514 /// such a glvalue will always create a temporary.
4516  return E->refersToBitField() || E->refersToVectorElement();
4517 }
4518 
4519 /// Reference initialization without resolving overloaded functions.
4521  const InitializedEntity &Entity,
4522  const InitializationKind &Kind,
4523  Expr *Initializer,
4524  QualType cv1T1, QualType T1,
4525  Qualifiers T1Quals,
4526  QualType cv2T2, QualType T2,
4527  Qualifiers T2Quals,
4528  InitializationSequence &Sequence) {
4529  QualType DestType = Entity.getType();
4530  SourceLocation DeclLoc = Initializer->getBeginLoc();
4531  // Compute some basic properties of the types and the initializer.
4532  bool isLValueRef = DestType->isLValueReferenceType();
4533  bool isRValueRef = !isLValueRef;
4534  bool DerivedToBase = false;
4535  bool ObjCConversion = false;
4536  bool ObjCLifetimeConversion = false;
4537  Expr::Classification InitCategory = Initializer->Classify(S.Context);
4538  Sema::ReferenceCompareResult RefRelationship
4539  = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4540  ObjCConversion, ObjCLifetimeConversion);
4541 
4542  // C++0x [dcl.init.ref]p5:
4543  // A reference to type "cv1 T1" is initialized by an expression of type
4544  // "cv2 T2" as follows:
4545  //
4546  // - If the reference is an lvalue reference and the initializer
4547  // expression
4548  // Note the analogous bullet points for rvalue refs to functions. Because
4549  // there are no function rvalues in C++, rvalue refs to functions are treated
4550  // like lvalue refs.
4551  OverloadingResult ConvOvlResult = OR_Success;
4552  bool T1Function = T1->isFunctionType();
4553  if (isLValueRef || T1Function) {
4554  if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4555  (RefRelationship == Sema::Ref_Compatible ||
4556  (Kind.isCStyleOrFunctionalCast() &&
4557  RefRelationship == Sema::Ref_Related))) {
4558  // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4559  // reference-compatible with "cv2 T2," or
4560  if (T1Quals != T2Quals)
4561  // Convert to cv1 T2. This should only add qualifiers unless this is a
4562  // c-style cast. The removal of qualifiers in that case notionally
4563  // happens after the reference binding, but that doesn't matter.
4565  S.Context.getQualifiedType(T2, T1Quals),
4566  Initializer->getValueKind());
4567  if (DerivedToBase)
4568  Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4569  else if (ObjCConversion)
4570  Sequence.AddObjCObjectConversionStep(cv1T1);
4571 
4572  // We only create a temporary here when binding a reference to a
4573  // bit-field or vector element. Those cases are't supposed to be
4574  // handled by this bullet, but the outcome is the same either way.
4575  Sequence.AddReferenceBindingStep(cv1T1, false);
4576  return;
4577  }
4578 
4579  // - has a class type (i.e., T2 is a class type), where T1 is not
4580  // reference-related to T2, and can be implicitly converted to an
4581  // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4582  // with "cv3 T3" (this conversion is selected by enumerating the
4583  // applicable conversion functions (13.3.1.6) and choosing the best
4584  // one through overload resolution (13.3)),
4585  // If we have an rvalue ref to function type here, the rhs must be
4586  // an rvalue. DR1287 removed the "implicitly" here.
4587  if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4588  (isLValueRef || InitCategory.isRValue())) {
4589  ConvOvlResult = TryRefInitWithConversionFunction(
4590  S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4591  /*IsLValueRef*/ isLValueRef, Sequence);
4592  if (ConvOvlResult == OR_Success)
4593  return;
4594  if (ConvOvlResult != OR_No_Viable_Function)
4595  Sequence.SetOverloadFailure(
4597  ConvOvlResult);
4598  }
4599  }
4600 
4601  // - Otherwise, the reference shall be an lvalue reference to a
4602  // non-volatile const type (i.e., cv1 shall be const), or the reference
4603  // shall be an rvalue reference.
4604  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4605  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4607  else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4608  Sequence.SetOverloadFailure(
4610  ConvOvlResult);
4611  else if (!InitCategory.isLValue())
4612  Sequence.SetFailed(
4614  else {
4616  switch (RefRelationship) {
4617  case Sema::Ref_Compatible:
4618  if (Initializer->refersToBitField())
4619  FK = InitializationSequence::
4620  FK_NonConstLValueReferenceBindingToBitfield;
4621  else if (Initializer->refersToVectorElement())
4622  FK = InitializationSequence::
4623  FK_NonConstLValueReferenceBindingToVectorElement;
4624  else
4625  llvm_unreachable("unexpected kind of compatible initializer");
4626  break;
4627  case Sema::Ref_Related:
4629  break;
4633  break;
4634  }
4635  Sequence.SetFailed(FK);
4636  }
4637  return;
4638  }
4639 
4640  // - If the initializer expression
4641  // - is an
4642  // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4643  // [1z] rvalue (but not a bit-field) or
4644  // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4645  //
4646  // Note: functions are handled above and below rather than here...
4647  if (!T1Function &&
4648  (RefRelationship == Sema::Ref_Compatible ||
4649  (Kind.isCStyleOrFunctionalCast() &&
4650  RefRelationship == Sema::Ref_Related)) &&
4651  ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4652  (InitCategory.isPRValue() &&
4653  (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
4654  T2->isArrayType())))) {
4655  ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
4656  if (InitCategory.isPRValue() && T2->isRecordType()) {
4657  // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4658  // compiler the freedom to perform a copy here or bind to the
4659  // object, while C++0x requires that we bind directly to the
4660  // object. Hence, we always bind to the object without making an
4661  // extra copy. However, in C++03 requires that we check for the
4662  // presence of a suitable copy constructor:
4663  //
4664  // The constructor that would be used to make the copy shall
4665  // be callable whether or not the copy is actually done.
4666  if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4667  Sequence.AddExtraneousCopyToTemporary(cv2T2);
4668  else if (S.getLangOpts().CPlusPlus11)
4669  CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4670  }
4671 
4672  // C++1z [dcl.init.ref]/5.2.1.2:
4673  // If the converted initializer is a prvalue, its type T4 is adjusted
4674  // to type "cv1 T4" and the temporary materialization conversion is
4675  // applied.
4676  QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4677  if (T1Quals != T2Quals)
4678  Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4679  Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4680  ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4681 
4682  // In any case, the reference is bound to the resulting glvalue (or to
4683  // an appropriate base class subobject).
4684  if (DerivedToBase)
4685  Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4686  else if (ObjCConversion)
4687  Sequence.AddObjCObjectConversionStep(cv1T1);
4688  return;
4689  }
4690 
4691  // - has a class type (i.e., T2 is a class type), where T1 is not
4692  // reference-related to T2, and can be implicitly converted to an
4693  // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4694  // where "cv1 T1" is reference-compatible with "cv3 T3",
4695  //
4696  // DR1287 removes the "implicitly" here.
4697  if (T2->isRecordType()) {
4698  if (RefRelationship == Sema::Ref_Incompatible) {
4699  ConvOvlResult = TryRefInitWithConversionFunction(
4700  S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4701  /*IsLValueRef*/ isLValueRef, Sequence);
4702  if (ConvOvlResult)
4703  Sequence.SetOverloadFailure(
4705  ConvOvlResult);
4706 
4707  return;
4708  }
4709 
4710  if (RefRelationship == Sema::Ref_Compatible &&
4711  isRValueRef && InitCategory.isLValue()) {
4712  Sequence.SetFailed(
4714  return;
4715  }
4716 
4718  return;
4719  }
4720 
4721  // - Otherwise, a temporary of type "cv1 T1" is created and initialized
4722  // from the initializer expression using the rules for a non-reference
4723  // copy-initialization (8.5). The reference is then bound to the
4724  // temporary. [...]
4725 
4727 
4728  // FIXME: Why do we use an implicit conversion here rather than trying
4729  // copy-initialization?
4731  = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4732  /*SuppressUserConversions=*/false,
4733  /*AllowExplicit=*/false,
4734  /*FIXME:InOverloadResolution=*/false,
4735  /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4736  /*AllowObjCWritebackConversion=*/false);
4737 
4738  if (ICS.isBad()) {
4739  // FIXME: Use the conversion function set stored in ICS to turn
4740  // this into an overloading ambiguity diagnostic. However, we need
4741  // to keep that set as an OverloadCandidateSet rather than as some
4742  // other kind of set.
4743  if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4744  Sequence.SetOverloadFailure(
4746  ConvOvlResult);
4747  else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4749  else
4751  return;
4752  } else {
4753  Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4754  }
4755 
4756  // [...] If T1 is reference-related to T2, cv1 must be the
4757  // same cv-qualification as, or greater cv-qualification
4758  // than, cv2; otherwise, the program is ill-formed.
4759  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4760  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4761  if (RefRelationship == Sema::Ref_Related &&
4762  (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4764  return;
4765  }
4766 
4767  // [...] If T1 is reference-related to T2 and the reference is an rvalue
4768  // reference, the initializer expression shall not be an lvalue.
4769  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4770  InitCategory.isLValue()) {
4771  Sequence.SetFailed(
4773  return;
4774  }
4775 
4776  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4777 }
4778 
4779 /// Attempt character array initialization from a string literal
4780 /// (C++ [dcl.init.string], C99 6.7.8).
4782  const InitializedEntity &Entity,
4783  const InitializationKind &Kind,
4784  Expr *Initializer,
4785  InitializationSequence &Sequence) {
4786  Sequence.AddStringInitStep(Entity.getType());
4787 }
4788 
4789 /// Attempt value initialization (C++ [dcl.init]p7).
4791  const InitializedEntity &Entity,
4792  const InitializationKind &Kind,
4793  InitializationSequence &Sequence,
4794  InitListExpr *InitList) {
4795  assert((!InitList || InitList->getNumInits() == 0) &&
4796  "Shouldn't use value-init for non-empty init lists");
4797 
4798  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4799  //
4800  // To value-initialize an object of type T means:
4801  QualType T = Entity.getType();
4802 
4803  // -- if T is an array type, then each element is value-initialized;
4804  T = S.Context.getBaseElementType(T);
4805 
4806  if (const RecordType *RT = T->getAs<RecordType>()) {
4807  if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4808  bool NeedZeroInitialization = true;
4809  // C++98:
4810  // -- if T is a class type (clause 9) with a user-declared constructor
4811  // (12.1), then the default constructor for T is called (and the
4812  // initialization is ill-formed if T has no accessible default
4813  // constructor);
4814  // C++11:
4815  // -- if T is a class type (clause 9) with either no default constructor
4816  // (12.1 [class.ctor]) or a default constructor that is user-provided
4817  // or deleted, then the object is default-initialized;
4818  //
4819  // Note that the C++11 rule is the same as the C++98 rule if there are no
4820  // defaulted or deleted constructors, so we just use it unconditionally.
4821  CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4822  if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4823  NeedZeroInitialization = false;
4824 
4825  // -- if T is a (possibly cv-qualified) non-union class type without a
4826  // user-provided or deleted default constructor, then the object is
4827  // zero-initialized and, if T has a non-trivial default constructor,
4828  // default-initialized;
4829  // The 'non-union' here was removed by DR1502. The 'non-trivial default
4830  // constructor' part was removed by DR1507.
4831  if (NeedZeroInitialization)
4832  Sequence.AddZeroInitializationStep(Entity.getType());
4833 
4834  // C++03:
4835  // -- if T is a non-union class type without a user-declared constructor,
4836  // then every non-static data member and base class component of T is
4837  // value-initialized;
4838  // [...] A program that calls for [...] value-initialization of an
4839  // entity of reference type is ill-formed.
4840  //
4841  // C++11 doesn't need this handling, because value-initialization does not
4842  // occur recursively there, and the implicit default constructor is
4843  // defined as deleted in the problematic cases.
4844  if (!S.getLangOpts().CPlusPlus11 &&
4845  ClassDecl->hasUninitializedReferenceMember()) {
4847  return;
4848  }
4849 
4850  // If this is list-value-initialization, pass the empty init list on when
4851  // building the constructor call. This affects the semantics of a few
4852  // things (such as whether an explicit default constructor can be called).
4853  Expr *InitListAsExpr = InitList;
4854  MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4855  bool InitListSyntax = InitList;
4856 
4857  // FIXME: Instead of creating a CXXConstructExpr of array type here,
4858  // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4860  S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4861  }
4862  }
4863 
4864  Sequence.AddZeroInitializationStep(Entity.getType());
4865 }
4866 
4867 /// Attempt default initialization (C++ [dcl.init]p6).
4869  const InitializedEntity &Entity,
4870  const InitializationKind &Kind,
4871  InitializationSequence &Sequence) {
4872  assert(Kind.getKind() == InitializationKind::IK_Default);
4873 
4874  // C++ [dcl.init]p6:
4875  // To default-initialize an object of type T means:
4876  // - if T is an array type, each element is default-initialized;
4877  QualType DestType = S.Context.getBaseElementType(Entity.getType());
4878 
4879  // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4880  // constructor for T is called (and the initialization is ill-formed if
4881  // T has no accessible default constructor);
4882  if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4883  TryConstructorInitialization(S, Entity, Kind, None, DestType,
4884  Entity.getType(), Sequence);
4885  return;
4886  }
4887 
4888  // - otherwise, no initialization is performed.
4889 
4890  // If a program calls for the default initialization of an object of
4891  // a const-qualified type T, T shall be a class type with a user-provided
4892  // default constructor.
4893  if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4894  if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4896  return;
4897  }
4898 
4899  // If the destination type has a lifetime property, zero-initialize it.
4900  if (DestType.getQualifiers().hasObjCLifetime()) {
4901  Sequence.AddZeroInitializationStep(Entity.getType());
4902  return;
4903  }
4904 }
4905 
4906 /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
4907 /// which enumerates all conversion functions and performs overload resolution
4908 /// to select the best.
4910  QualType DestType,
4911  const InitializationKind &Kind,
4912  Expr *Initializer,
4913  InitializationSequence &Sequence,
4914  bool TopLevelOfInitList) {
4915  assert(!DestType->isReferenceType() && "References are handled elsewhere");
4916  QualType SourceType = Initializer->getType();
4917  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4918  "Must have a class type to perform a user-defined conversion");
4919 
4920  // Build the candidate set directly in the initialization sequence
4921  // structure, so that it will persist if we fail.
4922  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4924 
4925  // Determine whether we are allowed to call explicit constructors or
4926  // explicit conversion operators.
4927  bool AllowExplicit = Kind.AllowExplicit();
4928 
4929  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4930  // The type we're converting to is a class type. Enumerate its constructors
4931  // to see if there is a suitable conversion.
4932  CXXRecordDecl *DestRecordDecl
4933  = cast<CXXRecordDecl>(DestRecordType->getDecl());
4934 
4935  // Try to complete the type we're converting to.
4936  if (S.isCompleteType(Kind.getLocation(), DestType)) {
4937  for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
4938  auto Info = getConstructorInfo(D);
4939  if (!Info.Constructor)
4940  continue;
4941 
4942  if (!Info.Constructor->isInvalidDecl() &&
4943  Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4944  if (Info.ConstructorTmpl)
4945  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4946  /*ExplicitArgs*/ nullptr,
4947  Initializer, CandidateSet,
4948  /*SuppressUserConversions=*/true);
4949  else
4950  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4951  Initializer, CandidateSet,
4952  /*SuppressUserConversions=*/true);
4953  }
4954  }
4955  }
4956  }
4957 
4958  SourceLocation DeclLoc = Initializer->getBeginLoc();
4959 
4960  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4961  // The type we're converting from is a class type, enumerate its conversion
4962  // functions.
4963 
4964  // We can only enumerate the conversion functions for a complete type; if
4965  // the type isn't complete, simply skip this step.
4966  if (S.isCompleteType(DeclLoc, SourceType)) {
4967  CXXRecordDecl *SourceRecordDecl
4968  = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4969 
4970  const auto &Conversions =
4971  SourceRecordDecl->getVisibleConversionFunctions();
4972  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4973  NamedDecl *D = *I;
4974  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4975  if (isa<UsingShadowDecl>(D))
4976  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4977 
4978  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4979  CXXConversionDecl *Conv;
4980  if (ConvTemplate)
4981  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4982  else
4983  Conv = cast<CXXConversionDecl>(D);
4984 
4985  if (AllowExplicit || !Conv->isExplicit()) {
4986  if (ConvTemplate)
4987  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4988  ActingDC, Initializer, DestType,
4989  CandidateSet, AllowExplicit);
4990  else
4991  S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4992  Initializer, DestType, CandidateSet,
4993  AllowExplicit);
4994  }
4995  }
4996  }
4997  }
4998 
4999  // Perform overload resolution. If it fails, return the failed result.
5002  = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5003  Sequence.SetOverloadFailure(
5005  Result);
5006  return;
5007  }
5008 
5009  FunctionDecl *Function = Best->Function;
5010  Function->setReferenced();
5011  bool HadMultipleCandidates = (CandidateSet.size() > 1);
5012 
5013  if (isa<CXXConstructorDecl>(Function)) {
5014  // Add the user-defined conversion step. Any cv-qualification conversion is
5015  // subsumed by the initialization. Per DR5, the created temporary is of the
5016  // cv-unqualified type of the destination.
5017  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5018  DestType.getUnqualifiedType(),
5019  HadMultipleCandidates);
5020 
5021  // C++14 and before:
5022  // - if the function is a constructor, the call initializes a temporary
5023  // of the cv-unqualified version of the destination type. The [...]
5024  // temporary [...] is then used to direct-initialize, according to the
5025  // rules above, the object that is the destination of the
5026  // copy-initialization.
5027  // Note that this just performs a simple object copy from the temporary.
5028  //
5029  // C++17:
5030  // - if the function is a constructor, the call is a prvalue of the
5031  // cv-unqualified version of the destination type whose return object
5032  // is initialized by the constructor. The call is used to
5033  // direct-initialize, according to the rules above, the object that
5034  // is the destination of the copy-initialization.
5035  // Therefore we need to do nothing further.
5036  //
5037  // FIXME: Mark this copy as extraneous.
5038  if (!S.getLangOpts().CPlusPlus17)
5039  Sequence.AddFinalCopy(DestType);
5040  else if (DestType.hasQualifiers())
5041  Sequence.AddQualificationConversionStep(DestType, VK_RValue);
5042  return;
5043  }
5044 
5045  // Add the user-defined conversion step that calls the conversion function.
5046  QualType ConvType = Function->getCallResultType();
5047  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5048  HadMultipleCandidates);
5049 
5050  if (ConvType->getAs<RecordType>()) {
5051  // The call is used to direct-initialize [...] the object that is the
5052  // destination of the copy-initialization.
5053  //
5054  // In C++17, this does not call a constructor if we enter /17.6.1:
5055  // - If the initializer expression is a prvalue and the cv-unqualified
5056  // version of the source type is the same as the class of the
5057  // destination [... do not make an extra copy]
5058  //
5059  // FIXME: Mark this copy as extraneous.
5060  if (!S.getLangOpts().CPlusPlus17 ||
5061  Function->getReturnType()->isReferenceType() ||
5062  !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5063  Sequence.AddFinalCopy(DestType);
5064  else if (!S.Context.hasSameType(ConvType, DestType))
5065  Sequence.AddQualificationConversionStep(DestType, VK_RValue);
5066  return;
5067  }
5068 
5069  // If the conversion following the call to the conversion function
5070  // is interesting, add it as a separate step.
5071  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5072  Best->FinalConversion.Third) {
5074  ICS.setStandard();
5075  ICS.Standard = Best->FinalConversion;
5076  Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5077  }
5078 }
5079 
5080 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5081 /// a function with a pointer return type contains a 'return false;' statement.
5082 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
5083 /// code using that header.
5084 ///
5085 /// Work around this by treating 'return false;' as zero-initializing the result
5086 /// if it's used in a pointer-returning function in a system header.
5088  const InitializedEntity &Entity,
5089  const Expr *Init) {
5090  return S.getLangOpts().CPlusPlus11 &&
5091  Entity.getKind() == InitializedEntity::EK_Result &&
5092  Entity.getType()->isPointerType() &&
5093  isa<CXXBoolLiteralExpr>(Init) &&
5094  !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5096 }
5097 
5098 /// The non-zero enum values here are indexes into diagnostic alternatives.
5100 
5101 /// Determines whether this expression is an acceptable ICR source.
5103  bool isAddressOf, bool &isWeakAccess) {
5104  // Skip parens.
5105  e = e->IgnoreParens();
5106 
5107  // Skip address-of nodes.
5108  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5109  if (op->getOpcode() == UO_AddrOf)
5110  return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5111  isWeakAccess);
5112 
5113  // Skip certain casts.
5114  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5115  switch (ce->getCastKind()) {
5116  case CK_Dependent:
5117  case CK_BitCast:
5118  case CK_LValueBitCast:
5119  case CK_NoOp:
5120  return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5121 
5122  case CK_ArrayToPointerDecay:
5123  return IIK_nonscalar;
5124 
5125  case CK_NullToPointer:
5126  return IIK_okay;
5127 
5128  default:
5129  break;
5130  }
5131 
5132  // If we have a declaration reference, it had better be a local variable.
5133  } else if (isa<DeclRefExpr>(e)) {
5134  // set isWeakAccess to true, to mean that there will be an implicit
5135  // load which requires a cleanup.
5137  isWeakAccess = true;
5138 
5139  if (!isAddressOf) return IIK_nonlocal;
5140 
5141  VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5142  if (!var) return IIK_nonlocal;
5143 
5144  return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5145 
5146  // If we have a conditional operator, check both sides.
5147  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5148  if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5149  isWeakAccess))
5150  return iik;
5151 
5152  return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5153 
5154  // These are never scalar.
5155  } else if (isa<ArraySubscriptExpr>(e)) {
5156  return IIK_nonscalar;
5157 
5158  // Otherwise, it needs to be a null pointer constant.
5159  } else {
5161  ? IIK_okay : IIK_nonlocal);
5162  }
5163 
5164  return IIK_nonlocal;
5165 }
5166 
5167 /// Check whether the given expression is a valid operand for an
5168 /// indirect copy/restore.
5170  assert(src->isRValue());
5171  bool isWeakAccess = false;
5172  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5173  // If isWeakAccess to true, there will be an implicit
5174  // load which requires a cleanup.
5175  if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5176  S.Cleanup.setExprNeedsCleanups(true);
5177 
5178  if (iik == IIK_okay) return;
5179 
5180  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5181  << ((unsigned) iik - 1) // shift index into diagnostic explanations
5182  << src->getSourceRange();
5183 }
5184 
5185 /// Determine whether we have compatible array types for the
5186 /// purposes of GNU by-copy array initialization.
5187 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5188  const ArrayType *Source) {
5189  // If the source and destination array types are equivalent, we're
5190  // done.
5191  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5192  return true;
5193 
5194  // Make sure that the element types are the same.
5195  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5196  return false;
5197 
5198  // The only mismatch we allow is when the destination is an
5199  // incomplete array type and the source is a constant array type.
5200  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5201 }
5202 
5204  InitializationSequence &Sequence,
5205  const InitializedEntity &Entity,
5206  Expr *Initializer) {
5207  bool ArrayDecay = false;
5208  QualType ArgType = Initializer->getType();
5209  QualType ArgPointee;
5210  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5211  ArrayDecay = true;
5212  ArgPointee = ArgArrayType->getElementType();
5213  ArgType = S.Context.getPointerType(ArgPointee);
5214  }
5215 
5216  // Handle write-back conversion.
5217  QualType ConvertedArgType;
5218  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5219  ConvertedArgType))
5220  return false;
5221 
5222  // We should copy unless we're passing to an argument explicitly
5223  // marked 'out'.
5224  bool ShouldCopy = true;
5225  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5226  ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5227 
5228  // Do we need an lvalue conversion?
5229  if (ArrayDecay || Initializer->isGLValue()) {
5231  ICS.setStandard();
5233 
5234  QualType ResultType;
5235  if (ArrayDecay) {
5237  ResultType = S.Context.getPointerType(ArgPointee);
5238  } else {
5240  ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5241  }
5242 
5243  Sequence.AddConversionSequenceStep(ICS, ResultType);
5244  }
5245 
5246  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5247  return true;
5248 }
5249 
5251  InitializationSequence &Sequence,
5252  QualType DestType,
5253  Expr *Initializer) {
5254  if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5255  (!Initializer->isIntegerConstantExpr(S.Context) &&
5256  !Initializer->getType()->isSamplerT()))
5257  return false;
5258 
5259  Sequence.AddOCLSamplerInitStep(DestType);
5260  return true;
5261 }
5262 
5263 //
5264 // OpenCL 1.2 spec, s6.12.10
5265 //
5266 // The event argument can also be used to associate the
5267 // async_work_group_copy with a previous async copy allowing
5268 // an event to be shared by multiple async copies; otherwise
5269 // event should be zero.
5270 //
5272  InitializationSequence &Sequence,
5273  QualType DestType,
5274  Expr *Initializer) {
5275  if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5276  !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5277  (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5278  return false;
5279 
5280  Sequence.AddOCLZeroEventStep(DestType);
5281  return true;
5282 }
5283 
5285  InitializationSequence &Sequence,
5286  QualType DestType,
5287  Expr *Initializer) {
5288  if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5289  !DestType->isQueueT() ||
5290  !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5291  (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5292  return false;
5293 
5294  Sequence.AddOCLZeroQueueStep(DestType);
5295  return true;
5296 }
5297 
5299  const InitializedEntity &Entity,
5300  const InitializationKind &Kind,
5301  MultiExprArg Args,
5302  bool TopLevelOfInitList,
5303  bool TreatUnavailableAsInvalid)
5304  : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5305  InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5306  TreatUnavailableAsInvalid);
5307 }
5308 
5309 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5310 /// address of that function, this returns true. Otherwise, it returns false.
5311 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5312  auto *DRE = dyn_cast<DeclRefExpr>(E);
5313  if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5314  return false;
5315 
5317  cast<FunctionDecl>(DRE->getDecl()));
5318 }
5319 
5320 /// Determine whether we can perform an elementwise array copy for this kind
5321 /// of entity.
5322 static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5323  switch (Entity.getKind()) {
5325  // C++ [expr.prim.lambda]p24:
5326  // For array members, the array elements are direct-initialized in
5327  // increasing subscript order.
5328  return true;
5329 
5331  // C++ [dcl.decomp]p1:
5332  // [...] each element is copy-initialized or direct-initialized from the
5333  // corresponding element of the assignment-expression [...]
5334  return isa<DecompositionDecl>(Entity.getDecl());
5335 
5337  // C++ [class.copy.ctor]p14:
5338  // - if the member is an array, each element is direct-initialized with
5339  // the corresponding subobject of x
5340  return Entity.isImplicitMemberInitializer();
5341 
5343  // All the above cases are intended to apply recursively, even though none
5344  // of them actually say that.
5345  if (auto *E = Entity.getParent())
5346  return canPerformArrayCopy(*E);
5347  break;
5348 
5349  default:
5350  break;
5351  }
5352 
5353  return false;
5354 }
5355 
5357  const InitializedEntity &Entity,
5358  const InitializationKind &Kind,
5359  MultiExprArg Args,
5360  bool TopLevelOfInitList,
5361  bool TreatUnavailableAsInvalid) {
5362  ASTContext &Context = S.Context;
5363 
5364  // Eliminate non-overload placeholder types in the arguments. We
5365  // need to do this before checking whether types are dependent
5366  // because lowering a pseudo-object expression might well give us
5367  // something of dependent type.
5368  for (unsigned I = 0, E = Args.size(); I != E; ++I)
5369  if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5370  // FIXME: should we be doing this here?
5371  ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5372  if (result.isInvalid()) {
5374  return;
5375  }
5376  Args[I] = result.get();
5377  }
5378 
5379  // C++0x [dcl.init]p16:
5380  // The semantics of initializers are as follows. The destination type is
5381  // the type of the object or reference being initialized and the source
5382  // type is the type of the initializer expression. The source type is not
5383  // defined when the initializer is a braced-init-list or when it is a
5384  // parenthesized list of expressions.
5385  QualType DestType = Entity.getType();
5386 
5387  if (DestType->isDependentType() ||
5390  return;
5391  }
5392 
5393  // Almost everything is a normal sequence.
5395 
5396  QualType SourceType;
5397  Expr *Initializer = nullptr;
5398  if (Args.size() == 1) {
5399  Initializer = Args[0];
5400  if (S.getLangOpts().ObjC1) {
5401  if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
5402  DestType, Initializer->getType(),
5403  Initializer) ||
5404  S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5405  Args[0] = Initializer;
5406  }
5407  if (!isa<InitListExpr>(Initializer))
5408  SourceType = Initializer->getType();
5409  }
5410 
5411  // - If the initializer is a (non-parenthesized) braced-init-list, the
5412  // object is list-initialized (8.5.4).
5413  if (Kind.getKind() != InitializationKind::IK_Direct) {
5414  if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5415  TryListInitialization(S, Entity, Kind, InitList, *this,
5416  TreatUnavailableAsInvalid);
5417  return;
5418  }
5419  }
5420 
5421  // - If the destination type is a reference type, see 8.5.3.
5422  if (DestType->isReferenceType()) {
5423  // C++0x [dcl.init.ref]p1:
5424  // A variable declared to be a T& or T&&, that is, "reference to type T"
5425  // (8.3.2), shall be initialized by an object, or function, of type T or
5426  // by an object that can be converted into a T.
5427  // (Therefore, multiple arguments are not permitted.)
5428  if (Args.size() != 1)
5430  // C++17 [dcl.init.ref]p5:
5431  // A reference [...] is initialized by an expression [...] as follows:
5432  // If the initializer is not an expression, presumably we should reject,
5433  // but the standard fails to actually say so.
5434  else if (isa<InitListExpr>(Args[0]))
5436  else
5437  TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5438  return;
5439  }
5440 
5441  // - If the initializer is (), the object is value-initialized.
5442  if (Kind.getKind() == InitializationKind::IK_Value ||
5443  (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
5444  TryValueInitialization(S, Entity, Kind, *this);
5445  return;
5446  }
5447 
5448  // Handle default initialization.
5449  if (Kind.getKind() == InitializationKind::IK_Default) {
5450  TryDefaultInitialization(S, Entity, Kind, *this);
5451  return;
5452  }
5453 
5454  // - If the destination type is an array of characters, an array of
5455  // char16_t, an array of char32_t, or an array of wchar_t, and the
5456  // initializer is a string literal, see 8.5.2.
5457  // - Otherwise, if the destination type is an array, the program is
5458  // ill-formed.
5459  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
5460  if (Initializer && isa<VariableArrayType>(DestAT)) {
5462  return;
5463  }
5464 
5465  if (Initializer) {
5466  switch (IsStringInit(Initializer, DestAT, Context)) {
5467  case SIF_None:
5468  TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5469  return;
5472  return;
5475  return;
5478  return;
5481  return;
5484  return;
5485  case SIF_Other:
5486  break;
5487  }
5488  }
5489 
5490  // Some kinds of initialization permit an array to be initialized from
5491  // another array of the same type, and perform elementwise initialization.
5492  if (Initializer && isa<ConstantArrayType>(DestAT) &&
5493  S.Context.hasSameUnqualifiedType(Initializer->getType(),
5494  Entity.getType()) &&
5495  canPerformArrayCopy(Entity)) {
5496  // If source is a prvalue, use it directly.
5497  if (Initializer->getValueKind() == VK_RValue) {
5498  AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5499  return;
5500  }
5501 
5502  // Emit element-at-a-time copy loop.
5503  InitializedEntity Element =
5505  QualType InitEltT =
5506  Context.getAsArrayType(Initializer->getType())->getElementType();
5507  OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5508  Initializer->getValueKind(),
5509  Initializer->getObjectKind());
5510  Expr *OVEAsExpr = &OVE;
5511  InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5512  TreatUnavailableAsInvalid);
5513  if (!Failed())
5514  AddArrayInitLoopStep(Entity.getType(), InitEltT);
5515  return;
5516  }
5517 
5518  // Note: as an GNU C extension, we allow initialization of an
5519  // array from a compound literal that creates an array of the same
5520  // type, so long as the initializer has no side effects.
5521  if (!S.getLangOpts().CPlusPlus && Initializer &&
5522  isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5523  Initializer->getType()->isArrayType()) {
5524  const ArrayType *SourceAT
5525  = Context.getAsArrayType(Initializer->getType());
5526  if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5528  else if (Initializer->HasSideEffects(S.Context))
5530  else {
5531  AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5532  }
5533  }
5534  // Note: as a GNU C++ extension, we allow list-initialization of a
5535  // class member of array type from a parenthesized initializer list.
5536  else if (S.getLangOpts().CPlusPlus &&
5537  Entity.getKind() == InitializedEntity::EK_Member &&
5538  Initializer && isa<InitListExpr>(Initializer)) {
5539  TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5540  *this, TreatUnavailableAsInvalid);
5542  } else if (DestAT->getElementType()->isCharType())
5544  else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5546  else
5547  SetFailed(