clang  3.9.0
SemaInit.cpp
Go to the documentation of this file.
1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for initializers.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Sema/Designator.h"
22 #include "clang/Sema/Lookup.h"
24 #include "llvm/ADT/APInt.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <map>
29 
30 using namespace clang;
31 
32 //===----------------------------------------------------------------------===//
33 // Sema Initialization Checking
34 //===----------------------------------------------------------------------===//
35 
36 /// \brief Check whether T is compatible with a wide character type (wchar_t,
37 /// char16_t or char32_t).
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 
54 };
55 
56 /// \brief Check whether the array of type AT can be initialized by the Init
57 /// expression by means of string initialization. Returns SIF_None if so,
58 /// otherwise returns a StringInitFailureKind that describes why the
59 /// initialization would not work.
62  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
63  return SIF_Other;
64 
65  // See if this is a string literal or @encode.
66  Init = Init->IgnoreParens();
67 
68  // Handle @encode, which is a narrow string.
69  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
70  return SIF_None;
71 
72  // Otherwise we can only handle string literals.
73  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
74  if (!SL)
75  return SIF_Other;
76 
77  const QualType ElemTy =
78  Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
79 
80  switch (SL->getKind()) {
83  // char array can be initialized with a narrow string.
84  // Only allow char x[] = "foo"; not char x[] = L"foo";
85  if (ElemTy->isCharType())
86  return SIF_None;
87  if (IsWideCharCompatible(ElemTy, Context))
89  return SIF_Other;
90  // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
91  // "An array with element type compatible with a qualified or unqualified
92  // version of wchar_t, char16_t, or char32_t may be initialized by a wide
93  // string literal with the corresponding encoding prefix (L, u, or U,
94  // respectively), optionally enclosed in braces.
96  if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
97  return SIF_None;
98  if (ElemTy->isCharType())
100  if (IsWideCharCompatible(ElemTy, Context))
102  return SIF_Other;
104  if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
105  return SIF_None;
106  if (ElemTy->isCharType())
107  return SIF_WideStringIntoChar;
108  if (IsWideCharCompatible(ElemTy, Context))
110  return SIF_Other;
111  case StringLiteral::Wide:
112  if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
113  return SIF_None;
114  if (ElemTy->isCharType())
115  return SIF_WideStringIntoChar;
116  if (IsWideCharCompatible(ElemTy, Context))
118  return SIF_Other;
119  }
120 
121  llvm_unreachable("missed a StringLiteral kind?");
122 }
123 
125  ASTContext &Context) {
126  const ArrayType *arrayType = Context.getAsArrayType(declType);
127  if (!arrayType)
128  return SIF_Other;
129  return IsStringInit(init, arrayType, Context);
130 }
131 
132 /// Update the type of a string literal, including any surrounding parentheses,
133 /// to match the type of the object which it is initializing.
135  while (true) {
136  E->setType(Ty);
137  if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
138  break;
139  else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
140  E = PE->getSubExpr();
141  else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
142  E = UO->getSubExpr();
143  else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
144  E = GSE->getResultExpr();
145  else
146  llvm_unreachable("unexpected expr in string literal init");
147  }
148 }
149 
150 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
151  Sema &S) {
152  // Get the length of the string as parsed.
153  auto *ConstantArrayTy =
154  cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
155  uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
156 
157  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
158  // C99 6.7.8p14. We have an array of character type with unknown size
159  // being initialized to a string literal.
160  llvm::APInt ConstVal(32, StrLength);
161  // Return a new array type (C99 6.7.8p22).
162  DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
163  ConstVal,
164  ArrayType::Normal, 0);
165  updateStringLiteralType(Str, DeclT);
166  return;
167  }
168 
169  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
170 
171  // We have an array of character type with known size. However,
172  // the size may be smaller or larger than the string we are initializing.
173  // FIXME: Avoid truncation for 64-bit length strings.
174  if (S.getLangOpts().CPlusPlus) {
175  if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
176  // For Pascal strings it's OK to strip off the terminating null character,
177  // so the example below is valid:
178  //
179  // unsigned char a[2] = "\pa";
180  if (SL->isPascal())
181  StrLength--;
182  }
183 
184  // [dcl.init.string]p2
185  if (StrLength > CAT->getSize().getZExtValue())
186  S.Diag(Str->getLocStart(),
187  diag::err_initializer_string_for_char_array_too_long)
188  << Str->getSourceRange();
189  } else {
190  // C99 6.7.8p14.
191  if (StrLength-1 > CAT->getSize().getZExtValue())
192  S.Diag(Str->getLocStart(),
193  diag::ext_initializer_string_for_char_array_too_long)
194  << Str->getSourceRange();
195  }
196 
197  // Set the type to the actual size that we are initializing. If we have
198  // something like:
199  // char x[1] = "foo";
200  // then this will set the string literal's type to char[1].
201  updateStringLiteralType(Str, DeclT);
202 }
203 
204 //===----------------------------------------------------------------------===//
205 // Semantic checking for initializer lists.
206 //===----------------------------------------------------------------------===//
207 
208 namespace {
209 
210 /// @brief Semantic checking for initializer lists.
211 ///
212 /// The InitListChecker class contains a set of routines that each
213 /// handle the initialization of a certain kind of entity, e.g.,
214 /// arrays, vectors, struct/union types, scalars, etc. The
215 /// InitListChecker itself performs a recursive walk of the subobject
216 /// structure of the type to be initialized, while stepping through
217 /// the initializer list one element at a time. The IList and Index
218 /// parameters to each of the Check* routines contain the active
219 /// (syntactic) initializer list and the index into that initializer
220 /// list that represents the current initializer. Each routine is
221 /// responsible for moving that Index forward as it consumes elements.
222 ///
223 /// Each Check* routine also has a StructuredList/StructuredIndex
224 /// arguments, which contains the current "structured" (semantic)
225 /// initializer list and the index into that initializer list where we
226 /// are copying initializers as we map them over to the semantic
227 /// list. Once we have completed our recursive walk of the subobject
228 /// structure, we will have constructed a full semantic initializer
229 /// list.
230 ///
231 /// C99 designators cause changes in the initializer list traversal,
232 /// because they make the initialization "jump" into a specific
233 /// subobject and then continue the initialization from that
234 /// point. CheckDesignatedInitializer() recursively steps into the
235 /// designated subobject and manages backing out the recursion to
236 /// initialize the subobjects after the one designated.
237 class InitListChecker {
238  Sema &SemaRef;
239  bool hadError;
240  bool VerifyOnly; // no diagnostics, no structure building
241  bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
242  llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
243  InitListExpr *FullyStructuredList;
244 
245  void CheckImplicitInitList(const InitializedEntity &Entity,
246  InitListExpr *ParentIList, QualType T,
247  unsigned &Index, InitListExpr *StructuredList,
248  unsigned &StructuredIndex);
249  void CheckExplicitInitList(const InitializedEntity &Entity,
250  InitListExpr *IList, QualType &T,
251  InitListExpr *StructuredList,
252  bool TopLevelObject = false);
253  void CheckListElementTypes(const InitializedEntity &Entity,
254  InitListExpr *IList, QualType &DeclType,
255  bool SubobjectIsDesignatorContext,
256  unsigned &Index,
257  InitListExpr *StructuredList,
258  unsigned &StructuredIndex,
259  bool TopLevelObject = false);
260  void CheckSubElementType(const InitializedEntity &Entity,
261  InitListExpr *IList, QualType ElemType,
262  unsigned &Index,
263  InitListExpr *StructuredList,
264  unsigned &StructuredIndex);
265  void CheckComplexType(const InitializedEntity &Entity,
266  InitListExpr *IList, QualType DeclType,
267  unsigned &Index,
268  InitListExpr *StructuredList,
269  unsigned &StructuredIndex);
270  void CheckScalarType(const InitializedEntity &Entity,
271  InitListExpr *IList, QualType DeclType,
272  unsigned &Index,
273  InitListExpr *StructuredList,
274  unsigned &StructuredIndex);
275  void CheckReferenceType(const InitializedEntity &Entity,
276  InitListExpr *IList, QualType DeclType,
277  unsigned &Index,
278  InitListExpr *StructuredList,
279  unsigned &StructuredIndex);
280  void CheckVectorType(const InitializedEntity &Entity,
281  InitListExpr *IList, QualType DeclType, unsigned &Index,
282  InitListExpr *StructuredList,
283  unsigned &StructuredIndex);
284  void CheckStructUnionTypes(const InitializedEntity &Entity,
285  InitListExpr *IList, QualType DeclType,
288  bool SubobjectIsDesignatorContext, unsigned &Index,
289  InitListExpr *StructuredList,
290  unsigned &StructuredIndex,
291  bool TopLevelObject = false);
292  void CheckArrayType(const InitializedEntity &Entity,
293  InitListExpr *IList, QualType &DeclType,
294  llvm::APSInt elementIndex,
295  bool SubobjectIsDesignatorContext, unsigned &Index,
296  InitListExpr *StructuredList,
297  unsigned &StructuredIndex);
298  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
299  InitListExpr *IList, DesignatedInitExpr *DIE,
300  unsigned DesigIdx,
301  QualType &CurrentObjectType,
302  RecordDecl::field_iterator *NextField,
303  llvm::APSInt *NextElementIndex,
304  unsigned &Index,
305  InitListExpr *StructuredList,
306  unsigned &StructuredIndex,
307  bool FinishSubobjectInit,
308  bool TopLevelObject);
309  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
310  QualType CurrentObjectType,
311  InitListExpr *StructuredList,
312  unsigned StructuredIndex,
313  SourceRange InitRange,
314  bool IsFullyOverwritten = false);
315  void UpdateStructuredListElement(InitListExpr *StructuredList,
316  unsigned &StructuredIndex,
317  Expr *expr);
318  int numArrayElements(QualType DeclType);
319  int numStructUnionElements(QualType DeclType);
320 
321  static ExprResult PerformEmptyInit(Sema &SemaRef,
322  SourceLocation Loc,
323  const InitializedEntity &Entity,
324  bool VerifyOnly,
325  bool TreatUnavailableAsInvalid);
326 
327  // Explanation on the "FillWithNoInit" mode:
328  //
329  // Assume we have the following definitions (Case#1):
330  // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
331  // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
332  //
333  // l.lp.x[1][0..1] should not be filled with implicit initializers because the
334  // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
335  //
336  // But if we have (Case#2):
337  // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
338  //
339  // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
340  // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
341  //
342  // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
343  // in the InitListExpr, the "holes" in Case#1 are filled not with empty
344  // initializers but with special "NoInitExpr" place holders, which tells the
345  // CodeGen not to generate any initializers for these parts.
346  void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
347  const InitializedEntity &ParentEntity,
348  InitListExpr *ILE, bool &RequiresSecondPass,
349  bool FillWithNoInit);
350  void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
351  const InitializedEntity &ParentEntity,
352  InitListExpr *ILE, bool &RequiresSecondPass,
353  bool FillWithNoInit = false);
354  void FillInEmptyInitializations(const InitializedEntity &Entity,
355  InitListExpr *ILE, bool &RequiresSecondPass,
356  bool FillWithNoInit = false);
357  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
358  Expr *InitExpr, FieldDecl *Field,
359  bool TopLevelObject);
360  void CheckEmptyInitializable(const InitializedEntity &Entity,
361  SourceLocation Loc);
362 
363 public:
364  InitListChecker(Sema &S, const InitializedEntity &Entity,
365  InitListExpr *IL, QualType &T, bool VerifyOnly,
366  bool TreatUnavailableAsInvalid);
367  bool HadError() { return hadError; }
368 
369  // @brief Retrieves the fully-structured initializer list used for
370  // semantic analysis and code generation.
371  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
372 };
373 
374 } // end anonymous namespace
375 
376 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
377  SourceLocation Loc,
378  const InitializedEntity &Entity,
379  bool VerifyOnly,
380  bool TreatUnavailableAsInvalid) {
382  true);
383  MultiExprArg SubInit;
384  Expr *InitExpr;
385  InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
386 
387  // C++ [dcl.init.aggr]p7:
388  // If there are fewer initializer-clauses in the list than there are
389  // members in the aggregate, then each member not explicitly initialized
390  // ...
391  bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
393  if (EmptyInitList) {
394  // C++1y / DR1070:
395  // shall be initialized [...] from an empty initializer list.
396  //
397  // We apply the resolution of this DR to C++11 but not C++98, since C++98
398  // does not have useful semantics for initialization from an init list.
399  // We treat this as copy-initialization, because aggregate initialization
400  // always performs copy-initialization on its elements.
401  //
402  // Only do this if we're initializing a class type, to avoid filling in
403  // the initializer list where possible.
404  InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
405  InitListExpr(SemaRef.Context, Loc, None, Loc);
406  InitExpr->setType(SemaRef.Context.VoidTy);
407  SubInit = InitExpr;
408  Kind = InitializationKind::CreateCopy(Loc, Loc);
409  } else {
410  // C++03:
411  // shall be value-initialized.
412  }
413 
414  InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
415  // libstdc++4.6 marks the vector default constructor as explicit in
416  // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
417  // stlport does so too. Look for std::__debug for libstdc++, and for
418  // std:: for stlport. This is effectively a compiler-side implementation of
419  // LWG2193.
420  if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
424  InitSeq.getFailedCandidateSet()
425  .BestViableFunction(SemaRef, Kind.getLocation(), Best);
426  (void)O;
427  assert(O == OR_Success && "Inconsistent overload resolution");
428  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
429  CXXRecordDecl *R = CtorDecl->getParent();
430 
431  if (CtorDecl->getMinRequiredArguments() == 0 &&
432  CtorDecl->isExplicit() && R->getDeclName() &&
433  SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
434  bool IsInStd = false;
435  for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
436  ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
437  if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
438  IsInStd = true;
439  }
440 
441  if (IsInStd && llvm::StringSwitch<bool>(R->getName())
442  .Cases("basic_string", "deque", "forward_list", true)
443  .Cases("list", "map", "multimap", "multiset", true)
444  .Cases("priority_queue", "queue", "set", "stack", true)
445  .Cases("unordered_map", "unordered_set", "vector", true)
446  .Default(false)) {
447  InitSeq.InitializeFrom(
448  SemaRef, Entity,
449  InitializationKind::CreateValue(Loc, Loc, Loc, true),
450  MultiExprArg(), /*TopLevelOfInitList=*/false,
451  TreatUnavailableAsInvalid);
452  // Emit a warning for this. System header warnings aren't shown
453  // by default, but people working on system headers should see it.
454  if (!VerifyOnly) {
455  SemaRef.Diag(CtorDecl->getLocation(),
456  diag::warn_invalid_initializer_from_system_header);
457  if (Entity.getKind() == InitializedEntity::EK_Member)
458  SemaRef.Diag(Entity.getDecl()->getLocation(),
459  diag::note_used_in_initialization_here);
460  else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
461  SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
462  }
463  }
464  }
465  }
466  if (!InitSeq) {
467  if (!VerifyOnly) {
468  InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
469  if (Entity.getKind() == InitializedEntity::EK_Member)
470  SemaRef.Diag(Entity.getDecl()->getLocation(),
471  diag::note_in_omitted_aggregate_initializer)
472  << /*field*/1 << Entity.getDecl();
473  else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
474  SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
475  << /*array element*/0 << Entity.getElementIndex();
476  }
477  return ExprError();
478  }
479 
480  return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
481  : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
482 }
483 
484 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
485  SourceLocation Loc) {
486  assert(VerifyOnly &&
487  "CheckEmptyInitializable is only inteded for verification mode.");
488  if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
489  TreatUnavailableAsInvalid).isInvalid())
490  hadError = true;
491 }
492 
493 void InitListChecker::FillInEmptyInitForBase(
494  unsigned Init, const CXXBaseSpecifier &Base,
495  const InitializedEntity &ParentEntity, InitListExpr *ILE,
496  bool &RequiresSecondPass, bool FillWithNoInit) {
497  assert(Init < ILE->getNumInits() && "should have been expanded");
498 
500  SemaRef.Context, &Base, false, &ParentEntity);
501 
502  if (!ILE->getInit(Init)) {
503  ExprResult BaseInit =
504  FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
505  : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
506  /*VerifyOnly*/ false,
507  TreatUnavailableAsInvalid);
508  if (BaseInit.isInvalid()) {
509  hadError = true;
510  return;
511  }
512 
513  ILE->setInit(Init, BaseInit.getAs<Expr>());
514  } else if (InitListExpr *InnerILE =
515  dyn_cast<InitListExpr>(ILE->getInit(Init))) {
516  FillInEmptyInitializations(BaseEntity, InnerILE,
517  RequiresSecondPass, FillWithNoInit);
518  } else if (DesignatedInitUpdateExpr *InnerDIUE =
519  dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
520  FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
521  RequiresSecondPass, /*FillWithNoInit =*/true);
522  }
523 }
524 
525 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
526  const InitializedEntity &ParentEntity,
527  InitListExpr *ILE,
528  bool &RequiresSecondPass,
529  bool FillWithNoInit) {
530  SourceLocation Loc = ILE->getLocEnd();
531  unsigned NumInits = ILE->getNumInits();
532  InitializedEntity MemberEntity
533  = InitializedEntity::InitializeMember(Field, &ParentEntity);
534 
535  if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
536  if (!RType->getDecl()->isUnion())
537  assert(Init < NumInits && "This ILE should have been expanded");
538 
539  if (Init >= NumInits || !ILE->getInit(Init)) {
540  if (FillWithNoInit) {
541  Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
542  if (Init < NumInits)
543  ILE->setInit(Init, Filler);
544  else
545  ILE->updateInit(SemaRef.Context, Init, Filler);
546  return;
547  }
548  // C++1y [dcl.init.aggr]p7:
549  // If there are fewer initializer-clauses in the list than there are
550  // members in the aggregate, then each member not explicitly initialized
551  // shall be initialized from its brace-or-equal-initializer [...]
552  if (Field->hasInClassInitializer()) {
553  ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
554  if (DIE.isInvalid()) {
555  hadError = true;
556  return;
557  }
558  if (Init < NumInits)
559  ILE->setInit(Init, DIE.get());
560  else {
561  ILE->updateInit(SemaRef.Context, Init, DIE.get());
562  RequiresSecondPass = true;
563  }
564  return;
565  }
566 
567  if (Field->getType()->isReferenceType()) {
568  // C++ [dcl.init.aggr]p9:
569  // If an incomplete or empty initializer-list leaves a
570  // member of reference type uninitialized, the program is
571  // ill-formed.
572  SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
573  << Field->getType()
574  << ILE->getSyntacticForm()->getSourceRange();
575  SemaRef.Diag(Field->getLocation(),
576  diag::note_uninit_reference_member);
577  hadError = true;
578  return;
579  }
580 
581  ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
582  /*VerifyOnly*/false,
583  TreatUnavailableAsInvalid);
584  if (MemberInit.isInvalid()) {
585  hadError = true;
586  return;
587  }
588 
589  if (hadError) {
590  // Do nothing
591  } else if (Init < NumInits) {
592  ILE->setInit(Init, MemberInit.getAs<Expr>());
593  } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
594  // Empty initialization requires a constructor call, so
595  // extend the initializer list to include the constructor
596  // call and make a note that we'll need to take another pass
597  // through the initializer list.
598  ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
599  RequiresSecondPass = true;
600  }
601  } else if (InitListExpr *InnerILE
602  = dyn_cast<InitListExpr>(ILE->getInit(Init)))
603  FillInEmptyInitializations(MemberEntity, InnerILE,
604  RequiresSecondPass, FillWithNoInit);
605  else if (DesignatedInitUpdateExpr *InnerDIUE
606  = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
607  FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
608  RequiresSecondPass, /*FillWithNoInit =*/ true);
609 }
610 
611 /// Recursively replaces NULL values within the given initializer list
612 /// with expressions that perform value-initialization of the
613 /// appropriate type.
614 void
615 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
616  InitListExpr *ILE,
617  bool &RequiresSecondPass,
618  bool FillWithNoInit) {
619  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
620  "Should not have void type");
621 
622  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
623  const RecordDecl *RDecl = RType->getDecl();
624  if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
625  FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
626  Entity, ILE, RequiresSecondPass, FillWithNoInit);
627  else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
628  cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
629  for (auto *Field : RDecl->fields()) {
630  if (Field->hasInClassInitializer()) {
631  FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
632  FillWithNoInit);
633  break;
634  }
635  }
636  } else {
637  // The fields beyond ILE->getNumInits() are default initialized, so in
638  // order to leave them uninitialized, the ILE is expanded and the extra
639  // fields are then filled with NoInitExpr.
640  unsigned NumElems = numStructUnionElements(ILE->getType());
641  if (RDecl->hasFlexibleArrayMember())
642  ++NumElems;
643  if (ILE->getNumInits() < NumElems)
644  ILE->resizeInits(SemaRef.Context, NumElems);
645 
646  unsigned Init = 0;
647 
648  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
649  for (auto &Base : CXXRD->bases()) {
650  if (hadError)
651  return;
652 
653  FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
654  FillWithNoInit);
655  ++Init;
656  }
657  }
658 
659  for (auto *Field : RDecl->fields()) {
660  if (Field->isUnnamedBitfield())
661  continue;
662 
663  if (hadError)
664  return;
665 
666  FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
667  FillWithNoInit);
668  if (hadError)
669  return;
670 
671  ++Init;
672 
673  // Only look at the first initialization of a union.
674  if (RDecl->isUnion())
675  break;
676  }
677  }
678 
679  return;
680  }
681 
682  QualType ElementType;
683 
684  InitializedEntity ElementEntity = Entity;
685  unsigned NumInits = ILE->getNumInits();
686  unsigned NumElements = NumInits;
687  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
688  ElementType = AType->getElementType();
689  if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
690  NumElements = CAType->getSize().getZExtValue();
691  ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
692  0, Entity);
693  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
694  ElementType = VType->getElementType();
695  NumElements = VType->getNumElements();
696  ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
697  0, Entity);
698  } else
699  ElementType = ILE->getType();
700 
701  for (unsigned Init = 0; Init != NumElements; ++Init) {
702  if (hadError)
703  return;
704 
705  if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
706  ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
707  ElementEntity.setElementIndex(Init);
708 
709  Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
710  if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
711  ILE->setInit(Init, ILE->getArrayFiller());
712  else if (!InitExpr && !ILE->hasArrayFiller()) {
713  Expr *Filler = nullptr;
714 
715  if (FillWithNoInit)
716  Filler = new (SemaRef.Context) NoInitExpr(ElementType);
717  else {
718  ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
719  ElementEntity,
720  /*VerifyOnly*/false,
721  TreatUnavailableAsInvalid);
722  if (ElementInit.isInvalid()) {
723  hadError = true;
724  return;
725  }
726 
727  Filler = ElementInit.getAs<Expr>();
728  }
729 
730  if (hadError) {
731  // Do nothing
732  } else if (Init < NumInits) {
733  // For arrays, just set the expression used for value-initialization
734  // of the "holes" in the array.
735  if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
736  ILE->setArrayFiller(Filler);
737  else
738  ILE->setInit(Init, Filler);
739  } else {
740  // For arrays, just set the expression used for value-initialization
741  // of the rest of elements and exit.
742  if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
743  ILE->setArrayFiller(Filler);
744  return;
745  }
746 
747  if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
748  // Empty initialization requires a constructor call, so
749  // extend the initializer list to include the constructor
750  // call and make a note that we'll need to take another pass
751  // through the initializer list.
752  ILE->updateInit(SemaRef.Context, Init, Filler);
753  RequiresSecondPass = true;
754  }
755  }
756  } else if (InitListExpr *InnerILE
757  = dyn_cast_or_null<InitListExpr>(InitExpr))
758  FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
759  FillWithNoInit);
760  else if (DesignatedInitUpdateExpr *InnerDIUE
761  = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
762  FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
763  RequiresSecondPass, /*FillWithNoInit =*/ true);
764  }
765 }
766 
767 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
768  InitListExpr *IL, QualType &T,
769  bool VerifyOnly,
770  bool TreatUnavailableAsInvalid)
771  : SemaRef(S), VerifyOnly(VerifyOnly),
772  TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
773  // FIXME: Check that IL isn't already the semantic form of some other
774  // InitListExpr. If it is, we'd create a broken AST.
775 
776  hadError = false;
777 
778  FullyStructuredList =
779  getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
780  CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
781  /*TopLevelObject=*/true);
782 
783  if (!hadError && !VerifyOnly) {
784  bool RequiresSecondPass = false;
785  FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
786  if (RequiresSecondPass && !hadError)
787  FillInEmptyInitializations(Entity, FullyStructuredList,
788  RequiresSecondPass);
789  }
790 }
791 
792 int InitListChecker::numArrayElements(QualType DeclType) {
793  // FIXME: use a proper constant
794  int maxElements = 0x7FFFFFFF;
795  if (const ConstantArrayType *CAT =
796  SemaRef.Context.getAsConstantArrayType(DeclType)) {
797  maxElements = static_cast<int>(CAT->getSize().getZExtValue());
798  }
799  return maxElements;
800 }
801 
802 int InitListChecker::numStructUnionElements(QualType DeclType) {
803  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
804  int InitializableMembers = 0;
805  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
806  InitializableMembers += CXXRD->getNumBases();
807  for (const auto *Field : structDecl->fields())
808  if (!Field->isUnnamedBitfield())
809  ++InitializableMembers;
810 
811  if (structDecl->isUnion())
812  return std::min(InitializableMembers, 1);
813  return InitializableMembers - structDecl->hasFlexibleArrayMember();
814 }
815 
816 /// Check whether the range of the initializer \p ParentIList from element
817 /// \p Index onwards can be used to initialize an object of type \p T. Update
818 /// \p Index to indicate how many elements of the list were consumed.
819 ///
820 /// This also fills in \p StructuredList, from element \p StructuredIndex
821 /// onwards, with the fully-braced, desugared form of the initialization.
822 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
823  InitListExpr *ParentIList,
824  QualType T, unsigned &Index,
825  InitListExpr *StructuredList,
826  unsigned &StructuredIndex) {
827  int maxElements = 0;
828 
829  if (T->isArrayType())
830  maxElements = numArrayElements(T);
831  else if (T->isRecordType())
832  maxElements = numStructUnionElements(T);
833  else if (T->isVectorType())
834  maxElements = T->getAs<VectorType>()->getNumElements();
835  else
836  llvm_unreachable("CheckImplicitInitList(): Illegal type");
837 
838  if (maxElements == 0) {
839  if (!VerifyOnly)
840  SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
841  diag::err_implicit_empty_initializer);
842  ++Index;
843  hadError = true;
844  return;
845  }
846 
847  // Build a structured initializer list corresponding to this subobject.
848  InitListExpr *StructuredSubobjectInitList
849  = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
850  StructuredIndex,
851  SourceRange(ParentIList->getInit(Index)->getLocStart(),
852  ParentIList->getSourceRange().getEnd()));
853  unsigned StructuredSubobjectInitIndex = 0;
854 
855  // Check the element types and build the structural subobject.
856  unsigned StartIndex = Index;
857  CheckListElementTypes(Entity, ParentIList, T,
858  /*SubobjectIsDesignatorContext=*/false, Index,
859  StructuredSubobjectInitList,
860  StructuredSubobjectInitIndex);
861 
862  if (!VerifyOnly) {
863  StructuredSubobjectInitList->setType(T);
864 
865  unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
866  // Update the structured sub-object initializer so that it's ending
867  // range corresponds with the end of the last initializer it used.
868  if (EndIndex < ParentIList->getNumInits() &&
869  ParentIList->getInit(EndIndex)) {
870  SourceLocation EndLoc
871  = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
872  StructuredSubobjectInitList->setRBraceLoc(EndLoc);
873  }
874 
875  // Complain about missing braces.
876  if (T->isArrayType() || T->isRecordType()) {
877  SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
878  diag::warn_missing_braces)
879  << StructuredSubobjectInitList->getSourceRange()
880  << FixItHint::CreateInsertion(
881  StructuredSubobjectInitList->getLocStart(), "{")
882  << FixItHint::CreateInsertion(
883  SemaRef.getLocForEndOfToken(
884  StructuredSubobjectInitList->getLocEnd()),
885  "}");
886  }
887  }
888 }
889 
890 /// Warn that \p Entity was of scalar type and was initialized by a
891 /// single-element braced initializer list.
892 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
893  SourceRange Braces) {
894  // Don't warn during template instantiation. If the initialization was
895  // non-dependent, we warned during the initial parse; otherwise, the
896  // type might not be scalar in some uses of the template.
897  if (!S.ActiveTemplateInstantiations.empty())
898  return;
899 
900  unsigned DiagID = 0;
901 
902  switch (Entity.getKind()) {
903  case InitializedEntity::EK_VectorElement:
904  case InitializedEntity::EK_ComplexElement:
905  case InitializedEntity::EK_ArrayElement:
906  case InitializedEntity::EK_Parameter:
907  case InitializedEntity::EK_Parameter_CF_Audited:
908  case InitializedEntity::EK_Result:
909  // Extra braces here are suspicious.
910  DiagID = diag::warn_braces_around_scalar_init;
911  break;
912 
913  case InitializedEntity::EK_Member:
914  // Warn on aggregate initialization but not on ctor init list or
915  // default member initializer.
916  if (Entity.getParent())
917  DiagID = diag::warn_braces_around_scalar_init;
918  break;
919 
920  case InitializedEntity::EK_Variable:
921  case InitializedEntity::EK_LambdaCapture:
922  // No warning, might be direct-list-initialization.
923  // FIXME: Should we warn for copy-list-initialization in these cases?
924  break;
925 
926  case InitializedEntity::EK_New:
927  case InitializedEntity::EK_Temporary:
928  case InitializedEntity::EK_CompoundLiteralInit:
929  // No warning, braces are part of the syntax of the underlying construct.
930  break;
931 
932  case InitializedEntity::EK_RelatedResult:
933  // No warning, we already warned when initializing the result.
934  break;
935 
936  case InitializedEntity::EK_Exception:
937  case InitializedEntity::EK_Base:
938  case InitializedEntity::EK_Delegating:
939  case InitializedEntity::EK_BlockElement:
940  llvm_unreachable("unexpected braced scalar init");
941  }
942 
943  if (DiagID) {
944  S.Diag(Braces.getBegin(), DiagID)
945  << Braces
946  << FixItHint::CreateRemoval(Braces.getBegin())
947  << FixItHint::CreateRemoval(Braces.getEnd());
948  }
949 }
950 
951 /// Check whether the initializer \p IList (that was written with explicit
952 /// braces) can be used to initialize an object of type \p T.
953 ///
954 /// This also fills in \p StructuredList with the fully-braced, desugared
955 /// form of the initialization.
956 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
957  InitListExpr *IList, QualType &T,
958  InitListExpr *StructuredList,
959  bool TopLevelObject) {
960  if (!VerifyOnly) {
961  SyntacticToSemantic[IList] = StructuredList;
962  StructuredList->setSyntacticForm(IList);
963  }
964 
965  unsigned Index = 0, StructuredIndex = 0;
966  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
967  Index, StructuredList, StructuredIndex, TopLevelObject);
968  if (!VerifyOnly) {
969  QualType ExprTy = T;
970  if (!ExprTy->isArrayType())
971  ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
972  IList->setType(ExprTy);
973  StructuredList->setType(ExprTy);
974  }
975  if (hadError)
976  return;
977 
978  if (Index < IList->getNumInits()) {
979  // We have leftover initializers
980  if (VerifyOnly) {
981  if (SemaRef.getLangOpts().CPlusPlus ||
982  (SemaRef.getLangOpts().OpenCL &&
983  IList->getType()->isVectorType())) {
984  hadError = true;
985  }
986  return;
987  }
988 
989  if (StructuredIndex == 1 &&
990  IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
991  SIF_None) {
992  unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
993  if (SemaRef.getLangOpts().CPlusPlus) {
994  DK = diag::err_excess_initializers_in_char_array_initializer;
995  hadError = true;
996  }
997  // Special-case
998  SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
999  << IList->getInit(Index)->getSourceRange();
1000  } else if (!T->isIncompleteType()) {
1001  // Don't complain for incomplete types, since we'll get an error
1002  // elsewhere
1003  QualType CurrentObjectType = StructuredList->getType();
1004  int initKind =
1005  CurrentObjectType->isArrayType()? 0 :
1006  CurrentObjectType->isVectorType()? 1 :
1007  CurrentObjectType->isScalarType()? 2 :
1008  CurrentObjectType->isUnionType()? 3 :
1009  4;
1010 
1011  unsigned DK = diag::ext_excess_initializers;
1012  if (SemaRef.getLangOpts().CPlusPlus) {
1013  DK = diag::err_excess_initializers;
1014  hadError = true;
1015  }
1016  if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1017  DK = diag::err_excess_initializers;
1018  hadError = true;
1019  }
1020 
1021  SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1022  << initKind << IList->getInit(Index)->getSourceRange();
1023  }
1024  }
1025 
1026  if (!VerifyOnly && T->isScalarType() &&
1027  IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1028  warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1029 }
1030 
1031 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1032  InitListExpr *IList,
1033  QualType &DeclType,
1034  bool SubobjectIsDesignatorContext,
1035  unsigned &Index,
1036  InitListExpr *StructuredList,
1037  unsigned &StructuredIndex,
1038  bool TopLevelObject) {
1039  if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1040  // Explicitly braced initializer for complex type can be real+imaginary
1041  // parts.
1042  CheckComplexType(Entity, IList, DeclType, Index,
1043  StructuredList, StructuredIndex);
1044  } else if (DeclType->isScalarType()) {
1045  CheckScalarType(Entity, IList, DeclType, Index,
1046  StructuredList, StructuredIndex);
1047  } else if (DeclType->isVectorType()) {
1048  CheckVectorType(Entity, IList, DeclType, Index,
1049  StructuredList, StructuredIndex);
1050  } else if (DeclType->isRecordType()) {
1051  assert(DeclType->isAggregateType() &&
1052  "non-aggregate records should be handed in CheckSubElementType");
1053  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1054  auto Bases =
1057  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1058  Bases = CXXRD->bases();
1059  CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1060  SubobjectIsDesignatorContext, Index, StructuredList,
1061  StructuredIndex, TopLevelObject);
1062  } else if (DeclType->isArrayType()) {
1063  llvm::APSInt Zero(
1064  SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1065  false);
1066  CheckArrayType(Entity, IList, DeclType, Zero,
1067  SubobjectIsDesignatorContext, Index,
1068  StructuredList, StructuredIndex);
1069  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1070  // This type is invalid, issue a diagnostic.
1071  ++Index;
1072  if (!VerifyOnly)
1073  SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1074  << DeclType;
1075  hadError = true;
1076  } else if (DeclType->isReferenceType()) {
1077  CheckReferenceType(Entity, IList, DeclType, Index,
1078  StructuredList, StructuredIndex);
1079  } else if (DeclType->isObjCObjectType()) {
1080  if (!VerifyOnly)
1081  SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1082  << DeclType;
1083  hadError = true;
1084  } else {
1085  if (!VerifyOnly)
1086  SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1087  << DeclType;
1088  hadError = true;
1089  }
1090 }
1091 
1092 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1093  InitListExpr *IList,
1094  QualType ElemType,
1095  unsigned &Index,
1096  InitListExpr *StructuredList,
1097  unsigned &StructuredIndex) {
1098  Expr *expr = IList->getInit(Index);
1099 
1100  if (ElemType->isReferenceType())
1101  return CheckReferenceType(Entity, IList, ElemType, Index,
1102  StructuredList, StructuredIndex);
1103 
1104  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1105  if (SubInitList->getNumInits() == 1 &&
1106  IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1107  SIF_None) {
1108  expr = SubInitList->getInit(0);
1109  } else if (!SemaRef.getLangOpts().CPlusPlus) {
1110  InitListExpr *InnerStructuredList
1111  = getStructuredSubobjectInit(IList, Index, ElemType,
1112  StructuredList, StructuredIndex,
1113  SubInitList->getSourceRange(), true);
1114  CheckExplicitInitList(Entity, SubInitList, ElemType,
1115  InnerStructuredList);
1116 
1117  if (!hadError && !VerifyOnly) {
1118  bool RequiresSecondPass = false;
1119  FillInEmptyInitializations(Entity, InnerStructuredList,
1120  RequiresSecondPass);
1121  if (RequiresSecondPass && !hadError)
1122  FillInEmptyInitializations(Entity, InnerStructuredList,
1123  RequiresSecondPass);
1124  }
1125  ++StructuredIndex;
1126  ++Index;
1127  return;
1128  }
1129  // C++ initialization is handled later.
1130  } else if (isa<ImplicitValueInitExpr>(expr)) {
1131  // This happens during template instantiation when we see an InitListExpr
1132  // that we've already checked once.
1133  assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1134  "found implicit initialization for the wrong type");
1135  if (!VerifyOnly)
1136  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1137  ++Index;
1138  return;
1139  }
1140 
1141  if (SemaRef.getLangOpts().CPlusPlus) {
1142  // C++ [dcl.init.aggr]p2:
1143  // Each member is copy-initialized from the corresponding
1144  // initializer-clause.
1145 
1146  // FIXME: Better EqualLoc?
1147  InitializationKind Kind =
1148  InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1149  InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1150  /*TopLevelOfInitList*/ true);
1151 
1152  // C++14 [dcl.init.aggr]p13:
1153  // If the assignment-expression can initialize a member, the member is
1154  // initialized. Otherwise [...] brace elision is assumed
1155  //
1156  // Brace elision is never performed if the element is not an
1157  // assignment-expression.
1158  if (Seq || isa<InitListExpr>(expr)) {
1159  if (!VerifyOnly) {
1160  ExprResult Result =
1161  Seq.Perform(SemaRef, Entity, Kind, expr);
1162  if (Result.isInvalid())
1163  hadError = true;
1164 
1165  UpdateStructuredListElement(StructuredList, StructuredIndex,
1166  Result.getAs<Expr>());
1167  } else if (!Seq)
1168  hadError = true;
1169  ++Index;
1170  return;
1171  }
1172 
1173  // Fall through for subaggregate initialization
1174  } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1175  // FIXME: Need to handle atomic aggregate types with implicit init lists.
1176  return CheckScalarType(Entity, IList, ElemType, Index,
1177  StructuredList, StructuredIndex);
1178  } else if (const ArrayType *arrayType =
1179  SemaRef.Context.getAsArrayType(ElemType)) {
1180  // arrayType can be incomplete if we're initializing a flexible
1181  // array member. There's nothing we can do with the completed
1182  // type here, though.
1183 
1184  if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1185  if (!VerifyOnly) {
1186  CheckStringInit(expr, ElemType, arrayType, SemaRef);
1187  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1188  }
1189  ++Index;
1190  return;
1191  }
1192 
1193  // Fall through for subaggregate initialization.
1194 
1195  } else {
1196  assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1197  ElemType->isClkEventT()) && "Unexpected type");
1198 
1199  // C99 6.7.8p13:
1200  //
1201  // The initializer for a structure or union object that has
1202  // automatic storage duration shall be either an initializer
1203  // list as described below, or a single expression that has
1204  // compatible structure or union type. In the latter case, the
1205  // initial value of the object, including unnamed members, is
1206  // that of the expression.
1207  ExprResult ExprRes = expr;
1209  ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1210  if (ExprRes.isInvalid())
1211  hadError = true;
1212  else {
1213  ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1214  if (ExprRes.isInvalid())
1215  hadError = true;
1216  }
1217  UpdateStructuredListElement(StructuredList, StructuredIndex,
1218  ExprRes.getAs<Expr>());
1219  ++Index;
1220  return;
1221  }
1222  ExprRes.get();
1223  // Fall through for subaggregate initialization
1224  }
1225 
1226  // C++ [dcl.init.aggr]p12:
1227  //
1228  // [...] Otherwise, if the member is itself a non-empty
1229  // subaggregate, brace elision is assumed and the initializer is
1230  // considered for the initialization of the first member of
1231  // the subaggregate.
1232  if (!SemaRef.getLangOpts().OpenCL &&
1233  (ElemType->isAggregateType() || ElemType->isVectorType())) {
1234  CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1235  StructuredIndex);
1236  ++StructuredIndex;
1237  } else {
1238  if (!VerifyOnly) {
1239  // We cannot initialize this element, so let
1240  // PerformCopyInitialization produce the appropriate diagnostic.
1241  SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1242  /*TopLevelOfInitList=*/true);
1243  }
1244  hadError = true;
1245  ++Index;
1246  ++StructuredIndex;
1247  }
1248 }
1249 
1250 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1251  InitListExpr *IList, QualType DeclType,
1252  unsigned &Index,
1253  InitListExpr *StructuredList,
1254  unsigned &StructuredIndex) {
1255  assert(Index == 0 && "Index in explicit init list must be zero");
1256 
1257  // As an extension, clang supports complex initializers, which initialize
1258  // a complex number component-wise. When an explicit initializer list for
1259  // a complex number contains two two initializers, this extension kicks in:
1260  // it exepcts the initializer list to contain two elements convertible to
1261  // the element type of the complex type. The first element initializes
1262  // the real part, and the second element intitializes the imaginary part.
1263 
1264  if (IList->getNumInits() != 2)
1265  return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1266  StructuredIndex);
1267 
1268  // This is an extension in C. (The builtin _Complex type does not exist
1269  // in the C++ standard.)
1270  if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1271  SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1272  << IList->getSourceRange();
1273 
1274  // Initialize the complex number.
1275  QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1276  InitializedEntity ElementEntity =
1277  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1278 
1279  for (unsigned i = 0; i < 2; ++i) {
1280  ElementEntity.setElementIndex(Index);
1281  CheckSubElementType(ElementEntity, IList, elementType, Index,
1282  StructuredList, StructuredIndex);
1283  }
1284 }
1285 
1286 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1287  InitListExpr *IList, QualType DeclType,
1288  unsigned &Index,
1289  InitListExpr *StructuredList,
1290  unsigned &StructuredIndex) {
1291  if (Index >= IList->getNumInits()) {
1292  if (!VerifyOnly)
1293  SemaRef.Diag(IList->getLocStart(),
1294  SemaRef.getLangOpts().CPlusPlus11 ?
1295  diag::warn_cxx98_compat_empty_scalar_initializer :
1296  diag::err_empty_scalar_initializer)
1297  << IList->getSourceRange();
1298  hadError = !SemaRef.getLangOpts().CPlusPlus11;
1299  ++Index;
1300  ++StructuredIndex;
1301  return;
1302  }
1303 
1304  Expr *expr = IList->getInit(Index);
1305  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1306  // FIXME: This is invalid, and accepting it causes overload resolution
1307  // to pick the wrong overload in some corner cases.
1308  if (!VerifyOnly)
1309  SemaRef.Diag(SubIList->getLocStart(),
1310  diag::ext_many_braces_around_scalar_init)
1311  << SubIList->getSourceRange();
1312 
1313  CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1314  StructuredIndex);
1315  return;
1316  } else if (isa<DesignatedInitExpr>(expr)) {
1317  if (!VerifyOnly)
1318  SemaRef.Diag(expr->getLocStart(),
1319  diag::err_designator_for_scalar_init)
1320  << DeclType << expr->getSourceRange();
1321  hadError = true;
1322  ++Index;
1323  ++StructuredIndex;
1324  return;
1325  }
1326 
1327  if (VerifyOnly) {
1328  if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1329  hadError = true;
1330  ++Index;
1331  return;
1332  }
1333 
1334  ExprResult Result =
1335  SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1336  /*TopLevelOfInitList=*/true);
1337 
1338  Expr *ResultExpr = nullptr;
1339 
1340  if (Result.isInvalid())
1341  hadError = true; // types weren't compatible.
1342  else {
1343  ResultExpr = Result.getAs<Expr>();
1344 
1345  if (ResultExpr != expr) {
1346  // The type was promoted, update initializer list.
1347  IList->setInit(Index, ResultExpr);
1348  }
1349  }
1350  if (hadError)
1351  ++StructuredIndex;
1352  else
1353  UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1354  ++Index;
1355 }
1356 
1357 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1358  InitListExpr *IList, QualType DeclType,
1359  unsigned &Index,
1360  InitListExpr *StructuredList,
1361  unsigned &StructuredIndex) {
1362  if (Index >= IList->getNumInits()) {
1363  // FIXME: It would be wonderful if we could point at the actual member. In
1364  // general, it would be useful to pass location information down the stack,
1365  // so that we know the location (or decl) of the "current object" being
1366  // initialized.
1367  if (!VerifyOnly)
1368  SemaRef.Diag(IList->getLocStart(),
1369  diag::err_init_reference_member_uninitialized)
1370  << DeclType
1371  << IList->getSourceRange();
1372  hadError = true;
1373  ++Index;
1374  ++StructuredIndex;
1375  return;
1376  }
1377 
1378  Expr *expr = IList->getInit(Index);
1379  if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1380  if (!VerifyOnly)
1381  SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1382  << DeclType << IList->getSourceRange();
1383  hadError = true;
1384  ++Index;
1385  ++StructuredIndex;
1386  return;
1387  }
1388 
1389  if (VerifyOnly) {
1390  if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1391  hadError = true;
1392  ++Index;
1393  return;
1394  }
1395 
1396  ExprResult Result =
1397  SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1398  /*TopLevelOfInitList=*/true);
1399 
1400  if (Result.isInvalid())
1401  hadError = true;
1402 
1403  expr = Result.getAs<Expr>();
1404  IList->setInit(Index, expr);
1405 
1406  if (hadError)
1407  ++StructuredIndex;
1408  else
1409  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1410  ++Index;
1411 }
1412 
1413 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1414  InitListExpr *IList, QualType DeclType,
1415  unsigned &Index,
1416  InitListExpr *StructuredList,
1417  unsigned &StructuredIndex) {
1418  const VectorType *VT = DeclType->getAs<VectorType>();
1419  unsigned maxElements = VT->getNumElements();
1420  unsigned numEltsInit = 0;
1421  QualType elementType = VT->getElementType();
1422 
1423  if (Index >= IList->getNumInits()) {
1424  // Make sure the element type can be value-initialized.
1425  if (VerifyOnly)
1426  CheckEmptyInitializable(
1427  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1428  IList->getLocEnd());
1429  return;
1430  }
1431 
1432  if (!SemaRef.getLangOpts().OpenCL) {
1433  // If the initializing element is a vector, try to copy-initialize
1434  // instead of breaking it apart (which is doomed to failure anyway).
1435  Expr *Init = IList->getInit(Index);
1436  if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1437  if (VerifyOnly) {
1438  if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1439  hadError = true;
1440  ++Index;
1441  return;
1442  }
1443 
1444  ExprResult Result =
1445  SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1446  /*TopLevelOfInitList=*/true);
1447 
1448  Expr *ResultExpr = nullptr;
1449  if (Result.isInvalid())
1450  hadError = true; // types weren't compatible.
1451  else {
1452  ResultExpr = Result.getAs<Expr>();
1453 
1454  if (ResultExpr != Init) {
1455  // The type was promoted, update initializer list.
1456  IList->setInit(Index, ResultExpr);
1457  }
1458  }
1459  if (hadError)
1460  ++StructuredIndex;
1461  else
1462  UpdateStructuredListElement(StructuredList, StructuredIndex,
1463  ResultExpr);
1464  ++Index;
1465  return;
1466  }
1467 
1468  InitializedEntity ElementEntity =
1469  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1470 
1471  for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1472  // Don't attempt to go past the end of the init list
1473  if (Index >= IList->getNumInits()) {
1474  if (VerifyOnly)
1475  CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
1476  break;
1477  }
1478 
1479  ElementEntity.setElementIndex(Index);
1480  CheckSubElementType(ElementEntity, IList, elementType, Index,
1481  StructuredList, StructuredIndex);
1482  }
1483 
1484  if (VerifyOnly)
1485  return;
1486 
1487  bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1488  const VectorType *T = Entity.getType()->getAs<VectorType>();
1489  if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1490  T->getVectorKind() == VectorType::NeonPolyVector)) {
1491  // The ability to use vector initializer lists is a GNU vector extension
1492  // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1493  // endian machines it works fine, however on big endian machines it
1494  // exhibits surprising behaviour:
1495  //
1496  // uint32x2_t x = {42, 64};
1497  // return vget_lane_u32(x, 0); // Will return 64.
1498  //
1499  // Because of this, explicitly call out that it is non-portable.
1500  //
1501  SemaRef.Diag(IList->getLocStart(),
1502  diag::warn_neon_vector_initializer_non_portable);
1503 
1504  const char *typeCode;
1505  unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1506 
1507  if (elementType->isFloatingType())
1508  typeCode = "f";
1509  else if (elementType->isSignedIntegerType())
1510  typeCode = "s";
1511  else if (elementType->isUnsignedIntegerType())
1512  typeCode = "u";
1513  else
1514  llvm_unreachable("Invalid element type!");
1515 
1516  SemaRef.Diag(IList->getLocStart(),
1517  SemaRef.Context.getTypeSize(VT) > 64 ?
1518  diag::note_neon_vector_initializer_non_portable_q :
1519  diag::note_neon_vector_initializer_non_portable)
1520  << typeCode << typeSize;
1521  }
1522 
1523  return;
1524  }
1525 
1526  InitializedEntity ElementEntity =
1527  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1528 
1529  // OpenCL initializers allows vectors to be constructed from vectors.
1530  for (unsigned i = 0; i < maxElements; ++i) {
1531  // Don't attempt to go past the end of the init list
1532  if (Index >= IList->getNumInits())
1533  break;
1534 
1535  ElementEntity.setElementIndex(Index);
1536 
1537  QualType IType = IList->getInit(Index)->getType();
1538  if (!IType->isVectorType()) {
1539  CheckSubElementType(ElementEntity, IList, elementType, Index,
1540  StructuredList, StructuredIndex);
1541  ++numEltsInit;
1542  } else {
1543  QualType VecType;
1544  const VectorType *IVT = IType->getAs<VectorType>();
1545  unsigned numIElts = IVT->getNumElements();
1546 
1547  if (IType->isExtVectorType())
1548  VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1549  else
1550  VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1551  IVT->getVectorKind());
1552  CheckSubElementType(ElementEntity, IList, VecType, Index,
1553  StructuredList, StructuredIndex);
1554  numEltsInit += numIElts;
1555  }
1556  }
1557 
1558  // OpenCL requires all elements to be initialized.
1559  if (numEltsInit != maxElements) {
1560  if (!VerifyOnly)
1561  SemaRef.Diag(IList->getLocStart(),
1562  diag::err_vector_incorrect_num_initializers)
1563  << (numEltsInit < maxElements) << maxElements << numEltsInit;
1564  hadError = true;
1565  }
1566 }
1567 
1568 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1569  InitListExpr *IList, QualType &DeclType,
1570  llvm::APSInt elementIndex,
1571  bool SubobjectIsDesignatorContext,
1572  unsigned &Index,
1573  InitListExpr *StructuredList,
1574  unsigned &StructuredIndex) {
1575  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1576 
1577  // Check for the special-case of initializing an array with a string.
1578  if (Index < IList->getNumInits()) {
1579  if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1580  SIF_None) {
1581  // We place the string literal directly into the resulting
1582  // initializer list. This is the only place where the structure
1583  // of the structured initializer list doesn't match exactly,
1584  // because doing so would involve allocating one character
1585  // constant for each string.
1586  if (!VerifyOnly) {
1587  CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1588  UpdateStructuredListElement(StructuredList, StructuredIndex,
1589  IList->getInit(Index));
1590  StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1591  }
1592  ++Index;
1593  return;
1594  }
1595  }
1596  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1597  // Check for VLAs; in standard C it would be possible to check this
1598  // earlier, but I don't know where clang accepts VLAs (gcc accepts
1599  // them in all sorts of strange places).
1600  if (!VerifyOnly)
1601  SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1602  diag::err_variable_object_no_init)
1603  << VAT->getSizeExpr()->getSourceRange();
1604  hadError = true;
1605  ++Index;
1606  ++StructuredIndex;
1607  return;
1608  }
1609 
1610  // We might know the maximum number of elements in advance.
1611  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1612  elementIndex.isUnsigned());
1613  bool maxElementsKnown = false;
1614  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1615  maxElements = CAT->getSize();
1616  elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1617  elementIndex.setIsUnsigned(maxElements.isUnsigned());
1618  maxElementsKnown = true;
1619  }
1620 
1621  QualType elementType = arrayType->getElementType();
1622  while (Index < IList->getNumInits()) {
1623  Expr *Init = IList->getInit(Index);
1624  if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1625  // If we're not the subobject that matches up with the '{' for
1626  // the designator, we shouldn't be handling the
1627  // designator. Return immediately.
1628  if (!SubobjectIsDesignatorContext)
1629  return;
1630 
1631  // Handle this designated initializer. elementIndex will be
1632  // updated to be the next array element we'll initialize.
1633  if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1634  DeclType, nullptr, &elementIndex, Index,
1635  StructuredList, StructuredIndex, true,
1636  false)) {
1637  hadError = true;
1638  continue;
1639  }
1640 
1641  if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1642  maxElements = maxElements.extend(elementIndex.getBitWidth());
1643  else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1644  elementIndex = elementIndex.extend(maxElements.getBitWidth());
1645  elementIndex.setIsUnsigned(maxElements.isUnsigned());
1646 
1647  // If the array is of incomplete type, keep track of the number of
1648  // elements in the initializer.
1649  if (!maxElementsKnown && elementIndex > maxElements)
1650  maxElements = elementIndex;
1651 
1652  continue;
1653  }
1654 
1655  // If we know the maximum number of elements, and we've already
1656  // hit it, stop consuming elements in the initializer list.
1657  if (maxElementsKnown && elementIndex == maxElements)
1658  break;
1659 
1660  InitializedEntity ElementEntity =
1661  InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1662  Entity);
1663  // Check this element.
1664  CheckSubElementType(ElementEntity, IList, elementType, Index,
1665  StructuredList, StructuredIndex);
1666  ++elementIndex;
1667 
1668  // If the array is of incomplete type, keep track of the number of
1669  // elements in the initializer.
1670  if (!maxElementsKnown && elementIndex > maxElements)
1671  maxElements = elementIndex;
1672  }
1673  if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1674  // If this is an incomplete array type, the actual type needs to
1675  // be calculated here.
1676  llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1677  if (maxElements == Zero) {
1678  // Sizing an array implicitly to zero is not allowed by ISO C,
1679  // but is supported by GNU.
1680  SemaRef.Diag(IList->getLocStart(),
1681  diag::ext_typecheck_zero_array_size);
1682  }
1683 
1684  DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1685  ArrayType::Normal, 0);
1686  }
1687  if (!hadError && VerifyOnly) {
1688  // Check if there are any members of the array that get value-initialized.
1689  // If so, check if doing that is possible.
1690  // FIXME: This needs to detect holes left by designated initializers too.
1691  if (maxElementsKnown && elementIndex < maxElements)
1692  CheckEmptyInitializable(InitializedEntity::InitializeElement(
1693  SemaRef.Context, 0, Entity),
1694  IList->getLocEnd());
1695  }
1696 }
1697 
1698 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1699  Expr *InitExpr,
1700  FieldDecl *Field,
1701  bool TopLevelObject) {
1702  // Handle GNU flexible array initializers.
1703  unsigned FlexArrayDiag;
1704  if (isa<InitListExpr>(InitExpr) &&
1705  cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1706  // Empty flexible array init always allowed as an extension
1707  FlexArrayDiag = diag::ext_flexible_array_init;
1708  } else if (SemaRef.getLangOpts().CPlusPlus) {
1709  // Disallow flexible array init in C++; it is not required for gcc
1710  // compatibility, and it needs work to IRGen correctly in general.
1711  FlexArrayDiag = diag::err_flexible_array_init;
1712  } else if (!TopLevelObject) {
1713  // Disallow flexible array init on non-top-level object
1714  FlexArrayDiag = diag::err_flexible_array_init;
1715  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1716  // Disallow flexible array init on anything which is not a variable.
1717  FlexArrayDiag = diag::err_flexible_array_init;
1718  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1719  // Disallow flexible array init on local variables.
1720  FlexArrayDiag = diag::err_flexible_array_init;
1721  } else {
1722  // Allow other cases.
1723  FlexArrayDiag = diag::ext_flexible_array_init;
1724  }
1725 
1726  if (!VerifyOnly) {
1727  SemaRef.Diag(InitExpr->getLocStart(),
1728  FlexArrayDiag)
1729  << InitExpr->getLocStart();
1730  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1731  << Field;
1732  }
1733 
1734  return FlexArrayDiag != diag::ext_flexible_array_init;
1735 }
1736 
1737 void InitListChecker::CheckStructUnionTypes(
1738  const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1740  bool SubobjectIsDesignatorContext, unsigned &Index,
1741  InitListExpr *StructuredList, unsigned &StructuredIndex,
1742  bool TopLevelObject) {
1743  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1744 
1745  // If the record is invalid, some of it's members are invalid. To avoid
1746  // confusion, we forgo checking the intializer for the entire record.
1747  if (structDecl->isInvalidDecl()) {
1748  // Assume it was supposed to consume a single initializer.
1749  ++Index;
1750  hadError = true;
1751  return;
1752  }
1753 
1754  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1755  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1756 
1757  // If there's a default initializer, use it.
1758  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1759  if (VerifyOnly)
1760  return;
1761  for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1762  Field != FieldEnd; ++Field) {
1763  if (Field->hasInClassInitializer()) {
1764  StructuredList->setInitializedFieldInUnion(*Field);
1765  // FIXME: Actually build a CXXDefaultInitExpr?
1766  return;
1767  }
1768  }
1769  }
1770 
1771  // Value-initialize the first member of the union that isn't an unnamed
1772  // bitfield.
1773  for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1774  Field != FieldEnd; ++Field) {
1775  if (!Field->isUnnamedBitfield()) {
1776  if (VerifyOnly)
1777  CheckEmptyInitializable(
1778  InitializedEntity::InitializeMember(*Field, &Entity),
1779  IList->getLocEnd());
1780  else
1781  StructuredList->setInitializedFieldInUnion(*Field);
1782  break;
1783  }
1784  }
1785  return;
1786  }
1787 
1788  bool InitializedSomething = false;
1789 
1790  // If we have any base classes, they are initialized prior to the fields.
1791  for (auto &Base : Bases) {
1792  Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1793  SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1794 
1795  // Designated inits always initialize fields, so if we see one, all
1796  // remaining base classes have no explicit initializer.
1797  if (Init && isa<DesignatedInitExpr>(Init))
1798  Init = nullptr;
1799 
1800  InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1801  SemaRef.Context, &Base, false, &Entity);
1802  if (Init) {
1803  CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1804  StructuredList, StructuredIndex);
1805  InitializedSomething = true;
1806  } else if (VerifyOnly) {
1807  CheckEmptyInitializable(BaseEntity, InitLoc);
1808  }
1809  }
1810 
1811  // If structDecl is a forward declaration, this loop won't do
1812  // anything except look at designated initializers; That's okay,
1813  // because an error should get printed out elsewhere. It might be
1814  // worthwhile to skip over the rest of the initializer, though.
1815  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1816  RecordDecl::field_iterator FieldEnd = RD->field_end();
1817  bool CheckForMissingFields = true;
1818  while (Index < IList->getNumInits()) {
1819  Expr *Init = IList->getInit(Index);
1820 
1821  if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1822  // If we're not the subobject that matches up with the '{' for
1823  // the designator, we shouldn't be handling the
1824  // designator. Return immediately.
1825  if (!SubobjectIsDesignatorContext)
1826  return;
1827 
1828  // Handle this designated initializer. Field will be updated to
1829  // the next field that we'll be initializing.
1830  if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1831  DeclType, &Field, nullptr, Index,
1832  StructuredList, StructuredIndex,
1833  true, TopLevelObject))
1834  hadError = true;
1835 
1836  InitializedSomething = true;
1837 
1838  // Disable check for missing fields when designators are used.
1839  // This matches gcc behaviour.
1840  CheckForMissingFields = false;
1841  continue;
1842  }
1843 
1844  if (Field == FieldEnd) {
1845  // We've run out of fields. We're done.
1846  break;
1847  }
1848 
1849  // We've already initialized a member of a union. We're done.
1850  if (InitializedSomething && DeclType->isUnionType())
1851  break;
1852 
1853  // If we've hit the flexible array member at the end, we're done.
1854  if (Field->getType()->isIncompleteArrayType())
1855  break;
1856 
1857  if (Field->isUnnamedBitfield()) {
1858  // Don't initialize unnamed bitfields, e.g. "int : 20;"
1859  ++Field;
1860  continue;
1861  }
1862 
1863  // Make sure we can use this declaration.
1864  bool InvalidUse;
1865  if (VerifyOnly)
1866  InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
1867  else
1868  InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1869  IList->getInit(Index)->getLocStart());
1870  if (InvalidUse) {
1871  ++Index;
1872  ++Field;
1873  hadError = true;
1874  continue;
1875  }
1876 
1877  InitializedEntity MemberEntity =
1878  InitializedEntity::InitializeMember(*Field, &Entity);
1879  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1880  StructuredList, StructuredIndex);
1881  InitializedSomething = true;
1882 
1883  if (DeclType->isUnionType() && !VerifyOnly) {
1884  // Initialize the first field within the union.
1885  StructuredList->setInitializedFieldInUnion(*Field);
1886  }
1887 
1888  ++Field;
1889  }
1890 
1891  // Emit warnings for missing struct field initializers.
1892  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1893  Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1894  !DeclType->isUnionType()) {
1895  // It is possible we have one or more unnamed bitfields remaining.
1896  // Find first (if any) named field and emit warning.
1897  for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1898  it != end; ++it) {
1899  if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1900  SemaRef.Diag(IList->getSourceRange().getEnd(),
1901  diag::warn_missing_field_initializers) << *it;
1902  break;
1903  }
1904  }
1905  }
1906 
1907  // Check that any remaining fields can be value-initialized.
1908  if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1909  !Field->getType()->isIncompleteArrayType()) {
1910  // FIXME: Should check for holes left by designated initializers too.
1911  for (; Field != FieldEnd && !hadError; ++Field) {
1912  if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1913  CheckEmptyInitializable(
1914  InitializedEntity::InitializeMember(*Field, &Entity),
1915  IList->getLocEnd());
1916  }
1917  }
1918 
1919  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1920  Index >= IList->getNumInits())
1921  return;
1922 
1923  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1924  TopLevelObject)) {
1925  hadError = true;
1926  ++Index;
1927  return;
1928  }
1929 
1930  InitializedEntity MemberEntity =
1931  InitializedEntity::InitializeMember(*Field, &Entity);
1932 
1933  if (isa<InitListExpr>(IList->getInit(Index)))
1934  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1935  StructuredList, StructuredIndex);
1936  else
1937  CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1938  StructuredList, StructuredIndex);
1939 }
1940 
1941 /// \brief Expand a field designator that refers to a member of an
1942 /// anonymous struct or union into a series of field designators that
1943 /// refers to the field within the appropriate subobject.
1944 ///
1946  DesignatedInitExpr *DIE,
1947  unsigned DesigIdx,
1948  IndirectFieldDecl *IndirectField) {
1950 
1951  // Build the replacement designators.
1953  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1954  PE = IndirectField->chain_end(); PI != PE; ++PI) {
1955  if (PI + 1 == PE)
1956  Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1957  DIE->getDesignator(DesigIdx)->getDotLoc(),
1958  DIE->getDesignator(DesigIdx)->getFieldLoc()));
1959  else
1960  Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1962  assert(isa<FieldDecl>(*PI));
1963  Replacements.back().setField(cast<FieldDecl>(*PI));
1964  }
1965 
1966  // Expand the current designator into the set of replacement
1967  // designators, so we have a full subobject path down to where the
1968  // member of the anonymous struct/union is actually stored.
1969  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1970  &Replacements[0] + Replacements.size());
1971 }
1972 
1974  DesignatedInitExpr *DIE) {
1975  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1976  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1977  for (unsigned I = 0; I < NumIndexExprs; ++I)
1978  IndexExprs[I] = DIE->getSubExpr(I + 1);
1979  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
1980  IndexExprs,
1981  DIE->getEqualOrColonLoc(),
1982  DIE->usesGNUSyntax(), DIE->getInit());
1983 }
1984 
1985 namespace {
1986 
1987 // Callback to only accept typo corrections that are for field members of
1988 // the given struct or union.
1989 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1990  public:
1991  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1992  : Record(RD) {}
1993 
1994  bool ValidateCandidate(const TypoCorrection &candidate) override {
1995  FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1996  return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1997  }
1998 
1999  private:
2000  RecordDecl *Record;
2001 };
2002 
2003 } // end anonymous namespace
2004 
2005 /// @brief Check the well-formedness of a C99 designated initializer.
2006 ///
2007 /// Determines whether the designated initializer @p DIE, which
2008 /// resides at the given @p Index within the initializer list @p
2009 /// IList, is well-formed for a current object of type @p DeclType
2010 /// (C99 6.7.8). The actual subobject that this designator refers to
2011 /// within the current subobject is returned in either
2012 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2013 ///
2014 /// @param IList The initializer list in which this designated
2015 /// initializer occurs.
2016 ///
2017 /// @param DIE The designated initializer expression.
2018 ///
2019 /// @param DesigIdx The index of the current designator.
2020 ///
2021 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2022 /// into which the designation in @p DIE should refer.
2023 ///
2024 /// @param NextField If non-NULL and the first designator in @p DIE is
2025 /// a field, this will be set to the field declaration corresponding
2026 /// to the field named by the designator.
2027 ///
2028 /// @param NextElementIndex If non-NULL and the first designator in @p
2029 /// DIE is an array designator or GNU array-range designator, this
2030 /// will be set to the last index initialized by this designator.
2031 ///
2032 /// @param Index Index into @p IList where the designated initializer
2033 /// @p DIE occurs.
2034 ///
2035 /// @param StructuredList The initializer list expression that
2036 /// describes all of the subobject initializers in the order they'll
2037 /// actually be initialized.
2038 ///
2039 /// @returns true if there was an error, false otherwise.
2040 bool
2041 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2042  InitListExpr *IList,
2043  DesignatedInitExpr *DIE,
2044  unsigned DesigIdx,
2045  QualType &CurrentObjectType,
2046  RecordDecl::field_iterator *NextField,
2047  llvm::APSInt *NextElementIndex,
2048  unsigned &Index,
2049  InitListExpr *StructuredList,
2050  unsigned &StructuredIndex,
2051  bool FinishSubobjectInit,
2052  bool TopLevelObject) {
2053  if (DesigIdx == DIE->size()) {
2054  // Check the actual initialization for the designated object type.
2055  bool prevHadError = hadError;
2056 
2057  // Temporarily remove the designator expression from the
2058  // initializer list that the child calls see, so that we don't try
2059  // to re-process the designator.
2060  unsigned OldIndex = Index;
2061  IList->setInit(OldIndex, DIE->getInit());
2062 
2063  CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2064  StructuredList, StructuredIndex);
2065 
2066  // Restore the designated initializer expression in the syntactic
2067  // form of the initializer list.
2068  if (IList->getInit(OldIndex) != DIE->getInit())
2069  DIE->setInit(IList->getInit(OldIndex));
2070  IList->setInit(OldIndex, DIE);
2071 
2072  return hadError && !prevHadError;
2073  }
2074 
2075  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2076  bool IsFirstDesignator = (DesigIdx == 0);
2077  if (!VerifyOnly) {
2078  assert((IsFirstDesignator || StructuredList) &&
2079  "Need a non-designated initializer list to start from");
2080 
2081  // Determine the structural initializer list that corresponds to the
2082  // current subobject.
2083  if (IsFirstDesignator)
2084  StructuredList = SyntacticToSemantic.lookup(IList);
2085  else {
2086  Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2087  StructuredList->getInit(StructuredIndex) : nullptr;
2088  if (!ExistingInit && StructuredList->hasArrayFiller())
2089  ExistingInit = StructuredList->getArrayFiller();
2090 
2091  if (!ExistingInit)
2092  StructuredList =
2093  getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2094  StructuredList, StructuredIndex,
2095  SourceRange(D->getLocStart(),
2096  DIE->getLocEnd()));
2097  else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2098  StructuredList = Result;
2099  else {
2101  dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2102  StructuredList = E->getUpdater();
2103  else {
2104  DesignatedInitUpdateExpr *DIUE =
2105  new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2106  D->getLocStart(), ExistingInit,
2107  DIE->getLocEnd());
2108  StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2109  StructuredList = DIUE->getUpdater();
2110  }
2111 
2112  // We need to check on source range validity because the previous
2113  // initializer does not have to be an explicit initializer. e.g.,
2114  //
2115  // struct P { int a, b; };
2116  // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2117  //
2118  // There is an overwrite taking place because the first braced initializer
2119  // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2120  if (ExistingInit->getSourceRange().isValid()) {
2121  // We are creating an initializer list that initializes the
2122  // subobjects of the current object, but there was already an
2123  // initialization that completely initialized the current
2124  // subobject, e.g., by a compound literal:
2125  //
2126  // struct X { int a, b; };
2127  // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2128  //
2129  // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2130  // designated initializer re-initializes the whole
2131  // subobject [0], overwriting previous initializers.
2132  SemaRef.Diag(D->getLocStart(),
2133  diag::warn_subobject_initializer_overrides)
2134  << SourceRange(D->getLocStart(), DIE->getLocEnd());
2135 
2136  SemaRef.Diag(ExistingInit->getLocStart(),
2137  diag::note_previous_initializer)
2138  << /*FIXME:has side effects=*/0
2139  << ExistingInit->getSourceRange();
2140  }
2141  }
2142  }
2143  assert(StructuredList && "Expected a structured initializer list");
2144  }
2145 
2146  if (D->isFieldDesignator()) {
2147  // C99 6.7.8p7:
2148  //
2149  // If a designator has the form
2150  //
2151  // . identifier
2152  //
2153  // then the current object (defined below) shall have
2154  // structure or union type and the identifier shall be the
2155  // name of a member of that type.
2156  const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2157  if (!RT) {
2158  SourceLocation Loc = D->getDotLoc();
2159  if (Loc.isInvalid())
2160  Loc = D->getFieldLoc();
2161  if (!VerifyOnly)
2162  SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2163  << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2164  ++Index;
2165  return true;
2166  }
2167 
2168  FieldDecl *KnownField = D->getField();
2169  if (!KnownField) {
2170  IdentifierInfo *FieldName = D->getFieldName();
2171  DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2172  for (NamedDecl *ND : Lookup) {
2173  if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2174  KnownField = FD;
2175  break;
2176  }
2177  if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2178  // In verify mode, don't modify the original.
2179  if (VerifyOnly)
2180  DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2181  ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2182  D = DIE->getDesignator(DesigIdx);
2183  KnownField = cast<FieldDecl>(*IFD->chain_begin());
2184  break;
2185  }
2186  }
2187  if (!KnownField) {
2188  if (VerifyOnly) {
2189  ++Index;
2190  return true; // No typo correction when just trying this out.
2191  }
2192 
2193  // Name lookup found something, but it wasn't a field.
2194  if (!Lookup.empty()) {
2195  SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2196  << FieldName;
2197  SemaRef.Diag(Lookup.front()->getLocation(),
2198  diag::note_field_designator_found);
2199  ++Index;
2200  return true;
2201  }
2202 
2203  // Name lookup didn't find anything.
2204  // Determine whether this was a typo for another field name.
2205  if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2206  DeclarationNameInfo(FieldName, D->getFieldLoc()),
2207  Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
2208  llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2209  Sema::CTK_ErrorRecovery, RT->getDecl())) {
2210  SemaRef.diagnoseTypo(
2211  Corrected,
2212  SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2213  << FieldName << CurrentObjectType);
2214  KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2215  hadError = true;
2216  } else {
2217  // Typo correction didn't find anything.
2218  SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2219  << FieldName << CurrentObjectType;
2220  ++Index;
2221  return true;
2222  }
2223  }
2224  }
2225 
2226  unsigned FieldIndex = 0;
2227  for (auto *FI : RT->getDecl()->fields()) {
2228  if (FI->isUnnamedBitfield())
2229  continue;
2230  if (declaresSameEntity(KnownField, FI)) {
2231  KnownField = FI;
2232  break;
2233  }
2234  ++FieldIndex;
2235  }
2236 
2239 
2240  // All of the fields of a union are located at the same place in
2241  // the initializer list.
2242  if (RT->getDecl()->isUnion()) {
2243  FieldIndex = 0;
2244  if (!VerifyOnly) {
2245  FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2246  if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2247  assert(StructuredList->getNumInits() == 1
2248  && "A union should never have more than one initializer!");
2249 
2250  // We're about to throw away an initializer, emit warning.
2251  SemaRef.Diag(D->getFieldLoc(),
2252  diag::warn_initializer_overrides)
2253  << D->getSourceRange();
2254  Expr *ExistingInit = StructuredList->getInit(0);
2255  SemaRef.Diag(ExistingInit->getLocStart(),
2256  diag::note_previous_initializer)
2257  << /*FIXME:has side effects=*/0
2258  << ExistingInit->getSourceRange();
2259 
2260  // remove existing initializer
2261  StructuredList->resizeInits(SemaRef.Context, 0);
2262  StructuredList->setInitializedFieldInUnion(nullptr);
2263  }
2264 
2265  StructuredList->setInitializedFieldInUnion(*Field);
2266  }
2267  }
2268 
2269  // Make sure we can use this declaration.
2270  bool InvalidUse;
2271  if (VerifyOnly)
2272  InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2273  else
2274  InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2275  if (InvalidUse) {
2276  ++Index;
2277  return true;
2278  }
2279 
2280  if (!VerifyOnly) {
2281  // Update the designator with the field declaration.
2282  D->setField(*Field);
2283 
2284  // Make sure that our non-designated initializer list has space
2285  // for a subobject corresponding to this field.
2286  if (FieldIndex >= StructuredList->getNumInits())
2287  StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2288  }
2289 
2290  // This designator names a flexible array member.
2291  if (Field->getType()->isIncompleteArrayType()) {
2292  bool Invalid = false;
2293  if ((DesigIdx + 1) != DIE->size()) {
2294  // We can't designate an object within the flexible array
2295  // member (because GCC doesn't allow it).
2296  if (!VerifyOnly) {
2298  = DIE->getDesignator(DesigIdx + 1);
2299  SemaRef.Diag(NextD->getLocStart(),
2300  diag::err_designator_into_flexible_array_member)
2301  << SourceRange(NextD->getLocStart(),
2302  DIE->getLocEnd());
2303  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2304  << *Field;
2305  }
2306  Invalid = true;
2307  }
2308 
2309  if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2310  !isa<StringLiteral>(DIE->getInit())) {
2311  // The initializer is not an initializer list.
2312  if (!VerifyOnly) {
2313  SemaRef.Diag(DIE->getInit()->getLocStart(),
2314  diag::err_flexible_array_init_needs_braces)
2315  << DIE->getInit()->getSourceRange();
2316  SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2317  << *Field;
2318  }
2319  Invalid = true;
2320  }
2321 
2322  // Check GNU flexible array initializer.
2323  if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2324  TopLevelObject))
2325  Invalid = true;
2326 
2327  if (Invalid) {
2328  ++Index;
2329  return true;
2330  }
2331 
2332  // Initialize the array.
2333  bool prevHadError = hadError;
2334  unsigned newStructuredIndex = FieldIndex;
2335  unsigned OldIndex = Index;
2336  IList->setInit(Index, DIE->getInit());
2337 
2338  InitializedEntity MemberEntity =
2339  InitializedEntity::InitializeMember(*Field, &Entity);
2340  CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2341  StructuredList, newStructuredIndex);
2342 
2343  IList->setInit(OldIndex, DIE);
2344  if (hadError && !prevHadError) {
2345  ++Field;
2346  ++FieldIndex;
2347  if (NextField)
2348  *NextField = Field;
2349  StructuredIndex = FieldIndex;
2350  return true;
2351  }
2352  } else {
2353  // Recurse to check later designated subobjects.
2354  QualType FieldType = Field->getType();
2355  unsigned newStructuredIndex = FieldIndex;
2356 
2357  InitializedEntity MemberEntity =
2358  InitializedEntity::InitializeMember(*Field, &Entity);
2359  if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2360  FieldType, nullptr, nullptr, Index,
2361  StructuredList, newStructuredIndex,
2362  FinishSubobjectInit, false))
2363  return true;
2364  }
2365 
2366  // Find the position of the next field to be initialized in this
2367  // subobject.
2368  ++Field;
2369  ++FieldIndex;
2370 
2371  // If this the first designator, our caller will continue checking
2372  // the rest of this struct/class/union subobject.
2373  if (IsFirstDesignator) {
2374  if (NextField)
2375  *NextField = Field;
2376  StructuredIndex = FieldIndex;
2377  return false;
2378  }
2379 
2380  if (!FinishSubobjectInit)
2381  return false;
2382 
2383  // We've already initialized something in the union; we're done.
2384  if (RT->getDecl()->isUnion())
2385  return hadError;
2386 
2387  // Check the remaining fields within this class/struct/union subobject.
2388  bool prevHadError = hadError;
2389 
2390  auto NoBases =
2393  CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2394  false, Index, StructuredList, FieldIndex);
2395  return hadError && !prevHadError;
2396  }
2397 
2398  // C99 6.7.8p6:
2399  //
2400  // If a designator has the form
2401  //
2402  // [ constant-expression ]
2403  //
2404  // then the current object (defined below) shall have array
2405  // type and the expression shall be an integer constant
2406  // expression. If the array is of unknown size, any
2407  // nonnegative value is valid.
2408  //
2409  // Additionally, cope with the GNU extension that permits
2410  // designators of the form
2411  //
2412  // [ constant-expression ... constant-expression ]
2413  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2414  if (!AT) {
2415  if (!VerifyOnly)
2416  SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2417  << CurrentObjectType;
2418  ++Index;
2419  return true;
2420  }
2421 
2422  Expr *IndexExpr = nullptr;
2423  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2424  if (D->isArrayDesignator()) {
2425  IndexExpr = DIE->getArrayIndex(*D);
2426  DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2427  DesignatedEndIndex = DesignatedStartIndex;
2428  } else {
2429  assert(D->isArrayRangeDesignator() && "Need array-range designator");
2430 
2431  DesignatedStartIndex =
2433  DesignatedEndIndex =
2434  DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2435  IndexExpr = DIE->getArrayRangeEnd(*D);
2436 
2437  // Codegen can't handle evaluating array range designators that have side
2438  // effects, because we replicate the AST value for each initialized element.
2439  // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2440  // elements with something that has a side effect, so codegen can emit an
2441  // "error unsupported" error instead of miscompiling the app.
2442  if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2443  DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2444  FullyStructuredList->sawArrayRangeDesignator();
2445  }
2446 
2447  if (isa<ConstantArrayType>(AT)) {
2448  llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2449  DesignatedStartIndex
2450  = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2451  DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2452  DesignatedEndIndex
2453  = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2454  DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2455  if (DesignatedEndIndex >= MaxElements) {
2456  if (!VerifyOnly)
2457  SemaRef.Diag(IndexExpr->getLocStart(),
2458  diag::err_array_designator_too_large)
2459  << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2460  << IndexExpr->getSourceRange();
2461  ++Index;
2462  return true;
2463  }
2464  } else {
2465  unsigned DesignatedIndexBitWidth =
2466  ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2467  DesignatedStartIndex =
2468  DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2469  DesignatedEndIndex =
2470  DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2471  DesignatedStartIndex.setIsUnsigned(true);
2472  DesignatedEndIndex.setIsUnsigned(true);
2473  }
2474 
2475  if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2476  // We're modifying a string literal init; we have to decompose the string
2477  // so we can modify the individual characters.
2478  ASTContext &Context = SemaRef.Context;
2479  Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2480 
2481  // Compute the character type
2482  QualType CharTy = AT->getElementType();
2483 
2484  // Compute the type of the integer literals.
2485  QualType PromotedCharTy = CharTy;
2486  if (CharTy->isPromotableIntegerType())
2487  PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2488  unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2489 
2490  if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2491  // Get the length of the string.
2492  uint64_t StrLen = SL->getLength();
2493  if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2494  StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2495  StructuredList->resizeInits(Context, StrLen);
2496 
2497  // Build a literal for each character in the string, and put them into
2498  // the init list.
2499  for (unsigned i = 0, e = StrLen; i != e; ++i) {
2500  llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2501  Expr *Init = new (Context) IntegerLiteral(
2502  Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2503  if (CharTy != PromotedCharTy)
2504  Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2505  Init, nullptr, VK_RValue);
2506  StructuredList->updateInit(Context, i, Init);
2507  }
2508  } else {
2509  ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2510  std::string Str;
2511  Context.getObjCEncodingForType(E->getEncodedType(), Str);
2512 
2513  // Get the length of the string.
2514  uint64_t StrLen = Str.size();
2515  if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2516  StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2517  StructuredList->resizeInits(Context, StrLen);
2518 
2519  // Build a literal for each character in the string, and put them into
2520  // the init list.
2521  for (unsigned i = 0, e = StrLen; i != e; ++i) {
2522  llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2523  Expr *Init = new (Context) IntegerLiteral(
2524  Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2525  if (CharTy != PromotedCharTy)
2526  Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2527  Init, nullptr, VK_RValue);
2528  StructuredList->updateInit(Context, i, Init);
2529  }
2530  }
2531  }
2532 
2533  // Make sure that our non-designated initializer list has space
2534  // for a subobject corresponding to this array element.
2535  if (!VerifyOnly &&
2536  DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2537  StructuredList->resizeInits(SemaRef.Context,
2538  DesignatedEndIndex.getZExtValue() + 1);
2539 
2540  // Repeatedly perform subobject initializations in the range
2541  // [DesignatedStartIndex, DesignatedEndIndex].
2542 
2543  // Move to the next designator
2544  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2545  unsigned OldIndex = Index;
2546 
2547  InitializedEntity ElementEntity =
2548  InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2549 
2550  while (DesignatedStartIndex <= DesignatedEndIndex) {
2551  // Recurse to check later designated subobjects.
2552  QualType ElementType = AT->getElementType();
2553  Index = OldIndex;
2554 
2555  ElementEntity.setElementIndex(ElementIndex);
2556  if (CheckDesignatedInitializer(
2557  ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2558  nullptr, Index, StructuredList, ElementIndex,
2559  FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2560  false))
2561  return true;
2562 
2563  // Move to the next index in the array that we'll be initializing.
2564  ++DesignatedStartIndex;
2565  ElementIndex = DesignatedStartIndex.getZExtValue();
2566  }
2567 
2568  // If this the first designator, our caller will continue checking
2569  // the rest of this array subobject.
2570  if (IsFirstDesignator) {
2571  if (NextElementIndex)
2572  *NextElementIndex = DesignatedStartIndex;
2573  StructuredIndex = ElementIndex;
2574  return false;
2575  }
2576 
2577  if (!FinishSubobjectInit)
2578  return false;
2579 
2580  // Check the remaining elements within this array subobject.
2581  bool prevHadError = hadError;
2582  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2583  /*SubobjectIsDesignatorContext=*/false, Index,
2584  StructuredList, ElementIndex);
2585  return hadError && !prevHadError;
2586 }
2587 
2588 // Get the structured initializer list for a subobject of type
2589 // @p CurrentObjectType.
2590 InitListExpr *
2591 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2592  QualType CurrentObjectType,
2593  InitListExpr *StructuredList,
2594  unsigned StructuredIndex,
2595  SourceRange InitRange,
2596  bool IsFullyOverwritten) {
2597  if (VerifyOnly)
2598  return nullptr; // No structured list in verification-only mode.
2599  Expr *ExistingInit = nullptr;
2600  if (!StructuredList)
2601  ExistingInit = SyntacticToSemantic.lookup(IList);
2602  else if (StructuredIndex < StructuredList->getNumInits())
2603  ExistingInit = StructuredList->getInit(StructuredIndex);
2604 
2605  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2606  // There might have already been initializers for subobjects of the current
2607  // object, but a subsequent initializer list will overwrite the entirety
2608  // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2609  //
2610  // struct P { char x[6]; };
2611  // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2612  //
2613  // The first designated initializer is ignored, and l.x is just "f".
2614  if (!IsFullyOverwritten)
2615  return Result;
2616 
2617  if (ExistingInit) {
2618  // We are creating an initializer list that initializes the
2619  // subobjects of the current object, but there was already an
2620  // initialization that completely initialized the current
2621  // subobject, e.g., by a compound literal:
2622  //
2623  // struct X { int a, b; };
2624  // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2625  //
2626  // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2627  // designated initializer re-initializes the whole
2628  // subobject [0], overwriting previous initializers.
2629  SemaRef.Diag(InitRange.getBegin(),
2630  diag::warn_subobject_initializer_overrides)
2631  << InitRange;
2632  SemaRef.Diag(ExistingInit->getLocStart(),
2633  diag::note_previous_initializer)
2634  << /*FIXME:has side effects=*/0
2635  << ExistingInit->getSourceRange();
2636  }
2637 
2638  InitListExpr *Result
2639  = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2640  InitRange.getBegin(), None,
2641  InitRange.getEnd());
2642 
2643  QualType ResultType = CurrentObjectType;
2644  if (!ResultType->isArrayType())
2645  ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2646  Result->setType(ResultType);
2647 
2648  // Pre-allocate storage for the structured initializer list.
2649  unsigned NumElements = 0;
2650  unsigned NumInits = 0;
2651  bool GotNumInits = false;
2652  if (!StructuredList) {
2653  NumInits = IList->getNumInits();
2654  GotNumInits = true;
2655  } else if (Index < IList->getNumInits()) {
2656  if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2657  NumInits = SubList->getNumInits();
2658  GotNumInits = true;
2659  }
2660  }
2661 
2662  if (const ArrayType *AType
2663  = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2664  if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2665  NumElements = CAType->getSize().getZExtValue();
2666  // Simple heuristic so that we don't allocate a very large
2667  // initializer with many empty entries at the end.
2668  if (GotNumInits && NumElements > NumInits)
2669  NumElements = 0;
2670  }
2671  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2672  NumElements = VType->getNumElements();
2673  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2674  RecordDecl *RDecl = RType->getDecl();
2675  if (RDecl->isUnion())
2676  NumElements = 1;
2677  else
2678  NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2679  }
2680 
2681  Result->reserveInits(SemaRef.Context, NumElements);
2682 
2683  // Link this new initializer list into the structured initializer
2684  // lists.
2685  if (StructuredList)
2686  StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2687  else {
2688  Result->setSyntacticForm(IList);
2689  SyntacticToSemantic[IList] = Result;
2690  }
2691 
2692  return Result;
2693 }
2694 
2695 /// Update the initializer at index @p StructuredIndex within the
2696 /// structured initializer list to the value @p expr.
2697 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2698  unsigned &StructuredIndex,
2699  Expr *expr) {
2700  // No structured initializer list to update
2701  if (!StructuredList)
2702  return;
2703 
2704  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2705  StructuredIndex, expr)) {
2706  // This initializer overwrites a previous initializer. Warn.
2707  // We need to check on source range validity because the previous
2708  // initializer does not have to be an explicit initializer.
2709  // struct P { int a, b; };
2710  // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2711  // There is an overwrite taking place because the first braced initializer
2712  // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2713  if (PrevInit->getSourceRange().isValid()) {
2714  SemaRef.Diag(expr->getLocStart(),
2715  diag::warn_initializer_overrides)
2716  << expr->getSourceRange();
2717 
2718  SemaRef.Diag(PrevInit->getLocStart(),
2719  diag::note_previous_initializer)
2720  << /*FIXME:has side effects=*/0
2721  << PrevInit->getSourceRange();
2722  }
2723  }
2724 
2725  ++StructuredIndex;
2726 }
2727 
2728 /// Check that the given Index expression is a valid array designator
2729 /// value. This is essentially just a wrapper around
2730 /// VerifyIntegerConstantExpression that also checks for negative values
2731 /// and produces a reasonable diagnostic if there is a
2732 /// failure. Returns the index expression, possibly with an implicit cast
2733 /// added, on success. If everything went okay, Value will receive the
2734 /// value of the constant expression.
2735 static ExprResult
2736 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2737  SourceLocation Loc = Index->getLocStart();
2738 
2739  // Make sure this is an integer constant expression.
2740  ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2741  if (Result.isInvalid())
2742  return Result;
2743 
2744  if (Value.isSigned() && Value.isNegative())
2745  return S.Diag(Loc, diag::err_array_designator_negative)
2746  << Value.toString(10) << Index->getSourceRange();
2747 
2748  Value.setIsUnsigned(true);
2749  return Result;
2750 }
2751 
2752 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2753  SourceLocation Loc,
2754  bool GNUSyntax,
2755  ExprResult Init) {
2756  typedef DesignatedInitExpr::Designator ASTDesignator;
2757 
2758  bool Invalid = false;
2759  SmallVector<ASTDesignator, 32> Designators;
2760  SmallVector<Expr *, 32> InitExpressions;
2761 
2762  // Build designators and check array designator expressions.
2763  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2764  const Designator &D = Desig.getDesignator(Idx);
2765  switch (D.getKind()) {
2767  Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2768  D.getFieldLoc()));
2769  break;
2770 
2772  Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2773  llvm::APSInt IndexValue;
2774  if (!Index->isTypeDependent() && !Index->isValueDependent())
2775  Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2776  if (!Index)
2777  Invalid = true;
2778  else {
2779  Designators.push_back(ASTDesignator(InitExpressions.size(),
2780  D.getLBracketLoc(),
2781  D.getRBracketLoc()));
2782  InitExpressions.push_back(Index);
2783  }
2784  break;
2785  }
2786 
2788  Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2789  Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2790  llvm::APSInt StartValue;
2791  llvm::APSInt EndValue;
2792  bool StartDependent = StartIndex->isTypeDependent() ||
2793  StartIndex->isValueDependent();
2794  bool EndDependent = EndIndex->isTypeDependent() ||
2795  EndIndex->isValueDependent();
2796  if (!StartDependent)
2797  StartIndex =
2798  CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2799  if (!EndDependent)
2800  EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2801 
2802  if (!StartIndex || !EndIndex)
2803  Invalid = true;
2804  else {
2805  // Make sure we're comparing values with the same bit width.
2806  if (StartDependent || EndDependent) {
2807  // Nothing to compute.
2808  } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2809  EndValue = EndValue.extend(StartValue.getBitWidth());
2810  else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2811  StartValue = StartValue.extend(EndValue.getBitWidth());
2812 
2813  if (!StartDependent && !EndDependent && EndValue < StartValue) {
2814  Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2815  << StartValue.toString(10) << EndValue.toString(10)
2816  << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2817  Invalid = true;
2818  } else {
2819  Designators.push_back(ASTDesignator(InitExpressions.size(),
2820  D.getLBracketLoc(),
2821  D.getEllipsisLoc(),
2822  D.getRBracketLoc()));
2823  InitExpressions.push_back(StartIndex);
2824  InitExpressions.push_back(EndIndex);
2825  }
2826  }
2827  break;
2828  }
2829  }
2830  }
2831 
2832  if (Invalid || Init.isInvalid())
2833  return ExprError();
2834 
2835  // Clear out the expressions within the designation.
2836  Desig.ClearExprs(*this);
2837 
2838  DesignatedInitExpr *DIE
2839  = DesignatedInitExpr::Create(Context,
2840  Designators,
2841  InitExpressions, Loc, GNUSyntax,
2842  Init.getAs<Expr>());
2843 
2844  if (!getLangOpts().C99)
2845  Diag(DIE->getLocStart(), diag::ext_designated_init)
2846  << DIE->getSourceRange();
2847 
2848  return DIE;
2849 }
2850 
2851 //===----------------------------------------------------------------------===//
2852 // Initialization entity
2853 //===----------------------------------------------------------------------===//
2854 
2855 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2856  const InitializedEntity &Parent)
2857  : Parent(&Parent), Index(Index)
2858 {
2859  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2860  Kind = EK_ArrayElement;
2861  Type = AT->getElementType();
2862  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2863  Kind = EK_VectorElement;
2864  Type = VT->getElementType();
2865  } else {
2866  const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2867  assert(CT && "Unexpected type");
2868  Kind = EK_ComplexElement;
2869  Type = CT->getElementType();
2870  }
2871 }
2872 
2875  const CXXBaseSpecifier *Base,
2876  bool IsInheritedVirtualBase,
2877  const InitializedEntity *Parent) {
2879  Result.Kind = EK_Base;
2880  Result.Parent = Parent;
2881  Result.Base = reinterpret_cast<uintptr_t>(Base);
2882  if (IsInheritedVirtualBase)
2883  Result.Base |= 0x01;
2884 
2885  Result.Type = Base->getType();
2886  return Result;
2887 }
2888 
2890  switch (getKind()) {
2891  case EK_Parameter:
2892  case EK_Parameter_CF_Audited: {
2893  ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2894  return (D ? D->getDeclName() : DeclarationName());
2895  }
2896 
2897  case EK_Variable:
2898  case EK_Member:
2899  return VariableOrMember->getDeclName();
2900 
2901  case EK_LambdaCapture:
2902  return DeclarationName(Capture.VarID);
2903 
2904  case EK_Result:
2905  case EK_Exception:
2906  case EK_New:
2907  case EK_Temporary:
2908  case EK_Base:
2909  case EK_Delegating:
2910  case EK_ArrayElement:
2911  case EK_VectorElement:
2912  case EK_ComplexElement:
2913  case EK_BlockElement:
2915  case EK_RelatedResult:
2916  return DeclarationName();
2917  }
2918 
2919  llvm_unreachable("Invalid EntityKind!");
2920 }
2921 
2923  switch (getKind()) {
2924  case EK_Variable:
2925  case EK_Member:
2926  return VariableOrMember;
2927 
2928  case EK_Parameter:
2930  return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2931 
2932  case EK_Result:
2933  case EK_Exception:
2934  case EK_New:
2935  case EK_Temporary:
2936  case EK_Base:
2937  case EK_Delegating:
2938  case EK_ArrayElement:
2939  case EK_VectorElement:
2940  case EK_ComplexElement:
2941  case EK_BlockElement:
2942  case EK_LambdaCapture:
2944  case EK_RelatedResult:
2945  return nullptr;
2946  }
2947 
2948  llvm_unreachable("Invalid EntityKind!");
2949 }
2950 
2952  switch (getKind()) {
2953  case EK_Result:
2954  case EK_Exception:
2955  return LocAndNRVO.NRVO;
2956 
2957  case EK_Variable:
2958  case EK_Parameter:
2960  case EK_Member:
2961  case EK_New:
2962  case EK_Temporary:
2964  case EK_Base:
2965  case EK_Delegating:
2966  case EK_ArrayElement:
2967  case EK_VectorElement:
2968  case EK_ComplexElement:
2969  case EK_BlockElement:
2970  case EK_LambdaCapture:
2971  case EK_RelatedResult:
2972  break;
2973  }
2974 
2975  return false;
2976 }
2977 
2978 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
2979  assert(getParent() != this);
2980  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2981  for (unsigned I = 0; I != Depth; ++I)
2982  OS << "`-";
2983 
2984  switch (getKind()) {
2985  case EK_Variable: OS << "Variable"; break;
2986  case EK_Parameter: OS << "Parameter"; break;
2987  case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2988  break;
2989  case EK_Result: OS << "Result"; break;
2990  case EK_Exception: OS << "Exception"; break;
2991  case EK_Member: OS << "Member"; break;
2992  case EK_New: OS << "New"; break;
2993  case EK_Temporary: OS << "Temporary"; break;
2994  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
2995  case EK_RelatedResult: OS << "RelatedResult"; break;
2996  case EK_Base: OS << "Base"; break;
2997  case EK_Delegating: OS << "Delegating"; break;
2998  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2999  case EK_VectorElement: OS << "VectorElement " << Index; break;
3000  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3001  case EK_BlockElement: OS << "Block"; break;
3002  case EK_LambdaCapture:
3003  OS << "LambdaCapture ";
3004  OS << DeclarationName(Capture.VarID);
3005  break;
3006  }
3007 
3008  if (Decl *D = getDecl()) {
3009  OS << " ";
3010  cast<NamedDecl>(D)->printQualifiedName(OS);
3011  }
3012 
3013  OS << " '" << getType().getAsString() << "'\n";
3014 
3015  return Depth + 1;
3016 }
3017 
3018 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3019  dumpImpl(llvm::errs());
3020 }
3021 
3022 //===----------------------------------------------------------------------===//
3023 // Initialization sequence
3024 //===----------------------------------------------------------------------===//
3025 
3027  switch (Kind) {
3032  case SK_BindReference:
3035  case SK_UserConversion:
3039  case SK_AtomicConversion:
3040  case SK_LValueToRValue:
3041  case SK_ListInitialization:
3042  case SK_UnwrapInitList:
3043  case SK_RewrapInitList:
3046  case SK_ZeroInitialization:
3047  case SK_CAssignment:
3048  case SK_StringInit:
3050  case SK_ArrayInit:
3054  case SK_ProduceObjCObject:
3055  case SK_StdInitializerList:
3057  case SK_OCLSamplerInit:
3058  case SK_OCLZeroEvent:
3059  break;
3060 
3061  case SK_ConversionSequence:
3063  delete ICS;
3064  }
3065 }
3066 
3068  return !Steps.empty() && Steps.back().Kind == SK_BindReference;
3069 }
3070 
3072  if (!Failed())
3073  return false;
3074 
3075  switch (getFailureKind()) {
3077  case FK_ArrayNeedsInitList:
3083  case FK_AddressOfOverloadFailed: // FIXME: Could do better
3089  case FK_ConversionFailed:
3094  case FK_DefaultInitOfConst:
3095  case FK_Incomplete:
3096  case FK_ArrayTypeMismatch:
3100  case FK_PlaceholderType:
3103  return false;
3104 
3109  return FailedOverloadResult == OR_Ambiguous;
3110  }
3111 
3112  llvm_unreachable("Invalid EntityKind!");
3113 }
3114 
3116  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3117 }
3118 
3119 void
3122  DeclAccessPair Found,
3123  bool HadMultipleCandidates) {
3124  Step S;
3126  S.Type = Function->getType();
3127  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3128  S.Function.Function = Function;
3129  S.Function.FoundDecl = Found;
3130  Steps.push_back(S);
3131 }
3132 
3134  ExprValueKind VK) {
3135  Step S;
3136  switch (VK) {
3137  case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3138  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3139  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3140  }
3141  S.Type = BaseType;
3142  Steps.push_back(S);
3143 }
3144 
3146  bool BindingTemporary) {
3147  Step S;
3148  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3149  S.Type = T;
3150  Steps.push_back(S);
3151 }
3152 
3154  Step S;
3156  S.Type = T;
3157  Steps.push_back(S);
3158 }
3159 
3160 void
3162  DeclAccessPair FoundDecl,
3163  QualType T,
3164  bool HadMultipleCandidates) {
3165  Step S;
3166  S.Kind = SK_UserConversion;
3167  S.Type = T;
3168  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3169  S.Function.Function = Function;
3170  S.Function.FoundDecl = FoundDecl;
3171  Steps.push_back(S);
3172 }
3173 
3175  ExprValueKind VK) {
3176  Step S;
3177  S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3178  switch (VK) {
3179  case VK_RValue:
3181  break;
3182  case VK_XValue:
3184  break;
3185  case VK_LValue:
3187  break;
3188  }
3189  S.Type = Ty;
3190  Steps.push_back(S);
3191 }
3192 
3194  Step S;
3196  S.Type = Ty;
3197  Steps.push_back(S);
3198 }
3199 
3201  assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3202 
3203  Step S;
3204  S.Kind = SK_LValueToRValue;
3205  S.Type = Ty;
3206  Steps.push_back(S);
3207 }
3208 
3210  const ImplicitConversionSequence &ICS, QualType T,
3211  bool TopLevelOfInitList) {
3212  Step S;
3213  S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3215  S.Type = T;
3216  S.ICS = new ImplicitConversionSequence(ICS);
3217  Steps.push_back(S);
3218 }
3219 
3221  Step S;
3223  S.Type = T;
3224  Steps.push_back(S);
3225 }
3226 
3228  DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3229  bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3230  Step S;
3231  S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3234  S.Type = T;
3235  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3236  S.Function.Function = Constructor;
3237  S.Function.FoundDecl = FoundDecl;
3238  Steps.push_back(S);
3239 }
3240 
3242  Step S;
3244  S.Type = T;
3245  Steps.push_back(S);
3246 }
3247 
3249  Step S;
3250  S.Kind = SK_CAssignment;
3251  S.Type = T;
3252  Steps.push_back(S);
3253 }
3254 
3256  Step S;
3257  S.Kind = SK_StringInit;
3258  S.Type = T;
3259  Steps.push_back(S);
3260 }
3261 
3263  Step S;
3265  S.Type = T;
3266  Steps.push_back(S);
3267 }
3268 
3270  Step S;
3271  S.Kind = SK_ArrayInit;
3272  S.Type = T;
3273  Steps.push_back(S);
3274 }
3275 
3277  Step S;
3279  S.Type = T;
3280  Steps.push_back(S);
3281 }
3282 
3284  bool shouldCopy) {
3285  Step s;
3286  s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3288  s.Type = type;
3289  Steps.push_back(s);
3290 }
3291 
3293  Step S;
3295  S.Type = T;
3296  Steps.push_back(S);
3297 }
3298 
3300  Step S;
3302  S.Type = T;
3303  Steps.push_back(S);
3304 }
3305 
3307  Step S;
3308  S.Kind = SK_OCLSamplerInit;
3309  S.Type = T;
3310  Steps.push_back(S);
3311 }
3312 
3314  Step S;
3315  S.Kind = SK_OCLZeroEvent;
3316  S.Type = T;
3317  Steps.push_back(S);
3318 }
3319 
3321  InitListExpr *Syntactic) {
3322  assert(Syntactic->getNumInits() == 1 &&
3323  "Can only rewrap trivial init lists.");
3324  Step S;
3325  S.Kind = SK_UnwrapInitList;
3326  S.Type = Syntactic->getInit(0)->getType();
3327  Steps.insert(Steps.begin(), S);
3328 
3329  S.Kind = SK_RewrapInitList;
3330  S.Type = T;
3331  S.WrappingSyntacticList = Syntactic;
3332  Steps.push_back(S);
3333 }
3334 
3336  OverloadingResult Result) {
3338  this->Failure = Failure;
3339  this->FailedOverloadResult = Result;
3340 }
3341 
3342 //===----------------------------------------------------------------------===//
3343 // Attempt initialization
3344 //===----------------------------------------------------------------------===//
3345 
3346 /// Tries to add a zero initializer. Returns true if that worked.
3347 static bool
3349  const InitializedEntity &Entity) {
3350  if (Entity.getKind() != InitializedEntity::EK_Variable)
3351  return false;
3352 
3353  VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3354  if (VD->getInit() || VD->getLocEnd().isMacroID())
3355  return false;
3356 
3357  QualType VariableTy = VD->getType().getCanonicalType();
3358  SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3359  std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3360  if (!Init.empty()) {
3361  Sequence.AddZeroInitializationStep(Entity.getType());
3362  Sequence.SetZeroInitializationFixit(Init, Loc);
3363  return true;
3364  }
3365  return false;
3366 }
3367 
3369  InitializationSequence &Sequence,
3370  const InitializedEntity &Entity) {
3371  if (!S.getLangOpts().ObjCAutoRefCount) return;
3372 
3373  /// When initializing a parameter, produce the value if it's marked
3374  /// __attribute__((ns_consumed)).
3375  if (Entity.isParameterKind()) {
3376  if (!Entity.isParameterConsumed())
3377  return;
3378 
3379  assert(Entity.getType()->isObjCRetainableType() &&
3380  "consuming an object of unretainable type?");
3381  Sequence.AddProduceObjCObjectStep(Entity.getType());
3382 
3383  /// When initializing a return value, if the return type is a
3384  /// retainable type, then returns need to immediately retain the
3385  /// object. If an autorelease is required, it will be done at the
3386  /// last instant.
3387  } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3388  if (!Entity.getType()->isObjCRetainableType())
3389  return;
3390 
3391  Sequence.AddProduceObjCObjectStep(Entity.getType());
3392  }
3393 }
3394 
3395 static void TryListInitialization(Sema &S,
3396  const InitializedEntity &Entity,
3397  const InitializationKind &Kind,
3398  InitListExpr *InitList,
3399  InitializationSequence &Sequence,
3400  bool TreatUnavailableAsInvalid);
3401 
3402 /// \brief When initializing from init list via constructor, handle
3403 /// initialization of an object of type std::initializer_list<T>.
3404 ///
3405 /// \return true if we have handled initialization of an object of type
3406 /// std::initializer_list<T>, false otherwise.
3408  InitListExpr *List,
3409  QualType DestType,
3410  InitializationSequence &Sequence,
3411  bool TreatUnavailableAsInvalid) {
3412  QualType E;
3413  if (!S.isStdInitializerList(DestType, &E))
3414  return false;
3415 
3416  if (!S.isCompleteType(List->getExprLoc(), E)) {
3417  Sequence.setIncompleteTypeFailure(E);
3418  return true;
3419  }
3420 
3421  // Try initializing a temporary array from the init list.
3423  E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3424  List->getNumInits()),
3426  InitializedEntity HiddenArray =
3428  InitializationKind Kind =
3430  TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3431  TreatUnavailableAsInvalid);
3432  if (Sequence)
3433  Sequence.AddStdInitializerListConstructionStep(DestType);
3434  return true;
3435 }
3436 
3437 static OverloadingResult
3439  MultiExprArg Args,
3440  OverloadCandidateSet &CandidateSet,
3443  bool CopyInitializing, bool AllowExplicit,
3444  bool OnlyListConstructors, bool IsListInit) {
3445  CandidateSet.clear();
3446 
3447  for (NamedDecl *D : Ctors) {
3448  auto Info = getConstructorInfo(D);
3449  if (!Info.Constructor)
3450  continue;
3451 
3452  bool SuppressUserConversions = false;
3453 
3454  if (!Info.ConstructorTmpl) {
3455  // C++11 [over.best.ics]p4:
3456  // ... and the constructor or user-defined conversion function is a
3457  // candidate by
3458  // - 13.3.1.3, when the argument is the temporary in the second step
3459  // of a class copy-initialization, or
3460  // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
3461  // user-defined conversion sequences are not considered.
3462  // FIXME: This breaks backward compatibility, e.g. PR12117. As a
3463  // temporary fix, let's re-instate the third bullet above until
3464  // there is a resolution in the standard, i.e.,
3465  // - 13.3.1.7 when the initializer list has exactly one element that is
3466  // itself an initializer list and a conversion to some class X or
3467  // reference to (possibly cv-qualified) X is considered for the first
3468  // parameter of a constructor of X.
3469  if ((CopyInitializing ||
3470  (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3471  Info.Constructor->isCopyOrMoveConstructor())
3472  SuppressUserConversions = true;
3473  }
3474 
3475  if (!Info.Constructor->isInvalidDecl() &&
3476  (AllowExplicit || !Info.Constructor->isExplicit()) &&
3477  (!OnlyListConstructors || S.isInitListConstructor(Info.Constructor))) {
3478  if (Info.ConstructorTmpl)
3479  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3480  /*ExplicitArgs*/ nullptr, Args,
3481  CandidateSet, SuppressUserConversions);
3482  else {
3483  // C++ [over.match.copy]p1:
3484  // - When initializing a temporary to be bound to the first parameter
3485  // of a constructor that takes a reference to possibly cv-qualified
3486  // T as its first argument, called with a single argument in the
3487  // context of direct-initialization, explicit conversion functions
3488  // are also considered.
3489  bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3490  Args.size() == 1 &&
3491  Info.Constructor->isCopyOrMoveConstructor();
3492  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3493  CandidateSet, SuppressUserConversions,
3494  /*PartialOverloading=*/false,
3495  /*AllowExplicit=*/AllowExplicitConv);
3496  }
3497  }
3498  }
3499 
3500  // Perform overload resolution and return the result.
3501  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3502 }
3503 
3504 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3505 /// enumerates the constructors of the initialized entity and performs overload
3506 /// resolution to select the best.
3507 /// \param IsListInit Is this list-initialization?
3508 /// \param IsInitListCopy Is this non-list-initialization resulting from a
3509 /// list-initialization from {x} where x is the same
3510 /// type as the entity?
3512  const InitializedEntity &Entity,
3513  const InitializationKind &Kind,
3514  MultiExprArg Args, QualType DestType,
3515  InitializationSequence &Sequence,
3516  bool IsListInit = false,
3517  bool IsInitListCopy = false) {
3518  assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3519  "IsListInit must come with a single initializer list argument.");
3520 
3521  // The type we're constructing needs to be complete.
3522  if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3523  Sequence.setIncompleteTypeFailure(DestType);
3524  return;
3525  }
3526 
3527  const RecordType *DestRecordType = DestType->getAs<RecordType>();
3528  assert(DestRecordType && "Constructor initialization requires record type");
3529  CXXRecordDecl *DestRecordDecl
3530  = cast<CXXRecordDecl>(DestRecordType->getDecl());
3531 
3532  // Build the candidate set directly in the initialization sequence
3533  // structure, so that it will persist if we fail.
3534  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3535 
3536  // Determine whether we are allowed to call explicit constructors or
3537  // explicit conversion operators.
3538  bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3539  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3540 
3541  // - Otherwise, if T is a class type, constructors are considered. The
3542  // applicable constructors are enumerated, and the best one is chosen
3543  // through overload resolution.
3544  DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3545 
3548  bool AsInitializerList = false;
3549 
3550  // C++11 [over.match.list]p1, per DR1467:
3551  // When objects of non-aggregate type T are list-initialized, such that
3552  // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3553  // according to the rules in this section, overload resolution selects
3554  // the constructor in two phases:
3555  //
3556  // - Initially, the candidate functions are the initializer-list
3557  // constructors of the class T and the argument list consists of the
3558  // initializer list as a single argument.
3559  if (IsListInit) {
3560  InitListExpr *ILE = cast<InitListExpr>(Args[0]);
3561  AsInitializerList = true;
3562 
3563  // If the initializer list has no elements and T has a default constructor,
3564  // the first phase is omitted.
3565  if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
3566  Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3567  CandidateSet, Ctors, Best,
3568  CopyInitialization, AllowExplicit,
3569  /*OnlyListConstructor=*/true,
3570  IsListInit);
3571 
3572  // Time to unwrap the init list.
3573  Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
3574  }
3575 
3576  // C++11 [over.match.list]p1:
3577  // - If no viable initializer-list constructor is found, overload resolution
3578  // is performed again, where the candidate functions are all the
3579  // constructors of the class T and the argument list consists of the
3580  // elements of the initializer list.
3581  if (Result == OR_No_Viable_Function) {
3582  AsInitializerList = false;
3583  Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3584  CandidateSet, Ctors, Best,
3585  CopyInitialization, AllowExplicit,
3586  /*OnlyListConstructors=*/false,
3587  IsListInit);
3588  }
3589  if (Result) {
3590  Sequence.SetOverloadFailure(IsListInit ?
3593  Result);
3594  return;
3595  }
3596 
3597  // C++11 [dcl.init]p6:
3598  // If a program calls for the default initialization of an object
3599  // of a const-qualified type T, T shall be a class type with a
3600  // user-provided default constructor.
3601  // C++ core issue 253 proposal:
3602  // If the implicit default constructor initializes all subobjects, no
3603  // initializer should be required.
3604  // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3605  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3606  if (Kind.getKind() == InitializationKind::IK_Default &&
3607  Entity.getType().isConstQualified()) {
3608  if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3609  if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3611  return;
3612  }
3613  }
3614 
3615  // C++11 [over.match.list]p1:
3616  // In copy-list-initialization, if an explicit constructor is chosen, the
3617  // initializer is ill-formed.
3618  if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3620  return;
3621  }
3622 
3623  // Add the constructor initialization step. Any cv-qualification conversion is
3624  // subsumed by the initialization.
3625  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3627  Best->FoundDecl, CtorDecl, DestType, HadMultipleCandidates,
3628  IsListInit | IsInitListCopy, AsInitializerList);
3629 }
3630 
3631 static bool
3633  Expr *Initializer,
3634  QualType &SourceType,
3635  QualType &UnqualifiedSourceType,
3636  QualType UnqualifiedTargetType,
3637  InitializationSequence &Sequence) {
3638  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3639  S.Context.OverloadTy) {
3640  DeclAccessPair Found;
3641  bool HadMultipleCandidates = false;
3642  if (FunctionDecl *Fn
3643  = S.ResolveAddressOfOverloadedFunction(Initializer,
3644  UnqualifiedTargetType,
3645  false, Found,
3646  &HadMultipleCandidates)) {
3647  Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3648  HadMultipleCandidates);
3649  SourceType = Fn->getType();
3650  UnqualifiedSourceType = SourceType.getUnqualifiedType();
3651  } else if (!UnqualifiedTargetType->isRecordType()) {
3653  return true;
3654  }
3655  }
3656  return false;
3657 }
3658 
3659 static void TryReferenceInitializationCore(Sema &S,
3660  const InitializedEntity &Entity,
3661  const InitializationKind &Kind,
3662  Expr *Initializer,
3663  QualType cv1T1, QualType T1,
3664  Qualifiers T1Quals,
3665  QualType cv2T2, QualType T2,
3666  Qualifiers T2Quals,
3667  InitializationSequence &Sequence);
3668 
3669 static void TryValueInitialization(Sema &S,
3670  const InitializedEntity &Entity,
3671  const InitializationKind &Kind,
3672  InitializationSequence &Sequence,
3673  InitListExpr *InitList = nullptr);
3674 
3675 /// \brief Attempt list initialization of a reference.
3677  const InitializedEntity &Entity,
3678  const InitializationKind &Kind,
3679  InitListExpr *InitList,
3680  InitializationSequence &Sequence,
3681  bool TreatUnavailableAsInvalid) {
3682  // First, catch C++03 where this isn't possible.
3683  if (!S.getLangOpts().CPlusPlus11) {
3685  return;
3686  }
3687  // Can't reference initialize a compound literal.
3690  return;
3691  }
3692 
3693  QualType DestType = Entity.getType();
3694  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3695  Qualifiers T1Quals;
3696  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3697 
3698  // Reference initialization via an initializer list works thus:
3699  // If the initializer list consists of a single element that is
3700  // reference-related to the referenced type, bind directly to that element
3701  // (possibly creating temporaries).
3702  // Otherwise, initialize a temporary with the initializer list and
3703  // bind to that.
3704  if (InitList->getNumInits() == 1) {
3705  Expr *Initializer = InitList->getInit(0);
3706  QualType cv2T2 = Initializer->getType();
3707  Qualifiers T2Quals;
3708  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3709 
3710  // If this fails, creating a temporary wouldn't work either.
3711  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3712  T1, Sequence))
3713  return;
3714 
3715  SourceLocation DeclLoc = Initializer->getLocStart();
3716  bool dummy1, dummy2, dummy3;
3717  Sema::ReferenceCompareResult RefRelationship
3718  = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3719  dummy2, dummy3);
3720  if (RefRelationship >= Sema::Ref_Related) {
3721  // Try to bind the reference here.
3722  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3723  T1Quals, cv2T2, T2, T2Quals, Sequence);
3724  if (Sequence)
3725  Sequence.RewrapReferenceInitList(cv1T1, InitList);
3726  return;
3727  }
3728 
3729  // Update the initializer if we've resolved an overloaded function.
3730  if (Sequence.step_begin() != Sequence.step_end())
3731  Sequence.RewrapReferenceInitList(cv1T1, InitList);
3732  }
3733 
3734  // Not reference-related. Create a temporary and bind to that.
3736 
3737  TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3738  TreatUnavailableAsInvalid);
3739  if (Sequence) {
3740  if (DestType->isRValueReferenceType() ||
3741  (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3742  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3743  else
3744  Sequence.SetFailed(
3746  }
3747 }
3748 
3749 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3751  const InitializedEntity &Entity,
3752  const InitializationKind &Kind,
3753  InitListExpr *InitList,
3754  InitializationSequence &Sequence,
3755  bool TreatUnavailableAsInvalid) {
3756  QualType DestType = Entity.getType();
3757 
3758  // C++ doesn't allow scalar initialization with more than one argument.
3759  // But C99 complex numbers are scalars and it makes sense there.
3760  if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3761  !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3763  return;
3764  }
3765  if (DestType->isReferenceType()) {
3766  TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
3767  TreatUnavailableAsInvalid);
3768  return;
3769  }
3770 
3771  if (DestType->isRecordType() &&
3772  !S.isCompleteType(InitList->getLocStart(), DestType)) {
3773  Sequence.setIncompleteTypeFailure(DestType);
3774  return;
3775  }
3776 
3777  // C++11 [dcl.init.list]p3, per DR1467:
3778  // - If T is a class type and the initializer list has a single element of
3779  // type cv U, where U is T or a class derived from T, the object is
3780  // initialized from that element (by copy-initialization for
3781  // copy-list-initialization, or by direct-initialization for
3782  // direct-list-initialization).
3783  // - Otherwise, if T is a character array and the initializer list has a
3784  // single element that is an appropriately-typed string literal
3785  // (8.5.2 [dcl.init.string]), initialization is performed as described
3786  // in that section.
3787  // - Otherwise, if T is an aggregate, [...] (continue below).
3788  if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
3789  if (DestType->isRecordType()) {
3790  QualType InitType = InitList->getInit(0)->getType();
3791  if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
3792  S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
3793  Expr *InitAsExpr = InitList->getInit(0);
3794  TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
3795  Sequence, /*InitListSyntax*/ false,
3796  /*IsInitListCopy*/ true);
3797  return;
3798  }
3799  }
3800  if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3801  Expr *SubInit[1] = {InitList->getInit(0)};
3802  if (!isa<VariableArrayType>(DestAT) &&
3803  IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3804  InitializationKind SubKind =
3807  InitList->getLBraceLoc(),
3808  InitList->getRBraceLoc())
3809  : Kind;
3810  Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3811  /*TopLevelOfInitList*/ true,
3812  TreatUnavailableAsInvalid);
3813 
3814  // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3815  // the element is not an appropriately-typed string literal, in which
3816  // case we should proceed as in C++11 (below).
3817  if (Sequence) {
3818  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3819  return;
3820  }
3821  }
3822  }
3823  }
3824 
3825  // C++11 [dcl.init.list]p3:
3826  // - If T is an aggregate, aggregate initialization is performed.
3827  if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
3828  (S.getLangOpts().CPlusPlus11 &&
3829  S.isStdInitializerList(DestType, nullptr))) {
3830  if (S.getLangOpts().CPlusPlus11) {
3831  // - Otherwise, if the initializer list has no elements and T is a
3832  // class type with a default constructor, the object is
3833  // value-initialized.
3834  if (InitList->getNumInits() == 0) {
3835  CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3836  if (RD->hasDefaultConstructor()) {
3837  TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3838  return;
3839  }
3840  }
3841 
3842  // - Otherwise, if T is a specialization of std::initializer_list<E>,
3843  // an initializer_list object constructed [...]
3844  if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
3845  TreatUnavailableAsInvalid))
3846  return;
3847 
3848  // - Otherwise, if T is a class type, constructors are considered.
3849  Expr *InitListAsExpr = InitList;
3850  TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3851  Sequence, /*InitListSyntax*/ true);
3852  } else
3854  return;
3855  }
3856 
3857  if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3858  InitList->getNumInits() == 1) {
3859  Expr *E = InitList->getInit(0);
3860 
3861  // - Otherwise, if T is an enumeration with a fixed underlying type,
3862  // the initializer-list has a single element v, and the initialization
3863  // is direct-list-initialization, the object is initialized with the
3864  // value T(v); if a narrowing conversion is required to convert v to
3865  // the underlying type of T, the program is ill-formed.
3866  auto *ET = DestType->getAs<EnumType>();
3867  if (S.getLangOpts().CPlusPlus1z &&
3869  ET && ET->getDecl()->isFixed() &&
3870  !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
3872  E->getType()->isFloatingType())) {
3873  // There are two ways that T(v) can work when T is an enumeration type.
3874  // If there is either an implicit conversion sequence from v to T or
3875  // a conversion function that can convert from v to T, then we use that.
3876  // Otherwise, if v is of integral, enumeration, or floating-point type,
3877  // it is converted to the enumeration type via its underlying type.
3878  // There is no overlap possible between these two cases (except when the
3879  // source value is already of the destination type), and the first
3880  // case is handled by the general case for single-element lists below.
3882  ICS.setStandard();
3884  // If E is of a floating-point type, then the conversion is ill-formed
3885  // due to narrowing, but go through the motions in order to produce the
3886  // right diagnostic.
3887  ICS.Standard.Second = E->getType()->isFloatingType()
3890  ICS.Standard.setFromType(E->getType());
3891  ICS.Standard.setToType(0, E->getType());
3892  ICS.Standard.setToType(1, DestType);
3893  ICS.Standard.setToType(2, DestType);
3894  Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
3895  /*TopLevelOfInitList*/true);
3896  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3897  return;
3898  }
3899 
3900  // - Otherwise, if the initializer list has a single element of type E
3901  // [...references are handled above...], the object or reference is
3902  // initialized from that element (by copy-initialization for
3903  // copy-list-initialization, or by direct-initialization for
3904  // direct-list-initialization); if a narrowing conversion is required
3905  // to convert the element to T, the program is ill-formed.
3906  //
3907  // Per core-24034, this is direct-initialization if we were performing
3908  // direct-list-initialization and copy-initialization otherwise.
3909  // We can't use InitListChecker for this, because it always performs
3910  // copy-initialization. This only matters if we might use an 'explicit'
3911  // conversion operator, so we only need to handle the cases where the source
3912  // is of record type.
3913  if (InitList->getInit(0)->getType()->isRecordType()) {
3914  InitializationKind SubKind =
3917  InitList->getLBraceLoc(),
3918  InitList->getRBraceLoc())
3919  : Kind;
3920  Expr *SubInit[1] = { InitList->getInit(0) };
3921  Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3922  /*TopLevelOfInitList*/true,
3923  TreatUnavailableAsInvalid);
3924  if (Sequence)
3925  Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3926  return;
3927  }
3928  }
3929 
3930  InitListChecker CheckInitList(S, Entity, InitList,
3931  DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
3932  if (CheckInitList.HadError()) {
3934  return;
3935  }
3936 
3937  // Add the list initialization step with the built init list.
3938  Sequence.AddListInitializationStep(DestType);
3939 }
3940 
3941 /// \brief Try a reference initialization that involves calling a conversion
3942 /// function.
3944  const InitializedEntity &Entity,
3945  const InitializationKind &Kind,
3946  Expr *Initializer,
3947  bool AllowRValues,
3948  InitializationSequence &Sequence) {
3949  QualType DestType = Entity.getType();
3950  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3951  QualType T1 = cv1T1.getUnqualifiedType();
3952  QualType cv2T2 = Initializer->getType();
3953  QualType T2 = cv2T2.getUnqualifiedType();
3954 
3955  bool DerivedToBase;
3956  bool ObjCConversion;
3957  bool ObjCLifetimeConversion;
3958  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3959  T1, T2, DerivedToBase,
3960  ObjCConversion,
3961  ObjCLifetimeConversion) &&
3962  "Must have incompatible references when binding via conversion");
3963  (void)DerivedToBase;
3964  (void)ObjCConversion;
3965  (void)ObjCLifetimeConversion;
3966 
3967  // Build the candidate set directly in the initialization sequence
3968  // structure, so that it will persist if we fail.
3969  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3970  CandidateSet.clear();
3971 
3972  // Determine whether we are allowed to call explicit constructors or
3973  // explicit conversion operators.
3974  bool AllowExplicit = Kind.AllowExplicit();
3975  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3976 
3977  const RecordType *T1RecordType = nullptr;
3978  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3979  S.isCompleteType(Kind.getLocation(), T1)) {
3980  // The type we're converting to is a class type. Enumerate its constructors
3981  // to see if there is a suitable conversion.
3982  CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3983 
3984  for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
3985  auto Info = getConstructorInfo(D);
3986  if (!Info.Constructor)
3987  continue;
3988 
3989  if (!Info.Constructor->isInvalidDecl() &&
3990  Info.Constructor->isConvertingConstructor(AllowExplicit)) {
3991  if (Info.ConstructorTmpl)
3992  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3993  /*ExplicitArgs*/ nullptr,
3994  Initializer, CandidateSet,
3995  /*SuppressUserConversions=*/true);
3996  else
3997  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3998  Initializer, CandidateSet,
3999  /*SuppressUserConversions=*/true);
4000  }
4001  }
4002  }
4003  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4004  return OR_No_Viable_Function;
4005 
4006  const RecordType *T2RecordType = nullptr;
4007  if ((T2RecordType = T2->getAs<RecordType>()) &&
4008  S.isCompleteType(Kind.getLocation(), T2)) {
4009  // The type we're converting from is a class type, enumerate its conversion
4010  // functions.
4011  CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4012 
4013  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4014  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4015  NamedDecl *D = *I;
4016  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4017  if (isa<UsingShadowDecl>(D))
4018  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4019 
4020  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4021  CXXConversionDecl *Conv;
4022  if (ConvTemplate)
4023  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4024  else
4025  Conv = cast<CXXConversionDecl>(D);
4026 
4027  // If the conversion function doesn't return a reference type,
4028  // it can't be considered for this conversion unless we're allowed to
4029  // consider rvalues.
4030  // FIXME: Do we need to make sure that we only consider conversion
4031  // candidates with reference-compatible results? That might be needed to
4032  // break recursion.
4033  if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4034  (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4035  if (ConvTemplate)
4036  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4037  ActingDC, Initializer,
4038  DestType, CandidateSet,
4039  /*AllowObjCConversionOnExplicit=*/
4040  false);
4041  else
4042  S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4043  Initializer, DestType, CandidateSet,
4044  /*AllowObjCConversionOnExplicit=*/false);
4045  }
4046  }
4047  }
4048  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4049  return OR_No_Viable_Function;
4050 
4051  SourceLocation DeclLoc = Initializer->getLocStart();
4052 
4053  // Perform overload resolution. If it fails, return the failed result.
4055  if (OverloadingResult Result
4056  = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
4057  return Result;
4058 
4059  FunctionDecl *Function = Best->Function;
4060  // This is the overload that will be used for this initialization step if we
4061  // use this initialization. Mark it as referenced.
4062  Function->setReferenced();
4063 
4064  // Compute the returned type of the conversion.
4065  if (isa<CXXConversionDecl>(Function))
4066  T2 = Function->getReturnType();
4067  else
4068  T2 = cv1T1;
4069 
4070  // Add the user-defined conversion step.
4071  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4072  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4073  T2.getNonLValueExprType(S.Context),
4074  HadMultipleCandidates);
4075 
4076  // Determine whether we need to perform derived-to-base or
4077  // cv-qualification adjustments.
4078  ExprValueKind VK = VK_RValue;
4079  if (T2->isLValueReferenceType())
4080  VK = VK_LValue;
4081  else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
4082  VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4083 
4084  bool NewDerivedToBase = false;
4085  bool NewObjCConversion = false;
4086  bool NewObjCLifetimeConversion = false;
4087  Sema::ReferenceCompareResult NewRefRelationship
4088  = S.CompareReferenceRelationship(DeclLoc, T1,
4090  NewDerivedToBase, NewObjCConversion,
4091  NewObjCLifetimeConversion);
4092  if (NewRefRelationship == Sema::Ref_Incompatible) {
4093  // If the type we've converted to is not reference-related to the
4094  // type we're looking for, then there is another conversion step
4095  // we need to perform to produce a temporary of the right type
4096  // that we'll be binding to.
4098  ICS.setStandard();
4099  ICS.Standard = Best->FinalConversion;
4100  T2 = ICS.Standard.getToType(2);
4101  Sequence.AddConversionSequenceStep(ICS, T2);
4102  } else if (NewDerivedToBase)
4103  Sequence.AddDerivedToBaseCastStep(
4106  VK);
4107  else if (NewObjCConversion)
4108  Sequence.AddObjCObjectConversionStep(
4111 
4112  if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
4113  Sequence.AddQualificationConversionStep(cv1T1, VK);
4114 
4115  Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
4116  return OR_Success;
4117 }
4118 
4119 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4120  const InitializedEntity &Entity,
4121  Expr *CurInitExpr);
4122 
4123 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4125  const InitializedEntity &Entity,
4126  const InitializationKind &Kind,
4127  Expr *Initializer,
4128  InitializationSequence &Sequence) {
4129  QualType DestType = Entity.getType();
4130  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4131  Qualifiers T1Quals;
4132  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4133  QualType cv2T2 = Initializer->getType();
4134  Qualifiers T2Quals;
4135  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4136 
4137  // If the initializer is the address of an overloaded function, try
4138  // to resolve the overloaded function. If all goes well, T2 is the
4139  // type of the resulting function.
4140  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4141  T1, Sequence))
4142  return;
4143 
4144  // Delegate everything else to a subfunction.
4145  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4146  T1Quals, cv2T2, T2, T2Quals, Sequence);
4147 }
4148 
4149 /// Converts the target of reference initialization so that it has the
4150 /// appropriate qualifiers and value kind.
4151 ///
4152 /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
4153 /// \code
4154 /// int x;
4155 /// const int &r = x;
4156 /// \endcode
4157 ///
4158 /// In this case the reference is binding to a bitfield lvalue, which isn't
4159 /// valid. Perform a load to create a lifetime-extended temporary instead.
4160 /// \code
4161 /// const int &r = someStruct.bitfield;
4162 /// \endcode
4163 static ExprValueKind
4165  InitializationSequence &Sequence,
4166  Expr *Initializer,
4167  QualType cv1T1,
4168  Qualifiers T1Quals,
4169  Qualifiers T2Quals,
4170  bool IsLValueRef) {
4171  bool IsNonAddressableType = Initializer->refersToBitField() ||
4172  Initializer->refersToVectorElement();
4173 
4174  if (IsNonAddressableType) {
4175  // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
4176  // lvalue reference to a non-volatile const type, or the reference shall be
4177  // an rvalue reference.
4178  //
4179  // If not, we can't make a temporary and bind to that. Give up and allow the
4180  // error to be diagnosed later.
4181  if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
4182  assert(Initializer->isGLValue());
4183  return Initializer->getValueKind();
4184  }
4185 
4186  // Force a load so we can materialize a temporary.
4187  Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
4188  return VK_RValue;
4189  }
4190 
4191  if (T1Quals != T2Quals) {
4192  Sequence.AddQualificationConversionStep(cv1T1,
4193  Initializer->getValueKind());
4194  }
4195 
4196  return Initializer->getValueKind();
4197 }
4198 
4199 /// \brief Reference initialization without resolving overloaded functions.
4201  const InitializedEntity &Entity,
4202  const InitializationKind &Kind,
4203  Expr *Initializer,
4204  QualType cv1T1, QualType T1,
4205  Qualifiers T1Quals,
4206  QualType cv2T2, QualType T2,
4207  Qualifiers T2Quals,
4208  InitializationSequence &Sequence) {
4209  QualType DestType = Entity.getType();
4210  SourceLocation DeclLoc = Initializer->getLocStart();
4211  // Compute some basic properties of the types and the initializer.
4212  bool isLValueRef = DestType->isLValueReferenceType();
4213  bool isRValueRef = !isLValueRef;
4214  bool DerivedToBase = false;
4215  bool ObjCConversion = false;
4216  bool ObjCLifetimeConversion = false;
4217  Expr::Classification InitCategory = Initializer->Classify(S.Context);
4218  Sema::ReferenceCompareResult RefRelationship
4219  = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4220  ObjCConversion, ObjCLifetimeConversion);
4221 
4222  // C++0x [dcl.init.ref]p5:
4223  // A reference to type "cv1 T1" is initialized by an expression of type
4224  // "cv2 T2" as follows:
4225  //
4226  // - If the reference is an lvalue reference and the initializer
4227  // expression
4228  // Note the analogous bullet points for rvalue refs to functions. Because
4229  // there are no function rvalues in C++, rvalue refs to functions are treated
4230  // like lvalue refs.
4231  OverloadingResult ConvOvlResult = OR_Success;
4232  bool T1Function = T1->isFunctionType();
4233  if (isLValueRef || T1Function) {
4234  if (InitCategory.isLValue() &&
4235  (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
4236  (Kind.isCStyleOrFunctionalCast() &&
4237  RefRelationship == Sema::Ref_Related))) {
4238  // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4239  // reference-compatible with "cv2 T2," or
4240  //
4241  // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
4242  // bit-field when we're determining whether the reference initialization
4243  // can occur. However, we do pay attention to whether it is a bit-field
4244  // to decide whether we're actually binding to a temporary created from
4245  // the bit-field.
4246  if (DerivedToBase)
4247  Sequence.AddDerivedToBaseCastStep(
4248  S.Context.getQualifiedType(T1, T2Quals),
4249  VK_LValue);
4250  else if (ObjCConversion)
4251  Sequence.AddObjCObjectConversionStep(
4252  S.Context.getQualifiedType(T1, T2Quals));
4253 
4254  ExprValueKind ValueKind =
4255  convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
4256  cv1T1, T1Quals, T2Quals,
4257  isLValueRef);
4258  Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
4259  return;
4260  }
4261 
4262  // - has a class type (i.e., T2 is a class type), where T1 is not
4263  // reference-related to T2, and can be implicitly converted to an
4264  // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4265  // with "cv3 T3" (this conversion is selected by enumerating the
4266  // applicable conversion functions (13.3.1.6) and choosing the best
4267  // one through overload resolution (13.3)),
4268  // If we have an rvalue ref to function type here, the rhs must be
4269  // an rvalue. DR1287 removed the "implicitly" here.
4270  if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4271  (isLValueRef || InitCategory.isRValue())) {
4272  ConvOvlResult = TryRefInitWithConversionFunction(
4273  S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
4274  if (ConvOvlResult == OR_Success)
4275  return;
4276  if (ConvOvlResult != OR_No_Viable_Function)
4277  Sequence.SetOverloadFailure(
4279  ConvOvlResult);
4280  }
4281  }
4282 
4283  // - Otherwise, the reference shall be an lvalue reference to a
4284  // non-volatile const type (i.e., cv1 shall be const), or the reference
4285  // shall be an rvalue reference.
4286  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4287  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4289  else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4290  Sequence.SetOverloadFailure(
4292  ConvOvlResult);
4293  else
4294  Sequence.SetFailed(InitCategory.isLValue()
4295  ? (RefRelationship == Sema::Ref_Related
4299 
4300  return;
4301  }
4302 
4303  // - If the initializer expression
4304  // - is an xvalue, class prvalue, array prvalue, or function lvalue and
4305  // "cv1 T1" is reference-compatible with "cv2 T2"
4306  // Note: functions are handled below.
4307  if (!T1Function &&
4308  (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
4309  (Kind.isCStyleOrFunctionalCast() &&
4310  RefRelationship == Sema::Ref_Related)) &&
4311  (InitCategory.isXValue() ||
4312  (InitCategory.isPRValue() && T2->isRecordType()) ||
4313  (InitCategory.isPRValue() && T2->isArrayType()))) {
4314  ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
4315  if (InitCategory.isPRValue() && T2->isRecordType()) {
4316  // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4317  // compiler the freedom to perform a copy here or bind to the
4318  // object, while C++0x requires that we bind directly to the
4319  // object. Hence, we always bind to the object without making an
4320  // extra copy. However, in C++03 requires that we check for the
4321  // presence of a suitable copy constructor:
4322  //
4323  // The constructor that would be used to make the copy shall
4324  // be callable whether or not the copy is actually done.
4325  if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4326  Sequence.AddExtraneousCopyToTemporary(cv2T2);
4327  else if (S.getLangOpts().CPlusPlus11)
4328  CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4329  }
4330 
4331  if (DerivedToBase)
4332  Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
4333  ValueKind);
4334  else if (ObjCConversion)
4335  Sequence.AddObjCObjectConversionStep(
4336  S.Context.getQualifiedType(T1, T2Quals));
4337 
4338  ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
4339  Initializer, cv1T1,
4340  T1Quals, T2Quals,
4341  isLValueRef);
4342 
4343  Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
4344  return;
4345  }
4346 
4347  // - has a class type (i.e., T2 is a class type), where T1 is not
4348  // reference-related to T2, and can be implicitly converted to an
4349  // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4350  // where "cv1 T1" is reference-compatible with "cv3 T3",
4351  //
4352  // DR1287 removes the "implicitly" here.
4353  if (T2->isRecordType()) {
4354  if (RefRelationship == Sema::Ref_Incompatible) {
4355  ConvOvlResult = TryRefInitWithConversionFunction(
4356  S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
4357  if (ConvOvlResult)
4358  Sequence.SetOverloadFailure(
4360  ConvOvlResult);
4361 
4362  return;
4363  }
4364 
4365  if ((RefRelationship == Sema::Ref_Compatible ||
4366  RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
4367  isRValueRef && InitCategory.isLValue()) {
4368  Sequence.SetFailed(
4370  return;
4371  }
4372 
4374  return;
4375  }
4376 
4377  // - Otherwise, a temporary of type "cv1 T1" is created and initialized
4378  // from the initializer expression using the rules for a non-reference
4379  // copy-initialization (8.5). The reference is then bound to the
4380  // temporary. [...]
4381 
4383 
4384  // FIXME: Why do we use an implicit conversion here rather than trying
4385  // copy-initialization?
4387  = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4388  /*SuppressUserConversions=*/false,
4389  /*AllowExplicit=*/false,
4390  /*FIXME:InOverloadResolution=*/false,
4391  /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4392  /*AllowObjCWritebackConversion=*/false);
4393 
4394  if (ICS.isBad()) {
4395  // FIXME: Use the conversion function set stored in ICS to turn
4396  // this into an overloading ambiguity diagnostic. However, we need
4397  // to keep that set as an OverloadCandidateSet rather than as some
4398  // other kind of set.
4399  if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4400  Sequence.SetOverloadFailure(
4402  ConvOvlResult);
4403  else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4405  else
4407  return;
4408  } else {
4409  Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4410  }
4411 
4412  // [...] If T1 is reference-related to T2, cv1 must be the
4413  // same cv-qualification as, or greater cv-qualification
4414  // than, cv2; otherwise, the program is ill-formed.
4415  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4416  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4417  if (RefRelationship == Sema::Ref_Related &&
4418  (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4420  return;
4421  }
4422 
4423  // [...] If T1 is reference-related to T2 and the reference is an rvalue
4424  // reference, the initializer expression shall not be an lvalue.
4425  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4426  InitCategory.isLValue()) {
4427  Sequence.SetFailed(
4429  return;
4430  }
4431 
4432  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4433 }
4434 
4435 /// \brief Attempt character array initialization from a string literal
4436 /// (C++ [dcl.init.string], C99 6.7.8).
4438  const InitializedEntity &Entity,
4439  const InitializationKind &Kind,
4440  Expr *Initializer,
4441  InitializationSequence &Sequence) {
4442  Sequence.AddStringInitStep(Entity.getType());
4443 }
4444 
4445 /// \brief Attempt value initialization (C++ [dcl.init]p7).
4447  const InitializedEntity &Entity,
4448  const InitializationKind &Kind,
4449  InitializationSequence &Sequence,
4450  InitListExpr *InitList) {
4451  assert((!InitList || InitList->getNumInits() == 0) &&
4452  "Shouldn't use value-init for non-empty init lists");
4453 
4454  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4455  //
4456  // To value-initialize an object of type T means:
4457  QualType T = Entity.getType();
4458 
4459  // -- if T is an array type, then each element is value-initialized;
4460  T = S.Context.getBaseElementType(T);
4461 
4462  if (const RecordType *RT = T->getAs<RecordType>()) {
4463  if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4464  bool NeedZeroInitialization = true;
4465  if (!S.getLangOpts().CPlusPlus11) {
4466  // C++98:
4467  // -- if T is a class type (clause 9) with a user-declared constructor
4468  // (12.1), then the default constructor for T is called (and the
4469  // initialization is ill-formed if T has no accessible default
4470  // constructor);
4471  if (ClassDecl->hasUserDeclaredConstructor())
4472  NeedZeroInitialization = false;
4473  } else {
4474  // C++11:
4475  // -- if T is a class type (clause 9) with either no default constructor
4476  // (12.1 [class.ctor]) or a default constructor that is user-provided
4477  // or deleted, then the object is default-initialized;
4478  CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4479  if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4480  NeedZeroInitialization = false;
4481  }
4482 
4483  // -- if T is a (possibly cv-qualified) non-union class type without a
4484  // user-provided or deleted default constructor, then the object is
4485  // zero-initialized and, if T has a non-trivial default constructor,
4486  // default-initialized;
4487  // The 'non-union' here was removed by DR1502. The 'non-trivial default
4488  // constructor' part was removed by DR1507.
4489  if (NeedZeroInitialization)
4490  Sequence.AddZeroInitializationStep(Entity.getType());
4491 
4492  // C++03:
4493  // -- if T is a non-union class type without a user-declared constructor,
4494  // then every non-static data member and base class component of T is
4495  // value-initialized;
4496  // [...] A program that calls for [...] value-initialization of an
4497  // entity of reference type is ill-formed.
4498  //
4499  // C++11 doesn't need this handling, because value-initialization does not
4500  // occur recursively there, and the implicit default constructor is
4501  // defined as deleted in the problematic cases.
4502  if (!S.getLangOpts().CPlusPlus11 &&
4503  ClassDecl->hasUninitializedReferenceMember()) {
4505  return;
4506  }
4507 
4508  // If this is list-value-initialization, pass the empty init list on when
4509  // building the constructor call. This affects the semantics of a few
4510  // things (such as whether an explicit default constructor can be called).
4511  Expr *InitListAsExpr = InitList;
4512  MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4513  bool InitListSyntax = InitList;
4514 
4515  return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4516  InitListSyntax);
4517  }
4518  }
4519 
4520  Sequence.AddZeroInitializationStep(Entity.getType());
4521 }
4522 
4523 /// \brief Attempt default initialization (C++ [dcl.init]p6).
4525  const InitializedEntity &Entity,
4526  const InitializationKind &Kind,
4527  InitializationSequence &Sequence) {
4528  assert(Kind.getKind() == InitializationKind::IK_Default);
4529 
4530  // C++ [dcl.init]p6:
4531  // To default-initialize an object of type T means:
4532  // - if T is an array type, each element is default-initialized;
4533  QualType DestType = S.Context.getBaseElementType(Entity.getType());
4534 
4535  // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4536  // constructor for T is called (and the initialization is ill-formed if
4537  // T has no accessible default constructor);
4538  if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4539  TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
4540  return;
4541  }
4542 
4543  // - otherwise, no initialization is performed.
4544 
4545  // If a program calls for the default initialization of an object of
4546  // a const-qualified type T, T shall be a class type with a user-provided
4547  // default constructor.
4548  if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4549  if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4551  return;
4552  }
4553 
4554  // If the destination type has a lifetime property, zero-initialize it.
4555  if (DestType.getQualifiers().hasObjCLifetime()) {
4556  Sequence.AddZeroInitializationStep(Entity.getType());
4557  return;
4558  }
4559 }
4560 
4561 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4562 /// which enumerates all conversion functions and performs overload resolution
4563 /// to select the best.
4565  QualType DestType,
4566  const InitializationKind &Kind,
4567  Expr *Initializer,
4568  InitializationSequence &Sequence,
4569  bool TopLevelOfInitList) {
4570  assert(!DestType->isReferenceType() && "References are handled elsewhere");
4571  QualType SourceType = Initializer->getType();
4572  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4573  "Must have a class type to perform a user-defined conversion");
4574 
4575  // Build the candidate set directly in the initialization sequence
4576  // structure, so that it will persist if we fail.
4577  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4578  CandidateSet.clear();
4579 
4580  // Determine whether we are allowed to call explicit constructors or
4581  // explicit conversion operators.
4582  bool AllowExplicit = Kind.AllowExplicit();
4583 
4584  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4585  // The type we're converting to is a class type. Enumerate its constructors
4586  // to see if there is a suitable conversion.
4587  CXXRecordDecl *DestRecordDecl
4588  = cast<CXXRecordDecl>(DestRecordType->getDecl());
4589 
4590  // Try to complete the type we're converting to.
4591  if (S.isCompleteType(Kind.getLocation(), DestType)) {
4592  DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
4593  // The container holding the constructors can under certain conditions
4594  // be changed while iterating. To be safe we copy the lookup results
4595  // to a new container.
4596  SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
4598  Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
4599  Con != ConEnd; ++Con) {
4600  NamedDecl *D = *Con;
4601  auto Info = getConstructorInfo(D);
4602  if (!Info.Constructor)
4603  continue;
4604 
4605  if (!Info.Constructor->isInvalidDecl() &&
4606  Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4607  if (Info.ConstructorTmpl)
4608  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4609  /*ExplicitArgs*/ nullptr,
4610  Initializer, CandidateSet,
4611  /*SuppressUserConversions=*/true);
4612  else
4613  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4614  Initializer, CandidateSet,
4615  /*SuppressUserConversions=*/true);
4616  }
4617  }
4618  }
4619  }
4620 
4621  SourceLocation DeclLoc = Initializer->getLocStart();
4622 
4623  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4624  // The type we're converting from is a class type, enumerate its conversion
4625  // functions.
4626 
4627  // We can only enumerate the conversion functions for a complete type; if
4628  // the type isn't complete, simply skip this step.
4629  if (S.isCompleteType(DeclLoc, SourceType)) {
4630  CXXRecordDecl *SourceRecordDecl
4631  = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4632 
4633  const auto &Conversions =
4634  SourceRecordDecl->getVisibleConversionFunctions();
4635  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4636  NamedDecl *D = *I;
4637  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4638  if (isa<UsingShadowDecl>(D))
4639  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4640 
4641  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4642  CXXConversionDecl *Conv;
4643  if (ConvTemplate)
4644  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4645  else
4646  Conv = cast<CXXConversionDecl>(D);
4647 
4648  if (AllowExplicit || !Conv->isExplicit()) {
4649  if (ConvTemplate)
4650  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4651  ActingDC, Initializer, DestType,
4652  CandidateSet, AllowExplicit);
4653  else
4654  S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4655  Initializer, DestType, CandidateSet,
4656  AllowExplicit);
4657  }
4658  }
4659  }
4660  }
4661 
4662  // Perform overload resolution. If it fails, return the failed result.
4664  if (OverloadingResult Result
4665  = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4666  Sequence.SetOverloadFailure(
4668  Result);
4669  return;
4670  }
4671 
4672  FunctionDecl *Function = Best->Function;
4673  Function->setReferenced();
4674  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4675 
4676  if (isa<CXXConstructorDecl>(Function)) {
4677  // Add the user-defined conversion step. Any cv-qualification conversion is
4678  // subsumed by the initialization. Per DR5, the created temporary is of the
4679  // cv-unqualified type of the destination.
4680  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4681  DestType.getUnqualifiedType(),
4682  HadMultipleCandidates);
4683  return;
4684  }
4685 
4686  // Add the user-defined conversion step that calls the conversion function.
4687  QualType ConvType = Function->getCallResultType();
4688  if (ConvType->getAs<RecordType>()) {
4689  // If we're converting to a class type, there may be an copy of
4690  // the resulting temporary object (possible to create an object of
4691  // a base class type). That copy is not a separate conversion, so
4692  // we just make a note of the actual destination type (possibly a
4693  // base class of the type returned by the conversion function) and
4694  // let the user-defined conversion step handle the conversion.
4695  Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4696  HadMultipleCandidates);
4697  return;
4698  }
4699 
4700  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4701  HadMultipleCandidates);
4702 
4703  // If the conversion following the call to the conversion function
4704  // is interesting, add it as a separate step.
4705  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4706  Best->FinalConversion.Third) {
4708  ICS.setStandard();
4709  ICS.Standard = Best->FinalConversion;
4710  Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4711  }
4712 }
4713 
4714 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4715 /// a function with a pointer return type contains a 'return false;' statement.
4716 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
4717 /// code using that header.
4718 ///
4719 /// Work around this by treating 'return false;' as zero-initializing the result
4720 /// if it's used in a pointer-returning function in a system header.
4722  const InitializedEntity &Entity,
4723  const Expr *Init) {
4724  return S.getLangOpts().CPlusPlus11 &&
4725  Entity.getKind() == InitializedEntity::EK_Result &&
4726  Entity.getType()->isPointerType() &&
4727  isa<CXXBoolLiteralExpr>(Init) &&
4728  !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4730 }
4731 
4732 /// The non-zero enum values here are indexes into diagnostic alternatives.
4734 
4735 /// Determines whether this expression is an acceptable ICR source.
4737  bool isAddressOf, bool &isWeakAccess) {
4738  // Skip parens.
4739  e = e->IgnoreParens();
4740 
4741  // Skip address-of nodes.
4742  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4743  if (op->getOpcode() == UO_AddrOf)
4744  return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4745  isWeakAccess);
4746 
4747  // Skip certain casts.
4748  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4749  switch (ce->getCastKind()) {
4750  case CK_Dependent:
4751  case CK_BitCast:
4752  case CK_LValueBitCast:
4753  case CK_NoOp:
4754  return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4755 
4756  case CK_ArrayToPointerDecay:
4757  return IIK_nonscalar;
4758 
4759  case CK_NullToPointer:
4760  return IIK_okay;
4761 
4762  default:
4763  break;
4764  }
4765 
4766  // If we have a declaration reference, it had better be a local variable.
4767  } else if (isa<DeclRefExpr>(e)) {
4768  // set isWeakAccess to true, to mean that there will be an implicit
4769  // load which requires a cleanup.
4771  isWeakAccess = true;
4772 
4773  if (!isAddressOf) return IIK_nonlocal;
4774 
4775  VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4776  if (!var) return IIK_nonlocal;
4777 
4778  return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4779 
4780  // If we have a conditional operator, check both sides.
4781  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4782  if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4783  isWeakAccess))
4784  return iik;
4785 
4786  return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4787 
4788  // These are never scalar.
4789  } else if (isa<ArraySubscriptExpr>(e)) {
4790  return IIK_nonscalar;
4791 
4792  // Otherwise, it needs to be a null pointer constant.
4793  } else {
4795  ? IIK_okay : IIK_nonlocal);
4796  }
4797 
4798  return IIK_nonlocal;
4799 }
4800 
4801 /// Check whether the given expression is a valid operand for an
4802 /// indirect copy/restore.
4804  assert(src->isRValue());
4805  bool isWeakAccess = false;
4806  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4807  // If isWeakAccess to true, there will be an implicit
4808  // load which requires a cleanup.
4809  if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4810  S.Cleanup.setExprNeedsCleanups(true);
4811 
4812  if (iik == IIK_okay) return;
4813 
4814  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4815  << ((unsigned) iik - 1) // shift index into diagnostic explanations
4816  << src->getSourceRange();
4817 }
4818 
4819 /// \brief Determine whether we have compatible array types for the
4820 /// purposes of GNU by-copy array initialization.
4821 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
4822  const ArrayType *Source) {
4823  // If the source and destination array types are equivalent, we're
4824  // done.
4825  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4826  return true;
4827 
4828  // Make sure that the element types are the same.
4829  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4830  return false;
4831 
4832  // The only mismatch we allow is when the destination is an
4833  // incomplete array type and the source is a constant array type.
4834  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4835 }
4836 
4838  InitializationSequence &Sequence,
4839  const InitializedEntity &Entity,
4840  Expr *Initializer) {
4841  bool ArrayDecay = false;
4842  QualType ArgType = Initializer->getType();
4843  QualType ArgPointee;
4844  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4845  ArrayDecay = true;
4846  ArgPointee = ArgArrayType->getElementType();
4847  ArgType = S.Context.getPointerType(ArgPointee);
4848  }
4849 
4850  // Handle write-back conversion.
4851  QualType ConvertedArgType;
4852  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4853  ConvertedArgType))
4854  return false;
4855 
4856  // We should copy unless we're passing to an argument explicitly
4857  // marked 'out'.
4858  bool ShouldCopy = true;
4859  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4860  ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4861 
4862  // Do we need an lvalue conversion?
4863  if (ArrayDecay || Initializer->isGLValue()) {
4865  ICS.setStandard();
4867 
4868  QualType ResultType;
4869  if (ArrayDecay) {
4871  ResultType = S.Context.getPointerType(ArgPointee);
4872  } else {
4874  ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4875  }
4876 
4877  Sequence.AddConversionSequenceStep(ICS, ResultType);
4878  }
4879 
4880  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4881  return true;
4882 }
4883 
4885  InitializationSequence &Sequence,
4886  QualType DestType,
4887  Expr *Initializer) {
4888  if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4889  !Initializer->isIntegerConstantExpr(S.getASTContext()))
4890  return false;
4891 
4892  Sequence.AddOCLSamplerInitStep(DestType);
4893  return true;
4894 }
4895 
4896 //
4897 // OpenCL 1.2 spec, s6.12.10
4898 //
4899 // The event argument can also be used to associate the
4900 // async_work_group_copy with a previous async copy allowing
4901 // an event to be shared by multiple async copies; otherwise
4902 // event should be zero.
4903 //
4905  InitializationSequence &Sequence,
4906  QualType DestType,
4907  Expr *Initializer) {
4908  if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4909  !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4910  (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4911  return false;
4912 
4913  Sequence.AddOCLZeroEventStep(DestType);
4914  return true;
4915 }
4916 
4918  const InitializedEntity &Entity,
4919  const InitializationKind &Kind,
4920  MultiExprArg Args,
4921  bool TopLevelOfInitList,
4922  bool TreatUnavailableAsInvalid)
4923  : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
4924  InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
4925  TreatUnavailableAsInvalid);
4926 }
4927 
4928 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
4929 /// address of that function, this returns true. Otherwise, it returns false.
4930 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
4931  auto *DRE = dyn_cast<DeclRefExpr>(E);
4932  if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
4933  return false;
4934 
4936  cast<FunctionDecl>(DRE->getDecl()));
4937 }
4938 
4940  const InitializedEntity &Entity,
4941  const InitializationKind &Kind,
4942  MultiExprArg Args,
4943  bool TopLevelOfInitList,
4944  bool TreatUnavailableAsInvalid) {
4945  ASTContext &Context = S.Context;
4946 
4947  // Eliminate non-overload placeholder types in the arguments. We
4948  // need to do this before checking whether types are dependent
4949  // because lowering a pseudo-object expression might well give us
4950  // something of dependent type.
4951  for (unsigned I = 0, E = Args.size(); I != E; ++I)
4952  if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4953  // FIXME: should we be doing this here?
4954  ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4955  if (result.isInvalid()) {
4957  return;
4958  }
4959  Args[I] = result.get();
4960  }
4961 
4962  // C++0x [dcl.init]p16:
4963  // The semantics of initializers are as follows. The destination type is
4964  // the type of the object or reference being initialized and the source
4965  // type is the type of the initializer expression. The source type is not
4966  // defined when the initializer is a braced-init-list or when it is a
4967  // parenthesized list of expressions.
4968  QualType DestType = Entity.getType();
4969 
4970  if (DestType->isDependentType() ||
4973  return;
4974  }
4975 
4976  // Almost everything is a normal sequence.
4978 
4979  QualType SourceType;
4980  Expr *Initializer = nullptr;
4981  if (Args.size() == 1) {
4982  Initializer = Args[0];
4983  if (S.getLangOpts().ObjC1) {
4984  if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4985  DestType, Initializer->getType(),
4986  Initializer) ||
4987  S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4988  Args[0] = Initializer;
4989  }
4990  if (!isa<InitListExpr>(Initializer))
4991  SourceType = Initializer->getType();
4992  }
4993 
4994  // - If the initializer is a (non-parenthesized) braced-init-list, the
4995  // object is list-initialized (8.5.4).
4996  if (Kind.getKind() != InitializationKind::IK_Direct) {
4997  if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4998  TryListInitialization(S, Entity, Kind, InitList, *this,
4999  TreatUnavailableAsInvalid);
5000  return;
5001  }
5002  }
5003 
5004  // - If the destination type is a reference type, see 8.5.3.
5005  if (DestType->isReferenceType()) {
5006  // C++0x [dcl.init.ref]p1:
5007  // A variable declared to be a T& or T&&, that is, "reference to type T"
5008  // (8.3.2), shall be initialized by an object, or function, of type T or
5009  // by an object that can be converted into a T.
5010  // (Therefore, multiple arguments are not permitted.)
5011  if (Args.size() != 1)
5013  else
5014  TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5015  return;
5016  }
5017 
5018  // - If the initializer is (), the object is value-initialized.
5019  if (Kind.getKind() == InitializationKind::IK_Value ||
5020  (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
5021  TryValueInitialization(S, Entity, Kind, *this);
5022  return;
5023  }
5024 
5025  // Handle default initialization.
5026  if (Kind.getKind() == InitializationKind::IK_Default) {
5027  TryDefaultInitialization(S, Entity, Kind, *this);
5028  return;
5029  }
5030 
5031  // - If the destination type is an array of characters, an array of
5032  // char16_t, an array of char32_t, or an array of wchar_t, and the
5033  // initializer is a string literal, see 8.5.2.
5034  // - Otherwise, if the destination type is an array, the program is
5035  // ill-formed.
5036  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
5037  if (Initializer && isa<VariableArrayType>(DestAT)) {
5039  return;
5040  }
5041 
5042  if (Initializer) {
5043  switch (IsStringInit(Initializer, DestAT, Context)) {
5044  case SIF_None:
5045  TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5046  return;
5049  return;
5052  return;
5055  return;
5056  case SIF_Other:
5057  break;
5058  }
5059  }
5060 
5061  // Note: as an GNU C extension, we allow initialization of an
5062  // array from a compound literal that creates an array of the same
5063  // type, so long as the initializer has no side effects.
5064  if (!S.getLangOpts().CPlusPlus && Initializer &&
5065  isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5066  Initializer->getType()->isArrayType()) {
5067  const ArrayType *SourceAT
5068  = Context.getAsArrayType(Initializer->getType());
5069  if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5071  else if (Initializer->HasSideEffects(S.Context))
5073  else {
5074  AddArrayInitStep(DestType);
5075  }
5076  }
5077  // Note: as a GNU C++ extension, we allow list-initialization of a
5078  // class member of array type from a parenthesized initializer list.
5079  else if (S.getLangOpts().CPlusPlus &&
5080  Entity.getKind() == InitializedEntity::EK_Member &&
5081  Initializer && isa<InitListExpr>(Initializer)) {
5082  TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5083  *this, TreatUnavailableAsInvalid);
5085  } else if (DestAT->getElementType()->isCharType())
5087  else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5089  else
5091 
5092  return;
5093  }
5094 
5095  // Determine whether we should consider writeback conversions for
5096  // Objective-C ARC.
5097  bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
5098  Entity.isParameterKind();
5099 
5100  // We're at the end of the line for C: it's either a write-back conversion
5101  // or it's a C assignment. There's no need to check anything else.
5102  if (!S.getLangOpts().CPlusPlus) {
5103  // If allowed, check whether this is an Objective-C writeback conversion.
5104  if (allowObjCWritebackConversion &&
5105  tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5106  return;
5107  }
5108 
5109  if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5110  return;
5111 
5112  if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5113  return;
5114 
5115  // Handle initialization in C
5116  AddCAssignmentStep(DestType);
5117  MaybeProduceObjCObject(S, *this, Entity);
5118  return;
5119  }
5120 
5121  assert(S.getLangOpts().CPlusPlus);
5122 
5123  // - If the destination type is a (possibly cv-qualified) class type:
5124  if (DestType->isRecordType()) {
5125  // - If the initialization is direct-initialization, or if it is
5126  // copy-initialization where the cv-unqualified version of the
5127  // source type is the same class as, or a derived class of, the
5128  // class of the destination, constructors are considered. [...]
5129  if (Kind.getKind() == InitializationKind::IK_Direct ||
5130  (Kind.getKind() == InitializationKind::IK_Copy &&
5131  (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5132  S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
5133  TryConstructorInitialization(S, Entity, Kind, Args,
5134  DestType, *this);
5135  // - Otherwise (i.e., for the remaining copy-initialization cases),
5136  // user-defined conversion sequences that can convert from the source
5137  // type to the destination type or (when a conversion function is
5138  // used) to a derived class thereof are enumerated as described in
5139  // 13.3.1.4, and the best one is chosen through overload resolution
5140  // (13.3).
5141  else
5142  TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5143  TopLevelOfInitList);
5144  return;
5145  }
5146 
5147  if (Args.size() > 1) {
5149  return;
5150  }
5151  assert(Args.size() == 1 && "Zero-argument case handled above");
5152 
5153  // - Otherwise, if the source type is a (possibly cv-qualified) class
5154  // type, conversion functions are considered.
5155  if (!SourceType.isNull() && SourceType->isRecordType()) {
5156  // For a conversion to _Atomic(T) from either T or a class type derived
5157  // from T, initialize the T object then convert to _Atomic type.
5158  bool NeedAtomicConversion = false;
5159  if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5160  if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5161  S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5162  Atomic->getValueType())) {
5163  DestType = Atomic->getValueType();
5164  NeedAtomicConversion = true;
5165  }
5166  }
5167 
5168  TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5169  TopLevelOfInitList);
5170  MaybeProduceObjCObject(S, *this, Entity);
5171  if (!Failed() && NeedAtomicConversion)
5172  AddAtomicConversionStep(Entity.getType());
5173  return;
5174  }
5175 
5176  // - Otherwise, the initial value of the object being initialized is the
5177  // (possibly converted) value of the initializer expression. Standard
5178  // conversions (Clause 4) will be used, if necessary, to convert the
5179  // initializer expression to the cv-unqualified version of the
5180  // destination type; no user-defined conversions are considered.
5181 
5183  = S.TryImplicitConversion(Initializer, DestType,
5184  /*SuppressUserConversions*/true,
5185  /*AllowExplicitConversions*/ false,
5186  /*InOverloadResolution*/ false,
5187  /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5188  allowObjCWritebackConversion);
5189 
5190  if (ICS.isStandard() &&
5192  // Objective-C ARC writeback conversion.
5193 
5194  // We should copy unless we're passing to an argument explicitly
5195  // marked 'out'.
5196  bool ShouldCopy = true;
5197  if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5198  ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5199 
5200  // If there was an lvalue adjustment, add it as a separate conversion.
5201  if (ICS.Standard.First == ICK_Array_To_Pointer ||
5203  ImplicitConversionSequence LvalueICS;
5204  LvalueICS.setStandard();
5205  LvalueICS.Standard.setAsIdentityConversion();
5206  LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5207  LvalueICS.Standard.First = ICS.Standard.First;
5208  AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
5209  }
5210 
5211  AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
5212  } else if (ICS.isBad()) {
5213  DeclAccessPair dap;
5214  if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5216  } else if (Initializer->getType() == Context.OverloadTy &&
5217  !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5218  false, dap))
5220  else if (Initializer->getType()->isFunctionType() &&
5221  isExprAnUnaddressableFunction(S, Initializer))
5223  else
5225  } else {
5226  AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5227 
5228  MaybeProduceObjCObject(S, *this, Entity);
5229  }
5230 }
5231 
5233  for (auto &S : Steps)
5234  S.Destroy();
5235 }
5236 
5237 //===----------------------------------------------------------------------===//
5238 // Perform initialization
5239 //===----------------------------------------------------------------------===//
5241 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
5242  switch(Entity.getKind()) {
5248  return Sema::AA_Initializing;
5249 
5251  if (Entity.getDecl() &&
5252  isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5253  return Sema::AA_Sending;
5254 
5255  return Sema::AA_Passing;
5256 
5258  if (Entity.getDecl() &&
5259  isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5260  return Sema::AA_Sending;
5261 
5262  return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5263 
5265  return Sema::AA_Returning;
5266 
5269  // FIXME: Can we tell apart casting vs. converting?
5270  return Sema::AA_Casting;
5271 
5279  return Sema::AA_Initializing;
5280  }
5281 
5282  llvm_unreachable("Invalid EntityKind!");
5283 }
5284 
5285 /// \brief Whether we should bind a created object as a temporary when
5286 /// initializing the given entity.
5287 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
5288  switch (Entity.getKind()) {
5302  return false;
5303 
5308  return true;
5309  }
5310 
5311  llvm_unreachable("missed an InitializedEntity kind?");
5312 }
5313 
5314 /// \brief Whether the given entity, when initialized with an object
5315 /// created for that initialization, requires destruction.
5316 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
5317  switch (Entity.getKind()) {
5326  return false;
5327 
5337  return true;
5338  }
5339 
5340  llvm_unreachable("missed an InitializedEntity kind?");
5341 }
5342 
5343 /// \brief Look for copy and move constructors and constructor templates, for
5344 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
5346  OverloadCandidateSet &CandidateSet,
5347  CXXRecordDecl *Class,
5348  Expr *CurInitExpr) {
5350  // The container holding the constructors can under certain conditions
5351  // be changed while iterating (e.g. because of deserialization).
5352  // To be safe we copy the lookup results to a new container.
5353  SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
5355  CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
5356  NamedDecl *D = *CI;
5357  auto Info = getConstructorInfo(D);
5358  if (!Info.Constructor)
5359  continue;
5360 
5361  if (!Info.ConstructorTmpl) {
5362  // Handle copy/move constructors, only.
5363  if (Info.Constructor->isInvalidDecl() ||
5364  !Info.Constructor->isCopyOrMoveConstructor() ||
5365  !Info.Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5366  continue;
5367 
5368  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5369  CurInitExpr, CandidateSet);
5370  continue;
5371  }
5372 
5373  // Handle constructor templates.
5374  if (Info.ConstructorTmpl->isInvalidDecl())
5375  continue;
5376 
5377  if (!Info.Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5378  continue;
5379 
5380  // FIXME: Do we need to limit this to copy-constructor-like
5381  // candidates?
5382  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
5383  nullptr, CurInitExpr, CandidateSet, true);
5384  }
5385 }
5386 
5387 /// \brief Get the location at which initialization diagnostics should appear.
5389  Expr *Initializer) {
5390  switch (Entity.getKind()) {
5392  return Entity.getReturnLoc();
5393 
5395  return Entity.getThrowLoc();
5396 
5398  return Entity.getDecl()->getLocation();
5399 
5401  return Entity.getCaptureLoc();
5402 
5416  return Initializer->getLocStart();
5417  }
5418  llvm_unreachable("missed an InitializedEntity kind?");
5419 }
5420 
5421 /// \brief Make a (potentially elidable) temporary copy of the object
5422 /// provided by the given initializer by calling the appropriate copy
5423 /// constructor.
5424 ///
5425 /// \param S The Sema object used for type-checking.
5426 ///
5427 /// \param T The type of the temporary object, which must either be
5428 /// the type of the initializer expression or a superclass thereof.
5429 ///
5430 /// \param Entity The entity being initialized.
5431 ///
5432 /// \param CurInit The initializer expression.
5433 ///
5434 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5435 /// is permitted in C++03 (but not C++0x) when binding a reference to
5436 /// an rvalue.
5437 ///
5438 /// \returns An expression that copies the initializer expression into
5439 /// a temporary object, or an error expression if a copy could not be
5440 /// created.
5442  QualType T,
5443  const InitializedEntity &Entity,
5444  ExprResult CurInit,
5445  bool IsExtraneousCopy) {
5446  if (CurInit.isInvalid())
5447  return CurInit;
5448  // Determine which class type we're copying to.
5449  Expr *CurInitExpr = (Expr *)CurInit.get();
5450  CXXRecordDecl *Class = nullptr;
5451  if (const RecordType *Record = T->getAs<RecordType>())
5452  Class = cast<CXXRecordDecl>(Record->getDecl());
5453  if (!Class)
5454  return CurInit;
5455 
5456  // C++0x [class.copy]p32:
5457  // When certain criteria are met, an implementation is allowed to
5458  // omit the copy/move construction of a class object, even if the
5459  // copy/move constructor and/or destructor for the object have
5460  // side effects. [...]
5461  // - when a temporary class object that has not been bound to a
5462  // reference (12.2) would be copied/moved to a class object
5463  // with the same cv-unqualified type, the copy/move operation
5464  // can be omitted by constructing the temporary object
5465  // directly into the target of the omitted copy/move
5466  //
5467  // Note that the other three bullets are handled elsewhere. Copy
5468  // elision for return statements and throw expressions are handled as part
5469  // of constructor initialization, while copy elision for exception handlers
5470  // is handled by the run-time.
5471  bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
5472  SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5473 
5474  // Make sure that the type we are copying is complete.
5475  if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5476  return CurInit;
5477 
5478  // Perform overload resolution using the class's copy/move constructors.
5479  // Only consider constructors and constructor templates. Per
5480  // C++0x [dcl.init]p16, second bullet to class types, this initialization
5481  // is direct-initialization.
5483  LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
5484 
5485  bool HadMultipleCandidates = (CandidateSet.size() > 1);
5486 
5488  switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
5489  case OR_Success:
5490  break;
5491 
5492  case OR_No_Viable_Function:
5493  S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5494  ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5495  : diag::err_temp_copy_no_viable)
5496  << (int)Entity.getKind() << CurInitExpr->getType()
5497  << CurInitExpr->getSourceRange();
5498  CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5499  if (!IsExtraneousCopy || S.isSFINAEContext())
5500  return ExprError();
5501  return CurInit;
5502 
5503  case OR_Ambiguous:
5504  S.Diag(Loc, diag::err_temp_copy_ambiguous)
5505  << (int)Entity.getKind() << CurInitExpr->getType()
5506  << CurInitExpr->getSourceRange();
5507  CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5508  return ExprError();
5509 
5510  case OR_Deleted:
5511  S.Diag(Loc, diag::err_temp_copy_deleted)
5512  << (int)Entity.getKind() << CurInitExpr->getType()
5513  << CurInitExpr->getSourceRange();
5514  S.NoteDeletedFunction(Best->Function);
5515  return ExprError();
5516  }
5517 
5518  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
5519  SmallVector<Expr*, 8> ConstructorArgs;
5520  CurInit.get(); // Ownership transferred into MultiExprArg, below.
5521 
5522  S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5523  IsExtraneousCopy);
5524 
5525  if (IsExtraneousCopy) {
5526  // If this is a totally extraneous copy for C++03 reference
5527  // binding purposes, just return the original initialization
5528  // expression. We don't generate an (elided) copy operation here
5529  // because doing so would require us to pass down a flag to avoid
5530  // infinite recursion, where each step adds another extraneous,
5531  // elidable copy.
5532 
5533  // Instantiate the default arguments of any extra parameters in
5534  // the selected copy constructor, as if we were going to create a
5535  // proper call to the copy constructor.
5536  for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5537  ParmVarDecl *Parm = Constructor->getParamDecl(I);
5538  if (S.RequireCompleteType(Loc, Parm->getType(),
5539  diag::err_call_incomplete_argument))
5540  break;
5541 
5542  // Build the default argument expression; we don't actually care
5543  // if this succeeds or not, because this routine will complain
5544  // if there was a problem.
5545  S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5546  }
5547 
5548  return CurInitExpr;
5549  }
5550 
5551  // Determine the arguments required to actually perform the
5552  // constructor call (we might have derived-to-base conversions, or
5553  // the copy constructor may have default arguments).
5554  if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5555  return ExprError();
5556 
5557  // Actually perform the constructor call.
5558  CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5559  Elidable,
5560  ConstructorArgs,
5561  HadMultipleCandidates,
5562  /*ListInit*/ false,
5563  /*StdInitListInit*/ false,
5564  /*ZeroInit*/ false,
5566  SourceRange());
5567 
5568  // If we're supposed to bind temporaries, do so.
5569  if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5570  CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
5571  return CurInit;
5572 }
5573 
5574 /// \brief Check whether elidable copy construction for binding a reference to
5575 /// a temporary would have succeeded if we were building in C++98 mode, for
5576 /// -Wc++98-compat.
5578  const InitializedEntity &Entity,
5579  Expr *CurInitExpr) {
5580  assert(S.getLangOpts().CPlusPlus11);
5581 
5582  const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5583  if (!Record)
5584  return;
5585 
5586  SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5587  if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
5588  return;
5589 
5590  // Find constructors which would have been considered.
5593  S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5594 
5595  // Perform overload resolution.
5597  OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5598 
5599  PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5600  << OR << (int)Entity.getKind() << CurInitExpr->getType()
5601  << CurInitExpr->getSourceRange();
5602 
5603  switch (OR) {
5604  case OR_Success:
5605  S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5606  Best->FoundDecl, Entity, Diag);
5607  // FIXME: Check default arguments as far as that's possible.
5608  break;
5609 
5610  case OR_No_Viable_Function:
5611  S.Diag(Loc, Diag);
5612  CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5613  break;
5614 
5615  case OR_Ambiguous:
5616  S.Diag(Loc, Diag);
5617  CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5618  break;
5619 
5620  case OR_Deleted:
5621  S.Diag(Loc, Diag);
5622  S.NoteDeletedFunction(Best->Function);
5623  break;
5624  }
5625 }
5626 
5627 void InitializationSequence::PrintInitLocationNote(Sema &S,
5628  const InitializedEntity &Entity) {
5629  if (Entity.isParameterKind() && Entity.getDecl()) {
5630  if (Entity.getDecl()->getLocation().isInvalid())
5631  return;
5632 
5633  if (Entity.getDecl()->getDeclName())
5634  S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5635  << Entity.getDecl()->getDeclName();
5636  else
5637  S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5638  }
5639  else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5640  Entity.getMethodDecl())
5641  S.Diag(Entity.getMethodDecl()->getLocation(),
5642  diag::note_method_return_type_change)
5643  << Entity.getMethodDecl()->getDeclName();
5644 }
5645 
5649 }
5650 
5651 /// Returns true if the parameters describe a constructor initialization of
5652 /// an explicit temporary object, e.g. "Point(x, y)".
5653 static bool isExplicitTemporary(const InitializedEntity &Entity,
5654  const InitializationKind &Kind,
5655  unsigned NumArgs) {
5656  switch (Entity.getKind()) {
5660  break;
5661  default:
5662  return false;
5663  }
5664 
5665  switch (Kind.getKind()) {
5667  return true;
5668  // FIXME: Hack to work around cast weirdness.
5671  return NumArgs != 1;
5672  default:
5673  return false;
5674  }
5675 }
5676 
5677 static ExprResult
5679  const InitializedEntity &Entity,
5680  const InitializationKind &Kind,
5681  MultiExprArg Args,
5683  bool &ConstructorInitRequiresZeroInit,
5684  bool IsListInitialization,
5685  bool IsStdInitListInitialization,
5686  SourceLocation LBraceLoc,
5687  SourceLocation RBraceLoc) {
5688  unsigned NumArgs = Args.size();
5689  CXXConstructorDecl *Constructor
5690  = cast<CXXConstructorDecl>(Step.Function.Function);
5691  bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5692 
5693  // Build a call to the selected constructor.
5694  SmallVector<Expr*, 8> ConstructorArgs;
5695  SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5696  ? Kind.getEqualLoc()
5697  : Kind.getLocation();
5698 
5699  if (Kind.getKind() == InitializationKind::IK_Default) {
5700  // Force even a trivial, implicit default constructor to be
5701  // semantically checked. We do this explicitly because we don't build
5702  // the definition for completely trivial constructors.
5703  assert(Constructor->getParent() && "No parent class for constructor.");
5704  if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5705  Constructor->isTrivial() && !Constructor->isUsed(false))
5706  S.DefineImplicitDefaultConstructor(Loc, Constructor);
5707  }
5708 
5709  ExprResult CurInit((Expr *)nullptr);
5710 
5711  // C++ [over.match.copy]p1:
5712  // - When initializing a temporary to be bound to the first parameter
5713  // of a constructor that takes a reference to possibly cv-qualified
5714  // T as its first argument, called with a single argument in the
5715  // context of direct-initialization, explicit conversion functions
5716  // are also considered.
5717  bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5718  Args.size() == 1 &&
5719  Constructor->isCopyOrMoveConstructor();
5720 
5721  // Determine the arguments required to actually perform the constructor
5722  // call.
5723  if (S.CompleteConstructorCall(Constructor, Args,
5724  Loc, ConstructorArgs,
5725  AllowExplicitConv,
5726  IsListInitialization))
5727  return ExprError();
5728 
5729 
5730  if (isExplicitTemporary(Entity, Kind, NumArgs)) {
5731  // An explicitly-constructed temporary, e.g., X(1, 2).
5732  if (S.DiagnoseUseOfDecl(Constructor, Loc))
5733  return ExprError();
5734 
5735  TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5736  if (!TSInfo)
5737  TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
5738  SourceRange ParenOrBraceRange =
5740  ? SourceRange(LBraceLoc, RBraceLoc)
5741  : Kind.getParenRange();
5742 
5743  if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
5744  Step.Function.FoundDecl.getDecl())) {
5745  Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
5746  if (S.DiagnoseUseOfDecl(Constructor, Loc))
5747  return ExprError();
5748  }
5749  S.MarkFunctionReferenced(Loc, Constructor);
5750 
5751  CurInit = new (S.Context) CXXTemporaryObjectExpr(
5752  S.Context, Constructor, TSInfo,
5753  ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
5754  IsListInitialization, IsStdInitListInitialization,
5755  ConstructorInitRequiresZeroInit);
5756  } else {
5757  CXXConstructExpr::ConstructionKind ConstructKind =
5759 
5760  if (Entity.getKind() == InitializedEntity::EK_Base) {
5761  ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5764  } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5765  ConstructKind = CXXConstructExpr::CK_Delegating;
5766  }
5767 
5768  // Only get the parenthesis or brace range if it is a list initialization or
5769  // direct construction.
5770  SourceRange ParenOrBraceRange;
5771  if (IsListInitialization)
5772  ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5773  else if (Kind.getKind() == InitializationKind::IK_Direct)
5774  ParenOrBraceRange = Kind.getParenRange();
5775 
5776  // If the entity allows NRVO, mark the construction as elidable
5777  // unconditionally.
5778  if (Entity.allowsNRVO())
5779  CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5780  Step.Function.FoundDecl,
5781  Constructor, /*Elidable=*/true,
5782  ConstructorArgs,
5783  HadMultipleCandidates,
5784  IsListInitialization,
5785  IsStdInitListInitialization,
5786  ConstructorInitRequiresZeroInit,
5787  ConstructKind,
5788  ParenOrBraceRange);
5789  else
5790  CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5791  Step.Function.FoundDecl,
5792  Constructor,
5793  ConstructorArgs,
5794  HadMultipleCandidates,
5795  IsListInitialization,
5796  IsStdInitListInitialization,
5797  ConstructorInitRequiresZeroInit,
5798  ConstructKind,
5799  ParenOrBraceRange);
5800  }
5801  if (CurInit.isInvalid())
5802  return ExprError();
5803 
5804  // Only check access if all of that succeeded.
5805  S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
5806  if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5807  return ExprError();
5808 
5809  if (shouldBindAsTemporary(Entity))
5810  CurInit = S.MaybeBindToTemporary(CurInit.get());
5811 
5812  return CurInit;
5813 }
5814 
5815 /// Determine whether the specified InitializedEntity definitely has a lifetime
5816 /// longer than the current full-expression. Conservatively returns false if
5817 /// it's unclear.
5818 static bool
5820  const InitializedEntity *Top = &Entity;
5821  while (Top->getParent())
5822  Top = Top->getParent();
5823 
5824  switch (Top->getKind()) {
5832  return true;
5833 
5838  // Could not determine what the full initialization is. Assume it might not
5839  // outlive the full-expression.
5840  return false;
5841 
5848  // The entity being initialized might not outlive the full-expression.
5849  return false;
5850  }
5851 
5852  llvm_unreachable("unknown entity kind");
5853 }
5854 
5855 /// Determine the declaration which an initialized entity ultimately refers to,
5856 /// for the purpose of lifetime-extending a temporary bound to a reference in
5857 /// the initialization of \p Entity.
5859  const InitializedEntity *Entity,
5860  const InitializedEntity *FallbackDecl = nullptr) {
5861  // C++11 [class.temporary]p5:
5862  switch (Entity->getKind()) {
5864  // The temporary [...] persists for the lifetime of the reference
5865  return Entity;
5866 
5868  // For subobjects, we look at the complete object.
5869  if (Entity->getParent())
5871  Entity);
5872 
5873  // except:
5874  // -- A temporary bound to a reference member in a constructor's
5875  // ctor-initializer persists until the constructor exits.
5876  return Entity;
5877 
5880  // -- A temporary bound to a reference parameter in a function call
5881  // persists until the completion of the full-expression containing
5882  // the call.
5884  // -- The lifetime of a temporary bound to the returned value in a
5885  // function return statement is not extended; the temporary is
5886  // destroyed at the end of the full-expression in the return statement.
5888  // -- A temporary bound to a reference in a new-initializer persists
5889  // until the completion of the full-expression containing the
5890  // new-initializer.
5891  return nullptr;
5892 
5896  // We don't yet know the storage duration of the surrounding temporary.
5897  // Assume it's got full-expression duration for now, it will patch up our
5898  // storage duration if that's not correct.
5899  return nullptr;
5900 
5902  // For subobjects, we look at the complete object.
5904  FallbackDecl);
5905 
5907  // For subobjects, we look at the complete object.
5908  if (Entity->getParent())
5910  Entity);
5911  // Fall through.
5913  // We can reach this case for aggregate initialization in a constructor:
5914  // struct A { int &&r; };
5915  // struct B : A { B() : A{0} {} };
5916  // In this case, use the innermost field decl as the context.
5917  return FallbackDecl;
5918 
5924  return nullptr;
5925  }
5926  llvm_unreachable("unknown entity kind");
5927 }
5928 
5929 static void performLifetimeExtension(Expr *Init,
5930  const InitializedEntity *ExtendingEntity);
5931 
5932 /// Update a glvalue expression that is used as the initializer of a reference
5933 /// to note that its lifetime is extended.
5934 /// \return \c true if any temporary had its lifetime extended.
5935 static bool
5937  const InitializedEntity *ExtendingEntity) {
5938  // Walk past any constructs which we can lifetime-extend across.
5939  Expr *Old;
5940  do {
5941  Old = Init;
5942 
5943  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5944  if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5945  // This is just redundant braces around an initializer. Step over it.
5946  Init = ILE->getInit(0);
5947  }
5948  }
5949 
5950  // Step over any subobject adjustments; we may have a materialized
5951  // temporary inside them.
5952  SmallVector<const Expr *, 2> CommaLHSs;
5954  Init = const_cast<Expr *>(
5955  Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5956 
5957  // Per current approach for DR1376, look through casts to reference type
5958  // when performing lifetime extension.
5959  if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5960  if (CE->getSubExpr()->isGLValue())
5961  Init = CE->getSubExpr();
5962 
5963  // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5964  // It's unclear if binding a reference to that xvalue extends the array
5965  // temporary.
5966  } while (Init != Old);
5967 
5968  if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5969  // Update the storage duration of the materialized temporary.
5970  // FIXME: Rebuild the expression instead of mutating it.
5971  ME->setExtendingDecl(ExtendingEntity->getDecl(),
5972  ExtendingEntity->allocateManglingNumber());
5973  performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
5974  return true;
5975  }
5976 
5977  return false;
5978 }
5979 
5980 /// Update a prvalue expression that is going to be materialized as a
5981 /// lifetime-extended temporary.
5982 static void performLifetimeExtension(Expr *Init,
5983  const InitializedEntity *ExtendingEntity) {
5984  // Dig out the expression which constructs the extended temporary.
5985  SmallVector<const Expr *, 2> CommaLHSs;
5987  Init = const_cast<Expr *>(
5988  Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5989 
5990  if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5991  Init = BTE->getSubExpr();
5992 
5993  if (CXXStdInitializerListExpr *ILE =
5994  dyn_cast<CXXStdInitializerListExpr>(Init)) {
5995  performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
5996  return;
5997  }
5998 
5999  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6000  if (ILE->getType()->isArrayType()) {
6001  for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
6002  performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
6003  return;
6004  }
6005 
6006  if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
6007  assert(RD->isAggregate() && "aggregate init on non-aggregate");
6008 
6009  // If we lifetime-extend a braced initializer which is initializing an
6010  // aggregate, and that aggregate contains reference members which are
6011  // bound to temporaries, those temporaries are also lifetime-extended.
6012  if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6013  ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
6014  performReferenceExtension(ILE->getInit(0), ExtendingEntity);
6015  else {
6016  unsigned Index = 0;
6017  for (const auto *I : RD->fields()) {
6018  if (Index >= ILE->getNumInits())
6019  break;
6020  if (I->isUnnamedBitfield())
6021  continue;
6022  Expr *SubInit = ILE->getInit(Index);
6023  if (I->getType()->isReferenceType())
6024  performReferenceExtension(SubInit, ExtendingEntity);
6025  else if (isa<InitListExpr>(SubInit) ||
6026  isa<CXXStdInitializerListExpr>(SubInit))
6027  // This may be either aggregate-initialization of a member or
6028  // initialization of a std::initializer_list object. Either way,
6029  // we should recursively lifetime-extend that initializer.
6030  performLifetimeExtension(SubInit, ExtendingEntity);
6031  ++Index;
6032  }
6033  }
6034  }
6035  }
6036 }
6037 
6038 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6039  const Expr *Init, bool IsInitializerList,
6040  const ValueDecl *ExtendingDecl) {
6041  // Warn if a field lifetime-extends a temporary.
6042  if (isa<FieldDecl>(ExtendingDecl)) {
6043  if (IsInitializerList) {
6044  S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6045  << /*at end of constructor*/true;
6046  return;
6047  }
6048 
6049  bool IsSubobjectMember = false;
6050  for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6051  Ent = Ent->getParent()) {
6052  if (Ent->getKind() != InitializedEntity::EK_Base) {
6053  IsSubobjectMember = true;
6054  break;
6055  }
6056  }
6057  S.Diag(Init->getExprLoc(),
6058  diag::warn_bind_ref_member_to_temporary)
6059  << ExtendingDecl << Init->getSourceRange()
6060  << IsSubobjectMember << IsInitializerList;
6061  if (IsSubobjectMember)
6062  S.Diag(ExtendingDecl->getLocation(),
6063  diag::note_ref_subobject_of_member_declared_here);
6064  else
6065  S.Diag(ExtendingDecl->getLocation(),
6066  diag::note_ref_or_ptr_member_declared_here)
6067  << /*is pointer*/false;
6068  }
6069 }
6070 
6071 static void DiagnoseNarrowingInInitList(Sema &S,
6072  const ImplicitConversionSequence &ICS,
6073  QualType PreNarrowingType,
6074  QualType EntityType,
6075  const Expr *PostInit);
6076 
6077 /// Provide warnings when std::move is used on construction.
6078 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6079  bool IsReturnStmt) {
6080  if (!InitExpr)
6081  return;
6082 
6083  if (!S.ActiveTemplateInstantiations.empty())
6084  return;
6085 
6086  QualType DestType = InitExpr->getType();
6087  if (!DestType->isRecordType())
6088  return;
6089 
6090  unsigned DiagID = 0;
6091  if (IsReturnStmt) {
6092  const CXXConstructExpr *CCE =
6093  dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6094  if (!CCE || CCE->getNumArgs() != 1)
6095  return;
6096 
6097  if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6098  return;
6099 
6100  InitExpr = CCE->getArg(0)->IgnoreImpCasts();
6101  }
6102 
6103  // Find the std::move call and get the argument.
6104  const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6105  if (!CE || CE->getNumArgs() != 1)
6106  return;
6107 
6108  const FunctionDecl *MoveFunction = CE->getDirectCallee();
6109  if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6110  !MoveFunction->getIdentifier() ||
6111  !MoveFunction->getIdentifier()->isStr("move"))
6112  return;
6113 
6114  const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6115 
6116  if (IsReturnStmt) {
6117  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6118  if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6119  return;
6120 
6121  const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6122  if (!VD || !VD->hasLocalStorage())
6123  return;
6124 
6125  QualType SourceType = VD->getType();
6126  if (!SourceType->isRecordType())
6127  return;
6128 
6129  if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
6130  return;
6131  }
6132 
6133  // If we're returning a function parameter, copy elision
6134  // is not possible.
6135  if (isa<ParmVarDecl>(VD))
6136  DiagID = diag::warn_redundant_move_on_return;
6137  else
6138  DiagID = diag::warn_pessimizing_move_on_return;
6139  } else {
6140  DiagID = diag::warn_pessimizing_move_on_initialization;
6141  const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6142  if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6143  return;
6144  }
6145 
6146  S.Diag(CE->getLocStart(), DiagID);
6147 
6148  // Get all the locations for a fix-it. Don't emit the fix-it if any location
6149  // is within a macro.
6150  SourceLocation CallBegin = CE->getCallee()->getLocStart();
6151  if (CallBegin.isMacroID())
6152  return;
6153  SourceLocation RParen = CE->getRParenLoc();
6154  if (RParen.isMacroID())
6155  return;
6156  SourceLocation LParen;
6157  SourceLocation ArgLoc = Arg->getLocStart();
6158 
6159  // Special testing for the argument location. Since the fix-it needs the
6160  // location right before the argument, the argument location can be in a
6161  // macro only if it is at the beginning of the macro.
6162  while (ArgLoc.isMacroID() &&
6164  ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6165  }
6166 
6167  if (LParen.isMacroID())
6168  return;
6169 
6170  LParen = ArgLoc.getLocWithOffset(-1);
6171 
6172  S.Diag(CE->getLocStart(), diag::note_remove_move)
6173  << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6174  << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6175 }
6176 
6177 static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6178  // Check to see if we are dereferencing a null pointer. If so, this is
6179  // undefined behavior, so warn about it. This only handles the pattern
6180  // "*null", which is a very syntactic check.
6181  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6182  if (UO->getOpcode() == UO_Deref &&
6183  UO->getSubExpr()->IgnoreParenCasts()->
6184  isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6185  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6186  S.PDiag(diag::warn_binding_null_to_reference)
6187  << UO->getSubExpr()->getSourceRange());
6188  }
6189 }
6190 
6193  bool BoundToLvalueReference) {
6194  auto MTE = new (Context)
6195  MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6196 
6197  // Order an ExprWithCleanups for lifetime marks.
6198  //
6199  // TODO: It'll be good to have a single place to check the access of the
6200  // destructor and generate ExprWithCleanups for various uses. Currently these
6201  // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6202  // but there may be a chance to merge them.
6204  return MTE;
6205 }
6206 
6207 ExprResult
6209  const InitializedEntity &Entity,
6210  const InitializationKind &Kind,
6211  MultiExprArg Args,
6212  QualType *ResultType) {
6213  if (Failed()) {
6214  Diagnose(S, Entity, Kind, Args);
6215  return ExprError();
6216  }
6217  if (!ZeroInitializationFixit.empty()) {
6218  unsigned DiagID = diag::err_default_init_const;
6219  if (Decl *D = Entity.getDecl())
6220  if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6221  DiagID = diag::ext_default_init_const;
6222 
6223  // The initialization would have succeeded with this fixit. Since the fixit
6224  // is on the error, we need to build a valid AST in this case, so this isn't
6225  // handled in the Failed() branch above.
6226  QualType DestType = Entity.getType();
6227  S.Diag(Kind.getLocation(), DiagID)
6228  << DestType << (bool)DestType->getAs<RecordType>()
6229  << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6230  ZeroInitializationFixit);
6231  }
6232 
6233  if (getKind() == DependentSequence) {
6234  // If the declaration is a non-dependent, incomplete array type
6235  // that has an initializer, then its type will be completed once
6236  // the initializer is instantiated.
6237  if (ResultType && !Entity.getType()->isDependentType() &&
6238  Args.size() == 1) {
6239  QualType DeclType = Entity.getType();
6240  if (const IncompleteArrayType *ArrayT
6241  = S.Context.getAsIncompleteArrayType(DeclType)) {
6242  // FIXME: We don't currently have the ability to accurately
6243  // compute the length of an initializer list without
6244  // performing full type-checking of the initializer list
6245  // (since we have to determine where braces are implicitly
6246  // introduced and such). So, we fall back to making the array
6247  // type a dependently-sized array type with no specified
6248  // bound.
6249  if (isa<InitListExpr>((Expr *)Args[0])) {
6250  SourceRange Brackets;
6251 
6252  // Scavange the location of the brackets from the entity, if we can.
6253  if (DeclaratorDecl *DD = Entity.getDecl()) {
6254  if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6255  TypeLoc TL = TInfo->getTypeLoc();
6256  if (IncompleteArrayTypeLoc ArrayLoc =
6258  Brackets = ArrayLoc.getBracketsRange();
6259  }
6260  }
6261 
6262  *ResultType
6263  = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
6264  /*NumElts=*/nullptr,
6265  ArrayT->getSizeModifier(),
6266  ArrayT->getIndexTypeCVRQualifiers(),
6267  Brackets);
6268  }
6269 
6270  }
6271  }
6272  if (Kind.getKind() == InitializationKind::IK_Direct &&
6273  !Kind.isExplicitCast()) {
6274  // Rebuild the ParenListExpr.
6275  SourceRange ParenRange = Kind.getParenRange();
6276  return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
6277  Args);
6278  }
6279  assert(Kind.getKind() == InitializationKind::IK_Copy ||
6280  Kind.isExplicitCast() ||
6282  return ExprResult(Args[0]);
6283  }
6284 
6285  // No steps means no initialization.
6286  if (Steps.empty())
6287  return ExprResult((Expr *)nullptr);
6288 
6289  if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
6290  Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
6291  !Entity.isParameterKind()) {
6292  // Produce a C++98 compatibility warning if we are initializing a reference
6293  // from an initializer list. For parameters, we produce a better warning
6294  // elsewhere.
6295  Expr *Init = Args[0];
6296  S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6297  << Init->getSourceRange();
6298  }
6299 
6300  // Diagnose cases where we initialize a pointer to an array temporary, and the
6301  // pointer obviously outlives the temporary.
6302  if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
6303  Entity.getType()->isPointerType() &&
6305  Expr *Init = Args[0];
6307  if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6308  S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6309  << Init->getSourceRange();
6310  }
6311 
6312  QualType DestType = Entity.getType().getNonReferenceType();
6313  // FIXME: Ugly hack around the fact that Entity.getType() is not
6314  // the same as Entity.getDecl()->getType() in cases involving type merging,
6315  // and we want latter when it makes sense.
6316  if (ResultType)
6317  *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
6318  Entity.getType();
6319 
6320  ExprResult CurInit((Expr *)nullptr);
6321 
6322  // For initialization steps that start with a single initializer,
6323  // grab the only argument out the Args and place it into the "current"
6324  // initializer.
6325  switch (Steps.front().Kind) {
6330  case SK_BindReference:
6333  case SK_UserConversion:
6337  case SK_AtomicConversion:
6338  case SK_LValueToRValue:
6339  case SK_ConversionSequence:
6341  case SK_ListInitialization:
6342  case SK_UnwrapInitList:
6343  case SK_RewrapInitList:
6344  case SK_CAssignment:
6345  case SK_StringInit:
6347  case SK_ArrayInit:
6351  case SK_ProduceObjCObject:
6352  case SK_StdInitializerList:
6353  case SK_OCLSamplerInit:
6354  case SK_OCLZeroEvent: {
6355  assert(Args.size() == 1);
6356  CurInit = Args[0];
6357  if (!CurInit.get()) return ExprError();
6358  break;
6359  }
6360 
6364  case SK_ZeroInitialization:
6365  break;
6366  }
6367 
6368  // Walk through the computed steps for the initialization sequence,
6369  // performing the specified conversions along the way.
6370  bool ConstructorInitRequiresZeroInit = false;
6371  for (step_iterator Step = step_begin(), StepEnd = step_end();
6372  Step != StepEnd; ++Step) {
6373  if (CurInit.isInvalid())
6374  return ExprError();
6375 
6376  QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
6377 
6378  switch (Step->Kind) {
6380  // Overload resolution determined which function invoke; update the
6381  // initializer to reflect that choice.
6384  return ExprError();
6385  CurInit = S.FixOverloadedFunctionReference(CurInit,
6388  break;
6389 
6393  // We have a derived-to-base cast that produces either an rvalue or an
6394  // lvalue. Perform that cast.
6395 
6396  CXXCastPath BasePath;
6397 
6398  // Casts to inaccessible base classes are allowed with C-style casts.
6399  bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6400  if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
6401  CurInit.get()->getLocStart(),
6402  CurInit.get()->getSourceRange(),
6403  &BasePath, IgnoreBaseAccess))
6404  return ExprError();
6405 
6406  ExprValueKind VK =
6408  VK_LValue :
6410  VK_XValue :
6411  VK_RValue);
6412  CurInit =
6413  ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6414  CurInit.get(), &BasePath, VK);
6415  break;
6416  }
6417 
6418  case SK_BindReference:
6419  // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
6420  if (CurInit.get()->refersToBitField()) {
6421  // We don't necessarily have an unambiguous source bit-field.
6422  FieldDecl *BitField = CurInit.get()->getSourceBitField();
6423  S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
6424  << Entity.getType().isVolatileQualified()
6425  << (BitField ? BitField->getDeclName() : DeclarationName())
6426  << (BitField != nullptr)
6427  << CurInit.get()->getSourceRange();
6428  if (BitField)
6429  S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
6430 
6431  return ExprError();
6432  }
6433 
6434  if (CurInit.get()->refersToVectorElement()) {
6435  // References cannot bind to vector elements.
6436  S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
6437  << Entity.getType().isVolatileQualified()
6438  << CurInit.get()->getSourceRange();
6439  PrintInitLocationNote(S, Entity);
6440  return ExprError();
6441  }
6442 
6443  // Reference binding does not have any corresponding ASTs.
6444 
6445  // Check exception specifications
6446  if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
6447  return ExprError();
6448 
6449  // Even though we didn't materialize a temporary, the binding may still
6450  // extend the lifetime of a temporary. This happens if we bind a reference
6451  // to the result of a cast to reference type.
6452  if (const InitializedEntity *ExtendingEntity =
6454  if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6455  warnOnLifetimeExtension(S, Entity, CurInit.get(),
6456  /*IsInitializerList=*/false,
6457  ExtendingEntity->getDecl());
6458 
6459  CheckForNullPointerDereference(S, CurInit.get());
6460  break;
6461 
6463  // Make sure the "temporary" is actually an rvalue.
6464  assert(CurInit.get()->isRValue() && "not a temporary");
6465 
6466  // Check exception specifications
6467  if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
6468  return ExprError();
6469 
6470  // Materialize the temporary into memory.
6472  Entity.getType().getNonReferenceType(), CurInit.get(),
6473  Entity.getType()->isLValueReferenceType());
6474 
6475  // Maybe lifetime-extend the temporary's subobjects to match the
6476  // entity's lifetime.
6477  if (const InitializedEntity *ExtendingEntity =
6479  if (performReferenceExtension(MTE, ExtendingEntity))
6480  warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
6481  ExtendingEntity->getDecl());
6482 
6483  // If we're binding to an Objective-C object that has lifetime, we
6484  // need cleanups. Likewise if we're extending this temporary to automatic
6485  // storage duration -- we need to register its cleanup during the
6486  // full-expression's cleanups.
6487  if ((S.getLangOpts().ObjCAutoRefCount &&
6488  MTE->getType()->isObjCLifetimeType()) ||
6489  (MTE->getStorageDuration() == SD_Automatic &&
6490  MTE->getType().isDestructedType()))
6491  S.Cleanup.setExprNeedsCleanups(true);
6492 
6493  CurInit = MTE;
6494  break;
6495  }
6496 
6498  CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6499  /*IsExtraneousCopy=*/true);
6500  break;
6501 
6502  case SK_UserConversion: {
6503  // We have a user-defined conversion that invokes either a constructor
6504  // or a conversion function.
6506  bool IsCopy = false;
6509  bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
6510  bool CreatedObject = false;
6511  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
6512  // Build a call to the selected constructor.
6513  SmallVector<Expr*, 8> ConstructorArgs;
6514  SourceLocation Loc = CurInit.get()->getLocStart();
6515  CurInit.get(); // Ownership transferred into MultiExprArg, below.
6516 
6517  // Determine the arguments required to actually perform the constructor
6518  // call.
6519  Expr *Arg = CurInit.get();
6520  if (S.CompleteConstructorCall(Constructor,
6521  MultiExprArg(&Arg, 1),
6522  Loc, ConstructorArgs))
6523  return ExprError();
6524 
6525  // Build an expression that constructs a temporary.
6526  CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6527  FoundFn, Constructor,
6528  ConstructorArgs,
6529  HadMultipleCandidates,
6530  /*ListInit*/ false,
6531  /*StdInitListInit*/ false,
6532  /*ZeroInit*/ false,
6534  SourceRange());
6535  if (CurInit.isInvalid())
6536  return ExprError();
6537 
6538  S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6539  Entity);
6540  if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6541  return ExprError();
6542 
6543  CastKind = CK_ConstructorConversion;
6544  QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6545  if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6546  S.IsDerivedFrom(Loc, SourceType, Class))
6547  IsCopy = true;
6548 
6549  CreatedObject = true;
6550  } else {
6551  // Build a call to the conversion function.
6552  CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
6553  S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
6554  FoundFn);
6555  if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6556  return ExprError();
6557 
6558  // FIXME: Should we move this initialization into a separate
6559  // derived-to-base conversion? I believe the answer is "no", because
6560  // we don't want to turn off access control here for c-style casts.
6561  ExprResult CurInitExprRes =
6563  /*Qualifier=*/nullptr,
6564  FoundFn, Conversion);
6565  if(CurInitExprRes.isInvalid())
6566  return ExprError();
6567  CurInit = CurInitExprRes;
6568 
6569  // Build the actual call to the conversion function.
6570  CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6571  HadMultipleCandidates);
6572  if (CurInit.isInvalid() || !CurInit.get())
6573  return ExprError();
6574 
6575  CastKind = CK_UserDefinedConversion;
6576 
6577  CreatedObject = Conversion->getReturnType()->isRecordType();
6578  }
6579 
6580  bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
6581  bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6582 
6583  if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
6584  QualType T = CurInit.get()->getType();
6585  if (const RecordType *Record = T->getAs<RecordType>()) {
6586  CXXDestructorDecl *Destructor
6587  = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
6588  S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
6589  S.PDiag(diag::err_access_dtor_temp) << T);
6590  S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
6591  if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6592  return ExprError();
6593  }
6594  }
6595 
6596  CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6597  CastKind, CurInit.get(), nullptr,
6598  CurInit.get()->getValueKind());
6599  if (MaybeBindToTemp)
6600  CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6601  if (RequiresCopy)
6602  CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
6603  CurInit, /*IsExtraneousCopy=*/false);
6604  break;
6605  }
6606 
6610  // Perform a qualification conversion; these can never go wrong.
6611  ExprValueKind VK =
6613  VK_LValue :
6615  VK_XValue :
6616  VK_RValue);
6617  CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
6618  break;
6619  }
6620 
6621  case SK_AtomicConversion: {
6622  assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6623  CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6624  CK_NonAtomicToAtomic, VK_RValue);
6625  break;
6626  }
6627 
6628  case SK_LValueToRValue: {
6629  assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
6630  CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6631  CK_LValueToRValue, CurInit.get(),
6632  /*BasePath=*/nullptr, VK_RValue);
6633  break;
6634  }
6635 
6636  case SK_ConversionSequence:
6643  ExprResult CurInitExprRes =
6644  S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
6645  getAssignmentAction(Entity), CCK);
6646  if (CurInitExprRes.isInvalid())
6647  return ExprError();
6648  CurInit = CurInitExprRes;
6649 
6651  S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6652  DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6653  CurInit.get());
6654  break;
6655  }
6656 
6657  case SK_ListInitialization: {
6658  InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
6659  // If we're not initializing the top-level entity, we need to create an
6660  // InitializeTemporary entity for our target type.
6661  QualType Ty = Step->Type;
6662  bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
6664  InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6665  InitListChecker PerformInitList(S, InitEntity,
6666  InitList, Ty, /*VerifyOnly=*/false,
6667  /*TreatUnavailableAsInvalid=*/false);
6668  if (PerformInitList.HadError())
6669  return ExprError();
6670 
6671  // Hack: We must update *ResultType if available in order to set the
6672  // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6673  // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6674  if (ResultType &&
6675  ResultType->getNonReferenceType()->isIncompleteArrayType()) {
6676  if ((*ResultType)->isRValueReferenceType())
6677  Ty = S.Context.getRValueReferenceType(Ty);
6678  else if ((*ResultType)->isLValueReferenceType())
6679  Ty = S.Context.getLValueReferenceType(Ty,
6680  (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6681  *ResultType = Ty;
6682  }
6683 
6684  InitListExpr *StructuredInitList =
6685  PerformInitList.getFullyStructuredList();
6686  CurInit.get();
6687  CurInit = shouldBindAsTemporary(InitEntity)
6688  ? S.MaybeBindToTemporary(StructuredInitList)
6689  : StructuredInitList;
6690  break;
6691  }
6692 
6694  // When an initializer list is passed for a parameter of type "reference
6695  // to object", we don't get an EK_Temporary entity, but instead an
6696  // EK_Parameter entity with reference type.
6697  // FIXME: This is a hack. What we really should do is create a user
6698  // conversion step for this case, but this makes it considerably more
6699  // complicated. For now, this will do.
6701  Entity.getType().getNonReferenceType());
6702  bool UseTemporary = Entity.getType()->isReferenceType();
6703  assert(Args.size() == 1 && "expected a single argument for list init");
6704  InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6705  S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6706  << InitList->getSourceRange();
6707  MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
6708  CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6709  Entity,
6710  Kind, Arg, *Step,
6711  ConstructorInitRequiresZeroInit,
6712  /*IsListInitialization*/true,
6713  /*IsStdInitListInit*/false,
6714  InitList->getLBraceLoc(),
6715  InitList->getRBraceLoc());
6716  break;
6717  }
6718 
6719  case SK_UnwrapInitList:
6720  CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
6721  break;
6722 
6723  case SK_RewrapInitList: {
6724  Expr *E = CurInit.get();
6725  InitListExpr *Syntactic = Step->WrappingSyntacticList;
6726  InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
6727  Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
6728  ILE->setSyntacticForm(Syntactic);
6729  ILE->setType(E->getType());
6730  ILE->setValueKind(E->getValueKind());
6731  CurInit = ILE;
6732  break;
6733  }
6734 
6737  // When an initializer list is passed for a parameter of type "reference
6738  // to object", we don't get an EK_Temporary entity, but instead an
6739  // EK_Parameter entity with reference type.
6740  // FIXME: This is a hack. What we really should do is create a user
6741  // conversion step for this case, but this makes it considerably more
6742  // complicated. For now, this will do.
6744  Entity.getType().getNonReferenceType());
6745  bool UseTemporary = Entity.getType()->isReferenceType();
6746  bool IsStdInitListInit =
6749  S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6750  ConstructorInitRequiresZeroInit,
6751  /*IsListInitialization*/IsStdInitListInit,
6752  /*IsStdInitListInitialization*/IsStdInitListInit,
6753  /*LBraceLoc*/SourceLocation(),
6754  /*RBraceLoc*/SourceLocation());
6755  break;
6756  }
6757 
6758  case SK_ZeroInitialization: {
6759  step_iterator NextStep = Step;
6760  ++NextStep;
6761  if (NextStep != StepEnd &&
6762  (NextStep->Kind == SK_ConstructorInitialization ||
6763  NextStep->Kind == SK_ConstructorInitializationFromList)) {
6764  // The need for zero-initialization is recorded directly into
6765  // the call to the object's constructor within the next step.
6766  ConstructorInitRequiresZeroInit = true;
6767  } else if (Kind.getKind() == InitializationKind::IK_Value &&
6768  S.getLangOpts().CPlusPlus &&
6769  !Kind.isImplicitValueInit()) {
6770  TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6771  if (!TSInfo)
6773  Kind.getRange().getBegin());
6774 
6775  CurInit = new (S.Context) CXXScalarValueInitExpr(
6776  TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6777  Kind.getRange().getEnd());
6778  } else {
6779  CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
6780  }
6781  break;
6782  }
6783 
6784  case SK_CAssignment: {
6785  QualType SourceType = CurInit.get()->getType();
6786  // Save off the initial CurInit in case we need to emit a diagnostic
6787  ExprResult InitialCurInit = CurInit;
6788  ExprResult Result = CurInit;
6789  Sema::AssignConvertType ConvTy =
6790  S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6792  if (Result.isInvalid())
6793  return ExprError();
6794  CurInit = Result;
6795 
6796  // If this is a call, allow conversion to a transparent union.
6797  ExprResult CurInitExprRes = CurInit;
6798  if (ConvTy != Sema::Compatible &&
6799  Entity.isParameterKind() &&
6801  == Sema::Compatible)
6802  ConvTy = Sema::Compatible;
6803  if (CurInitExprRes.isInvalid())
6804  return ExprError();
6805  CurInit = CurInitExprRes;
6806 
6807  bool Complained;
6808  if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6809  Step->Type, SourceType,
6810  InitialCurInit.get(),
6811  getAssignmentAction(Entity, true),
6812  &Complained)) {
6813  PrintInitLocationNote(S, Entity);
6814  return ExprError();
6815  } else if (Complained)
6816  PrintInitLocationNote(S, Entity);
6817  break;
6818  }
6819 
6820  case SK_StringInit: {
6821  QualType Ty = Step->Type;
6822  CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
6823  S.Context.getAsArrayType(Ty), S);
6824  break;
6825  }
6826 
6828  CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6829  CK_ObjCObjectLValueCast,
6830  CurInit.get()->getValueKind());
6831  break;
6832 
6833  case SK_ArrayInit:
6834  // Okay: we checked everything before creating this step. Note that
6835  // this is a GNU extension.
6836  S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
6837  << Step->Type << CurInit.get()->getType()
6838  << CurInit.get()->getSourceRange();
6839 
6840  // If the destination type is an incomplete array type, update the
6841  // type accordingly.
6842  if (ResultType) {
6843  if (const IncompleteArrayType *IncompleteDest
6845  if (const ConstantArrayType *ConstantSource
6846  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
6847  *ResultType = S.Context.getConstantArrayType(
6848  IncompleteDest->getElementType(),
6849  ConstantSource->getSize(),
6850  ArrayType::Normal, 0);
6851  }
6852  }
6853  }
6854  break;
6855 
6857  // Okay: we checked everything before creating this step. Note that
6858  // this is a GNU extension.
6859  S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6860  << CurInit.get()->getSourceRange();
6861  break;
6862 
6865  checkIndirectCopyRestoreSource(S, CurInit.get());
6866  CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6867  CurInit.get(), Step->Type,
6869  break;
6870 
6871  case SK_ProduceObjCObject:
6872  CurInit =
6873  ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6874  CurInit.get(), nullptr, VK_RValue);
6875  break;
6876 
6877  case SK_StdInitializerList: {
6878  S.Diag(CurInit.get()->getExprLoc(),
6879  diag::warn_cxx98_compat_initializer_list_init)
6880  << CurInit.get()->getSourceRange();
6881 
6882  // Materialize the temporary into memory.
6884  CurInit.get()->getType(), CurInit.get(),
6885  /*BoundToLvalueReference=*/false);
6886 
6887  // Maybe lifetime-extend the array temporary's subobjects to match the
6888  // entity's lifetime.
6889  if (const InitializedEntity *ExtendingEntity =
6891  if (performReferenceExtension(MTE, ExtendingEntity))
6892  warnOnLifetimeExtension(S, Entity, CurInit.get(),
6893  /*IsInitializerList=*/true,
6894  ExtendingEntity->getDecl());
6895 
6896  // Wrap it in a construction of a std::initializer_list<T>.
6897  CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
6898 
6899  // Bind the result, in case the library has given initializer_list a
6900  // non-trivial destructor.
6901  if (shouldBindAsTemporary(Entity))
6902  CurInit = S.MaybeBindToTemporary(CurInit.get());
6903  break;
6904  }
6905 
6906  case SK_OCLSamplerInit: {
6907  assert(Step->Type->isSamplerT() &&
6908  "Sampler initialization on non-sampler type.");
6909 
6910  QualType SourceType = CurInit.get()->getType();
6911 
6912  if (Entity.isParameterKind()) {
6913  if (!SourceType->isSamplerT())
6914  S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6915  << SourceType;
6916  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
6917  llvm_unreachable("Invalid EntityKind!");
6918  }
6919 
6920  break;
6921  }
6922  case SK_OCLZeroEvent: {
6923  assert(Step->Type->isEventT() &&
6924  "Event initialization on non-event type.");
6925 
6926  CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6927  CK_ZeroToOCLEvent,
6928  CurInit.get()->getValueKind());
6929  break;
6930  }
6931  }
6932  }
6933 
6934  // Diagnose non-fatal problems with the completed initialization.
6935  if (Entity.getKind() == InitializedEntity::EK_Member &&
6936  cast<FieldDecl>(Entity.getDecl())->isBitField())
6937  S.CheckBitFieldInitialization(Kind.getLocation(),
6938  cast<FieldDecl>(Entity.getDecl()),
6939  CurInit.get());
6940 
6941  // Check for std::move on construction.
6942  if (const Expr *E = CurInit.get()) {
6945  }
6946 
6947  return CurInit;
6948 }
6949 
6950 /// Somewhere within T there is an uninitialized reference subobject.
6951 /// Dig it out and diagnose it.
6953  QualType T) {
6954  if (T->isReferenceType()) {
6955  S.Diag(Loc, diag::err_reference_without_init)
6956  << T.getNonReferenceType();
6957  return true;
6958  }
6959 
6961  if (!RD || !RD->hasUninitializedReferenceMember())
6962  return false;
6963 
6964  for (const auto *FI : RD->fields()) {
6965  if (FI->isUnnamedBitfield())
6966  continue;
6967 
6968  if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6969  S.Diag(Loc, diag::note_value_initialization_here) << RD;
6970  return true;
6971  }
6972  }
6973 
6974  for (const auto &BI : RD->bases()) {
6975  if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
6976  S.Diag(Loc, diag::note_value_initialization_here) << RD;
6977  return true;
6978  }
6979  }
6980 
6981  return false;
6982 }
6983 
6984 
6985 //===----------------------------------------------------------------------===//
6986 // Diagnose initialization failures
6987 //===----------------------------------------------------------------------===//
6988 
6989 /// Emit notes associated with an initialization that failed due to a
6990 /// "simple" conversion failure.
6991 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6992  Expr *op) {
6993  QualType destType = entity.getType();
6994  if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6995  op->getType()->isObjCObjectPointerType()) {
6996 
6997  // Emit a possible note about the conversion failing because the
6998  // operand is a message send with a related result type.
7000 
7001  // Emit a possible note about a return failing because we're
7002  // expecting a related result type.
7003  if (entity.getKind() == InitializedEntity::EK_Result)
7005  }
7006 }
7007 
7008 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7009  InitListExpr *InitList) {
7010  QualType DestType = Entity.getType();
7011 
7012  QualType E;
7013  if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7015  E.withConst(),
7016  llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7017  InitList->getNumInits()),
7019  InitializedEntity HiddenArray =
7021  return diagnoseListInit(S, HiddenArray, InitList);
7022  }
7023 
7024  if (DestType->isReferenceType()) {
7025  // A list-initialization failure for a reference means that we tried to
7026  // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7027  // inner initialization failed.
7028  QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7030  SourceLocation Loc = InitList->getLocStart();
7031  if (auto *D = Entity.getDecl())
7032  Loc = D->getLocation();
7033  S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7034  return;
7035  }
7036 
7037  InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
7038  /*VerifyOnly=*/false,
7039  /*TreatUnavailableAsInvalid=*/false);
7040  assert(DiagnoseInitList.HadError() &&
7041  "Inconsistent init list check result.");
7042 }
7043 
7045  const InitializedEntity &Entity,
7046  const InitializationKind &Kind,
7047  ArrayRef<Expr *> Args) {
7048  if (!Failed())
7049  return false;
7050 
7051  QualType DestType = Entity.getType();
7052  switch (Failure) {
7054  // FIXME: Customize for the initialized entity?
7055  if (Args.empty()) {
7056  // Dig out the reference subobject which is uninitialized and diagnose it.
7057  // If this is value-initialization, this could be nested some way within
7058  // the target type.
7059  assert(Kind.getKind() == InitializationKind::IK_Value ||
7060  DestType->isReferenceType());
7061  bool Diagnosed =
7062  DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7063  assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7064  (void)Diagnosed;
7065  } else // FIXME: diagnostic below could be better!
7066  S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
7067  << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
7068  break;
7069 
7070  case FK_ArrayNeedsInitList:
7071  S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
7072  break;
7074  S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7075  break;
7077  S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7078  break;
7080  S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7081  break;
7083  S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7084  break;
7086  S.Diag(Kind.getLocation(),
7087  diag::err_array_init_incompat_wide_string_into_wchar);
7088  break;
7089  case FK_ArrayTypeMismatch:
7091  S.Diag(Kind.getLocation(),
7092  (Failure == FK_ArrayTypeMismatch
7093  ? diag::err_array_init_different_type
7094  : diag::err_array_init_non_constant_array))
7095  << DestType.getNonReferenceType()
7096  << Args[0]->getType()
7097  << Args[0]->getSourceRange();
7098  break;
7099 
7101  S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7102  << Args[0]->getSourceRange();
7103  break;
7104 
7106  DeclAccessPair Found;
7108  DestType.getNonReferenceType(),
7109  true,
7110  Found);
7111  break;
7112  }
7113 
7115  auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7116  S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7117  Args[0]->getLocStart());
7118  break;
7119  }
7120 
7123  switch (FailedOverloadResult) {
7124  case OR_Ambiguous:
7125  if (Failure == FK_UserConversionOverloadFailed)
7126  S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7127  << Args[0]->getType() << DestType
7128  << Args[0]->getSourceRange();
7129  else
7130  S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7131  << DestType << Args[0]->getType()
7132  << Args[0]->getSourceRange();
7133 
7134  FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
7135  break;
7136 
7137  case OR_No_Viable_Function:
7138  if (!S.RequireCompleteType(Kind.getLocation(),
7139  DestType.getNonReferenceType(),
7140  diag::err_typecheck_nonviable_condition_incomplete,
7141  Args[0]->getType(), Args[0]->getSourceRange()))
7142  S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
7143  << (Entity.getKind() == InitializedEntity::EK_Result)
7144  << Args[0]->getType() << Args[0]->getSourceRange()
7145  << DestType.getNonReferenceType();
7146 
7147  FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
7148  break;
7149 
7150  case OR_Deleted: {
7151  S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7152  << Args[0]->getType() << DestType.getNonReferenceType()
7153  << Args[0]->getSourceRange();
7155  OverloadingResult Ovl
7156  = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
7157  true);
7158  if (Ovl == OR_Deleted) {
7159  S.NoteDeletedFunction(Best->Function);
7160  } else {
7161  llvm_unreachable("Inconsistent overload resolution?");
7162  }
7163  break;
7164  }
7165 
7166  case OR_Success:
7167  llvm_unreachable("Conversion did not fail!");
7168  }
7169  break;
7170 
7172  if (isa<InitListExpr>(Args[0])) {
7173  S.Diag(Kind.getLocation(),
7174  diag::err_lvalue_reference_bind_to_initlist)
7176  << DestType.getNonReferenceType()
7177  << Args[0]->getSourceRange();
7178  break;
7179  }
7180  // Intentional fallthrough
7181 
7183  S.Diag(Kind.getLocation(),
7185  ? diag::err_lvalue_reference_bind_to_temporary
7186  : diag::err_lvalue_reference_bind_to_unrelated)
7188  << DestType.getNonReferenceType()
7189  << Args[0]->getType()
7190  << Args[0]->getSourceRange();
7191  break;
7192 
7194  S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
7195  << DestType.getNonReferenceType() << Args[0]->getType()
7196  << Args[0]->getSourceRange();
7197  break;
7198 
7200  QualType SourceType = Args[0]->getType();
7201  QualType NonRefType = DestType.getNonReferenceType();
7202  Qualifiers DroppedQualifiers =
7203  SourceType.getQualifiers() - NonRefType.getQualifiers();
7204 
7205  S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
7206  << SourceType
7207  << NonRefType
7208  << DroppedQualifiers.getCVRQualifiers()
7209  << Args[0]->getSourceRange();
7210  break;
7211  }
7212 
7214  S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7215  << DestType.getNonReferenceType()
7216  << Args[0]->isLValue()
7217  << Args[0]->getType()
7218  << Args[0]->getSourceRange();
7219  emitBadConversionNotes(S, Entity, Args[0]);
7220  break;
7221 
7222  case FK_ConversionFailed: {
7223  QualType FromType = Args[0]->getType();
7224  PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
7225  << (int)Entity.getKind()
7226  << DestType
7227  << Args[0]->isLValue()
7228  << FromType
7229  << Args[0]->getSourceRange();
7230  S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7231  S.Diag(Kind.getLocation(), PDiag);
7232  emitBadConversionNotes(S, Entity, Args[0]);
7233  break;
7234  }
7235 
7237  // No-op. This error has already been reported.
7238  break;
7239 
7240  case FK_TooManyInitsForScalar: {
7241  SourceRange R;
7242 
7243  auto *InitList = dyn_cast<InitListExpr>(Args[0]);
7244  if (InitList && InitList->getNumInits() >= 1) {
7245  R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
7246  } else {
7247  assert(Args.size() > 1 && "Expected multiple initializers!");
7248  R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
7249  }
7250 
7252  if (Kind.isCStyleOrFunctionalCast())
7253  S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7254  << R;
7255  else
7256  S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7257  << /*scalar=*/2 << R;
7258  break;
7259  }
7260 
7262  S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7263  << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7264  break;
7265 
7267  S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7268  << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7269  break;
7270 
7273  SourceRange ArgsRange;
7274  if (Args.size())
7275  ArgsRange = SourceRange(Args.front()->getLocStart(),
7276  Args.back()->getLocEnd());
7277 
7278  if (Failure == FK_ListConstructorOverloadFailed) {
7279  assert(Args.size() == 1 &&
7280  "List construction from other than 1 argument.");
7281  InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7282  Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
7283  }
7284 
7285  // FIXME: Using "DestType" for the entity we're printing is probably
7286  // bad.
7287  switch (FailedOverloadResult) {
7288  case OR_Ambiguous:
7289  S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7290  << DestType << ArgsRange;
7291  FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
7292  break;
7293 
7294  case OR_No_Viable_Function:
7295  if (Kind.getKind() == InitializationKind::IK_Default &&
7296  (Entity.getKind() == InitializedEntity::EK_Base ||
7297  Entity.getKind() == InitializedEntity::EK_Member) &&
7298  isa<CXXConstructorDecl>(S.CurContext)) {
7299  // This is implicit default initialization of a member or
7300  // base within a constructor. If no viable function was
7301  // found, notify the user that they need to explicitly
7302  // initialize this base/member.
7303  CXXConstructorDecl *Constructor
7304  = cast<CXXConstructorDecl>(S.CurContext);
7305  const CXXRecordDecl *InheritedFrom = nullptr;
7306  if (auto Inherited = Constructor->getInheritedConstructor())
7307  InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
7308  if (Entity.getKind() == InitializedEntity::EK_Base) {
7309  S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
7310  << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
7311  << S.Context.getTypeDeclType(Constructor->getParent())
7312  << /*base=*/0
7313  << Entity.getType()
7314  << InheritedFrom;
7315 
7316  RecordDecl *BaseDecl
7317  = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7318  ->getDecl();
7319  S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7320  << S.Context.getTagDeclType(BaseDecl);
7321  } else {
7322  S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
7323  << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
7324  << S.Context.getTypeDeclType(Constructor->getParent())
7325  << /*member=*/1
7326  << Entity.getName()
7327  << InheritedFrom;
7328  S.Diag(Entity.getDecl()->getLocation(),
7329  diag::note_member_declared_at);
7330 
7331  if (const RecordType *Record
7332  = Entity.getType()->getAs<RecordType>())
7333  S.Diag(Record->getDecl()->getLocation(),
7334  diag::note_previous_decl)
7335  << S.Context.getTagDeclType(Record->getDecl());
7336  }
7337  break;
7338  }
7339 
7340  S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7341  << DestType << ArgsRange;
7342  FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
7343  break;
7344 
7345  case OR_Deleted: {
7347  OverloadingResult Ovl
7348  = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7349  if (Ovl != OR_Deleted) {
7350  S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7351  << true << DestType << ArgsRange;
7352  llvm_unreachable("Inconsistent overload resolution?");
7353  break;
7354  }
7355 
7356  // If this is a defaulted or implicitly-declared function, then
7357  // it was implicitly deleted. Make it clear that the deletion was
7358  // implicit.
7359  if (S.isImplicitlyDeleted(Best->Function))
7360  S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
7361  << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
7362  << DestType << ArgsRange;
7363  else
7364  S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7365  << true << DestType << ArgsRange;
7366 
7367  S.NoteDeletedFunction(Best->Function);
7368  break;
7369  }
7370 
7371  case OR_Success:
7372  llvm_unreachable("Conversion did not fail!");
7373  }
7374  }
7375  break;
7376 
7377  case FK_DefaultInitOfConst:
7378  if (Entity.getKind() == InitializedEntity::EK_Member &&
7379  isa<CXXConstructorDecl>(S.CurContext)) {
7380  // This is implicit default-initialization of a const member in
7381  // a constructor. Complain that it needs to be explicitly
7382  // initialized.
7383  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7384  S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
7385  << (Constructor->getInheritedConstructor() ? 2 :
7386  Constructor->isImplicit() ? 1 : 0)
7387  << S.Context.getTypeDeclType(Constructor->getParent())
7388  << /*const=*/1
7389  << Entity.getName();
7390  S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7391  << Entity.getName();
7392  } else {
7393  S.Diag(Kind.getLocation(), diag::err_default_init_const)
7394  << DestType << (bool)DestType->getAs<RecordType>();
7395  }
7396  break;
7397 
7398  case FK_Incomplete:
7399  S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
7400  diag::err_init_incomplete_type);
7401  break;
7402 
7404  // Run the init list checker again to emit diagnostics.
7405  InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7406  diagnoseListInit(S, Entity, InitList);
7407  break;
7408  }
7409 
7410  case FK_PlaceholderType: {
7411  // FIXME: Already diagnosed!
7412  break;
7413  }
7414 
7415  case FK_ExplicitConstructor: {
7416  S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7417  << Args[0]->getSourceRange();
7419  OverloadingResult Ovl
7420  = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7421  (void)Ovl;
7422  assert(Ovl == OR_Success && "Inconsistent overload resolution");
7423  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
7424  S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
7425  break;
7426  }
7427  }
7428 
7429  PrintInitLocationNote(S, Entity);
7430  return true;
7431 }
7432 
7433 void InitializationSequence::dump(raw_ostream &OS) const {
7434  switch (SequenceKind) {
7435  case FailedSequence: {
7436  OS << "Failed sequence: ";
7437  switch (Failure) {
7439  OS << "too many initializers for reference";
7440  break;
7441 
7442  case FK_ArrayNeedsInitList:
7443  OS << "array requires initializer list";
7444  break;
7445 
7447  OS << "address of unaddressable function was taken";
7448  break;
7449 
7451  OS << "array requires initializer list or string literal";
7452  break;
7453 
7455  OS << "array requires initializer list or wide string literal";
7456  break;
7457 
7459  OS << "narrow string into wide char array";
7460  break;
7461 
7463  OS << "wide string into char array";
7464  break;
7465 
7467  OS << "incompatible wide string into wide char array";
7468  break;
7469 
7470  case FK_ArrayTypeMismatch:
7471  OS << "array type mismatch";
7472  break;
7473 
7475  OS << "non-constant array initializer";
7476  break;
7477 
7479  OS << "address of overloaded function failed";
7480  break;
7481 
7483  OS << "overload resolution for reference initialization failed";
7484  break;
7485 
7487  OS << "non-const lvalue reference bound to temporary";
7488  break;
7489 
7491  OS << "non-const lvalue reference bound to unrelated type";
7492  break;
7493 
7495  OS << "rvalue reference bound to an lvalue";
7496  break;
7497 
7499  OS << "reference initialization drops qualifiers";
7500  break;
7501 
7503  OS << "reference initialization failed";
7504  break;
7505 
7506  case FK_ConversionFailed:
7507  OS << "conversion failed";
7508  break;
7509 
7511  OS << "conversion from property failed";
7512  break;
7513 
7515  OS << "too many initializers for scalar";
7516  break;
7517 
7519  OS << "referencing binding to initializer list";
7520  break;
7521 
7523  OS << "initializer list for non-aggregate, non-scalar type";
7524  break;
7525 
7527  OS << "overloading failed for user-defined conversion";
7528  break;
7529 
7531  OS << "constructor overloading failed";
7532  break;
7533 
7534  case FK_DefaultInitOfConst:
7535  OS << "default initialization of a const variable";
7536  break;
7537 
7538  case FK_Incomplete:
7539  OS << "initialization of incomplete type";
7540  break;
7541 
7543  OS << "list initialization checker failure";
7544  break;
7545 
7547  OS << "variable length array has an initializer";
7548  break;
7549 
7550  case FK_PlaceholderType:
7551  OS << "initializer expression isn't contextually valid";
7552  break;
7553 
7555  OS << "list constructor overloading failed";
7556  break;
7557 
7559  OS << "list copy initialization chose explicit constructor";
7560  break;
7561  }
7562  OS << '\n';
7563  return;
7564  }
7565 
7566  case DependentSequence:
7567  OS << "Dependent sequence\n";
7568  return;
7569 
7570  case NormalSequence:
7571  OS << "Normal sequence: ";
7572  break;
7573  }
7574 
7575  for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7576  if (S != step_begin()) {
7577  OS << " -> ";
7578  }
7579 
7580  switch (S->Kind) {
7582  OS << "resolve address of overloaded function";
7583  break;
7584 
7586  OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7587  break;
7588 
7590  OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7591  break;
7592 
7594  OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7595  break;
7596 
7597  case SK_BindReference:
7598  OS << "bind reference to lvalue";
7599  break;
7600 
7602  OS << "bind reference to a temporary";
7603  break;
7604 
7606  OS << "extraneous C++03 copy to temporary";
7607  break;
7608 
7609  case SK_UserConversion:
7610  OS << "user-defined conversion via " << *S->Function.Function;
7611  break;
7612 
7614  OS << "qualification conversion (rvalue)";
7615  break;
7616 
7618  OS << "qualification conversion (xvalue)";
7619  break;
7620 
7622  OS << "qualification conversion (lvalue)";
7623  break;
7624 
7625  case SK_AtomicConversion:
7626  OS << "non-atomic-to-atomic conversion";
7627  break;
7628 
7629  case SK_LValueToRValue:
7630  OS << "load (lvalue to rvalue)";
7631  break;
7632 
7633  case SK_ConversionSequence:
7634  OS << "implicit conversion sequence (";
7635  S->ICS->dump(); // FIXME: use OS
7636  OS << ")";
7637  break;
7638 
7640  OS << "implicit conversion sequence with narrowing prohibited (";
7641  S->ICS->dump(); // FIXME: use OS
7642  OS << ")";
7643  break;
7644 
7645  case SK_ListInitialization:
7646  OS << "list aggregate initialization";
7647  break;
7648 
7649  case SK_UnwrapInitList:
7650  OS << "unwrap reference initializer list";
7651  break;
7652 
7653  case SK_RewrapInitList:
7654  OS << "rewrap reference initializer list";
7655  break;
7656 
7658  OS << "constructor initialization";
7659  break;
7660 
7662  OS << "list initialization via constructor";
7663  break;
7664 
7665  case SK_ZeroInitialization:
7666  OS << "zero initialization";
7667  break;
7668 
7669  case SK_CAssignment:
7670  OS << "C assignment";
7671  break;
7672 
7673  case SK_StringInit:
7674  OS << "string initialization";
7675  break;
7676 
7678  OS << "Objective-C object conversion";
7679  break;
7680 
7681  case SK_ArrayInit:
7682  OS << "array initialization";
7683  break;
7684 
7686  OS << "parenthesized array initialization";
7687  break;
7688 
7690  OS << "pass by indirect copy and restore";
7691  break;
7692 
7694  OS << "pass by indirect restore";
7695  break;
7696 
7697  case SK_ProduceObjCObject:
7698  OS << "Objective-C object retension";
7699  break;
7700 
7701  case SK_StdInitializerList:
7702  OS << "std::initializer_list from initializer list";
7703  break;
7704 
7706  OS << "list initialization from std::initializer_list";
7707  break;
7708 
7709  case SK_OCLSamplerInit:
7710  OS << "OpenCL sampler_t from integer constant";
7711  break;
7712 
7713  case SK_OCLZeroEvent:
7714  OS << "OpenCL event_t from zero";
7715  break;
7716  }
7717 
7718  OS << " [" << S->Type.getAsString() << ']';
7719  }
7720 
7721  OS << '\n';
7722 }
7723 
7725  dump(llvm::errs());
7726 }
7727 
7729  const ImplicitConversionSequence &ICS,
7730  QualType PreNarrowingType,
7731  QualType EntityType,
7732  const Expr *PostInit) {
7733  const StandardConversionSequence *SCS = nullptr;
7734  switch (ICS.getKind()) {
7736  SCS = &ICS.Standard;
7737  break;
7739  SCS = &ICS.UserDefined.After;
7740  break;
7744  return;
7745  }
7746 
7747  // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7748  APValue ConstantValue;
7749  QualType ConstantType;
7750  switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7751  ConstantType)) {
7752  case NK_Not_Narrowing:
7753  // No narrowing occurred.
7754  return;
7755 
7756  case NK_Type_Narrowing:
7757  // This was a floating-to-integer conversion, which is always considered a
7758  // narrowing conversion even if the value is a constant and can be
7759  // represented exactly as an integer.
7760  S.Diag(PostInit->getLocStart(),
7761  (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7762  ? diag::warn_init_list_type_narrowing
7763  : diag::ext_init_list_type_narrowing)
7764  << PostInit->getSourceRange()
7765  << PreNarrowingType.getLocalUnqualifiedType()
7766  << EntityType.getLocalUnqualifiedType();
7767  break;
7768 
7769  case NK_Constant_Narrowing:
7770  // A constant value was narrowed.
7771  S.Diag(PostInit->getLocStart(),
7772  (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7773  ? diag::warn_init_list_constant_narrowing
7774  : diag::ext_init_list_constant_narrowing)
7775  << PostInit->getSourceRange()
7776  << ConstantValue.getAsString(S.getASTContext(), ConstantType)
7777  << EntityType.getLocalUnqualifiedType();
7778  break;
7779 
7780  case NK_Variable_Narrowing:
7781  // A variable's value may have been narrowed.
7782  S.Diag(PostInit->getLocStart(),
7783  (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7784  ? diag::warn_init_list_variable_narrowing
7785  : diag::ext_init_list_variable_narrowing)
7786  << PostInit->getSourceRange()
7787  << PreNarrowingType.getLocalUnqualifiedType()
7788  << EntityType.getLocalUnqualifiedType();
7789  break;
7790  }
7791 
7792  SmallString<128> StaticCast;
7793  llvm::raw_svector_ostream OS(StaticCast);
7794  OS << "static_cast<";
7795  if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7796  // It's important to use the typedef's name if there is one so that the
7797  // fixit doesn't break code using types like int64_t.
7798  //
7799  // FIXME: This will break if the typedef requires qualification. But
7800  // getQualifiedNameAsString() includes non-machine-parsable components.
7801  OS << *TT->getDecl();
7802  } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
7803  OS << BT->getName(S.getLangOpts());
7804  else {
7805  // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7806  // with a broken cast.
7807  return;
7808  }
7809  OS << ">(";
7810  S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
7811  << PostInit->getSourceRange()
7812  << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7814  S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
7815 }
7816 
7817 //===----------------------------------------------------------------------===//
7818 // Initialization helper functions
7819 //===----------------------------------------------------------------------===//
7820 bool
7822  ExprResult Init) {
7823  if (Init.isInvalid())
7824  return false;
7825 
7826  Expr *InitE = Init.get();
7827  assert(InitE && "No initialization expression");
7828 
7829  InitializationKind Kind
7830  = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
7831  InitializationSequence Seq(*this, Entity, Kind, InitE);
7832  return !Seq.Failed();
7833 }
7834 
7835 ExprResult
7837  SourceLocation EqualLoc,
7838  ExprResult Init,
7839  bool TopLevelOfInitList,
7840  bool AllowExplicit) {
7841  if (Init.isInvalid())
7842  return ExprError();
7843 
7844  Expr *InitE = Init.get();
7845  assert(InitE && "No initialization expression?");
7846 
7847  if (EqualLoc.isInvalid())
7848  EqualLoc = InitE->getLocStart();
7849 
7850  InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
7851  EqualLoc,
7852  AllowExplicit);
7853  InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
7854 
7855  ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
7856 
7857  return Result;
7858 }
unsigned getNumElements() const
Definition: Type.h:2781
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition: ExprObjC.h:1464
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
llvm::iterator_range< base_class_iterator > base_class_range
Definition: DeclCXX.h:714
Represents a single C99 designator.
Definition: Expr.h:4028
Perform a derived-to-base cast, producing an lvalue.
Defines the clang::ASTContext interface.
unsigned getNumInits() const
Definition: Expr.h:3776
SourceLocation getEnd() const
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
static bool performReferenceExtension(Expr *Init, const InitializedEntity *ExtendingEntity)
Update a glvalue expression that is used as the initializer of a reference to note that its lifetime ...
Definition: SemaInit.cpp:5936
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1561
InitListExpr * WrappingSyntacticList
When Kind = SK_RewrapInitList, the syntactic form of the wrapping list.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchers.h:1367
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
iterator begin() const
Definition: DeclBase.h:1103
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:7044
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition: Decl.h:2538
void SetZeroInitializationFixit(const std::string &Fixit, SourceLocation L)
Call for initializations are invalid but that would be valid zero initialzations if Fixit was applied...
A (possibly-)qualified type.
Definition: Type.h:598
bool isConstantArrayType() const
Definition: Type.h:5524
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:208
DesignatorKind getKind() const
Definition: Designator.h:69
Simple class containing the result of Sema::CorrectTypo.
base_class_range bases()
Definition: DeclCXX.h:718
bool isInvalid() const
Definition: Ownership.h:160
unsigned Index
When Kind == EK_ArrayElement, EK_VectorElement, or EK_ComplexElement, the index of the array or vecto...
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
bool isMacroID() const
bool isCharType() const
Definition: Type.cpp:1656
step_iterator step_end() const
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2217
void setFromType(QualType T)
Definition: Overload.h:204
Produce an Objective-C object pointer.
A cast other than a C-style cast.
Definition: Sema.h:8507
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1032
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2045
void AddOCLZeroEventStep(QualType T)
Add a step to initialize an OpenCL event_t from a NULL constant.
Definition: SemaInit.cpp:3313
Initializing char array with wide string literal.
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:254
Perform an implicit conversion sequence without narrowing.
An initialization that "converts" an Objective-C object (not a point to an object) to another Objecti...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
Definition: SemaInit.cpp:4733
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:6107
static ExprResult CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value)
Check that the given Index expression is a valid array designator value.
Definition: SemaInit.cpp:2736
CanQualType Char32Ty
Definition: ASTContext.h:900
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2615
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1693
const LangOptions & getLangOpts() const
Definition: Sema.h:1062
static void TryReferenceInitializationCore(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, QualType cv1T1, QualType T1, Qualifiers T1Quals, QualType cv2T2, QualType T2, Qualifiers T2Quals, InitializationSequence &Sequence)
Reference initialization without resolving overloaded functions.
Definition: SemaInit.cpp:4200
Perform a qualification conversion, producing an rvalue.
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1281
SmallVectorImpl< Step >::const_iterator step_iterator
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Expr * getInit() const
Retrieve the initializer value.
Definition: Expr.h:4184
ActionResult< Expr * > ExprResult
Definition: Ownership.h:253
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:4499
std::set< Replacement > Replacements
A set of Replacements.
Definition: Replacement.h:148
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
Definition: SemaInit.cpp:1973
bool isRecordType() const
Definition: Type.h:5539
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:419
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:810
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1139
unsigned size() const
Returns the number of designators in this initializer.
Definition: Expr.h:4153
uintptr_t Base
When Kind == EK_Base, the base specifier that provides the base class.
void setType(QualType t)
Definition: Expr.h:127
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:8618
Not a narrowing conversion.
Definition: Overload.h:110
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions()
Get all conversion functions visible in current class, including conversion function templates...
Definition: DeclCXX.cpp:1238
bool hasFlexibleArrayMember() const
Definition: Decl.h:3305
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1619
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:7821
std::string getAsString() const
Definition: Type.h:924
PtrTy get() const
Definition: Ownership.h:164
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
The base class of the type hierarchy.
Definition: Type.h:1281
SourceLocation getEqualLoc() const
Retrieve the location of the equal sign for copy initialization (if present).
static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer)
Definition: SemaInit.cpp:4837
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2120
The entity being initialized is a variable.
InitListExpr * getSyntacticForm() const
Definition: Expr.h:3882
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2456
const Expr * getInit() const
Definition: Decl.h:1139
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:471
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1162
Overloading for a user-defined conversion failed.
Ambiguous candidates found.
Definition: Overload.h:43
A container of type source information.
Definition: Decl.h:62
void AddAddressOverloadResolutionStep(FunctionDecl *Function, DeclAccessPair Found, bool HadMultipleCandidates)
Add a new step in the initialization that resolves the address of an overloaded function to a specifi...
Definition: SemaInit.cpp:3121
Perform a derived-to-base cast, producing an xvalue.
The entity being initialized is a base member subobject.
bool isFunctionalCast() const
Determine whether this is a functional-style cast.
List-copy-initialization chose an explicit constructor.
static bool TryInitializerListConstruction(Sema &S, InitListExpr *List, QualType DestType, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
When initializing from init list via constructor, handle initialization of an object of type std::ini...
Definition: SemaInit.cpp:3407
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2187
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:2802
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:3962
bool isSpelledAsLValue() const
Definition: Type.h:2336
SourceLocation getDotLoc() const
Definition: Designator.h:79
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3)
Definition: SemaExpr.cpp:12949
const llvm::APInt & getSize() const
Definition: Type.h:2527
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
The entity being initialized is a function parameter; function is member of group of audited CF APIs...
static const InitializedEntity * getEntityForTemporaryLifetimeExtension(const InitializedEntity *Entity, const InitializedEntity *FallbackDecl=nullptr)
Determine the declaration which an initialized entity ultimately refers to, for the purpose of lifeti...
Definition: SemaInit.cpp:5858
Initialize an OpenCL sampler from an integer.
EntityKind getKind() const
Determine the kind of initialization.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
Definition: SemaInit.cpp:2874
static void LookupCopyAndMoveConstructors(Sema &S, OverloadCandidateSet &CandidateSet, CXXRecordDecl *Class, Expr *CurInitExpr)
Look for copy and move constructors and constructor templates, for copying an object via direct-initi...
Definition: SemaInit.cpp:5345
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:768
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:4564
void AddCAssignmentStep(QualType T)
Add a C assignment step.
Definition: SemaInit.cpp:3248
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:446
DiagnosticsEngine & Diags
Definition: Sema.h:301
const Expr * getCallee() const
Definition: Expr.h:2188
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, ASTContext &Context)
Check whether the array of type AT can be initialized by the Init expression by means of string initi...
Definition: SemaInit.cpp:60
static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, SourceRange Braces)
Warn that Entity was of scalar type and was initialized by a single-element braced initializer list...
Definition: SemaInit.cpp:892
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SourceRange getParenRange() const
Retrieve the source range containing the locations of the open and closing parentheses for value and ...
SourceLocation getLBracketLoc() const
Definition: Designator.h:103
field_iterator field_begin() const
Definition: Decl.cpp:3767
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:1793
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1813
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:3795
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:724
Non-const lvalue reference binding to an lvalue of unrelated type.
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:533
step_iterator step_begin() const
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:1883
SourceLocation getThrowLoc() const
Determine the location of the 'throw' keyword when initializing an exception object.
void setBegin(SourceLocation b)
Perform a derived-to-base cast, producing an rvalue.
void AddReferenceBindingStep(QualType T, bool BindingTemporary)
Add a new step binding a reference to an object.
Definition: SemaInit.cpp:3145
static InitializationKind CreateDirectList(SourceLocation InitLoc)
bool allowsNRVO() const
Determine whether this initialization allows the named return value optimization, which also applies ...
Definition: SemaInit.cpp:2951
void setElementIndex(unsigned Index)
If this is already the initializer for an array or vector element, sets the element index...
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1377
The entity being initialized is a temporary object.
bool isObjCRetainableType() const
Definition: Type.cpp:3699
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3132
Defines the clang::Expr interface and subclasses for C++ expressions.
bool isUnionType() const
Definition: Type.cpp:391
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:3641
bool isVoidType() const
Definition: Type.h:5680
bool allowExplicitConversionFunctionsInRefBinding() const
Retrieve whether this initialization allows the use of explicit conversion functions when binding a r...
bool isLValue() const
Definition: Expr.h:348
The collection of all-type qualifiers we support.
Definition: Type.h:117
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
Definition: SemaInit.cpp:6078
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3289
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit=false)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType...
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:2777
Expr * FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3253
Represents a C99 designated initializer expression.
Definition: Expr.h:3953
Construct a std::initializer_list from an initializer list.
Trying to take the address of a function that doesn't support having its address taken.
One of these records is kept for each identifier that is lexed.
static void CheckForNullPointerDereference(Sema &S, const Expr *E)
Definition: SemaInit.cpp:6177
bool isScalarType() const
Definition: Type.h:5715
Expr * getSubExpr(unsigned Idx) const
Definition: Expr.h:4198
Step
Definition: OpenMPClause.h:313
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
Definition: SemaInit.cpp:4930
void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic)
Add steps to unwrap a initializer list for a reference around a single element and rewrap it at the e...
Definition: SemaInit.cpp:3320
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init.ref]).
Definition: SemaInit.cpp:3067
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:92
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1067
A C-style cast.
Definition: Sema.h:8503
ImplicitConversionSequence * ICS
When Kind = SK_ConversionSequence, the implicit conversion sequence.
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isReferenceType() const
Definition: Type.h:5491
DeclaratorDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
Definition: SemaInit.cpp:2922
QualType getReturnType() const
Definition: Decl.h:2034
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size...
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2293
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:899
Represents a place-holder for an object not to be initialized by anything.
Definition: Expr.h:4240
SourceLocation getReturnLoc() const
Determine the location of the 'return' keyword when initializing the result of a function call...
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
static bool isLibstdcxxPointerReturnFalseHack(Sema &S, const InitializedEntity &Entity, const Expr *Init)
An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, a function with a pointer r...
Definition: SemaInit.cpp:4721
bool isPRValue() const
Definition: Expr.h:351
static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity, const Expr *Init, bool IsInitializerList, const ValueDecl *ExtendingDecl)
Definition: SemaInit.cpp:6038
Rewrap the single-element initializer list for a reference.
unsigned getCVRQualifiers() const
Definition: Type.h:258
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:1982
void AddOCLSamplerInitStep(QualType T)
Add a step to initialize an OpenCL sampler from an integer constant.
Definition: SemaInit.cpp:3306
TypeSourceInfo * getTypeSourceInfo() const
Retrieve complete type-source information for the object being constructed, if known.
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible...
Definition: Sema.h:8856
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition: Expr.cpp:3330
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
Definition: SemaInit.cpp:3335
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1199
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2007
SourceLocation getRParenLoc() const
Definition: Expr.h:2284
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:205
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:105
Perform initialization via a constructor taking a single std::initializer_list argument.
static bool shouldDestroyTemporary(const InitializedEntity &Entity)
Whether the given entity, when initialized with an object created for that initialization, requires destruction.
Definition: SemaInit.cpp:5316
Describes an C or C++ initializer list.
Definition: Expr.h:3746
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:52
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2383
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1452
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:588
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:317
static void ExpandAnonymousFieldDesignator(Sema &SemaRef, DesignatedInitExpr *DIE, unsigned DesigIdx, IndirectFieldDecl *IndirectField)
Expand a field designator that refers to a member of an anonymous struct or union into a series of fi...
Definition: SemaInit.cpp:1945
const LangOptions & getLangOpts() const
Definition: ASTContext.h:604
StepKind Kind
The kind of conversion or initialization step we are taking.
SourceRange getRange() const
Retrieve the source range that covers the initialization.
Succeeded, but refers to a deleted function.
Definition: Overload.h:44
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, bool &DerivedToBase, bool &ObjCConversion, bool &ObjCLifetimeConversion)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
Ref_Compatible - The two types are reference-compatible and have equivalent qualifiers (cv1 == cv2)...
Definition: Sema.h:8868
unsigned getMinRequiredArguments() const
getMinRequiredArguments - Returns the minimum number of arguments needed to call this function...
Definition: Decl.cpp:2785
OverloadCandidateSet & getFailedCandidateSet()
Retrieve a reference to the candidate set when overload resolution fails.
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:1838
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:1853
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:114
field_range fields() const
Definition: Decl.h:3382
InitializationSequence(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList=false, bool TreatUnavailableAsInvalid=true)
Try to perform initialization of the given entity, creating a record of the steps required to perform...
Definition: SemaInit.cpp:4917
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3718
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition: Expr.cpp:54
SourceLocation getRBraceLoc() const
Definition: Expr.h:3875
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:147
Variable-length array must not have an initializer.
RecordDecl * getDecl() const
Definition: Type.h:3716
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion, integral conversion, floating point conversion, floating-integral conversion, pointer conversion, pointer-to-member conversion, or boolean conversion.
Definition: Overload.h:142
Initialization of an incomplete type.
The entity being initialized is a non-static data member subobject.
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:8499
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1746
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:116
Unwrap the single-element initializer list for a reference.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over...
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
Definition: SemaInit.cpp:3276
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2326
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:6208
chain_iterator chain_begin() const
Definition: Decl.h:2543
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1039
The entity being initialized is an element of a vector.
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3071
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2632
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1892
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1119
bool hasConst() const
Definition: Type.h:236
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
iterator end() const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:727
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Definition: SemaExpr.cpp:7677
Perform initialization via a constructor.
Perform a user-defined conversion, either via a conversion function or via a constructor.
bool isExtVectorType() const
Definition: Type.h:5551
detail::InMemoryDirectory::const_iterator I
The entity being initialized is a function parameter.
QualType getType() const
Definition: Decl.h:599
bool isInvalid() const
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:2367
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
Definition: SemaInit.cpp:7008
field_iterator field_end() const
Definition: Decl.h:3385
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:5835
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
bool isUnion() const
Definition: Decl.h:2939
Perform an implicit conversion sequence.
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3170
CXXConstructorDecl * getCanonicalDecl() override
Definition: DeclCXX.h:2388
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:263
void setField(FieldDecl *FD)
Definition: Expr.h:4090
Overloading for list-initialization by constructor failed.
Perform list-initialization without a constructor.
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
IdentifierInfo * getFieldName() const
Definition: Expr.cpp:3512
A functional-style cast.
Definition: Sema.h:8505
void AddObjCObjectConversionStep(QualType T)
Add an Objective-C object conversion step, which is always a no-op.
Definition: SemaInit.cpp:3262
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1009
Cannot resolve the address of an overloaded function.
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL...
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:646
CastKind
CastKind - The kind of operation required for a conversion.
The return type of classify().
Definition: Expr.h:299
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
Definition: SemaInit.cpp:3299
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a member subobject.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1652
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
NamedDecl * getDecl() const
ASTContext * Context
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:113
The entity being initialized is a field of block descriptor for the copied-in c++ object...
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
bool hasVolatile() const
Definition: Type.h:243
SourceLocation getEllipsisLoc() const
Definition: Designator.h:121
int * Depth
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Initializing wide char array with incompatible wide string literal.
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2383
The entity being initialized is the real or imaginary part of a complex number.
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type...
Definition: ExprCXX.h:1764
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:1909
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:4129
llvm::MutableArrayRef< Designator > designators()
Definition: Expr.h:4156
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:590
Expr - This represents one expression.
Definition: Expr.h:105
void setRBraceLoc(SourceLocation Loc)
Definition: Expr.h:3876
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:3622
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:102
bool isAnyComplexType() const
Definition: Type.h:5545
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4006
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion...
Definition: Overload.h:269
static void updateStringLiteralType(Expr *E, QualType Ty)
Update the type of a string literal, including any surrounding parentheses, to match the type of the ...
Definition: SemaInit.cpp:134
uintptr_t Parameter
When Kind == EK_Parameter, the ParmVarDecl, with the low bit indicating whether the parameter is "con...
The entity being initialized is an object (or array of objects) allocated via new.
Perform a qualification conversion, producing an xvalue.
void setSyntacticForm(InitListExpr *Init)
Definition: Expr.h:3886
Represents a C++ functional cast expression that builds a temporary object.
Definition: ExprCXX.h:1454
SourceLocation getLBraceLoc() const
Definition: Expr.h:3873
static void performLifetimeExtension(Expr *Init, const InitializedEntity *ExtendingEntity)
Update a prvalue expression that is going to be materialized as a lifetime-extended temporary...
Definition: SemaInit.cpp:5982
bool isAtomicType() const
Definition: Type.h:5564
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2414
Initializing a wide char array with narrow string literal.
void ClearExprs(Sema &Actions)
ClearExprs - Null out any expression references, which prevents them from being 'delete'd later...
Definition: Designator.h:201
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
Definition: SemaInit.cpp:3292
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:750
Passing zero to a function where OpenCL event_t is expected.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:12635
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:1851
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2011
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition: Expr.h:4175
bool isInitListConstructor(const CXXConstructorDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init.list]p2.
Resolve the address of an overloaded function to a specific function declaration. ...
Expr * getArrayRangeStart(const Designator &D) const
Definition: Expr.cpp:3646
Overload resolution succeeded.
Definition: Overload.h:41
void AddArrayInitStep(QualType T)
Add an array initialization step.
Definition: SemaInit.cpp:3269
The entity being initialized is an exception object that is being thrown.
bool isFloatingType() const
Definition: Type.cpp:1783
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:12391
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:14955
struct F Function
When Kind == SK_ResolvedOverloadedFunction or Kind == SK_UserConversion, the function that the expres...
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:373
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8860
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition: Sema.h:8853
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:6826
Defines the clang::TypeLoc interface and its subclasses.
Floating-integral conversions (C++ 4.9)
Definition: Overload.h:73
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:692
bool isExplicit() const
Determine whether this constructor was marked "explicit" or not.
Definition: DeclCXX.h:2238
ObjCMethodDecl * getMethodDecl() const
Retrieve the ObjectiveC method being initialized.
void NoteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation())
PrintOverloadCandidates - When overload resolution fails, prints diagnostic messages containing the c...
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1774
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:418
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence...
Definition: Overload.h:415
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
Definition: SemaInit.cpp:4524
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
Initializer has a placeholder type which cannot be resolved by initialization.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1668
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Definition: Sema.h:6732
Represents a GCC generic vector type.
Definition: Type.h:2756
static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence)
Attempt reference initialization (C++0x [dcl.init.ref])
Definition: SemaInit.cpp:4124
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2366
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
class LLVM_ALIGNAS(8) TemplateSpecializationType unsigned NumArgs
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4154
const IdentifierInfo * getField() const
Definition: Designator.h:74
FailureKind getFailureKind() const
Determine why initialization failed.
ValueDecl * getDecl()
Definition: Expr.h:1017
bool isGLValue() const
Definition: Expr.h:250
QualType getElementType() const
Definition: Type.h:2780
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2461
void AddStringInitStep(QualType T)
Add a string init step.
Definition: SemaInit.cpp:3255
The result type of a method or function.
InitKind getKind() const
Determine the initialization kind.
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
Definition: opencl-c.h:75
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1346
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
Definition: SemaInit.cpp:3241
bool hasUninitializedReferenceMember() const
Whether this class or any of its subobjects has any members of reference type which would make value-...
Definition: DeclCXX.h:1122
static void TryReferenceListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization of a reference.
Definition: SemaInit.cpp:3676
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression, including the actual initialized value and any expressions that occur within array and array-range designators.
Definition: Expr.h:4196
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
InitListExpr * getUpdater() const
Definition: Expr.h:4295
FailureKind
Describes why initialization failed.
A narrowing conversion, because a non-constant-expression variable might have got narrowed...
Definition: Overload.h:120
bool isArrayRangeDesignator() const
Definition: Expr.h:4078
Lvalue-to-rvalue conversion (C++ 4.1)
Definition: Overload.h:62
List initialization failed at some point.
Perform a conversion adding _Atomic to a type.
void AddListInitializationStep(QualType T)
Add a list-initialization step.
Definition: SemaInit.cpp:3220
SourceLocation getDotLoc() const
Definition: Expr.h:4095
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
CanQualType OverloadTy
Definition: ASTContext.h:909
void ExpandDesignator(const ASTContext &C, unsigned Idx, const Designator *First, const Designator *Last)
Replaces the designator at index Idx with the series of designators in [First, Last).
Definition: Expr.cpp:3660
Perform a qualification conversion, producing an lvalue.
Integral conversions (C++ 4.7)
Definition: Overload.h:70
void AddLValueToRValueStep(QualType Ty)
Add a new step that performs a load of the given type.
Definition: SemaInit.cpp:3200
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor...
Kind
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:376
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5730
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:3652
SequenceKind
Describes the kind of initialization sequence computed.
Encodes a location in the source.
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2742
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3733
Reference initialization from an initializer list.
QualType getElementType() const
Definition: Type.h:2131
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:1561
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity...
Definition: SemaInit.cpp:5287
SourceLocation getLocation() const
Retrieve the location at which initialization is occurring.
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:12337
SourceLocation getCaptureLoc() const
Determine the location of the capture when initializing field from a captured variable in a lambda...
bool isValid() const
Return true if this is a valid SourceLocation object.
Expr * getArrayRangeStart() const
Definition: Designator.h:94
FieldDecl * getField() const
Definition: Expr.h:4082
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
ASTContext & getASTContext() const
Definition: Sema.h:1069
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1141
VectorKind getVectorKind() const
Definition: Type.h:2789
StringInitFailureKind
Definition: SemaInit.cpp:48
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition: Overload.h:40
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
QualType withConst() const
Definition: Type.h:764
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
Definition: SemaInit.cpp:4736
bool isExplicitCast() const
Determine whether this initialization is an explicit cast.
const Designator & getDesignator(unsigned Idx) const
Definition: Designator.h:194
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit)
Adds a conversion function template specialization candidate to the overload set, using template argu...
const InitializedEntity * getParent() const
Retrieve the parent of the entity being initialized, when the initialization itself is occurring with...
Initialization of some unused destination type with an initializer list.
The entity being initialized is the result of a function call.
void InitializeFrom(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
Definition: SemaInit.cpp:4939
SourceLocation getLBracketLoc() const
Definition: Expr.h:4105
Objective-C ARC writeback conversion.
Definition: Overload.h:84
The entity being implicitly initialized back to the formal result type.
SourceLocation getRBracketLoc() const
Definition: Designator.h:112
The entity being initialized is the initializer for a compound literal.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2114
Ref_Compatible_With_Added_Qualification - The two types are reference-compatible with added qualifica...
Definition: Sema.h:8865
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
void AddExtraneousCopyToTemporary(QualType T)
Add a new step that makes an extraneous copy of the input to a temporary of the same class type...
Definition: SemaInit.cpp:3153
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:696
CanQualType VoidTy
Definition: ASTContext.h:893
Expr * updateInit(const ASTContext &C, unsigned Init, Expr *expr)
Updates the initializer at index Init with the new expression expr, and returns the old expression at...
Definition: Expr.cpp:1797
Describes the kind of initialization being performed, along with location information for tokens rela...
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:7625
The entity being initialized is an element of an array.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:5774
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion...
bool isCStyleOrFunctionalCast() const
Determine whether this initialization is a C-style cast.
static ExprResult PerformConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, const InitializationSequence::Step &Step, bool &ConstructorInitRequiresZeroInit, bool IsListInitialization, bool IsStdInitListInitialization, SourceLocation LBraceLoc, SourceLocation RBraceLoc)
Definition: SemaInit.cpp:5678
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
Definition: SemaInit.cpp:6952
bool isRValue() const
Definition: Expr.h:352
bool isRValue() const
Definition: Expr.h:248
Expr ** getInits()
Retrieve the set of initializers.
Definition: Expr.h:3779
Overloading for initialization by constructor failed.
QualType getToType(unsigned Idx) const
Definition: Overload.h:218
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
Definition: SemaInit.cpp:3632
SourceLocation getBegin() const
Requests that all candidates be shown.
Definition: Overload.h:50
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:165
An optional copy of a temporary object to another temporary object, which is permitted (but not requi...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1407
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:3586
bool isVectorType() const
Definition: Type.h:5548
void AddAtomicConversionStep(QualType Ty)
Add a new step that performs conversion from non-atomic to atomic type.
Definition: SemaInit.cpp:3193
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2320
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
Definition: SemaInit.cpp:3283
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1833
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5329
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:701
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:3831
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:652
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:433
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S)
Definition: SemaInit.cpp:150
enum SequenceKind getKind() const
Determine the kind of initialization sequence computed.
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:262
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:193
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
getSpecialMember - get the special member enum for a method.
Definition: SemaDecl.cpp:2600
Pass an object by indirect copy-and-restore.
A POD class for pairing a NamedDecl* with an access specifier.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
Represents a C11 generic selection.
Definition: Expr.h:4413
void SetFailed(FailureKind Failure)
Note that this initialization sequence failed.
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1412
bool isCStyleCast() const
Determine whether this is a C-style cast.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
QualType getType() const
Definition: Expr.h:126
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:7836
Array must be initialized with an initializer list or a string literal.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
static bool isInvalid(LocType Loc, bool *Invalid)
void setIncompleteTypeFailure(QualType IncompleteType)
Note that this initialization sequence failed due to an incomplete type.
A single step in the initialization sequence.
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type. ...
Definition: Type.cpp:1868
Array must be initialized with an initializer list or a wide string literal.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1209
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1983
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:368
Too many initializers provided for a reference.
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type...
Definition: Expr.cpp:2520
static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, const ArrayType *Source)
Determine whether we have compatible array types for the purposes of GNU by-copy array initialization...
Definition: SemaInit.cpp:4821
bool isXValue() const
Definition: Expr.h:349
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
Perform a load from a glvalue, producing an rvalue.
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
Definition: SemaInit.cpp:4803
IndirectFieldDecl - An instance of this class is created to represent a field injected from an anonym...
Definition: Decl.h:2521
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types...
static bool InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity)
Determine whether the specified InitializedEntity definitely has a lifetime longer than the current f...
Definition: SemaInit.cpp:5819
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:14216
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the beginning of the immediate macro expansion...
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:104
Array-to-pointer conversion (C++ 4.2)
Definition: Overload.h:63
std::pair< SourceLocation, SourceLocation > getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
DeclarationName - The name of a declaration.
chain_iterator chain_end() const
Definition: Decl.h:2544
static void TryConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, InitializationSequence &Sequence, bool IsListInit=false, bool IsInitListCopy=false)
Attempt initialization by constructor (C++ [dcl.init]), which enumerates the constructors of the init...
Definition: SemaInit.cpp:3511
static bool IsWideCharCompatible(QualType T, ASTContext &Context)
Check whether T is compatible with a wide character type (wchar_t, char16_t or char32_t).
Definition: SemaInit.cpp:38
std::string getAsString(ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:545
StringKind getKind() const
Definition: Expr.h:1554
Requests that only viable candidates be shown.
Definition: Overload.h:53
detail::InMemoryDirectory::const_iterator E
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition: Expr.h:4180
DeclaratorDecl * VariableOrMember
When Kind == EK_Variable, or EK_Member, the VarDecl or FieldDecl, respectively.
bool isSamplerT() const
Definition: Type.h:5603
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2205
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1966
static ExprResult CopyObject(Sema &S, QualType T, const InitializedEntity &Entity, ExprResult CurInit, bool IsExtraneousCopy)
Make a (potentially elidable) temporary copy of the object provided by the given initializer by calli...
Definition: SemaInit.cpp:5441
bool isLValueReferenceType() const
Definition: Type.h:5494
Overloading due to reference initialization failed.
Expr * getArrayIndex() const
Definition: Designator.h:89
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
unsigned getNumArgs() const
Definition: ExprCXX.h:1285
bool isParameterKind() const
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:3855
DeclClass * getCorrectionDeclAs() const
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1473
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2413
bool isRValueReferenceType() const
Definition: Type.h:5497
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5432
static bool isRValueRef(QualType ParamType)
Definition: Consumed.cpp:180
bool isObjCObjectType() const
Definition: Type.h:5557
const CXXBaseSpecifier * getBaseSpecifier() const
Retrieve the base specifier.
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:831
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3707
void setAllToTypes(QualType T)
Definition: Overload.h:209
Complex values, per C99 6.2.5p11.
Definition: Type.h:2119
static bool TryOCLZeroEventInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:4904
SourceManager & getSourceManager() const
Definition: Sema.h:1067
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5818
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.cpp:3637
QualType getCanonicalType() const
Definition: Type.h:5298
Array must be initialized with an initializer list.
static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, Expr *op)
Emit notes associated with an initialization that failed due to a "simple" conversion failure...
Definition: SemaInit.cpp:6991
bool isParameterConsumed() const
Determine whether this initialization consumes the parameter.
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:355
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
SourceLocation getFieldLoc() const
Definition: Designator.h:84
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1291
bool isFunctionType() const
Definition: Type.h:5479
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:6192
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1288
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2319
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1225
LValueClassification
Definition: Expr.h:252
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1528
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl)
Checks access to an overloaded member operator, including conversion operators.
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:1848
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:78
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
Definition: SemaInit.cpp:3133
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:29
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
Represents a base class of a C++ class.
Definition: DeclCXX.h:159
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:4884
QualType getType() const
Retrieve type being initialized.
static OverloadingResult ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, MultiExprArg Args, OverloadCandidateSet &CandidateSet, DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, bool IsListInit)
Definition: SemaInit.cpp:3438
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
Definition: SemaInit.cpp:5388
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:1863
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
An implicit conversion.
Definition: Sema.h:8501
bool AllowExplicit() const
Retrieve whether this initialization allows the use of explicit constructors.
Reading or writing from this object requires a barrier call.
Definition: Type.h:148
void AddUserConversionStep(FunctionDecl *Function, DeclAccessPair FoundDecl, QualType T, bool HadMultipleCandidates)
Add a new step invoking a conversion function, which is either a constructor or a conversion function...
Definition: SemaInit.cpp:3161
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
static void TryListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization (C++0x [dcl.init.list])
Definition: SemaInit.cpp:3750
bool Failed() const
Determine whether the initialization sequence is invalid.
static void TryStringLiteralInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence)
Attempt character array initialization from a string literal (C++ [dcl.init.string], C99 6.7.8).
Definition: SemaInit.cpp:4437
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
Definition: SemaInit.cpp:3018
Describes the sequence of initializations required to initialize a given object or reference with a s...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5339
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:3841
bool isClkEventT() const
Definition: Type.h:5611
Represents a C++ struct/union/class.
Definition: DeclCXX.h:263
Compatible - the types are compatible according to the standard.
Definition: Sema.h:8620
Perform initialization via a constructor, taking arguments from a single InitListExpr.
static ExprValueKind convertQualifiersAndValueKindIfNecessary(Sema &S, InitializationSequence &Sequence, Expr *Initializer, QualType cv1T1, Qualifiers T1Quals, Qualifiers T2Quals, bool IsLValueRef)
Converts the target of reference initialization so that it has the appropriate qualifiers and value k...
Definition: SemaInit.cpp:4164
bool isObjCObjectPointerType() const
Definition: Type.h:5554
Represents a C array with an unspecified size.
Definition: Type.h:2562
QualType getEncodedType() const
Definition: ExprObjC.h:376
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
Expr * getArrayRangeEnd() const
Definition: Designator.h:98
CanQualType Char16Ty
Definition: ASTContext.h:899
The entity being initialized is the field that captures a variable in a lambda.
void setSequenceKind(enum SequenceKind SK)
Set the kind of sequence computed.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:311
static void TryValueInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence, InitListExpr *InitList=nullptr)
Attempt value initialization (C++ [dcl.init]p7).
Definition: SemaInit.cpp:4446
A dependent initialization, which could not be type-checked due to the presence of dependent types or...
bool isEventT() const
Definition: Type.h:5607
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
This class is used for builtin types like 'int'.
Definition: Type.h:2039
bool isArrayType() const
Definition: Type.h:5521
bool isImplicitValueInit() const
Determine whether this initialization is an implicit value-initialization, e.g., as occurs during agg...
unsigned allocateManglingNumber() const
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best, bool UserDefinedConversion=false)
Find the best viable function on this overload set, if it exists.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1466
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2148
static OverloadingResult TryRefInitWithConversionFunction(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, bool AllowRValues, InitializationSequence &Sequence)
Try a reference initialization that involves calling a conversion function.
Definition: SemaInit.cpp:3943
Designator * getDesignator(unsigned Idx)
Definition: Expr.h:4164
void setInit(Expr *init)
Definition: Expr.h:4188
ExprResult ExprError()
Definition: Ownership.h:268
DeclarationName getName() const
Retrieve the name of the entity being initialized.
Definition: SemaInit.cpp:2889
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:2606
void reserveInits(const ASTContext &C, unsigned NumInits)
Reserve space for some number of initializers.
Definition: Expr.cpp:1788
static bool isReferenceBinding(const InitializationSequence::Step &s)
Definition: SemaInit.cpp:5646
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type...
bool isIncompleteArrayType() const
Definition: Type.h:5527
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
Definition: SemaInit.cpp:3227
Designation - Represent a full designation, which is a sequence of designators.
Definition: Designator.h:181
static Sema::AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
Definition: SemaInit.cpp:5241
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:932
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:401
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:37
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
QualType getElementType() const
Definition: Type.h:2490
The initialization is being done by a delegating constructor.
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
Definition: SemaInit.cpp:3174
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:5334
SourceManager & SourceMgr
Definition: Sema.h:302
void clear()
Clear out all of the candidates.
bool hasDefaultConstructor() const
Determine whether this class has any default constructors.
Definition: DeclCXX.h:823
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion...
Definition: Overload.h:136
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3785
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:3849
No viable function found.
Definition: Overload.h:42
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
Definition: SemaInit.cpp:3115
A failed initialization sequence.
Array initialization (from an array rvalue).
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:109
Default-initialization of a 'const' object.
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
Definition: SemaInit.cpp:3209
size_t size() const
Definition: Overload.h:754
A trivial tuple used to represent a source range.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ASTContext & Context
Definition: Sema.h:299
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes...
Definition: SemaInit.cpp:7724
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2607
unsigned getElementIndex() const
If this is an array, vector, or complex number element, get the element's index.
Automatic storage duration (most local variables).
Definition: Specifiers.h:271
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1706
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5318
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
Definition: SemaInit.cpp:7728
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:665
Describes an entity that is being initialized.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:205
NamespaceDecl * getStdNamespace() const
unsigned getNumDesignators() const
Definition: Designator.h:193
AssignmentAction
Definition: Sema.h:2223
SourceLocation getFieldLoc() const
Definition: Expr.h:4100
static void CheckCXX98CompatAccessibleCopy(Sema &S, const InitializedEntity &Entity, Expr *CurInitExpr)
Check whether elidable copy construction for binding a reference to a temporary would have succeeded ...
Definition: SemaInit.cpp:5577
Direct list-initialization.
Array initialization from a parenthesized initializer list.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2512
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Definition: SemaInit.cpp:3368
Declaration of a template function.
Definition: DeclTemplate.h:838
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:4315
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals...
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
Definition: SemaInit.cpp:3348
bool hasLocalStorage() const
hasLocalStorage - Returns true if a variable with function scope is a non-static local variable...
Definition: Decl.h:963
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2295
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5286
bool hasInClassInitializer() const
hasInClassInitializer - Determine whether this member has a C++11 in-class initializer.
Definition: Decl.h:2408
bool isPointerType() const
Definition: Type.h:5482
SourceRange getSourceRange() const LLVM_READONLY
Definition: Expr.h:4138
static bool isExplicitTemporary(const InitializedEntity &Entity, const InitializationKind &Kind, unsigned NumArgs)
Returns true if the parameters describe a constructor initialization of an explicit temporary object...
Definition: SemaInit.cpp:5653
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3.1.1).
Definition: Overload.h:131