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