clang 24.0.0git
SemaInit.cpp
Go to the documentation of this file.
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeBase.h"
21#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/Lookup.h"
31#include "clang/Sema/SemaHLSL.h"
32#include "clang/Sema/SemaObjC.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/PointerIntPair.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/raw_ostream.h"
41
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// Sema Initialization Checking
46//===----------------------------------------------------------------------===//
47
48/// Check whether T is compatible with a wide character type (wchar_t,
49/// char16_t or char32_t).
50static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
51 if (Context.typesAreCompatible(Context.getWideCharType(), T))
52 return true;
53 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
54 return Context.typesAreCompatible(Context.Char16Ty, T) ||
55 Context.typesAreCompatible(Context.Char32Ty, T);
56 }
57 return false;
58}
59
69
70/// Check whether the array of type AT can be initialized by the Init
71/// expression by means of string initialization. Returns SIF_None if so,
72/// otherwise returns a StringInitFailureKind that describes why the
73/// initialization would not work.
75 ASTContext &Context) {
77 return SIF_Other;
78
79 // See if this is a string literal or @encode.
80 Init = Init->IgnoreParens();
81
82 // Handle @encode, which is a narrow string.
84 return SIF_None;
85
86 // Otherwise we can only handle string literals.
87 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
88 if (!SL)
89 return SIF_Other;
90
91 const QualType ElemTy =
93
94 auto IsCharOrUnsignedChar = [](const QualType &T) {
95 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
96 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
97 };
98
99 switch (SL->getKind()) {
101 // char8_t array can be initialized with a UTF-8 string.
102 // - C++20 [dcl.init.string] (DR)
103 // Additionally, an array of char or unsigned char may be initialized
104 // by a UTF-8 string literal.
105 if (ElemTy->isChar8Type() ||
106 (Context.getLangOpts().Char8 &&
107 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
108 return SIF_None;
109 [[fallthrough]];
112 // char array can be initialized with a narrow string.
113 // Only allow char x[] = "foo"; not char x[] = L"foo";
114 if (ElemTy->isCharType())
115 return (SL->getKind() == StringLiteralKind::UTF8 &&
116 Context.getLangOpts().Char8)
118 : SIF_None;
119 if (ElemTy->isChar8Type())
121 if (IsWideCharCompatible(ElemTy, Context))
123 return SIF_Other;
124 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
125 // "An array with element type compatible with a qualified or unqualified
126 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
127 // string literal with the corresponding encoding prefix (L, u, or U,
128 // respectively), optionally enclosed in braces.
130 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
131 return SIF_None;
132 if (ElemTy->isCharType() || ElemTy->isChar8Type())
134 if (IsWideCharCompatible(ElemTy, Context))
136 return SIF_Other;
138 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
139 return SIF_None;
140 if (ElemTy->isCharType() || ElemTy->isChar8Type())
142 if (IsWideCharCompatible(ElemTy, Context))
144 return SIF_Other;
146 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
147 return SIF_None;
148 if (ElemTy->isCharType() || ElemTy->isChar8Type())
150 if (IsWideCharCompatible(ElemTy, Context))
152 return SIF_Other;
154 assert(false && "Unevaluated string literal in initialization");
155 break;
156 }
157
158 llvm_unreachable("missed a StringLiteral kind?");
159}
160
162 ASTContext &Context) {
163 const ArrayType *arrayType = Context.getAsArrayType(declType);
164 if (!arrayType)
165 return SIF_Other;
166 return IsStringInit(init, arrayType, Context);
167}
168
170 return ::IsStringInit(Init, AT, Context) == SIF_None;
171}
172
173/// Update the type of a string literal, including any surrounding parentheses,
174/// to match the type of the object which it is initializing.
176 while (true) {
177 E->setType(Ty);
180 break;
182 }
183}
184
185/// Fix a compound literal initializing an array so it's correctly marked
186/// as an rvalue.
188 while (true) {
191 break;
193 }
194}
195
197 Decl *D = Entity.getDecl();
198 const InitializedEntity *Parent = &Entity;
199
200 while (Parent) {
201 D = Parent->getDecl();
202 Parent = Parent->getParent();
203 }
204
205 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
206 return true;
207
208 return false;
209}
210
212 Sema &SemaRef, QualType &TT);
213
214static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
215 Sema &S, const InitializedEntity &Entity,
216 bool CheckC23ConstexprInit = false) {
217 // Get the length of the string as parsed.
218 auto *ConstantArrayTy =
220 uint64_t StrLength = ConstantArrayTy->getZExtSize();
221
222 if (CheckC23ConstexprInit)
223 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
225
226 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
227 // C99 6.7.8p14. We have an array of character type with unknown size
228 // being initialized to a string literal.
229 llvm::APInt ConstVal(32, StrLength);
230 // Return a new array type (C99 6.7.8p22).
232 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
233 updateStringLiteralType(Str, DeclT);
234 return;
235 }
236
238 uint64_t ArrayLen = CAT->getZExtSize();
239
240 // We have an array of character type with known size. However,
241 // the size may be smaller or larger than the string we are initializing.
242 // FIXME: Avoid truncation for 64-bit length strings.
243 if (S.getLangOpts().CPlusPlus) {
244 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
245 // For Pascal strings it's OK to strip off the terminating null character,
246 // so the example below is valid:
247 //
248 // unsigned char a[2] = "\pa";
249 if (SL->isPascal())
250 StrLength--;
251 }
252
253 // [dcl.init.string]p2
254 if (StrLength > ArrayLen)
255 S.Diag(Str->getBeginLoc(),
256 diag::err_initializer_string_for_char_array_too_long)
257 << ArrayLen << StrLength << Str->getSourceRange();
258 } else {
259 // C99 6.7.8p14.
260 if (StrLength - 1 > ArrayLen)
261 S.Diag(Str->getBeginLoc(),
262 diag::ext_initializer_string_for_char_array_too_long)
263 << Str->getSourceRange();
264 else if (StrLength - 1 == ArrayLen) {
265 // In C, if the string literal is null-terminated explicitly, e.g., `char
266 // a[4] = "ABC\0"`, there should be no warning:
267 const auto *SL = dyn_cast<StringLiteral>(Str->IgnoreParens());
268 bool IsSLSafe = SL && SL->getLength() > 0 &&
269 SL->getCodeUnit(SL->getLength() - 1) == 0;
270
271 if (!IsSLSafe) {
272 // If the entity being initialized has the nonstring attribute, then
273 // silence the "missing nonstring" diagnostic. If there's no entity,
274 // check whether we're initializing an array of arrays; if so, walk the
275 // parents to find an entity.
276 auto FindCorrectEntity =
277 [](const InitializedEntity *Entity) -> const ValueDecl * {
278 while (Entity) {
279 if (const ValueDecl *VD = Entity->getDecl())
280 return VD;
281 if (!Entity->getType()->isArrayType())
282 return nullptr;
283 Entity = Entity->getParent();
284 }
285
286 return nullptr;
287 };
288 if (const ValueDecl *D = FindCorrectEntity(&Entity);
289 !D || !D->hasAttr<NonStringAttr>())
290 S.Diag(
291 Str->getBeginLoc(),
292 diag::
293 warn_initializer_string_for_char_array_too_long_no_nonstring)
294 << ArrayLen << StrLength << Str->getSourceRange();
295 }
296 // Always emit the C++ compatibility diagnostic.
297 S.Diag(Str->getBeginLoc(),
298 diag::warn_initializer_string_for_char_array_too_long_for_cpp)
299 << ArrayLen << StrLength << Str->getSourceRange();
300 }
301 }
302
303 // Set the type to the actual size that we are initializing. If we have
304 // something like:
305 // char x[1] = "foo";
306 // then this will set the string literal's type to char[1].
307 updateStringLiteralType(Str, DeclT);
308}
309
311 for (const FieldDecl *Field : R->fields()) {
312 if (Field->hasAttr<ExplicitInitAttr>())
313 S.Diag(Field->getLocation(), diag::note_entity_declared_at) << Field;
314 }
315}
316
317//===----------------------------------------------------------------------===//
318// Semantic checking for initializer lists.
319//===----------------------------------------------------------------------===//
320
321namespace {
322
323/// Semantic checking for initializer lists.
324///
325/// The InitListChecker class contains a set of routines that each
326/// handle the initialization of a certain kind of entity, e.g.,
327/// arrays, vectors, struct/union types, scalars, etc. The
328/// InitListChecker itself performs a recursive walk of the subobject
329/// structure of the type to be initialized, while stepping through
330/// the initializer list one element at a time. The IList and Index
331/// parameters to each of the Check* routines contain the active
332/// (syntactic) initializer list and the index into that initializer
333/// list that represents the current initializer. Each routine is
334/// responsible for moving that Index forward as it consumes elements.
335///
336/// Each Check* routine also has a StructuredList/StructuredIndex
337/// arguments, which contains the current "structured" (semantic)
338/// initializer list and the index into that initializer list where we
339/// are copying initializers as we map them over to the semantic
340/// list. Once we have completed our recursive walk of the subobject
341/// structure, we will have constructed a full semantic initializer
342/// list.
343///
344/// C99 designators cause changes in the initializer list traversal,
345/// because they make the initialization "jump" into a specific
346/// subobject and then continue the initialization from that
347/// point. CheckDesignatedInitializer() recursively steps into the
348/// designated subobject and manages backing out the recursion to
349/// initialize the subobjects after the one designated.
350///
351/// If an initializer list contains any designators, we build a placeholder
352/// structured list even in 'verify only' mode, so that we can track which
353/// elements need 'empty' initializtion.
354class InitListChecker {
355 Sema &SemaRef;
356 bool hadError = false;
357 bool VerifyOnly; // No diagnostics.
358 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
359 bool InOverloadResolution;
360 InitListExpr *FullyStructuredList = nullptr;
361 NoInitExpr *DummyExpr = nullptr;
362 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
363 EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
364 unsigned CurEmbedIndex = 0;
365
366 NoInitExpr *getDummyInit() {
367 if (!DummyExpr)
368 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
369 return DummyExpr;
370 }
371
372 void CheckImplicitInitList(const InitializedEntity &Entity,
373 InitListExpr *ParentIList, QualType T,
374 unsigned &Index, InitListExpr *StructuredList,
375 unsigned &StructuredIndex);
376 void CheckExplicitInitList(const InitializedEntity &Entity,
377 InitListExpr *IList, QualType &T,
378 InitListExpr *StructuredList,
379 bool TopLevelObject = false);
380 void CheckListElementTypes(const InitializedEntity &Entity,
381 InitListExpr *IList, QualType &DeclType,
382 bool SubobjectIsDesignatorContext,
383 unsigned &Index,
384 InitListExpr *StructuredList,
385 unsigned &StructuredIndex,
386 bool TopLevelObject = false);
387 void CheckSubElementType(const InitializedEntity &Entity,
388 InitListExpr *IList, QualType ElemType,
389 unsigned &Index,
390 InitListExpr *StructuredList,
391 unsigned &StructuredIndex,
392 bool DirectlyDesignated = false);
393 void CheckComplexType(const InitializedEntity &Entity,
394 InitListExpr *IList, QualType DeclType,
395 unsigned &Index,
396 InitListExpr *StructuredList,
397 unsigned &StructuredIndex);
398 void CheckScalarType(const InitializedEntity &Entity,
399 InitListExpr *IList, QualType DeclType,
400 unsigned &Index,
401 InitListExpr *StructuredList,
402 unsigned &StructuredIndex);
403 void CheckReferenceType(const InitializedEntity &Entity,
404 InitListExpr *IList, QualType DeclType,
405 unsigned &Index,
406 InitListExpr *StructuredList,
407 unsigned &StructuredIndex);
408 void CheckMatrixType(const InitializedEntity &Entity, InitListExpr *IList,
409 QualType DeclType, unsigned &Index,
410 InitListExpr *StructuredList, unsigned &StructuredIndex);
411 void CheckVectorType(const InitializedEntity &Entity,
412 InitListExpr *IList, QualType DeclType, unsigned &Index,
413 InitListExpr *StructuredList,
414 unsigned &StructuredIndex);
415 void CheckStructUnionTypes(const InitializedEntity &Entity,
416 InitListExpr *IList, QualType DeclType,
419 bool SubobjectIsDesignatorContext, unsigned &Index,
420 InitListExpr *StructuredList,
421 unsigned &StructuredIndex,
422 bool TopLevelObject = false);
423 void CheckArrayType(const InitializedEntity &Entity,
424 InitListExpr *IList, QualType &DeclType,
425 llvm::APSInt elementIndex,
426 bool SubobjectIsDesignatorContext, unsigned &Index,
427 InitListExpr *StructuredList,
428 unsigned &StructuredIndex);
429 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
430 InitListExpr *IList, DesignatedInitExpr *DIE,
431 unsigned DesigIdx,
432 QualType &CurrentObjectType,
434 llvm::APSInt *NextElementIndex,
435 unsigned &Index,
436 InitListExpr *StructuredList,
437 unsigned &StructuredIndex,
438 bool FinishSubobjectInit,
439 bool TopLevelObject);
440 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
441 QualType CurrentObjectType,
442 InitListExpr *StructuredList,
443 unsigned StructuredIndex,
444 SourceRange InitRange,
445 bool IsFullyOverwritten = false);
446 void UpdateStructuredListElement(InitListExpr *StructuredList,
447 unsigned &StructuredIndex,
448 Expr *expr);
449 InitListExpr *createInitListExpr(QualType CurrentObjectType,
450 SourceRange InitRange,
451 unsigned ExpectedNumInits, bool IsExplicit);
452 int numArrayElements(QualType DeclType);
453 int numStructUnionElements(QualType DeclType);
454
455 ExprResult PerformEmptyInit(SourceLocation Loc,
456 const InitializedEntity &Entity);
457
458 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
459 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
460 bool UnionOverride = false,
461 bool FullyOverwritten = true) {
462 // Overriding an initializer via a designator is valid with C99 designated
463 // initializers, but ill-formed with C++20 designated initializers.
464 unsigned DiagID =
465 SemaRef.getLangOpts().CPlusPlus
466 ? (UnionOverride ? diag::ext_initializer_union_overrides
467 : diag::ext_initializer_overrides)
468 : diag::warn_initializer_overrides;
469
470 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
471 // In overload resolution, we have to strictly enforce the rules, and so
472 // don't allow any overriding of prior initializers. This matters for a
473 // case such as:
474 //
475 // union U { int a, b; };
476 // struct S { int a, b; };
477 // void f(U), f(S);
478 //
479 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
480 // consistency, we disallow all overriding of prior initializers in
481 // overload resolution, not only overriding of union members.
482 hadError = true;
483 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
484 // If we'll be keeping around the old initializer but overwriting part of
485 // the object it initialized, and that object is not trivially
486 // destructible, this can leak. Don't allow that, not even as an
487 // extension.
488 //
489 // FIXME: It might be reasonable to allow this in cases where the part of
490 // the initializer that we're overriding has trivial destruction.
491 DiagID = diag::err_initializer_overrides_destructed;
492 } else if (!OldInit->getSourceRange().isValid()) {
493 // We need to check on source range validity because the previous
494 // initializer does not have to be an explicit initializer. e.g.,
495 //
496 // struct P { int a, b; };
497 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
498 //
499 // There is an overwrite taking place because the first braced initializer
500 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
501 //
502 // Such overwrites are harmless, so we don't diagnose them. (Note that in
503 // C++, this cannot be reached unless we've already seen and diagnosed a
504 // different conformance issue, such as a mixture of designated and
505 // non-designated initializers or a multi-level designator.)
506 return;
507 }
508
509 if (!VerifyOnly) {
510 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
511 << NewInitRange << FullyOverwritten << OldInit->getType();
512 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
513 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
514 << OldInit->getSourceRange();
515 }
516 }
517
518 // Explanation on the "FillWithNoInit" mode:
519 //
520 // Assume we have the following definitions (Case#1):
521 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
522 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
523 //
524 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
525 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
526 //
527 // But if we have (Case#2):
528 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
529 //
530 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
531 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
532 //
533 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
534 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
535 // initializers but with special "NoInitExpr" place holders, which tells the
536 // CodeGen not to generate any initializers for these parts.
537 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
538 const InitializedEntity &ParentEntity,
539 InitListExpr *ILE, bool &RequiresSecondPass,
540 bool FillWithNoInit);
541 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
542 const InitializedEntity &ParentEntity,
543 InitListExpr *ILE, bool &RequiresSecondPass,
544 bool FillWithNoInit = false);
545 void FillInEmptyInitializations(const InitializedEntity &Entity,
546 InitListExpr *ILE, bool &RequiresSecondPass,
547 InitListExpr *OuterILE, unsigned OuterIndex,
548 bool FillWithNoInit = false);
549 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
550 Expr *InitExpr, FieldDecl *Field,
551 bool TopLevelObject);
552 void CheckEmptyInitializable(const InitializedEntity &Entity,
553 SourceLocation Loc);
554
555 Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {
556 Expr *Result = nullptr;
557 // Undrestand which part of embed we'd like to reference.
558 if (!CurEmbed) {
559 CurEmbed = Embed;
560 CurEmbedIndex = 0;
561 }
562 // Reference just one if we're initializing a single scalar.
563 uint64_t ElsCount = 1;
564 // Otherwise try to fill whole array with embed data.
566 unsigned ArrIndex = Entity.getElementIndex();
567 auto *AType =
568 SemaRef.Context.getAsArrayType(Entity.getParent()->getType());
569 assert(AType && "expected array type when initializing array");
570 ElsCount = Embed->getDataElementCount();
571 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
572 ElsCount = std::min(CAType->getSize().getZExtValue() - ArrIndex,
573 ElsCount - CurEmbedIndex);
574 if (ElsCount == Embed->getDataElementCount()) {
575 CurEmbed = nullptr;
576 CurEmbedIndex = 0;
577 return Embed;
578 }
579 }
580
581 Result = new (SemaRef.Context)
582 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
583 CurEmbedIndex, ElsCount);
584 CurEmbedIndex += ElsCount;
585 if (CurEmbedIndex >= Embed->getDataElementCount()) {
586 CurEmbed = nullptr;
587 CurEmbedIndex = 0;
588 }
589 return Result;
590 }
591
592public:
593 InitListChecker(
594 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
595 bool VerifyOnly, bool TreatUnavailableAsInvalid,
596 bool InOverloadResolution = false,
597 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
598 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
599 QualType &T,
600 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
601 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
602 /*TreatUnavailableAsInvalid=*/false,
603 /*InOverloadResolution=*/false,
604 &AggrDeductionCandidateParamTypes) {}
605
606 bool HadError() { return hadError; }
607
608 // Retrieves the fully-structured initializer list used for
609 // semantic analysis and code generation.
610 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
611};
612
613} // end anonymous namespace
614
615ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
616 const InitializedEntity &Entity) {
618 true);
619 MultiExprArg SubInit;
620 Expr *InitExpr;
621 InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc,
622 /*isExplicit=*/false);
623
624 // C++ [dcl.init.aggr]p7:
625 // If there are fewer initializer-clauses in the list than there are
626 // members in the aggregate, then each member not explicitly initialized
627 // ...
628 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
630 if (EmptyInitList) {
631 // C++1y / DR1070:
632 // shall be initialized [...] from an empty initializer list.
633 //
634 // We apply the resolution of this DR to C++11 but not C++98, since C++98
635 // does not have useful semantics for initialization from an init list.
636 // We treat this as copy-initialization, because aggregate initialization
637 // always performs copy-initialization on its elements.
638 //
639 // Only do this if we're initializing a class type, to avoid filling in
640 // the initializer list where possible.
641 InitExpr = VerifyOnly ? &DummyInitList
642 : new (SemaRef.Context)
643 InitListExpr(SemaRef.Context, Loc, {}, Loc,
644 /*isExplicit=*/false);
645 InitExpr->setType(SemaRef.Context.VoidTy);
646 SubInit = InitExpr;
648 } else {
649 // C++03:
650 // shall be value-initialized.
651 }
652
653 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
654 // HACK: libstdc++ prior to 4.9 marks the vector default constructor
655 // as explicit in _GLIBCXX_DEBUG mode, so recover using the C++03 logic
656 // in that case. stlport does so too.
657 // Look for std::__debug for libstdc++, and for std:: for stlport.
658 // This is effectively a compiler-side implementation of LWG2193.
659 if (!InitSeq && EmptyInitList &&
660 InitSeq.getFailureKind() ==
662 SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2014'04'22)) {
665 InitSeq.getFailedCandidateSet()
666 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
667 (void)O;
668 assert(O == OR_Success && "Inconsistent overload resolution");
669 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
670 CXXRecordDecl *R = CtorDecl->getParent();
671
672 if (CtorDecl->getMinRequiredArguments() == 0 &&
673 CtorDecl->isExplicit() && R->getDeclName() &&
674 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
675 bool IsInStd = false;
676 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
677 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
679 IsInStd = true;
680 }
681
682 if (IsInStd &&
683 llvm::StringSwitch<bool>(R->getName())
684 .Cases({"basic_string", "deque", "forward_list"}, true)
685 .Cases({"list", "map", "multimap", "multiset"}, true)
686 .Cases({"priority_queue", "queue", "set", "stack"}, true)
687 .Cases({"unordered_map", "unordered_set", "vector"}, true)
688 .Default(false)) {
689 InitSeq.InitializeFrom(
690 SemaRef, Entity,
691 InitializationKind::CreateValue(Loc, Loc, Loc, true),
692 MultiExprArg(), /*TopLevelOfInitList=*/false,
693 TreatUnavailableAsInvalid);
694 // Emit a warning for this. System header warnings aren't shown
695 // by default, but people working on system headers should see it.
696 if (!VerifyOnly) {
697 SemaRef.Diag(CtorDecl->getLocation(),
698 diag::warn_invalid_initializer_from_system_header);
700 SemaRef.Diag(Entity.getDecl()->getLocation(),
701 diag::note_used_in_initialization_here);
702 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
703 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
704 }
705 }
706 }
707 }
708 if (!InitSeq) {
709 if (!VerifyOnly) {
710 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
712 SemaRef.Diag(Entity.getDecl()->getLocation(),
713 diag::note_in_omitted_aggregate_initializer)
714 << /*field*/1 << Entity.getDecl();
715 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
716 bool IsTrailingArrayNewMember =
717 Entity.getParent() &&
719 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
720 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
721 << Entity.getElementIndex();
722 }
723 }
724 hadError = true;
725 return ExprError();
726 }
727
728 return VerifyOnly ? ExprResult()
729 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
730}
731
732void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
733 SourceLocation Loc) {
734 // If we're building a fully-structured list, we'll check this at the end
735 // once we know which elements are actually initialized. Otherwise, we know
736 // that there are no designators so we can just check now.
737 if (FullyStructuredList)
738 return;
739 PerformEmptyInit(Loc, Entity);
740}
741
742void InitListChecker::FillInEmptyInitForBase(
743 unsigned Init, const CXXBaseSpecifier &Base,
744 const InitializedEntity &ParentEntity, InitListExpr *ILE,
745 bool &RequiresSecondPass, bool FillWithNoInit) {
747 SemaRef.Context, &Base, false, &ParentEntity);
748
749 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
750 ExprResult BaseInit = FillWithNoInit
751 ? new (SemaRef.Context) NoInitExpr(Base.getType())
752 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
753 if (BaseInit.isInvalid()) {
754 hadError = true;
755 return;
756 }
757
758 if (!VerifyOnly) {
759 assert(Init < ILE->getNumInits() && "should have been expanded");
760 ILE->setInit(Init, BaseInit.getAs<Expr>());
761 }
762 } else if (InitListExpr *InnerILE =
763 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
764 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
765 ILE, Init, FillWithNoInit);
766 } else if (DesignatedInitUpdateExpr *InnerDIUE =
767 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
768 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
769 RequiresSecondPass, ILE, Init,
770 /*FillWithNoInit =*/true);
771 }
772}
773
774void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
775 const InitializedEntity &ParentEntity,
776 InitListExpr *ILE,
777 bool &RequiresSecondPass,
778 bool FillWithNoInit) {
779 SourceLocation Loc = ILE->getEndLoc();
780 unsigned NumInits = ILE->getNumInits();
781 InitializedEntity MemberEntity
782 = InitializedEntity::InitializeMember(Field, &ParentEntity);
783
784 if (Init >= NumInits || !ILE->getInit(Init)) {
785 if (const RecordType *RType = ILE->getType()->getAsCanonical<RecordType>())
786 if (!RType->getDecl()->isUnion())
787 assert((Init < NumInits || VerifyOnly) &&
788 "This ILE should have been expanded");
789
790 if (FillWithNoInit) {
791 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
792 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
793 if (Init < NumInits)
794 ILE->setInit(Init, Filler);
795 else
796 ILE->updateInit(SemaRef.Context, Init, Filler);
797 return;
798 }
799
800 if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>() &&
801 !SemaRef.isUnevaluatedContext()) {
802 SemaRef.Diag(ILE->getExprLoc(), diag::warn_field_requires_explicit_init)
803 << /* Var-in-Record */ 0 << Field;
804 SemaRef.Diag(Field->getLocation(), diag::note_entity_declared_at)
805 << Field;
806 }
807
808 // C++1y [dcl.init.aggr]p7:
809 // If there are fewer initializer-clauses in the list than there are
810 // members in the aggregate, then each member not explicitly initialized
811 // shall be initialized from its brace-or-equal-initializer [...]
812 if (Field->hasInClassInitializer()) {
813 if (VerifyOnly)
814 return;
815
816 ExprResult DIE;
817 {
818 // Enter a default initializer rebuild context, then we can support
819 // lifetime extension of temporary created by aggregate initialization
820 // using a default member initializer.
821 // CWG1815 (https://wg21.link/CWG1815).
822 EnterExpressionEvaluationContext RebuildDefaultInit(
825 true;
831 DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
832 }
833 if (DIE.isInvalid()) {
834 hadError = true;
835 return;
836 }
837 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
838 if (Init < NumInits)
839 ILE->setInit(Init, DIE.get());
840 else {
841 ILE->updateInit(SemaRef.Context, Init, DIE.get());
842 RequiresSecondPass = true;
843 }
844 return;
845 }
846
847 if (Field->getType()->isReferenceType()) {
848 if (!VerifyOnly) {
849 // C++ [dcl.init.aggr]p9:
850 // If an incomplete or empty initializer-list leaves a
851 // member of reference type uninitialized, the program is
852 // ill-formed.
853 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
854 << Field->getType()
855 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
856 ->getSourceRange();
857 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
858 }
859 hadError = true;
860 return;
861 }
862
863 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
864 if (MemberInit.isInvalid()) {
865 hadError = true;
866 return;
867 }
868
869 if (hadError || VerifyOnly) {
870 // Do nothing
871 } else if (Init < NumInits) {
872 ILE->setInit(Init, MemberInit.getAs<Expr>());
873 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
874 // Empty initialization requires a constructor call, so
875 // extend the initializer list to include the constructor
876 // call and make a note that we'll need to take another pass
877 // through the initializer list.
878 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
879 RequiresSecondPass = true;
880 }
881 } else if (InitListExpr *InnerILE
882 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
883 FillInEmptyInitializations(MemberEntity, InnerILE,
884 RequiresSecondPass, ILE, Init, FillWithNoInit);
885 } else if (DesignatedInitUpdateExpr *InnerDIUE =
886 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
887 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
888 RequiresSecondPass, ILE, Init,
889 /*FillWithNoInit =*/true);
890 }
891}
892
893/// Recursively replaces NULL values within the given initializer list
894/// with expressions that perform value-initialization of the
895/// appropriate type, and finish off the InitListExpr formation.
896void
897InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
898 InitListExpr *ILE,
899 bool &RequiresSecondPass,
900 InitListExpr *OuterILE,
901 unsigned OuterIndex,
902 bool FillWithNoInit) {
903 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
904 "Should not have void type");
905
906 // We don't need to do any checks when just filling NoInitExprs; that can't
907 // fail.
908 if (FillWithNoInit && VerifyOnly)
909 return;
910
911 // If this is a nested initializer list, we might have changed its contents
912 // (and therefore some of its properties, such as instantiation-dependence)
913 // while filling it in. Inform the outer initializer list so that its state
914 // can be updated to match.
915 // FIXME: We should fully build the inner initializers before constructing
916 // the outer InitListExpr instead of mutating AST nodes after they have
917 // been used as subexpressions of other nodes.
918 struct UpdateOuterILEWithUpdatedInit {
919 InitListExpr *Outer;
920 unsigned OuterIndex;
921 ~UpdateOuterILEWithUpdatedInit() {
922 if (Outer)
923 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
924 }
925 } UpdateOuterRAII = {OuterILE, OuterIndex};
926
927 // A transparent ILE is not performing aggregate initialization and should
928 // not be filled in.
929 if (ILE->isTransparent())
930 return;
931
932 if (const auto *RDecl = ILE->getType()->getAsRecordDecl()) {
933 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
934 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,
935 RequiresSecondPass, FillWithNoInit);
936 } else {
937 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
938 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
939 "We should have computed initialized fields already");
940 // The fields beyond ILE->getNumInits() are default initialized, so in
941 // order to leave them uninitialized, the ILE is expanded and the extra
942 // fields are then filled with NoInitExpr.
943 unsigned NumElems = numStructUnionElements(ILE->getType());
944 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
945 ++NumElems;
946 if (!VerifyOnly && ILE->getNumInits() < NumElems)
947 ILE->resizeInits(SemaRef.Context, NumElems);
948
949 unsigned Init = 0;
950
951 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
952 for (auto &Base : CXXRD->bases()) {
953 if (hadError)
954 return;
955
956 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
957 FillWithNoInit);
958 ++Init;
959 }
960 }
961
962 for (auto *Field : RDecl->fields()) {
963 if (Field->isUnnamedBitField())
964 continue;
965
966 if (hadError)
967 return;
968
969 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
970 FillWithNoInit);
971 if (hadError)
972 return;
973
974 ++Init;
975
976 // Only look at the first initialization of a union.
977 if (RDecl->isUnion())
978 break;
979 }
980 }
981
982 return;
983 }
984
985 QualType ElementType;
986
987 InitializedEntity ElementEntity = Entity;
988 unsigned NumInits = ILE->getNumInits();
989 uint64_t NumElements = NumInits;
990 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
991 ElementType = AType->getElementType();
992 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
993 NumElements = CAType->getZExtSize();
994 // For an array new with an unknown bound, ask for one additional element
995 // in order to populate the array filler.
996 if (Entity.isVariableLengthArrayNew())
997 ++NumElements;
998 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
999 0, Entity);
1000 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
1001 ElementType = VType->getElementType();
1002 NumElements = VType->getNumElements();
1003 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
1004 0, Entity);
1005 } else
1006 ElementType = ILE->getType();
1007
1008 bool SkipEmptyInitChecks = false;
1009 for (uint64_t Init = 0; Init != NumElements; ++Init) {
1010 if (hadError)
1011 return;
1012
1013 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
1014 ElementEntity.getKind() == InitializedEntity::EK_VectorElement ||
1016 ElementEntity.setElementIndex(Init);
1017
1018 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
1019 return;
1020
1021 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
1022 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
1023 ILE->setInit(Init, ILE->getArrayFiller());
1024 else if (!InitExpr && !ILE->hasArrayFiller()) {
1025 // In VerifyOnly mode, there's no point performing empty initialization
1026 // more than once.
1027 if (SkipEmptyInitChecks)
1028 continue;
1029
1030 Expr *Filler = nullptr;
1031
1032 if (FillWithNoInit)
1033 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
1034 else {
1035 ExprResult ElementInit =
1036 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
1037 if (ElementInit.isInvalid()) {
1038 hadError = true;
1039 return;
1040 }
1041
1042 Filler = ElementInit.getAs<Expr>();
1043 }
1044
1045 if (hadError) {
1046 // Do nothing
1047 } else if (VerifyOnly) {
1048 SkipEmptyInitChecks = true;
1049 } else if (Init < NumInits) {
1050 // For arrays, just set the expression used for value-initialization
1051 // of the "holes" in the array.
1052 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
1053 ILE->setArrayFiller(Filler);
1054 else
1055 ILE->setInit(Init, Filler);
1056 } else {
1057 // For arrays, just set the expression used for value-initialization
1058 // of the rest of elements and exit.
1059 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
1060 ILE->setArrayFiller(Filler);
1061 return;
1062 }
1063
1064 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
1065 // Empty initialization requires a constructor call, so
1066 // extend the initializer list to include the constructor
1067 // call and make a note that we'll need to take another pass
1068 // through the initializer list.
1069 ILE->updateInit(SemaRef.Context, Init, Filler);
1070 RequiresSecondPass = true;
1071 }
1072 }
1073 } else if (InitListExpr *InnerILE
1074 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
1075 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
1076 ILE, Init, FillWithNoInit);
1077 } else if (DesignatedInitUpdateExpr *InnerDIUE =
1078 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
1079 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1080 RequiresSecondPass, ILE, Init,
1081 /*FillWithNoInit =*/true);
1082 }
1083 }
1084}
1085
1086static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1087 for (const Stmt *Init : *IL)
1088 if (isa_and_nonnull<DesignatedInitExpr>(Init))
1089 return true;
1090 return false;
1091}
1092
1093InitListChecker::InitListChecker(
1094 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1095 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1096 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1097 : SemaRef(S), VerifyOnly(VerifyOnly),
1098 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1099 InOverloadResolution(InOverloadResolution),
1100 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1101 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1102 FullyStructuredList = createInitListExpr(
1103 T, IL->getSourceRange(), IL->getNumInits(), IL->isExplicit());
1104
1105 // FIXME: Check that IL isn't already the semantic form of some other
1106 // InitListExpr. If it is, we'd create a broken AST.
1107 if (!VerifyOnly)
1108 FullyStructuredList->setSyntacticForm(IL);
1109 }
1110
1111 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1112 /*TopLevelObject=*/true);
1113
1114 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1115 bool RequiresSecondPass = false;
1116 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1117 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1118 if (RequiresSecondPass && !hadError)
1119 FillInEmptyInitializations(Entity, FullyStructuredList,
1120 RequiresSecondPass, nullptr, 0);
1121 }
1122 if (hadError && FullyStructuredList)
1123 FullyStructuredList->markError();
1124}
1125
1126int InitListChecker::numArrayElements(QualType DeclType) {
1127 // FIXME: use a proper constant
1128 int maxElements = 0x7FFFFFFF;
1129 if (const ConstantArrayType *CAT =
1130 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1131 maxElements = static_cast<int>(CAT->getZExtSize());
1132 }
1133 return maxElements;
1134}
1135
1136int InitListChecker::numStructUnionElements(QualType DeclType) {
1137 auto *structDecl = DeclType->castAsRecordDecl();
1138 int InitializableMembers = 0;
1139 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1140 InitializableMembers += CXXRD->getNumBases();
1141 for (const auto *Field : structDecl->fields())
1142 if (!Field->isUnnamedBitField())
1143 ++InitializableMembers;
1144
1145 if (structDecl->isUnion())
1146 return std::min(InitializableMembers, 1);
1147 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1148}
1149
1150/// Determine whether Entity is an entity for which it is idiomatic to elide
1151/// the braces in aggregate initialization.
1153 // Recursive initialization of the one and only field within an aggregate
1154 // class is considered idiomatic. This case arises in particular for
1155 // initialization of std::array, where the C++ standard suggests the idiom of
1156 //
1157 // std::array<T, N> arr = {1, 2, 3};
1158 //
1159 // (where std::array is an aggregate struct containing a single array field.
1160
1161 if (!Entity.getParent())
1162 return false;
1163
1164 // Allows elide brace initialization for aggregates with empty base.
1165 if (Entity.getKind() == InitializedEntity::EK_Base) {
1166 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1167 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1168 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1169 }
1170
1171 // Allow brace elision if the only subobject is a field.
1172 if (Entity.getKind() == InitializedEntity::EK_Member) {
1173 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1174 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1175 if (CXXRD->getNumBases()) {
1176 return false;
1177 }
1178 }
1179 auto FieldIt = ParentRD->field_begin();
1180 assert(FieldIt != ParentRD->field_end() &&
1181 "no fields but have initializer for member?");
1182 return ++FieldIt == ParentRD->field_end();
1183 }
1184
1185 return false;
1186}
1187
1188/// Check whether the range of the initializer \p ParentIList from element
1189/// \p Index onwards can be used to initialize an object of type \p T. Update
1190/// \p Index to indicate how many elements of the list were consumed.
1191///
1192/// This also fills in \p StructuredList, from element \p StructuredIndex
1193/// onwards, with the fully-braced, desugared form of the initialization.
1194void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1195 InitListExpr *ParentIList,
1196 QualType T, unsigned &Index,
1197 InitListExpr *StructuredList,
1198 unsigned &StructuredIndex) {
1199 int maxElements = 0;
1200
1201 if (T->isArrayType())
1202 maxElements = numArrayElements(T);
1203 else if (T->isRecordType())
1204 maxElements = numStructUnionElements(T);
1205 else if (T->isVectorType())
1206 maxElements = T->castAs<VectorType>()->getNumElements();
1207 else
1208 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1209
1210 if (maxElements == 0) {
1211 if (!VerifyOnly)
1212 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1213 diag::err_implicit_empty_initializer);
1214 ++Index;
1215 hadError = true;
1216 return;
1217 }
1218
1219 // Build a structured initializer list corresponding to this subobject.
1220 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1221 ParentIList, Index, T, StructuredList, StructuredIndex,
1222 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1223 ParentIList->getSourceRange().getEnd()));
1224 unsigned StructuredSubobjectInitIndex = 0;
1225
1226 // Check the element types and build the structural subobject.
1227 unsigned StartIndex = Index;
1228 CheckListElementTypes(Entity, ParentIList, T,
1229 /*SubobjectIsDesignatorContext=*/false, Index,
1230 StructuredSubobjectInitList,
1231 StructuredSubobjectInitIndex);
1232
1233 if (StructuredSubobjectInitList) {
1234 StructuredSubobjectInitList->setType(T);
1235
1236 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1237 // Update the structured sub-object initializer so that it's ending
1238 // range corresponds with the end of the last initializer it used.
1239 if (EndIndex < ParentIList->getNumInits() &&
1240 ParentIList->getInit(EndIndex)) {
1241 SourceLocation EndLoc
1242 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1243 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1244 }
1245
1246 // Complain about missing braces.
1247 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1248 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1250 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1251 diag::warn_missing_braces)
1252 << StructuredSubobjectInitList->getSourceRange()
1254 StructuredSubobjectInitList->getBeginLoc(), "{")
1256 SemaRef.getLocForEndOfToken(
1257 StructuredSubobjectInitList->getEndLoc()),
1258 "}");
1259 }
1260
1261 // Warn if this type won't be an aggregate in future versions of C++.
1262 auto *CXXRD = T->getAsCXXRecordDecl();
1263 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1264 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1265 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1266 << StructuredSubobjectInitList->getSourceRange() << T;
1267 }
1268 }
1269}
1270
1271/// Warn that \p Entity was of scalar type and was initialized by a
1272/// single-element braced initializer list.
1273static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1275 // Don't warn during template instantiation. If the initialization was
1276 // non-dependent, we warned during the initial parse; otherwise, the
1277 // type might not be scalar in some uses of the template.
1279 return;
1280
1281 unsigned DiagID = 0;
1282
1283 switch (Entity.getKind()) {
1293 // Extra braces here are suspicious.
1294 DiagID = diag::warn_braces_around_init;
1295 break;
1296
1298 // Warn on aggregate initialization but not on ctor init list or
1299 // default member initializer.
1300 if (Entity.getParent())
1301 DiagID = diag::warn_braces_around_init;
1302 break;
1303
1306 // No warning, might be direct-list-initialization.
1307 // FIXME: Should we warn for copy-list-initialization in these cases?
1308 break;
1309
1313 // No warning, braces are part of the syntax of the underlying construct.
1314 break;
1315
1317 // No warning, we already warned when initializing the result.
1318 break;
1319
1327 llvm_unreachable("unexpected braced scalar init");
1328 }
1329
1330 if (DiagID) {
1331 S.Diag(Braces.getBegin(), DiagID)
1332 << Entity.getType()->isSizelessBuiltinType() << Braces
1333 << FixItHint::CreateRemoval(Braces.getBegin())
1334 << FixItHint::CreateRemoval(Braces.getEnd());
1335 }
1336}
1337
1338/// Check whether the initializer \p IList (that was written with explicit
1339/// braces) can be used to initialize an object of type \p T.
1340///
1341/// This also fills in \p StructuredList with the fully-braced, desugared
1342/// form of the initialization.
1343void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1344 InitListExpr *IList, QualType &T,
1345 InitListExpr *StructuredList,
1346 bool TopLevelObject) {
1347 unsigned Index = 0, StructuredIndex = 0;
1348 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1349 Index, StructuredList, StructuredIndex, TopLevelObject);
1350 if (StructuredList) {
1351 QualType ExprTy = T;
1352 if (!ExprTy->isArrayType())
1353 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1354 if (!VerifyOnly)
1355 IList->setType(ExprTy);
1356 StructuredList->setType(ExprTy);
1357 }
1358 if (hadError)
1359 return;
1360
1361 // Don't complain for incomplete types, since we'll get an error elsewhere.
1362 if ((Index < IList->getNumInits() || CurEmbed) && !T->isIncompleteType()) {
1363 // We have leftover initializers
1364 Expr *ExtraInit =
1365 Index < IList->getNumInits() ? IList->getInit(Index) : CurEmbed;
1366 SourceLocation ExtraInitLoc =
1367 ExtraInit ? ExtraInit->getBeginLoc() : IList->getEndLoc();
1368 SourceRange ExtraInitRange =
1369 ExtraInit ? ExtraInit->getSourceRange() : IList->getSourceRange();
1370 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1371 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1372 hadError = ExtraInitsIsError;
1373 if (VerifyOnly) {
1374 return;
1375 } else if (StructuredIndex == 1 && StructuredList->getNumInits() != 0 &&
1376 StructuredList->getInit(0) &&
1377 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1378 SIF_None) {
1379 unsigned DK =
1380 ExtraInitsIsError
1381 ? diag::err_excess_initializers_in_char_array_initializer
1382 : diag::ext_excess_initializers_in_char_array_initializer;
1383 SemaRef.Diag(ExtraInitLoc, DK) << ExtraInitRange;
1384 } else if (T->isSizelessBuiltinType()) {
1385 unsigned DK = ExtraInitsIsError
1386 ? diag::err_excess_initializers_for_sizeless_type
1387 : diag::ext_excess_initializers_for_sizeless_type;
1388 SemaRef.Diag(ExtraInitLoc, DK) << T << ExtraInitRange;
1389 } else {
1390 int initKind = T->isArrayType() ? 0
1391 : T->isVectorType() ? 1
1392 : T->isMatrixType() ? 2
1393 : T->isScalarType() ? 3
1394 : T->isUnionType() ? 4
1395 : 5;
1396
1397 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1398 : diag::ext_excess_initializers;
1399 SemaRef.Diag(ExtraInitLoc, DK) << initKind << ExtraInitRange;
1400 }
1401 }
1402
1403 if (!VerifyOnly) {
1404 if (T->isScalarType() && IList->getNumInits() == 1 &&
1405 !isa<InitListExpr>(IList->getInit(0)))
1406 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1407
1408 // Warn if this is a class type that won't be an aggregate in future
1409 // versions of C++.
1410 auto *CXXRD = T->getAsCXXRecordDecl();
1411 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1412 // Don't warn if there's an equivalent default constructor that would be
1413 // used instead.
1414 bool HasEquivCtor = false;
1415 if (IList->getNumInits() == 0) {
1416 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1417 HasEquivCtor = CD && !CD->isDeleted();
1418 }
1419
1420 if (!HasEquivCtor) {
1421 SemaRef.Diag(IList->getBeginLoc(),
1422 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1423 << IList->getSourceRange() << T;
1424 }
1425 }
1426 }
1427}
1428
1429void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1430 InitListExpr *IList,
1431 QualType &DeclType,
1432 bool SubobjectIsDesignatorContext,
1433 unsigned &Index,
1434 InitListExpr *StructuredList,
1435 unsigned &StructuredIndex,
1436 bool TopLevelObject) {
1437 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1438 // Explicitly braced initializer for complex type can be real+imaginary
1439 // parts.
1440 CheckComplexType(Entity, IList, DeclType, Index,
1441 StructuredList, StructuredIndex);
1442 } else if (DeclType->isScalarType()) {
1443 CheckScalarType(Entity, IList, DeclType, Index,
1444 StructuredList, StructuredIndex);
1445 } else if (DeclType->isVectorType()) {
1446 CheckVectorType(Entity, IList, DeclType, Index,
1447 StructuredList, StructuredIndex);
1448 } else if (DeclType->isMatrixType()) {
1449 CheckMatrixType(Entity, IList, DeclType, Index, StructuredList,
1450 StructuredIndex);
1451 } else if (const RecordDecl *RD = DeclType->getAsRecordDecl()) {
1452 auto Bases =
1455 if (DeclType->isRecordType()) {
1456 assert(DeclType->isAggregateType() &&
1457 "non-aggregate records should be handed in CheckSubElementType");
1458 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1459 Bases = CXXRD->bases();
1460 } else {
1461 Bases = cast<CXXRecordDecl>(RD)->bases();
1462 }
1463 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1464 SubobjectIsDesignatorContext, Index, StructuredList,
1465 StructuredIndex, TopLevelObject);
1466 } else if (DeclType->isArrayType()) {
1467 llvm::APSInt Zero(
1468 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1469 false);
1470 CheckArrayType(Entity, IList, DeclType, Zero,
1471 SubobjectIsDesignatorContext, Index,
1472 StructuredList, StructuredIndex);
1473 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1474 // This type is invalid, issue a diagnostic.
1475 ++Index;
1476 if (!VerifyOnly)
1477 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1478 << DeclType;
1479 hadError = true;
1480 } else if (DeclType->isReferenceType()) {
1481 CheckReferenceType(Entity, IList, DeclType, Index,
1482 StructuredList, StructuredIndex);
1483 } else if (DeclType->isObjCObjectType()) {
1484 if (!VerifyOnly)
1485 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1486 hadError = true;
1487 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1488 DeclType->isSizelessBuiltinType()) {
1489 // Checks for scalar type are sufficient for these types too.
1490 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1491 StructuredIndex);
1492 } else if (DeclType->isDependentType()) {
1493 // C++ [over.match.class.deduct]p1.5:
1494 // brace elision is not considered for any aggregate element that has a
1495 // dependent non-array type or an array type with a value-dependent bound
1496 ++Index;
1497 assert(AggrDeductionCandidateParamTypes);
1498 AggrDeductionCandidateParamTypes->push_back(DeclType);
1499 } else {
1500 if (!VerifyOnly)
1501 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1502 << DeclType;
1503 hadError = true;
1504 }
1505}
1506
1507void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1508 InitListExpr *IList,
1509 QualType ElemType,
1510 unsigned &Index,
1511 InitListExpr *StructuredList,
1512 unsigned &StructuredIndex,
1513 bool DirectlyDesignated) {
1514 Expr *expr = IList->getInit(Index);
1515
1516 if (ElemType->isReferenceType())
1517 return CheckReferenceType(Entity, IList, ElemType, Index,
1518 StructuredList, StructuredIndex);
1519
1520 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1521 if (SubInitList->getNumInits() == 1 &&
1522 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1523 SIF_None) {
1524 // FIXME: It would be more faithful and no less correct to include an
1525 // InitListExpr in the semantic form of the initializer list in this case.
1526 expr = SubInitList->getInit(0);
1527 }
1528 // Nested aggregate initialization and C++ initialization are handled later.
1529 } else if (isa<ImplicitValueInitExpr>(expr)) {
1530 // This happens during template instantiation when we see an InitListExpr
1531 // that we've already checked once.
1532 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1533 "found implicit initialization for the wrong type");
1534 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1535 ++Index;
1536 return;
1537 }
1538
1539 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1540 // C++ [dcl.init.aggr]p2:
1541 // Each member is copy-initialized from the corresponding
1542 // initializer-clause.
1543
1544 // FIXME: Better EqualLoc?
1545 InitializationKind Kind =
1546 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1547
1548 // Vector elements can be initialized from other vectors in which case
1549 // we need initialization entity with a type of a vector (and not a vector
1550 // element!) initializing multiple vector elements.
1551 auto TmpEntity =
1552 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1554 : Entity;
1555
1556 if (TmpEntity.getType()->isDependentType()) {
1557 // C++ [over.match.class.deduct]p1.5:
1558 // brace elision is not considered for any aggregate element that has a
1559 // dependent non-array type or an array type with a value-dependent
1560 // bound
1561 assert(AggrDeductionCandidateParamTypes);
1562
1563 // In the presence of a braced-init-list within the initializer, we should
1564 // not perform brace-elision, even if brace elision would otherwise be
1565 // applicable. For example, given:
1566 //
1567 // template <class T> struct Foo {
1568 // T t[2];
1569 // };
1570 //
1571 // Foo t = {{1, 2}};
1572 //
1573 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1574 // {{1, 2}}.
1576 !isa_and_present<ConstantArrayType>(
1577 SemaRef.Context.getAsArrayType(ElemType))) {
1578 ++Index;
1579 AggrDeductionCandidateParamTypes->push_back(ElemType);
1580 return;
1581 }
1582 } else {
1583 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1584 /*TopLevelOfInitList*/ true);
1585 // C++14 [dcl.init.aggr]p13:
1586 // If the assignment-expression can initialize a member, the member is
1587 // initialized. Otherwise [...] brace elision is assumed
1588 //
1589 // Brace elision is never performed if the element is not an
1590 // assignment-expression.
1591 if (Seq || isa<InitListExpr>(expr)) {
1592 if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1593 expr = HandleEmbed(Embed, Entity);
1594 }
1595 if (!VerifyOnly) {
1596 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1597 if (Result.isInvalid())
1598 hadError = true;
1599
1600 UpdateStructuredListElement(StructuredList, StructuredIndex,
1601 Result.getAs<Expr>());
1602 } else if (!Seq) {
1603 hadError = true;
1604 } else if (StructuredList) {
1605 UpdateStructuredListElement(StructuredList, StructuredIndex,
1606 getDummyInit());
1607 }
1608 if (!CurEmbed)
1609 ++Index;
1610 if (AggrDeductionCandidateParamTypes)
1611 AggrDeductionCandidateParamTypes->push_back(ElemType);
1612 return;
1613 }
1614 }
1615
1616 // Fall through for subaggregate initialization
1617 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1618 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1619 return CheckScalarType(Entity, IList, ElemType, Index,
1620 StructuredList, StructuredIndex);
1621 } else if (const ArrayType *arrayType =
1622 SemaRef.Context.getAsArrayType(ElemType)) {
1623 // arrayType can be incomplete if we're initializing a flexible
1624 // array member. There's nothing we can do with the completed
1625 // type here, though.
1626
1627 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1628 // FIXME: Should we do this checking in verify-only mode?
1629 if (!VerifyOnly)
1630 CheckStringInit(expr, ElemType, arrayType, SemaRef, Entity,
1631 SemaRef.getLangOpts().C23 &&
1633 if (StructuredList)
1634 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1635 ++Index;
1636 return;
1637 }
1638
1639 // Fall through for subaggregate initialization.
1640
1641 } else {
1642 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1643 ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) &&
1644 "Unexpected type");
1645
1646 // C99 6.7.8p13:
1647 //
1648 // The initializer for a structure or union object that has
1649 // automatic storage duration shall be either an initializer
1650 // list as described below, or a single expression that has
1651 // compatible structure or union type. In the latter case, the
1652 // initial value of the object, including unnamed members, is
1653 // that of the expression.
1654 ExprResult ExprRes = expr;
1655 if (SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
1656 !VerifyOnly) !=
1657 AssignConvertType::Incompatible) {
1658 if (ExprRes.isInvalid())
1659 hadError = true;
1660 else {
1661 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1662 if (ExprRes.isInvalid())
1663 hadError = true;
1664 }
1665 UpdateStructuredListElement(StructuredList, StructuredIndex,
1666 ExprRes.getAs<Expr>());
1667 ++Index;
1668 return;
1669 }
1670 ExprRes.get();
1671 // Fall through for subaggregate initialization
1672 }
1673
1674 // C++ [dcl.init.aggr]p12:
1675 //
1676 // [...] Otherwise, if the member is itself a non-empty
1677 // subaggregate, brace elision is assumed and the initializer is
1678 // considered for the initialization of the first member of
1679 // the subaggregate.
1680 // OpenCL vector initializer is handled elsewhere.
1681 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1682 ElemType->isAggregateType()) {
1683 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1684 StructuredIndex);
1685 ++StructuredIndex;
1686
1687 // In C++20, brace elision is not permitted for a designated initializer.
1688 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1689 if (InOverloadResolution)
1690 hadError = true;
1691 if (!VerifyOnly) {
1692 SemaRef.Diag(expr->getBeginLoc(),
1693 diag::ext_designated_init_brace_elision)
1694 << expr->getSourceRange()
1695 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1697 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1698 }
1699 }
1700 } else {
1701 if (!VerifyOnly) {
1702 // We cannot initialize this element, so let PerformCopyInitialization
1703 // produce the appropriate diagnostic. We already checked that this
1704 // initialization will fail.
1706 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1707 /*TopLevelOfInitList=*/true);
1708 (void)Copy;
1709 assert(Copy.isInvalid() &&
1710 "expected non-aggregate initialization to fail");
1711 }
1712 hadError = true;
1713 ++Index;
1714 ++StructuredIndex;
1715 }
1716}
1717
1718void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1719 InitListExpr *IList, QualType DeclType,
1720 unsigned &Index,
1721 InitListExpr *StructuredList,
1722 unsigned &StructuredIndex) {
1723 assert(Index == 0 && "Index in explicit init list must be zero");
1724
1725 // As an extension, clang supports complex initializers, which initialize
1726 // a complex number component-wise. When an explicit initializer list for
1727 // a complex number contains two initializers, this extension kicks in:
1728 // it expects the initializer list to contain two elements convertible to
1729 // the element type of the complex type. The first element initializes
1730 // the real part, and the second element intitializes the imaginary part.
1731
1732 if (IList->getNumInits() < 2)
1733 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1734 StructuredIndex);
1735
1736 // This is an extension in C. (The builtin _Complex type does not exist
1737 // in the C++ standard.)
1738 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1739 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1740 << IList->getSourceRange();
1741
1742 // Initialize the complex number.
1743 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1744 InitializedEntity ElementEntity =
1746
1747 for (unsigned i = 0; i < 2; ++i) {
1748 ElementEntity.setElementIndex(Index);
1749 CheckSubElementType(ElementEntity, IList, elementType, Index,
1750 StructuredList, StructuredIndex);
1751 }
1752}
1753
1754void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1755 InitListExpr *IList, QualType DeclType,
1756 unsigned &Index,
1757 InitListExpr *StructuredList,
1758 unsigned &StructuredIndex) {
1759 if (Index >= IList->getNumInits()) {
1760 if (!VerifyOnly) {
1761 if (SemaRef.getLangOpts().CPlusPlus) {
1762 if (DeclType->isSizelessBuiltinType())
1763 SemaRef.Diag(IList->getBeginLoc(),
1764 SemaRef.getLangOpts().CPlusPlus11
1765 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1766 : diag::err_empty_sizeless_initializer)
1767 << DeclType << IList->getSourceRange();
1768 else
1769 SemaRef.Diag(IList->getBeginLoc(),
1770 SemaRef.getLangOpts().CPlusPlus11
1771 ? diag::warn_cxx98_compat_empty_scalar_initializer
1772 : diag::err_empty_scalar_initializer)
1773 << IList->getSourceRange();
1774 }
1775 }
1776 hadError =
1777 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1778 ++Index;
1779 ++StructuredIndex;
1780 return;
1781 }
1782
1783 Expr *expr = IList->getInit(Index);
1784 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1785 // FIXME: This is invalid, and accepting it causes overload resolution
1786 // to pick the wrong overload in some corner cases.
1787 if (!VerifyOnly)
1788 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1789 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1790
1791 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1792 StructuredIndex);
1793 return;
1794 } else if (isa<DesignatedInitExpr>(expr)) {
1795 if (!VerifyOnly)
1796 SemaRef.Diag(expr->getBeginLoc(),
1797 diag::err_designator_for_scalar_or_sizeless_init)
1798 << DeclType->isSizelessBuiltinType() << DeclType
1799 << expr->getSourceRange();
1800 hadError = true;
1801 ++Index;
1802 ++StructuredIndex;
1803 return;
1804 } else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1805 expr = HandleEmbed(Embed, Entity);
1806 }
1807
1809 if (VerifyOnly) {
1810 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1811 Result = getDummyInit();
1812 else
1813 Result = ExprError();
1814 } else {
1815 Result =
1816 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1817 /*TopLevelOfInitList=*/true);
1818 }
1819
1820 Expr *ResultExpr = nullptr;
1821
1822 if (Result.isInvalid())
1823 hadError = true; // types weren't compatible.
1824 else {
1825 ResultExpr = Result.getAs<Expr>();
1826
1827 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1828 // The type was promoted, update initializer list.
1829 // FIXME: Why are we updating the syntactic init list?
1830 IList->setInit(Index, ResultExpr);
1831 }
1832 }
1833
1834 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1835 if (!CurEmbed)
1836 ++Index;
1837 if (AggrDeductionCandidateParamTypes)
1838 AggrDeductionCandidateParamTypes->push_back(DeclType);
1839}
1840
1841void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1842 InitListExpr *IList, QualType DeclType,
1843 unsigned &Index,
1844 InitListExpr *StructuredList,
1845 unsigned &StructuredIndex) {
1846 if (Index >= IList->getNumInits()) {
1847 // FIXME: It would be wonderful if we could point at the actual member. In
1848 // general, it would be useful to pass location information down the stack,
1849 // so that we know the location (or decl) of the "current object" being
1850 // initialized.
1851 if (!VerifyOnly)
1852 SemaRef.Diag(IList->getBeginLoc(),
1853 diag::err_init_reference_member_uninitialized)
1854 << DeclType << IList->getSourceRange();
1855 hadError = true;
1856 ++Index;
1857 ++StructuredIndex;
1858 return;
1859 }
1860
1861 Expr *expr = IList->getInit(Index);
1862 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1863 if (!VerifyOnly)
1864 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1865 << DeclType << IList->getSourceRange();
1866 hadError = true;
1867 ++Index;
1868 ++StructuredIndex;
1869 return;
1870 }
1871
1873 if (VerifyOnly) {
1874 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1875 Result = getDummyInit();
1876 else
1877 Result = ExprError();
1878 } else {
1879 Result =
1880 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1881 /*TopLevelOfInitList=*/true);
1882 }
1883
1884 if (Result.isInvalid())
1885 hadError = true;
1886
1887 expr = Result.getAs<Expr>();
1888 // FIXME: Why are we updating the syntactic init list?
1889 if (!VerifyOnly && expr)
1890 IList->setInit(Index, expr);
1891
1892 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1893 ++Index;
1894 if (AggrDeductionCandidateParamTypes)
1895 AggrDeductionCandidateParamTypes->push_back(DeclType);
1896}
1897
1898void InitListChecker::CheckMatrixType(const InitializedEntity &Entity,
1899 InitListExpr *IList, QualType DeclType,
1900 unsigned &Index,
1901 InitListExpr *StructuredList,
1902 unsigned &StructuredIndex) {
1903 if (!SemaRef.getLangOpts().HLSL)
1904 return;
1905
1906 const ConstantMatrixType *MT = DeclType->castAs<ConstantMatrixType>();
1907
1908 // For HLSL, the error reporting for this case is handled in SemaHLSL's
1909 // initializer list diagnostics. That means the execution should require
1910 // getNumElementsFlattened to equal getNumInits. In other words the execution
1911 // should never reach this point if this condition is not true".
1912 assert(IList->getNumInits() == MT->getNumElementsFlattened() &&
1913 "Inits must equal Matrix element count");
1914
1915 QualType ElemTy = MT->getElementType();
1916
1917 Index = 0;
1918 InitializedEntity Element =
1920
1921 while (Index < IList->getNumInits()) {
1922 // Not a sublist: just consume directly.
1923 // Note: In HLSL, elements of the InitListExpr are in row-major order, so no
1924 // change is needed to the Index.
1925 Element.setElementIndex(Index);
1926 CheckSubElementType(Element, IList, ElemTy, Index, StructuredList,
1927 StructuredIndex);
1928 }
1929}
1930
1931void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1932 InitListExpr *IList, QualType DeclType,
1933 unsigned &Index,
1934 InitListExpr *StructuredList,
1935 unsigned &StructuredIndex) {
1936 const VectorType *VT = DeclType->castAs<VectorType>();
1937 unsigned maxElements = VT->getNumElements();
1938 unsigned numEltsInit = 0;
1939 QualType elementType = VT->getElementType();
1940
1941 if (Index >= IList->getNumInits()) {
1942 // Make sure the element type can be value-initialized.
1943 CheckEmptyInitializable(
1945 IList->getEndLoc());
1946 return;
1947 }
1948
1949 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1950 // If the initializing element is a vector, try to copy-initialize
1951 // instead of breaking it apart (which is doomed to failure anyway).
1952 Expr *Init = IList->getInit(Index);
1953 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1955 if (VerifyOnly) {
1956 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1957 Result = getDummyInit();
1958 else
1959 Result = ExprError();
1960 } else {
1961 Result =
1962 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1963 /*TopLevelOfInitList=*/true);
1964 }
1965
1966 Expr *ResultExpr = nullptr;
1967 if (Result.isInvalid())
1968 hadError = true; // types weren't compatible.
1969 else {
1970 ResultExpr = Result.getAs<Expr>();
1971
1972 if (ResultExpr != Init && !VerifyOnly) {
1973 // The type was promoted, update initializer list.
1974 // FIXME: Why are we updating the syntactic init list?
1975 IList->setInit(Index, ResultExpr);
1976 }
1977 }
1978 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1979 ++Index;
1980 if (AggrDeductionCandidateParamTypes)
1981 AggrDeductionCandidateParamTypes->push_back(elementType);
1982 return;
1983 }
1984
1985 InitializedEntity ElementEntity =
1987
1988 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1989 // Don't attempt to go past the end of the init list
1990 if (Index >= IList->getNumInits()) {
1991 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1992 break;
1993 }
1994
1995 ElementEntity.setElementIndex(Index);
1996 CheckSubElementType(ElementEntity, IList, elementType, Index,
1997 StructuredList, StructuredIndex);
1998 }
1999
2000 if (VerifyOnly)
2001 return;
2002
2003 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
2004 const VectorType *T = Entity.getType()->castAs<VectorType>();
2005 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
2006 T->getVectorKind() == VectorKind::NeonPoly)) {
2007 // The ability to use vector initializer lists is a GNU vector extension
2008 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
2009 // endian machines it works fine, however on big endian machines it
2010 // exhibits surprising behaviour:
2011 //
2012 // uint32x2_t x = {42, 64};
2013 // return vget_lane_u32(x, 0); // Will return 64.
2014 //
2015 // Because of this, explicitly call out that it is non-portable.
2016 //
2017 SemaRef.Diag(IList->getBeginLoc(),
2018 diag::warn_neon_vector_initializer_non_portable);
2019
2020 const char *typeCode;
2021 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
2022
2023 if (elementType->isFloatingType())
2024 typeCode = "f";
2025 else if (elementType->isSignedIntegerType())
2026 typeCode = "s";
2027 else if (elementType->isUnsignedIntegerType())
2028 typeCode = "u";
2029 else if (elementType->isMFloat8Type())
2030 typeCode = "mf";
2031 else
2032 llvm_unreachable("Invalid element type!");
2033
2034 SemaRef.Diag(IList->getBeginLoc(),
2035 SemaRef.Context.getTypeSize(VT) > 64
2036 ? diag::note_neon_vector_initializer_non_portable_q
2037 : diag::note_neon_vector_initializer_non_portable)
2038 << typeCode << typeSize;
2039 }
2040
2041 return;
2042 }
2043
2044 InitializedEntity ElementEntity =
2046
2047 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2048 for (unsigned i = 0; i < maxElements; ++i) {
2049 // Don't attempt to go past the end of the init list
2050 if (Index >= IList->getNumInits())
2051 break;
2052
2053 ElementEntity.setElementIndex(Index);
2054
2055 QualType IType = IList->getInit(Index)->getType();
2056 if (!IType->isVectorType()) {
2057 CheckSubElementType(ElementEntity, IList, elementType, Index,
2058 StructuredList, StructuredIndex);
2059 ++numEltsInit;
2060 } else {
2061 QualType VecType;
2062 const VectorType *IVT = IType->castAs<VectorType>();
2063 unsigned numIElts = IVT->getNumElements();
2064
2065 if (IType->isExtVectorType())
2066 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
2067 else
2068 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
2069 IVT->getVectorKind());
2070 CheckSubElementType(ElementEntity, IList, VecType, Index,
2071 StructuredList, StructuredIndex);
2072 numEltsInit += numIElts;
2073 }
2074 }
2075
2076 // OpenCL and HLSL require all elements to be initialized.
2077 if (numEltsInit != maxElements) {
2078 if (!VerifyOnly)
2079 SemaRef.Diag(IList->getBeginLoc(),
2080 diag::err_vector_incorrect_num_elements)
2081 << (numEltsInit < maxElements) << maxElements << numEltsInit
2082 << /*initialization*/ 0;
2083 hadError = true;
2084 }
2085}
2086
2087/// Check if the type of a class element has an accessible destructor, and marks
2088/// it referenced. Returns true if we shouldn't form a reference to the
2089/// destructor.
2090///
2091/// Aggregate initialization requires a class element's destructor be
2092/// accessible per 11.6.1 [dcl.init.aggr]:
2093///
2094/// The destructor for each element of class type is potentially invoked
2095/// (15.4 [class.dtor]) from the context where the aggregate initialization
2096/// occurs.
2098 Sema &SemaRef) {
2099 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2100 // Bail out on incomplete record types: a forward-declared class has no
2101 // destructor to look up, and `LookupDestructor` (via `LookupSpecialMember`)
2102 // asserts that the record is fully defined. Error recovery for init lists
2103 // of incomplete element types reaches this point even after the parser has
2104 // already diagnosed the incompleteness.
2105 if (!CXXRD || !CXXRD->hasDefinition())
2106 return false;
2107
2109 if (!Destructor)
2110 return false;
2111
2112 SemaRef.CheckDestructorAccess(Loc, Destructor,
2113 SemaRef.PDiag(diag::err_access_dtor_temp)
2114 << ElementType);
2115 SemaRef.MarkFunctionReferenced(Loc, Destructor);
2116 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
2117}
2118
2119static bool
2121 const InitializedEntity &Entity,
2122 ASTContext &Context) {
2123 QualType InitType = Entity.getType();
2124 const InitializedEntity *Parent = &Entity;
2125
2126 while (Parent) {
2127 InitType = Parent->getType();
2128 Parent = Parent->getParent();
2129 }
2130
2131 // Only one initializer, it's an embed and the types match;
2132 EmbedExpr *EE =
2133 ExprList.size() == 1
2134 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2135 : nullptr;
2136 if (!EE)
2137 return false;
2138
2139 if (InitType->isArrayType()) {
2140 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2142 return IsStringInit(SL, InitArrayType, Context) == SIF_None;
2143 }
2144 return false;
2145}
2146
2147void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2148 InitListExpr *IList, QualType &DeclType,
2149 llvm::APSInt elementIndex,
2150 bool SubobjectIsDesignatorContext,
2151 unsigned &Index,
2152 InitListExpr *StructuredList,
2153 unsigned &StructuredIndex) {
2154 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2155
2156 if (!VerifyOnly) {
2157 if (checkDestructorReference(arrayType->getElementType(),
2158 IList->getEndLoc(), SemaRef)) {
2159 hadError = true;
2160 return;
2161 }
2162 }
2163
2164 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2165 SemaRef.Context)) {
2166 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2167 IList->setInit(0, Embed->getDataStringLiteral());
2168 }
2169
2170 // Check for the special-case of initializing an array with a string.
2171 if (Index < IList->getNumInits()) {
2172 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2173 SIF_None) {
2174 // We place the string literal directly into the resulting
2175 // initializer list. This is the only place where the structure
2176 // of the structured initializer list doesn't match exactly,
2177 // because doing so would involve allocating one character
2178 // constant for each string.
2179 // FIXME: Should we do these checks in verify-only mode too?
2180 if (!VerifyOnly)
2182 IList->getInit(Index), DeclType, arrayType, SemaRef, Entity,
2183 SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2184 if (StructuredList) {
2185 UpdateStructuredListElement(StructuredList, StructuredIndex,
2186 IList->getInit(Index));
2187 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2188 }
2189 ++Index;
2190 if (AggrDeductionCandidateParamTypes)
2191 AggrDeductionCandidateParamTypes->push_back(DeclType);
2192 return;
2193 }
2194 }
2195 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2196 // Check for VLAs; in standard C it would be possible to check this
2197 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2198 // them in all sorts of strange places).
2199 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2200 if (!VerifyOnly) {
2201 // C23 6.7.10p4: An entity of variable length array type shall not be
2202 // initialized except by an empty initializer.
2203 //
2204 // The C extension warnings are issued from ParseBraceInitializer() and
2205 // do not need to be issued here. However, we continue to issue an error
2206 // in the case there are initializers or we are compiling C++. We allow
2207 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2208 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2209 // FIXME: should we allow this construct in C++ when it makes sense to do
2210 // so?
2211 if (HasErr)
2212 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2213 diag::err_variable_object_no_init)
2214 << VAT->getSizeExpr()->getSourceRange();
2215 }
2216 hadError = HasErr;
2217 ++Index;
2218 ++StructuredIndex;
2219 return;
2220 }
2221
2222 // We might know the maximum number of elements in advance.
2223 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2224 elementIndex.isUnsigned());
2225 bool maxElementsKnown = false;
2226 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2227 maxElements = CAT->getSize();
2228 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2229 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2230 maxElementsKnown = true;
2231 }
2232
2233 QualType elementType = arrayType->getElementType();
2234 while (Index < IList->getNumInits()) {
2235 Expr *Init = IList->getInit(Index);
2236 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2237 // If we're not the subobject that matches up with the '{' for
2238 // the designator, we shouldn't be handling the
2239 // designator. Return immediately.
2240 if (!SubobjectIsDesignatorContext)
2241 return;
2242
2243 // Handle this designated initializer. elementIndex will be
2244 // updated to be the next array element we'll initialize.
2245 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2246 DeclType, nullptr, &elementIndex, Index,
2247 StructuredList, StructuredIndex, true,
2248 false)) {
2249 hadError = true;
2250 continue;
2251 }
2252
2253 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2254 maxElements = maxElements.extend(elementIndex.getBitWidth());
2255 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2256 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2257 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2258
2259 // If the array is of incomplete type, keep track of the number of
2260 // elements in the initializer.
2261 if (!maxElementsKnown && elementIndex > maxElements)
2262 maxElements = elementIndex;
2263
2264 continue;
2265 }
2266
2267 // If we know the maximum number of elements, and we've already
2268 // hit it, stop consuming elements in the initializer list.
2269 if (maxElementsKnown && elementIndex == maxElements)
2270 break;
2271
2272 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2273 SemaRef.Context, StructuredIndex, Entity);
2274 ElementEntity.setElementIndex(elementIndex.getExtValue());
2275
2276 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2277 // Check this element.
2278 CheckSubElementType(ElementEntity, IList, elementType, Index,
2279 StructuredList, StructuredIndex);
2280 ++elementIndex;
2281 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2282 if (CurEmbed) {
2283 elementIndex =
2284 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2285 } else {
2286 auto Embed = cast<EmbedExpr>(Init);
2287 elementIndex = elementIndex + Embed->getDataElementCount() -
2288 EmbedElementIndexBeforeInit - 1;
2289 }
2290 }
2291
2292 // If the array is of incomplete type, keep track of the number of
2293 // elements in the initializer.
2294 if (!maxElementsKnown && elementIndex > maxElements)
2295 maxElements = elementIndex;
2296 }
2297 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2298 // If this is an incomplete array type, the actual type needs to
2299 // be calculated here.
2300 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2301 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2302 // Sizing an array implicitly to zero is not allowed by ISO C,
2303 // but is supported by GNU.
2304 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2305 }
2306
2307 DeclType = SemaRef.Context.getConstantArrayType(
2308 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2309 }
2310 if (!hadError) {
2311 // If there are any members of the array that get value-initialized, check
2312 // that is possible. That happens if we know the bound and don't have
2313 // enough elements, or if we're performing an array new with an unknown
2314 // bound.
2315 if ((maxElementsKnown && elementIndex < maxElements) ||
2316 Entity.isVariableLengthArrayNew())
2317 CheckEmptyInitializable(
2319 IList->getEndLoc());
2320 }
2321}
2322
2323bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2324 Expr *InitExpr,
2325 FieldDecl *Field,
2326 bool TopLevelObject) {
2327 // Handle GNU flexible array initializers.
2328 unsigned FlexArrayDiag;
2329 if (isa<InitListExpr>(InitExpr) &&
2330 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2331 // Empty flexible array init always allowed as an extension
2332 FlexArrayDiag = diag::ext_flexible_array_init;
2333 } else if (!TopLevelObject) {
2334 // Disallow flexible array init on non-top-level object
2335 FlexArrayDiag = diag::err_flexible_array_init;
2336 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2337 // Disallow flexible array init on anything which is not a variable.
2338 FlexArrayDiag = diag::err_flexible_array_init;
2339 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2340 // Disallow flexible array init on local variables.
2341 FlexArrayDiag = diag::err_flexible_array_init;
2342 } else {
2343 // Allow other cases.
2344 FlexArrayDiag = diag::ext_flexible_array_init;
2345 }
2346
2347 if (!VerifyOnly) {
2348 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2349 << InitExpr->getBeginLoc();
2350 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2351 << Field;
2352 }
2353
2354 return FlexArrayDiag != diag::ext_flexible_array_init;
2355}
2356
2357static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2358 return StructuredList && StructuredList->getNumInits() == 1U;
2359}
2360
2361void InitListChecker::CheckStructUnionTypes(
2362 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2364 bool SubobjectIsDesignatorContext, unsigned &Index,
2365 InitListExpr *StructuredList, unsigned &StructuredIndex,
2366 bool TopLevelObject) {
2367 const RecordDecl *RD = DeclType->getAsRecordDecl();
2368
2369 // If the record is invalid, some of it's members are invalid. To avoid
2370 // confusion, we forgo checking the initializer for the entire record.
2371 if (RD->isInvalidDecl()) {
2372 // Assume it was supposed to consume a single initializer.
2373 ++Index;
2374 hadError = true;
2375 return;
2376 }
2377
2378 if (RD->isUnion() && IList->getNumInits() == 0) {
2379 if (!VerifyOnly)
2380 for (FieldDecl *FD : RD->fields()) {
2381 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2382 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2383 hadError = true;
2384 return;
2385 }
2386 }
2387
2388 // If there's a default initializer, use it.
2389 if (isa<CXXRecordDecl>(RD) &&
2390 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2391 if (!StructuredList)
2392 return;
2393 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2394 Field != FieldEnd; ++Field) {
2395 if (Field->hasInClassInitializer() ||
2396 (Field->isAnonymousStructOrUnion() &&
2397 Field->getType()
2398 ->castAsCXXRecordDecl()
2399 ->hasInClassInitializer())) {
2400 StructuredList->setInitializedFieldInUnion(*Field);
2401 // FIXME: Actually build a CXXDefaultInitExpr?
2402 return;
2403 }
2404 }
2405 llvm_unreachable("Couldn't find in-class initializer");
2406 }
2407
2408 // Value-initialize the first member of the union that isn't an unnamed
2409 // bitfield.
2410 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2411 Field != FieldEnd; ++Field) {
2412 if (!Field->isUnnamedBitField()) {
2413 CheckEmptyInitializable(
2414 InitializedEntity::InitializeMember(*Field, &Entity),
2415 IList->getEndLoc());
2416 if (StructuredList)
2417 StructuredList->setInitializedFieldInUnion(*Field);
2418 break;
2419 }
2420 }
2421 return;
2422 }
2423
2424 bool InitializedSomething = false;
2425
2426 // If we have any base classes, they are initialized prior to the fields.
2427 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2428 auto &Base = *I;
2429 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2430
2431 // Designated inits always initialize fields, so if we see one, all
2432 // remaining base classes have no explicit initializer.
2433 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2434 Init = nullptr;
2435
2436 // C++ [over.match.class.deduct]p1.6:
2437 // each non-trailing aggregate element that is a pack expansion is assumed
2438 // to correspond to no elements of the initializer list, and (1.7) a
2439 // trailing aggregate element that is a pack expansion is assumed to
2440 // correspond to all remaining elements of the initializer list (if any).
2441
2442 // C++ [over.match.class.deduct]p1.9:
2443 // ... except that additional parameter packs of the form P_j... are
2444 // inserted into the parameter list in their original aggregate element
2445 // position corresponding to each non-trailing aggregate element of
2446 // type P_j that was skipped because it was a parameter pack, and the
2447 // trailing sequence of parameters corresponding to a trailing
2448 // aggregate element that is a pack expansion (if any) is replaced
2449 // by a single parameter of the form T_n....
2450 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2451 AggrDeductionCandidateParamTypes->push_back(
2452 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2453
2454 // Trailing pack expansion
2455 if (I + 1 == E && RD->field_empty()) {
2456 if (Index < IList->getNumInits())
2457 Index = IList->getNumInits();
2458 return;
2459 }
2460
2461 continue;
2462 }
2463
2464 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2465 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2466 SemaRef.Context, &Base, false, &Entity);
2467 if (Init) {
2468 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2469 StructuredList, StructuredIndex);
2470 InitializedSomething = true;
2471 } else {
2472 CheckEmptyInitializable(BaseEntity, InitLoc);
2473 }
2474
2475 if (!VerifyOnly)
2476 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2477 hadError = true;
2478 return;
2479 }
2480 }
2481
2482 // If structDecl is a forward declaration, this loop won't do
2483 // anything except look at designated initializers; That's okay,
2484 // because an error should get printed out elsewhere. It might be
2485 // worthwhile to skip over the rest of the initializer, though.
2486 RecordDecl::field_iterator FieldEnd = RD->field_end();
2487 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2488 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2489 });
2490 bool HasDesignatedInit = false;
2491
2492 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2493
2494 while (Index < IList->getNumInits()) {
2495 Expr *Init = IList->getInit(Index);
2496 SourceLocation InitLoc = Init->getBeginLoc();
2497
2498 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2499 // If we're not the subobject that matches up with the '{' for
2500 // the designator, we shouldn't be handling the
2501 // designator. Return immediately.
2502 if (!SubobjectIsDesignatorContext)
2503 return;
2504
2505 HasDesignatedInit = true;
2506
2507 // Handle this designated initializer. Field will be updated to
2508 // the next field that we'll be initializing.
2509 bool DesignatedInitFailed = CheckDesignatedInitializer(
2510 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2511 StructuredList, StructuredIndex, true, TopLevelObject);
2512 if (DesignatedInitFailed)
2513 hadError = true;
2514
2515 // Find the field named by the designated initializer.
2516 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2517 if (!VerifyOnly && D->isFieldDesignator()) {
2518 FieldDecl *F = D->getFieldDecl();
2519 InitializedFields.insert(F);
2520 if (!DesignatedInitFailed) {
2521 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2522 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2523 hadError = true;
2524 return;
2525 }
2526 }
2527 }
2528
2529 InitializedSomething = true;
2530 continue;
2531 }
2532
2533 // Check if this is an initializer of forms:
2534 //
2535 // struct foo f = {};
2536 // struct foo g = {0};
2537 //
2538 // These are okay for randomized structures. [C99 6.7.8p19]
2539 //
2540 // Also, if there is only one element in the structure, we allow something
2541 // like this, because it's really not randomized in the traditional sense.
2542 //
2543 // struct foo h = {bar};
2544 auto IsZeroInitializer = [&](const Expr *I) {
2545 if (IList->getNumInits() == 1) {
2546 if (NumRecordDecls == 1)
2547 return true;
2548 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2549 return IL->getValue().isZero();
2550 }
2551 return false;
2552 };
2553
2554 // Don't allow non-designated initializers on randomized structures.
2555 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2556 if (!VerifyOnly)
2557 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2558 hadError = true;
2559 break;
2560 }
2561
2562 if (Field == FieldEnd) {
2563 // We've run out of fields. We're done.
2564 break;
2565 }
2566
2567 // We've already initialized a member of a union. We can stop entirely.
2568 if (InitializedSomething && RD->isUnion())
2569 return;
2570
2571 // Stop if we've hit a flexible array member.
2572 if (Field->getType()->isIncompleteArrayType())
2573 break;
2574
2575 if (Field->isUnnamedBitField()) {
2576 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2577 ++Field;
2578 continue;
2579 }
2580
2581 // Make sure we can use this declaration.
2582 bool InvalidUse;
2583 if (VerifyOnly)
2584 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2585 else
2586 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2587 *Field, IList->getInit(Index)->getBeginLoc());
2588 if (InvalidUse) {
2589 ++Index;
2590 ++Field;
2591 hadError = true;
2592 continue;
2593 }
2594
2595 if (!VerifyOnly) {
2596 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2597 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2598 hadError = true;
2599 return;
2600 }
2601 }
2602
2603 InitializedEntity MemberEntity =
2604 InitializedEntity::InitializeMember(*Field, &Entity);
2605 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2606 StructuredList, StructuredIndex);
2607 InitializedSomething = true;
2608 InitializedFields.insert(*Field);
2609 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2610 // Initialize the first field within the union.
2611 StructuredList->setInitializedFieldInUnion(*Field);
2612 }
2613
2614 ++Field;
2615 }
2616
2617 // Emit warnings for missing struct field initializers.
2618 // This check is disabled for designated initializers in C.
2619 // This matches gcc behaviour.
2620 bool IsCDesignatedInitializer =
2621 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2622 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2623 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2624 !IsCDesignatedInitializer) {
2625 // It is possible we have one or more unnamed bitfields remaining.
2626 // Find first (if any) named field and emit warning.
2627 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2628 : Field,
2629 end = RD->field_end();
2630 it != end; ++it) {
2631 if (HasDesignatedInit && InitializedFields.count(*it))
2632 continue;
2633
2634 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2635 !it->getType()->isIncompleteArrayType()) {
2636 auto Diag = HasDesignatedInit
2637 ? diag::warn_missing_designated_field_initializers
2638 : diag::warn_missing_field_initializers;
2639 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2640 break;
2641 }
2642 }
2643 }
2644
2645 // Check that any remaining fields can be value-initialized if we're not
2646 // building a structured list. (If we are, we'll check this later.)
2647 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2648 !Field->getType()->isIncompleteArrayType()) {
2649 for (; Field != FieldEnd && !hadError; ++Field) {
2650 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2651 CheckEmptyInitializable(
2652 InitializedEntity::InitializeMember(*Field, &Entity),
2653 IList->getEndLoc());
2654 }
2655 }
2656
2657 // Check that the types of the remaining fields have accessible destructors.
2658 if (!VerifyOnly) {
2659 // If the initializer expression has a designated initializer, check the
2660 // elements for which a designated initializer is not provided too.
2661 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2662 : Field;
2663 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2664 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2665 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2666 hadError = true;
2667 return;
2668 }
2669 }
2670 }
2671
2672 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2673 Index >= IList->getNumInits())
2674 return;
2675
2676 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2677 TopLevelObject)) {
2678 hadError = true;
2679 ++Index;
2680 return;
2681 }
2682
2683 InitializedEntity MemberEntity =
2684 InitializedEntity::InitializeMember(*Field, &Entity);
2685
2686 if (isa<InitListExpr>(IList->getInit(Index)) ||
2687 AggrDeductionCandidateParamTypes)
2688 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2689 StructuredList, StructuredIndex);
2690 else
2691 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2692 StructuredList, StructuredIndex);
2693
2694 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2695 // Initialize the first field within the union.
2696 StructuredList->setInitializedFieldInUnion(*Field);
2697 }
2698}
2699
2700/// Expand a field designator that refers to a member of an
2701/// anonymous struct or union into a series of field designators that
2702/// refers to the field within the appropriate subobject.
2703///
2705 DesignatedInitExpr *DIE,
2706 unsigned DesigIdx,
2707 IndirectFieldDecl *IndirectField) {
2709
2710 // Build the replacement designators.
2711 SmallVector<Designator, 4> Replacements;
2712 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2713 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2714 if (PI + 1 == PE)
2715 Replacements.push_back(Designator::CreateFieldDesignator(
2716 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2717 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2718 else
2719 Replacements.push_back(Designator::CreateFieldDesignator(
2720 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2721 assert(isa<FieldDecl>(*PI));
2722 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2723 }
2724
2725 // Expand the current designator into the set of replacement
2726 // designators, so we have a full subobject path down to where the
2727 // member of the anonymous struct/union is actually stored.
2728 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2729 &Replacements[0] + Replacements.size());
2730}
2731
2733 DesignatedInitExpr *DIE) {
2734 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2735 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2736 for (unsigned I = 0; I < NumIndexExprs; ++I)
2737 IndexExprs[I] = DIE->getSubExpr(I + 1);
2738 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2739 IndexExprs,
2740 DIE->getEqualOrColonLoc(),
2741 DIE->usesGNUSyntax(), DIE->getInit());
2742}
2743
2744namespace {
2745
2746// Callback to only accept typo corrections that are for field members of
2747// the given struct or union.
2748class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2749 public:
2750 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2751 : Record(RD) {}
2752
2753 bool ValidateCandidate(const TypoCorrection &candidate) override {
2754 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2755 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2756 }
2757
2758 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2759 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2760 }
2761
2762 private:
2763 const RecordDecl *Record;
2764};
2765
2766} // end anonymous namespace
2767
2768/// Check the well-formedness of a C99 designated initializer.
2769///
2770/// Determines whether the designated initializer @p DIE, which
2771/// resides at the given @p Index within the initializer list @p
2772/// IList, is well-formed for a current object of type @p DeclType
2773/// (C99 6.7.8). The actual subobject that this designator refers to
2774/// within the current subobject is returned in either
2775/// @p NextField or @p NextElementIndex (whichever is appropriate).
2776///
2777/// @param IList The initializer list in which this designated
2778/// initializer occurs.
2779///
2780/// @param DIE The designated initializer expression.
2781///
2782/// @param DesigIdx The index of the current designator.
2783///
2784/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2785/// into which the designation in @p DIE should refer.
2786///
2787/// @param NextField If non-NULL and the first designator in @p DIE is
2788/// a field, this will be set to the field declaration corresponding
2789/// to the field named by the designator. On input, this is expected to be
2790/// the next field that would be initialized in the absence of designation,
2791/// if the complete object being initialized is a struct.
2792///
2793/// @param NextElementIndex If non-NULL and the first designator in @p
2794/// DIE is an array designator or GNU array-range designator, this
2795/// will be set to the last index initialized by this designator.
2796///
2797/// @param Index Index into @p IList where the designated initializer
2798/// @p DIE occurs.
2799///
2800/// @param StructuredList The initializer list expression that
2801/// describes all of the subobject initializers in the order they'll
2802/// actually be initialized.
2803///
2804/// @returns true if there was an error, false otherwise.
2805bool
2806InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2807 InitListExpr *IList,
2808 DesignatedInitExpr *DIE,
2809 unsigned DesigIdx,
2810 QualType &CurrentObjectType,
2811 RecordDecl::field_iterator *NextField,
2812 llvm::APSInt *NextElementIndex,
2813 unsigned &Index,
2814 InitListExpr *StructuredList,
2815 unsigned &StructuredIndex,
2816 bool FinishSubobjectInit,
2817 bool TopLevelObject) {
2818 if (DesigIdx == DIE->size()) {
2819 // C++20 designated initialization can result in direct-list-initialization
2820 // of the designated subobject. This is the only way that we can end up
2821 // performing direct initialization as part of aggregate initialization, so
2822 // it needs special handling.
2823 if (DIE->isDirectInit()) {
2824 Expr *Init = DIE->getInit();
2825 assert(isa<InitListExpr>(Init) &&
2826 "designator result in direct non-list initialization?");
2827 InitializationKind Kind = InitializationKind::CreateDirectList(
2828 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2829 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2830 /*TopLevelOfInitList*/ true);
2831 if (StructuredList) {
2832 ExprResult Result = VerifyOnly
2833 ? getDummyInit()
2834 : Seq.Perform(SemaRef, Entity, Kind, Init);
2835 UpdateStructuredListElement(StructuredList, StructuredIndex,
2836 Result.get());
2837 }
2838 ++Index;
2839 if (AggrDeductionCandidateParamTypes)
2840 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2841 return !Seq;
2842 }
2843
2844 // Check the actual initialization for the designated object type.
2845 bool prevHadError = hadError;
2846
2847 // Temporarily remove the designator expression from the
2848 // initializer list that the child calls see, so that we don't try
2849 // to re-process the designator.
2850 unsigned OldIndex = Index;
2851 auto *OldDIE =
2852 dyn_cast_if_present<DesignatedInitExpr>(IList->getInit(OldIndex));
2853 if (!OldDIE)
2854 OldDIE = DIE;
2855 IList->setInit(OldIndex, OldDIE->getInit());
2856
2857 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2858 StructuredIndex, /*DirectlyDesignated=*/true);
2859
2860 // Restore the designated initializer expression in the syntactic
2861 // form of the initializer list.
2862 if (IList->getInit(OldIndex) != OldDIE->getInit())
2863 OldDIE->setInit(IList->getInit(OldIndex));
2864 IList->setInit(OldIndex, OldDIE);
2865
2866 return hadError && !prevHadError;
2867 }
2868
2869 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2870 bool IsFirstDesignator = (DesigIdx == 0);
2871 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2872 // Determine the structural initializer list that corresponds to the
2873 // current subobject.
2874 if (IsFirstDesignator)
2875 StructuredList = FullyStructuredList;
2876 else {
2877 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2878 StructuredList->getInit(StructuredIndex) : nullptr;
2879 if (!ExistingInit && StructuredList->hasArrayFiller())
2880 ExistingInit = StructuredList->getArrayFiller();
2881
2882 if (!ExistingInit)
2883 StructuredList = getStructuredSubobjectInit(
2884 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2885 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2886 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2887 StructuredList = Result;
2888 else {
2889 // We are creating an initializer list that initializes the
2890 // subobjects of the current object, but there was already an
2891 // initialization that completely initialized the current
2892 // subobject, e.g., by a compound literal:
2893 //
2894 // struct X { int a, b; };
2895 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2896 //
2897 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2898 // designated initializer re-initializes only its current object
2899 // subobject [0].b.
2900 diagnoseInitOverride(ExistingInit,
2901 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2902 /*UnionOverride=*/false,
2903 /*FullyOverwritten=*/false);
2904
2905 if (!VerifyOnly) {
2906 if (DesignatedInitUpdateExpr *E =
2907 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2908 StructuredList = E->getUpdater();
2909 else {
2910 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2911 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2912 ExistingInit, DIE->getEndLoc());
2913 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2914 StructuredList = DIUE->getUpdater();
2915 }
2916 } else {
2917 // We don't need to track the structured representation of a
2918 // designated init update of an already-fully-initialized object in
2919 // verify-only mode. The only reason we would need the structure is
2920 // to determine where the uninitialized "holes" are, and in this
2921 // case, we know there aren't any and we can't introduce any.
2922 StructuredList = nullptr;
2923 }
2924 }
2925 }
2926 }
2927
2928 if (D->isFieldDesignator()) {
2929 // C99 6.7.8p7:
2930 //
2931 // If a designator has the form
2932 //
2933 // . identifier
2934 //
2935 // then the current object (defined below) shall have
2936 // structure or union type and the identifier shall be the
2937 // name of a member of that type.
2938 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2939 if (!RD) {
2940 SourceLocation Loc = D->getDotLoc();
2941 if (Loc.isInvalid())
2942 Loc = D->getFieldLoc();
2943 if (!VerifyOnly)
2944 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2945 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2946 ++Index;
2947 return true;
2948 }
2949
2950 FieldDecl *KnownField = D->getFieldDecl();
2951 if (!KnownField) {
2952 const IdentifierInfo *FieldName = D->getFieldName();
2953 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2954 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2955 KnownField = FD;
2956 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2957 // In verify mode, don't modify the original.
2958 if (VerifyOnly)
2959 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2960 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2961 D = DIE->getDesignator(DesigIdx);
2962 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2963 }
2964 if (!KnownField) {
2965 if (VerifyOnly) {
2966 ++Index;
2967 return true; // No typo correction when just trying this out.
2968 }
2969
2970 // We found a placeholder variable
2971 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2972 FieldName)) {
2973 ++Index;
2974 return true;
2975 }
2976 // Name lookup found something, but it wasn't a field.
2977 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2978 !Lookup.empty()) {
2979 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2980 << FieldName;
2981 SemaRef.Diag(Lookup.front()->getLocation(),
2982 diag::note_field_designator_found);
2983 ++Index;
2984 return true;
2985 }
2986
2987 // Name lookup didn't find anything.
2988 // Determine whether this was a typo for another field name.
2989 FieldInitializerValidatorCCC CCC(RD);
2990 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2991 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2992 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2993 CorrectTypoKind::ErrorRecovery, RD)) {
2994 SemaRef.diagnoseTypo(
2995 Corrected,
2996 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2997 << FieldName << CurrentObjectType);
2998 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2999 hadError = true;
3000 } else {
3001 // Typo correction didn't find anything.
3002 SourceLocation Loc = D->getFieldLoc();
3003
3004 // The loc can be invalid with a "null" designator (i.e. an anonymous
3005 // union/struct). Do our best to approximate the location.
3006 if (Loc.isInvalid())
3007 Loc = IList->getBeginLoc();
3008
3009 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
3010 << FieldName << CurrentObjectType << DIE->getSourceRange();
3011 ++Index;
3012 return true;
3013 }
3014 }
3015 }
3016
3017 unsigned NumBases = 0;
3018 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3019 NumBases = CXXRD->getNumBases();
3020
3021 unsigned FieldIndex = NumBases;
3022
3023 for (auto *FI : RD->fields()) {
3024 if (FI->isUnnamedBitField())
3025 continue;
3026 if (declaresSameEntity(KnownField, FI)) {
3027 KnownField = FI;
3028 break;
3029 }
3030 ++FieldIndex;
3031 }
3032
3034 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3035
3036 // All of the fields of a union are located at the same place in
3037 // the initializer list.
3038 if (RD->isUnion()) {
3039 FieldIndex = 0;
3040 if (StructuredList) {
3041 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3042 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
3043 assert(StructuredList->getNumInits() == 1
3044 && "A union should never have more than one initializer!");
3045
3046 Expr *ExistingInit = StructuredList->getInit(0);
3047 if (ExistingInit) {
3048 // We're about to throw away an initializer, emit warning.
3049 diagnoseInitOverride(
3050 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3051 /*UnionOverride=*/true,
3052 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3053 : true);
3054 }
3055
3056 // remove existing initializer
3057 StructuredList->resizeInits(SemaRef.Context, 0);
3058 StructuredList->setInitializedFieldInUnion(nullptr);
3059 }
3060
3061 StructuredList->setInitializedFieldInUnion(*Field);
3062 }
3063 }
3064
3065 // Make sure we can use this declaration.
3066 bool InvalidUse;
3067 if (VerifyOnly)
3068 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
3069 else
3070 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
3071 if (InvalidUse) {
3072 ++Index;
3073 return true;
3074 }
3075
3076 // C++20 [dcl.init.list]p3:
3077 // The ordered identifiers in the designators of the designated-
3078 // initializer-list shall form a subsequence of the ordered identifiers
3079 // in the direct non-static data members of T.
3080 //
3081 // Note that this is not a condition on forming the aggregate
3082 // initialization, only on actually performing initialization,
3083 // so it is not checked in VerifyOnly mode.
3084 //
3085 // FIXME: This is the only reordering diagnostic we produce, and it only
3086 // catches cases where we have a top-level field designator that jumps
3087 // backwards. This is the only such case that is reachable in an
3088 // otherwise-valid C++20 program, so is the only case that's required for
3089 // conformance, but for consistency, we should diagnose all the other
3090 // cases where a designator takes us backwards too.
3091 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3092 NextField &&
3093 (*NextField == RD->field_end() ||
3094 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3095 // Find the field that we just initialized.
3096 FieldDecl *PrevField = nullptr;
3097 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3098 if (FI->isUnnamedBitField())
3099 continue;
3100 if (*NextField != RD->field_end() &&
3101 declaresSameEntity(*FI, **NextField))
3102 break;
3103 PrevField = *FI;
3104 }
3105
3106 const auto GenerateDesignatedInitReorderingFixit =
3107 [&](SemaBase::SemaDiagnosticBuilder &Diag) {
3108 struct ReorderInfo {
3109 int Pos{};
3110 const Expr *InitExpr{};
3111 };
3112
3113 llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{};
3114 llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{};
3115
3116 const auto *CxxRecord =
3118
3119 for (const FieldDecl *Field : CxxRecord->fields())
3120 MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex();
3121
3122 for (const Expr *Init : IList->inits()) {
3123 if (const auto *DI =
3124 dyn_cast_if_present<DesignatedInitExpr>(Init)) {
3125 // We expect only one Designator
3126 if (DI->size() != 1)
3127 return;
3128
3129 const IdentifierInfo *const FieldName =
3130 DI->getDesignator(0)->getFieldName();
3131 // In case we have an unknown initializer in the source, not in
3132 // the record
3133 if (MemberNameInx.contains(FieldName))
3134 ReorderedInitExprs.emplace_back(
3135 ReorderInfo{MemberNameInx.at(FieldName), Init});
3136 }
3137 }
3138
3139 llvm::sort(ReorderedInitExprs,
3140 [](const ReorderInfo &A, const ReorderInfo &B) {
3141 return A.Pos < B.Pos;
3142 });
3143
3144 llvm::SmallString<128> FixedInitList{};
3145 SourceManager &SM = SemaRef.getSourceManager();
3146 const LangOptions &LangOpts = SemaRef.getLangOpts();
3147
3148 // In a derived Record, first n base-classes are initialized first.
3149 // They do not use designated init, so skip them
3150 const ArrayRef<clang::Expr *> IListInits =
3151 IList->inits().drop_front(CxxRecord->getNumBases());
3152 // loop over each existing expressions and apply replacement
3153 for (const auto &[OrigExpr, Repl] :
3154 llvm::zip(IListInits, ReorderedInitExprs)) {
3155 CharSourceRange CharRange = CharSourceRange::getTokenRange(
3156 Repl.InitExpr->getSourceRange());
3157 const StringRef InitText =
3158 Lexer::getSourceText(CharRange, SM, LangOpts);
3159
3160 Diag << FixItHint::CreateReplacement(OrigExpr->getSourceRange(),
3161 InitText.str());
3162 }
3163 };
3164
3165 if (PrevField &&
3166 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3167 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3168 diag::ext_designated_init_reordered)
3169 << KnownField << PrevField << DIE->getSourceRange();
3170
3171 unsigned OldIndex = StructuredIndex - 1;
3172 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3173 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3174 auto Diag = SemaRef.Diag(PrevInit->getBeginLoc(),
3175 diag::note_previous_field_init)
3176 << PrevField << PrevInit->getSourceRange();
3177 GenerateDesignatedInitReorderingFixit(Diag);
3178 }
3179 }
3180 }
3181 }
3182
3183
3184 // Update the designator with the field declaration.
3185 if (!VerifyOnly)
3186 D->setFieldDecl(*Field);
3187
3188 // Make sure that our non-designated initializer list has space
3189 // for a subobject corresponding to this field.
3190 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3191 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3192
3193 // This designator names a flexible array member.
3194 if (Field->getType()->isIncompleteArrayType()) {
3195 bool Invalid = false;
3196 if ((DesigIdx + 1) != DIE->size()) {
3197 // We can't designate an object within the flexible array
3198 // member (because GCC doesn't allow it).
3199 if (!VerifyOnly) {
3200 DesignatedInitExpr::Designator *NextD
3201 = DIE->getDesignator(DesigIdx + 1);
3202 SemaRef.Diag(NextD->getBeginLoc(),
3203 diag::err_designator_into_flexible_array_member)
3204 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3205 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3206 << *Field;
3207 }
3208 Invalid = true;
3209 }
3210
3211 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3212 !isa<StringLiteral>(DIE->getInit())) {
3213 // The initializer is not an initializer list.
3214 if (!VerifyOnly) {
3215 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3216 diag::err_flexible_array_init_needs_braces)
3217 << DIE->getInit()->getSourceRange();
3218 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3219 << *Field;
3220 }
3221 Invalid = true;
3222 }
3223
3224 // Check GNU flexible array initializer.
3225 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3226 TopLevelObject))
3227 Invalid = true;
3228
3229 if (Invalid) {
3230 ++Index;
3231 return true;
3232 }
3233
3234 // Initialize the array.
3235 bool prevHadError = hadError;
3236 unsigned newStructuredIndex = FieldIndex;
3237 unsigned OldIndex = Index;
3238 IList->setInit(Index, DIE->getInit());
3239
3240 InitializedEntity MemberEntity =
3241 InitializedEntity::InitializeMember(*Field, &Entity);
3242 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3243 StructuredList, newStructuredIndex);
3244
3245 IList->setInit(OldIndex, DIE);
3246 if (hadError && !prevHadError) {
3247 ++Field;
3248 ++FieldIndex;
3249 if (NextField)
3250 *NextField = Field;
3251 StructuredIndex = FieldIndex;
3252 return true;
3253 }
3254 } else {
3255 // Recurse to check later designated subobjects.
3256 QualType FieldType = Field->getType();
3257 unsigned newStructuredIndex = FieldIndex;
3258
3259 InitializedEntity MemberEntity =
3260 InitializedEntity::InitializeMember(*Field, &Entity);
3261 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3262 FieldType, nullptr, nullptr, Index,
3263 StructuredList, newStructuredIndex,
3264 FinishSubobjectInit, false))
3265 return true;
3266 }
3267
3268 // Find the position of the next field to be initialized in this
3269 // subobject.
3270 ++Field;
3271 ++FieldIndex;
3272
3273 // If this the first designator, our caller will continue checking
3274 // the rest of this struct/class/union subobject.
3275 if (IsFirstDesignator) {
3276 if (Field != RD->field_end() && Field->isUnnamedBitField())
3277 ++Field;
3278
3279 if (NextField)
3280 *NextField = Field;
3281
3282 StructuredIndex = FieldIndex;
3283 return false;
3284 }
3285
3286 if (!FinishSubobjectInit)
3287 return false;
3288
3289 // We've already initialized something in the union; we're done.
3290 if (RD->isUnion())
3291 return hadError;
3292
3293 // Check the remaining fields within this class/struct/union subobject.
3294 bool prevHadError = hadError;
3295
3296 auto NoBases =
3299 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3300 false, Index, StructuredList, FieldIndex);
3301 return hadError && !prevHadError;
3302 }
3303
3304 // C99 6.7.8p6:
3305 //
3306 // If a designator has the form
3307 //
3308 // [ constant-expression ]
3309 //
3310 // then the current object (defined below) shall have array
3311 // type and the expression shall be an integer constant
3312 // expression. If the array is of unknown size, any
3313 // nonnegative value is valid.
3314 //
3315 // Additionally, cope with the GNU extension that permits
3316 // designators of the form
3317 //
3318 // [ constant-expression ... constant-expression ]
3319 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3320 if (!AT) {
3321 if (!VerifyOnly)
3322 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3323 << CurrentObjectType;
3324 ++Index;
3325 return true;
3326 }
3327
3328 Expr *IndexExpr = nullptr;
3329 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3330 if (D->isArrayDesignator()) {
3331 IndexExpr = DIE->getArrayIndex(*D);
3332 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3333 DesignatedEndIndex = DesignatedStartIndex;
3334 } else {
3335 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3336
3337 DesignatedStartIndex =
3339 DesignatedEndIndex =
3341 IndexExpr = DIE->getArrayRangeEnd(*D);
3342
3343 // Codegen can't handle evaluating array range designators that have side
3344 // effects, because we replicate the AST value for each initialized element.
3345 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3346 // elements with something that has a side effect, so codegen can emit an
3347 // "error unsupported" error instead of miscompiling the app.
3348 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3349 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3350 FullyStructuredList->sawArrayRangeDesignator();
3351 }
3352
3353 if (isa<ConstantArrayType>(AT)) {
3354 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3355 DesignatedStartIndex
3356 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3357 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3358 DesignatedEndIndex
3359 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3360 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3361 if (DesignatedEndIndex >= MaxElements) {
3362 if (!VerifyOnly)
3363 SemaRef.Diag(IndexExpr->getBeginLoc(),
3364 diag::err_array_designator_too_large)
3365 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3366 << IndexExpr->getSourceRange();
3367 ++Index;
3368 return true;
3369 }
3370 } else {
3371 unsigned DesignatedIndexBitWidth =
3373 DesignatedStartIndex =
3374 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3375 DesignatedEndIndex =
3376 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3377 DesignatedStartIndex.setIsUnsigned(true);
3378 DesignatedEndIndex.setIsUnsigned(true);
3379 }
3380
3381 bool IsStringLiteralInitUpdate =
3382 StructuredList && StructuredList->isStringLiteralInit();
3383 if (IsStringLiteralInitUpdate && VerifyOnly) {
3384 // We're just verifying an update to a string literal init. We don't need
3385 // to split the string up into individual characters to do that.
3386 StructuredList = nullptr;
3387 } else if (IsStringLiteralInitUpdate) {
3388 // We're modifying a string literal init; we have to decompose the string
3389 // so we can modify the individual characters.
3390 ASTContext &Context = SemaRef.Context;
3391 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3392
3393 // Compute the character type
3394 QualType CharTy = AT->getElementType();
3395
3396 // Compute the type of the integer literals.
3397 QualType PromotedCharTy = CharTy;
3398 if (Context.isPromotableIntegerType(CharTy))
3399 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3400 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3401
3402 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3403 // Get the length of the string.
3404 uint64_t StrLen = SL->getLength();
3405 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3406 CAT && CAT->getSize().ult(StrLen))
3407 StrLen = CAT->getZExtSize();
3408 StructuredList->resizeInits(Context, StrLen);
3409
3410 // Build a literal for each character in the string, and put them into
3411 // the init list.
3412 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3413 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3414 Expr *Init = new (Context) IntegerLiteral(
3415 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3416 if (CharTy != PromotedCharTy)
3417 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3418 Init, nullptr, VK_PRValue,
3419 FPOptionsOverride());
3420 StructuredList->updateInit(Context, i, Init);
3421 }
3422 } else {
3423 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3424 std::string Str;
3425 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3426
3427 // Get the length of the string.
3428 uint64_t StrLen = Str.size();
3429 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3430 CAT && CAT->getSize().ult(StrLen))
3431 StrLen = CAT->getZExtSize();
3432 StructuredList->resizeInits(Context, StrLen);
3433
3434 // Build a literal for each character in the string, and put them into
3435 // the init list.
3436 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3437 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3438 Expr *Init = new (Context) IntegerLiteral(
3439 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3440 if (CharTy != PromotedCharTy)
3441 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3442 Init, nullptr, VK_PRValue,
3443 FPOptionsOverride());
3444 StructuredList->updateInit(Context, i, Init);
3445 }
3446 }
3447 }
3448
3449 // Make sure that our non-designated initializer list has space
3450 // for a subobject corresponding to this array element.
3451 if (StructuredList &&
3452 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3453 StructuredList->resizeInits(SemaRef.Context,
3454 DesignatedEndIndex.getZExtValue() + 1);
3455
3456 // Repeatedly perform subobject initializations in the range
3457 // [DesignatedStartIndex, DesignatedEndIndex].
3458
3459 // Move to the next designator
3460 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3461 unsigned OldIndex = Index;
3462
3463 InitializedEntity ElementEntity =
3465
3466 while (DesignatedStartIndex <= DesignatedEndIndex) {
3467 // Recurse to check later designated subobjects.
3468 QualType ElementType = AT->getElementType();
3469 Index = OldIndex;
3470
3471 ElementEntity.setElementIndex(ElementIndex);
3472 if (CheckDesignatedInitializer(
3473 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3474 nullptr, Index, StructuredList, ElementIndex,
3475 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3476 false))
3477 return true;
3478
3479 // Move to the next index in the array that we'll be initializing.
3480 ++DesignatedStartIndex;
3481 ElementIndex = DesignatedStartIndex.getZExtValue();
3482 }
3483
3484 // If this the first designator, our caller will continue checking
3485 // the rest of this array subobject.
3486 if (IsFirstDesignator) {
3487 if (NextElementIndex)
3488 *NextElementIndex = std::move(DesignatedStartIndex);
3489 StructuredIndex = ElementIndex;
3490 return false;
3491 }
3492
3493 if (!FinishSubobjectInit)
3494 return false;
3495
3496 // Check the remaining elements within this array subobject.
3497 bool prevHadError = hadError;
3498 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3499 /*SubobjectIsDesignatorContext=*/false, Index,
3500 StructuredList, ElementIndex);
3501 return hadError && !prevHadError;
3502}
3503
3504// Get the structured initializer list for a subobject of type
3505// @p CurrentObjectType.
3506InitListExpr *
3507InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3508 QualType CurrentObjectType,
3509 InitListExpr *StructuredList,
3510 unsigned StructuredIndex,
3511 SourceRange InitRange,
3512 bool IsFullyOverwritten) {
3513 if (!StructuredList)
3514 return nullptr;
3515
3516 Expr *ExistingInit = nullptr;
3517 if (StructuredIndex < StructuredList->getNumInits())
3518 ExistingInit = StructuredList->getInit(StructuredIndex);
3519
3520 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3521 // There might have already been initializers for subobjects of the current
3522 // object, but a subsequent initializer list will overwrite the entirety
3523 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3524 //
3525 // struct P { char x[6]; };
3526 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3527 //
3528 // The first designated initializer is ignored, and l.x is just "f".
3529 if (!IsFullyOverwritten)
3530 return Result;
3531
3532 if (ExistingInit) {
3533 // We are creating an initializer list that initializes the
3534 // subobjects of the current object, but there was already an
3535 // initialization that completely initialized the current
3536 // subobject:
3537 //
3538 // struct X { int a, b; };
3539 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3540 //
3541 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3542 // designated initializer overwrites the [0].b initializer
3543 // from the prior initialization.
3544 //
3545 // When the existing initializer is an expression rather than an
3546 // initializer list, we cannot decompose and update it in this way.
3547 // For example:
3548 //
3549 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3550 //
3551 // This case is handled by CheckDesignatedInitializer.
3552 diagnoseInitOverride(ExistingInit, InitRange);
3553 }
3554
3555 unsigned ExpectedNumInits = 0;
3556 if (Index < IList->getNumInits()) {
3557 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3558 ExpectedNumInits = Init->getNumInits();
3559 else
3560 ExpectedNumInits = IList->getNumInits() - Index;
3561 }
3562
3563 InitListExpr *Result = createInitListExpr(
3564 CurrentObjectType, InitRange, ExpectedNumInits, /*IsExplicit=*/false);
3565
3566 // Link this new initializer list into the structured initializer
3567 // lists.
3568 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3569 return Result;
3570}
3571
3572InitListExpr *InitListChecker::createInitListExpr(QualType CurrentObjectType,
3573 SourceRange InitRange,
3574 unsigned ExpectedNumInits,
3575 bool IsExplicit) {
3576 InitListExpr *Result =
3577 new (SemaRef.Context) InitListExpr(SemaRef.Context, InitRange.getBegin(),
3578 {}, InitRange.getEnd(), IsExplicit);
3579
3580 QualType ResultType = CurrentObjectType;
3581 if (!ResultType->isArrayType())
3582 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3583 Result->setType(ResultType);
3584
3585 // Pre-allocate storage for the structured initializer list.
3586 unsigned NumElements = 0;
3587
3588 if (const ArrayType *AType
3589 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3590 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3591 NumElements = CAType->getZExtSize();
3592 // Simple heuristic so that we don't allocate a very large
3593 // initializer with many empty entries at the end.
3594 if (NumElements > ExpectedNumInits)
3595 NumElements = 0;
3596 }
3597 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3598 NumElements = VType->getNumElements();
3599 } else if (CurrentObjectType->isRecordType()) {
3600 NumElements = numStructUnionElements(CurrentObjectType);
3601 } else if (CurrentObjectType->isDependentType()) {
3602 NumElements = 1;
3603 }
3604
3605 Result->reserveInits(SemaRef.Context, NumElements);
3606
3607 return Result;
3608}
3609
3610/// Update the initializer at index @p StructuredIndex within the
3611/// structured initializer list to the value @p expr.
3612void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3613 unsigned &StructuredIndex,
3614 Expr *expr) {
3615 // No structured initializer list to update
3616 if (!StructuredList)
3617 return;
3618
3619 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3620 StructuredIndex, expr)) {
3621 // This initializer overwrites a previous initializer.
3622 // No need to diagnose when `expr` is nullptr because a more relevant
3623 // diagnostic has already been issued and this diagnostic is potentially
3624 // noise.
3625 if (expr)
3626 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3627 }
3628
3629 ++StructuredIndex;
3630}
3631
3633 const InitializedEntity &Entity, InitListExpr *From) {
3634 QualType Type = Entity.getType();
3635 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3636 /*TreatUnavailableAsInvalid=*/false,
3637 /*InOverloadResolution=*/true);
3638 return !Check.HadError();
3639}
3640
3641/// Check that the given Index expression is a valid array designator
3642/// value. This is essentially just a wrapper around
3643/// VerifyIntegerConstantExpression that also checks for negative values
3644/// and produces a reasonable diagnostic if there is a
3645/// failure. Returns the index expression, possibly with an implicit cast
3646/// added, on success. If everything went okay, Value will receive the
3647/// value of the constant expression.
3648static ExprResult
3649CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3650 SourceLocation Loc = Index->getBeginLoc();
3651
3652 // Make sure this is an integer constant expression.
3655 if (Result.isInvalid())
3656 return Result;
3657
3658 if (Value.isSigned() && Value.isNegative())
3659 return S.Diag(Loc, diag::err_array_designator_negative)
3660 << toString(Value, 10) << Index->getSourceRange();
3661
3662 Value.setIsUnsigned(true);
3663 return Result;
3664}
3665
3667 SourceLocation EqualOrColonLoc,
3668 bool GNUSyntax,
3669 ExprResult Init) {
3670 typedef DesignatedInitExpr::Designator ASTDesignator;
3671
3672 bool Invalid = false;
3674 SmallVector<Expr *, 32> InitExpressions;
3675
3676 // Build designators and check array designator expressions.
3677 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3678 const Designator &D = Desig.getDesignator(Idx);
3679
3680 if (D.isFieldDesignator()) {
3681 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3682 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3683 } else if (D.isArrayDesignator()) {
3684 Expr *Index = D.getArrayIndex();
3685 llvm::APSInt IndexValue;
3686 if (!Index->isTypeDependent() && !Index->isValueDependent())
3687 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3688 if (!Index)
3689 Invalid = true;
3690 else {
3691 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3692 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3693 InitExpressions.push_back(Index);
3694 }
3695 } else if (D.isArrayRangeDesignator()) {
3696 Expr *StartIndex = D.getArrayRangeStart();
3697 Expr *EndIndex = D.getArrayRangeEnd();
3698 llvm::APSInt StartValue;
3699 llvm::APSInt EndValue;
3700 bool StartDependent = StartIndex->isTypeDependent() ||
3701 StartIndex->isValueDependent();
3702 bool EndDependent = EndIndex->isTypeDependent() ||
3703 EndIndex->isValueDependent();
3704 if (!StartDependent)
3705 StartIndex =
3706 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3707 if (!EndDependent)
3708 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3709
3710 if (!StartIndex || !EndIndex)
3711 Invalid = true;
3712 else {
3713 // Make sure we're comparing values with the same bit width.
3714 if (StartDependent || EndDependent) {
3715 // Nothing to compute.
3716 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3717 EndValue = EndValue.extend(StartValue.getBitWidth());
3718 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3719 StartValue = StartValue.extend(EndValue.getBitWidth());
3720
3721 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3722 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3723 << toString(StartValue, 10) << toString(EndValue, 10)
3724 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3725 Invalid = true;
3726 } else {
3727 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3728 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3729 D.getRBracketLoc()));
3730 InitExpressions.push_back(StartIndex);
3731 InitExpressions.push_back(EndIndex);
3732 }
3733 }
3734 }
3735 }
3736
3737 if (Invalid || Init.isInvalid())
3738 return ExprError();
3739
3740 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3741 EqualOrColonLoc, GNUSyntax,
3742 Init.getAs<Expr>());
3743}
3744
3745//===----------------------------------------------------------------------===//
3746// Initialization entity
3747//===----------------------------------------------------------------------===//
3748
3749InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3750 const InitializedEntity &Parent)
3751 : Parent(&Parent), Index(Index)
3752{
3753 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3754 Kind = EK_ArrayElement;
3755 Type = AT->getElementType();
3756 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3757 Kind = EK_VectorElement;
3758 Type = VT->getElementType();
3759 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3760 Kind = EK_MatrixElement;
3761 Type = MT->getElementType();
3762 } else {
3763 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3764 assert(CT && "Unexpected type");
3765 Kind = EK_ComplexElement;
3766 Type = CT->getElementType();
3767 }
3768}
3769
3772 const CXXBaseSpecifier *Base,
3773 bool IsInheritedVirtualBase,
3774 const InitializedEntity *Parent) {
3775 InitializedEntity Result;
3776 Result.Kind = EK_Base;
3777 Result.Parent = Parent;
3778 Result.Base = {Base, IsInheritedVirtualBase};
3779 Result.Type = Base->getType();
3780 return Result;
3781}
3782
3784 switch (getKind()) {
3785 case EK_Parameter:
3787 ParmVarDecl *D = Parameter.getPointer();
3788 return (D ? D->getDeclName() : DeclarationName());
3789 }
3790
3791 case EK_Variable:
3792 case EK_Member:
3794 case EK_Binding:
3796 return Variable.VariableOrMember->getDeclName();
3797
3798 case EK_LambdaCapture:
3799 return DeclarationName(Capture.VarID);
3800
3801 case EK_Result:
3802 case EK_StmtExprResult:
3803 case EK_Exception:
3804 case EK_New:
3805 case EK_Temporary:
3806 case EK_Base:
3807 case EK_Delegating:
3808 case EK_ArrayElement:
3809 case EK_VectorElement:
3810 case EK_MatrixElement:
3811 case EK_ComplexElement:
3812 case EK_BlockElement:
3815 case EK_RelatedResult:
3816 return DeclarationName();
3817 }
3818
3819 llvm_unreachable("Invalid EntityKind!");
3820}
3821
3823 switch (getKind()) {
3824 case EK_Variable:
3825 case EK_Member:
3827 case EK_Binding:
3829 return cast<ValueDecl>(Variable.VariableOrMember);
3830
3831 case EK_Parameter:
3833 return Parameter.getPointer();
3834
3835 case EK_Result:
3836 case EK_StmtExprResult:
3837 case EK_Exception:
3838 case EK_New:
3839 case EK_Temporary:
3840 case EK_Base:
3841 case EK_Delegating:
3842 case EK_ArrayElement:
3843 case EK_VectorElement:
3844 case EK_MatrixElement:
3845 case EK_ComplexElement:
3846 case EK_BlockElement:
3848 case EK_LambdaCapture:
3850 case EK_RelatedResult:
3851 return nullptr;
3852 }
3853
3854 llvm_unreachable("Invalid EntityKind!");
3855}
3856
3858 switch (getKind()) {
3859 case EK_Result:
3860 case EK_Exception:
3861 return LocAndNRVO.NRVO == NRVOKind::Allowed;
3862
3863 case EK_StmtExprResult:
3864 case EK_Variable:
3865 case EK_Parameter:
3868 case EK_Member:
3870 case EK_Binding:
3871 case EK_New:
3872 case EK_Temporary:
3874 case EK_Base:
3875 case EK_Delegating:
3876 case EK_ArrayElement:
3877 case EK_VectorElement:
3878 case EK_MatrixElement:
3879 case EK_ComplexElement:
3880 case EK_BlockElement:
3882 case EK_LambdaCapture:
3883 case EK_RelatedResult:
3884 break;
3885 }
3886
3887 return false;
3888}
3889
3890unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3891 assert(getParent() != this);
3892 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3893 for (unsigned I = 0; I != Depth; ++I)
3894 OS << "`-";
3895
3896 switch (getKind()) {
3897 case EK_Variable: OS << "Variable"; break;
3898 case EK_Parameter: OS << "Parameter"; break;
3899 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3900 break;
3901 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3902 case EK_Result: OS << "Result"; break;
3903 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3904 case EK_Exception: OS << "Exception"; break;
3905 case EK_Member:
3907 OS << "Member";
3908 break;
3909 case EK_Binding: OS << "Binding"; break;
3910 case EK_New: OS << "New"; break;
3911 case EK_Temporary: OS << "Temporary"; break;
3912 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3913 case EK_RelatedResult: OS << "RelatedResult"; break;
3914 case EK_Base: OS << "Base"; break;
3915 case EK_Delegating: OS << "Delegating"; break;
3916 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3917 case EK_VectorElement: OS << "VectorElement " << Index; break;
3918 case EK_MatrixElement:
3919 OS << "MatrixElement " << Index;
3920 break;
3921 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3922 case EK_BlockElement: OS << "Block"; break;
3924 OS << "Block (lambda)";
3925 break;
3926 case EK_LambdaCapture:
3927 OS << "LambdaCapture ";
3928 OS << DeclarationName(Capture.VarID);
3929 break;
3930 }
3931
3932 if (auto *D = getDecl()) {
3933 OS << " ";
3934 D->printQualifiedName(OS);
3935 }
3936
3937 OS << " '" << getType() << "'\n";
3938
3939 return Depth + 1;
3940}
3941
3942LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3943 dumpImpl(llvm::errs());
3944}
3945
3946//===----------------------------------------------------------------------===//
3947// Initialization sequence
3948//===----------------------------------------------------------------------===//
3949
3996
3998 // There can be some lvalue adjustments after the SK_BindReference step.
3999 for (const Step &S : llvm::reverse(Steps)) {
4000 if (S.Kind == SK_BindReference)
4001 return true;
4002 if (S.Kind == SK_BindReferenceToTemporary)
4003 return false;
4004 }
4005 return false;
4006}
4007
4009 if (!Failed())
4010 return false;
4011
4012 switch (getFailureKind()) {
4023 case FK_AddressOfOverloadFailed: // FIXME: Could do better
4040 case FK_Incomplete:
4045 case FK_PlaceholderType:
4051 return false;
4052
4057 return FailedOverloadResult == OR_Ambiguous;
4058 }
4059
4060 llvm_unreachable("Invalid EntityKind!");
4061}
4062
4064 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
4065}
4066
4067void
4068InitializationSequence
4069::AddAddressOverloadResolutionStep(FunctionDecl *Function,
4071 bool HadMultipleCandidates) {
4072 Step S;
4074 S.Type = Function->getType();
4075 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4078 Steps.push_back(S);
4079}
4080
4082 ExprValueKind VK) {
4083 Step S;
4084 switch (VK) {
4085 case VK_PRValue:
4087 break;
4088 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4089 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4090 }
4091 S.Type = BaseType;
4092 Steps.push_back(S);
4093}
4094
4096 bool BindingTemporary) {
4097 Step S;
4098 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4099 S.Type = T;
4100 Steps.push_back(S);
4101}
4102
4104 Step S;
4105 S.Kind = SK_FinalCopy;
4106 S.Type = T;
4107 Steps.push_back(S);
4108}
4109
4111 Step S;
4113 S.Type = T;
4114 Steps.push_back(S);
4115}
4116
4117void
4119 DeclAccessPair FoundDecl,
4120 QualType T,
4121 bool HadMultipleCandidates) {
4122 Step S;
4124 S.Type = T;
4125 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4127 S.Function.FoundDecl = FoundDecl;
4128 Steps.push_back(S);
4129}
4130
4132 ExprValueKind VK) {
4133 Step S;
4134 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4135 switch (VK) {
4136 case VK_PRValue:
4138 break;
4139 case VK_XValue:
4141 break;
4142 case VK_LValue:
4144 break;
4145 }
4146 S.Type = Ty;
4147 Steps.push_back(S);
4148}
4149
4151 Step S;
4153 S.Type = Ty;
4154 Steps.push_back(S);
4155}
4156
4158 Step S;
4160 S.Type = Ty;
4161 Steps.push_back(S);
4162}
4163
4166 bool TopLevelOfInitList) {
4167 Step S;
4168 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4170 S.Type = T;
4171 S.ICS = new ImplicitConversionSequence(ICS);
4172 Steps.push_back(S);
4173}
4174
4176 Step S;
4178 S.Type = T;
4179 Steps.push_back(S);
4180}
4181
4184 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4185 Step S;
4186 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4189 S.Type = T;
4190 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4192 S.Function.FoundDecl = FoundDecl;
4193 Steps.push_back(S);
4194}
4195
4197 Step S;
4199 S.Type = T;
4200 Steps.push_back(S);
4201}
4202
4204 Step S;
4205 S.Kind = SK_CAssignment;
4206 S.Type = T;
4207 Steps.push_back(S);
4208}
4209
4211 Step S;
4212 S.Kind = SK_StringInit;
4213 S.Type = T;
4214 Steps.push_back(S);
4215}
4216
4218 Step S;
4220 S.Type = T;
4221 Steps.push_back(S);
4222}
4223
4225 Step S;
4226 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4227 S.Type = T;
4228 Steps.push_back(S);
4229}
4230
4232 Step S;
4234 S.Type = EltT;
4235 Steps.insert(Steps.begin(), S);
4236
4238 S.Type = T;
4239 Steps.push_back(S);
4240}
4241
4243 Step S;
4245 S.Type = T;
4246 Steps.push_back(S);
4247}
4248
4250 bool shouldCopy) {
4251 Step s;
4252 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4254 s.Type = type;
4255 Steps.push_back(s);
4256}
4257
4259 Step S;
4261 S.Type = T;
4262 Steps.push_back(S);
4263}
4264
4266 Step S;
4268 S.Type = T;
4269 Steps.push_back(S);
4270}
4271
4273 Step S;
4275 S.Type = T;
4276 Steps.push_back(S);
4277}
4278
4280 Step S;
4282 S.Type = T;
4283 Steps.push_back(S);
4284}
4285
4287 Step S;
4289 S.Type = T;
4290 Steps.push_back(S);
4291}
4292
4294 InitListExpr *Syntactic) {
4295 assert(Syntactic->getNumInits() == 1 &&
4296 "Can only unwrap trivial init lists.");
4297 Step S;
4299 S.Type = Syntactic->getInit(0)->getType();
4300 Steps.insert(Steps.begin(), S);
4301}
4302
4304 InitListExpr *Syntactic) {
4305 assert(Syntactic->getNumInits() == 1 &&
4306 "Can only rewrap trivial init lists.");
4307 Step S;
4309 S.Type = Syntactic->getInit(0)->getType();
4310 Steps.insert(Steps.begin(), S);
4311
4313 S.Type = T;
4314 S.WrappingSyntacticList = Syntactic;
4315 Steps.push_back(S);
4316}
4317
4319 Step S;
4321 S.Type = T;
4322 Steps.push_back(S);
4323}
4324
4328 this->Failure = Failure;
4329 this->FailedOverloadResult = Result;
4330}
4331
4332//===----------------------------------------------------------------------===//
4333// Attempt initialization
4334//===----------------------------------------------------------------------===//
4335
4336/// Tries to add a zero initializer. Returns true if that worked.
4337static bool
4339 const InitializedEntity &Entity) {
4341 return false;
4342
4343 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4344 if (VD->getInit() || VD->getEndLoc().isMacroID())
4345 return false;
4346
4347 QualType VariableTy = VD->getType().getCanonicalType();
4349 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4350 if (!Init.empty()) {
4351 Sequence.AddZeroInitializationStep(Entity.getType());
4352 Sequence.SetZeroInitializationFixit(Init, Loc);
4353 return true;
4354 }
4355 return false;
4356}
4357
4359 InitializationSequence &Sequence,
4360 const InitializedEntity &Entity) {
4361 if (!S.getLangOpts().ObjCAutoRefCount) return;
4362
4363 /// When initializing a parameter, produce the value if it's marked
4364 /// __attribute__((ns_consumed)).
4365 if (Entity.isParameterKind()) {
4366 if (!Entity.isParameterConsumed())
4367 return;
4368
4369 assert(Entity.getType()->isObjCRetainableType() &&
4370 "consuming an object of unretainable type?");
4371 Sequence.AddProduceObjCObjectStep(Entity.getType());
4372
4373 /// When initializing a return value, if the return type is a
4374 /// retainable type, then returns need to immediately retain the
4375 /// object. If an autorelease is required, it will be done at the
4376 /// last instant.
4377 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4379 if (!Entity.getType()->isObjCRetainableType())
4380 return;
4381
4382 Sequence.AddProduceObjCObjectStep(Entity.getType());
4383 }
4384}
4385
4386/// Initialize an array from another array
4387static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4388 const InitializedEntity &Entity, Expr *Initializer,
4389 QualType DestType, InitializationSequence &Sequence,
4390 bool TreatUnavailableAsInvalid) {
4391 // If source is a prvalue, use it directly.
4392 if (Initializer->isPRValue()) {
4393 Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4394 return;
4395 }
4396
4397 // Emit element-at-a-time copy loop.
4398 InitializedEntity Element =
4400 QualType InitEltT =
4402
4403 // FIXME: Here's a functional memory leak cuz we don't have a temporary
4404 // allocator at the moment
4406 Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(),
4407 Initializer->getObjectKind());
4408 Expr *OVEAsExpr = OVE;
4409 Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4410 /*TopLevelOfInitList*/ false,
4411 TreatUnavailableAsInvalid);
4412 if (Sequence)
4413 Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4414}
4415
4416static void TryListInitialization(Sema &S,
4417 const InitializedEntity &Entity,
4418 const InitializationKind &Kind,
4419 InitListExpr *InitList,
4420 InitializationSequence &Sequence,
4421 bool TreatUnavailableAsInvalid);
4422
4423/// When initializing from init list via constructor, handle
4424/// initialization of an object of type std::initializer_list<T>.
4425///
4426/// \return true if we have handled initialization of an object of type
4427/// std::initializer_list<T>, false otherwise.
4429 InitListExpr *List,
4430 QualType DestType,
4431 InitializationSequence &Sequence,
4432 bool TreatUnavailableAsInvalid) {
4433 QualType E;
4434 if (!S.isStdInitializerList(DestType, &E))
4435 return false;
4436
4437 if (!S.isCompleteType(List->getExprLoc(), E)) {
4438 Sequence.setIncompleteTypeFailure(E);
4439 return true;
4440 }
4441
4442 // Try initializing a temporary array from the init list.
4444 E.withConst(),
4445 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4448 InitializedEntity HiddenArray =
4451 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4452 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4453 TreatUnavailableAsInvalid);
4454 if (Sequence)
4455 Sequence.AddStdInitializerListConstructionStep(DestType);
4456 return true;
4457}
4458
4459/// Determine if the constructor has the signature of a copy or move
4460/// constructor for the type T of the class in which it was found. That is,
4461/// determine if its first parameter is of type T or reference to (possibly
4462/// cv-qualified) T.
4464 const ConstructorInfo &Info) {
4465 if (Info.Constructor->getNumParams() == 0)
4466 return false;
4467
4468 QualType ParmT =
4470 CanQualType ClassT = Ctx.getCanonicalTagType(
4472
4473 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4474}
4475
4477 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4478 OverloadCandidateSet &CandidateSet, QualType DestType,
4480 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4481 bool IsListInit, bool RequireActualConstructor,
4482 bool SecondStepOfCopyInit = false) {
4484 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4485
4486 for (NamedDecl *D : Ctors) {
4487 auto Info = getConstructorInfo(D);
4488 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4489 continue;
4490
4491 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4492 continue;
4493
4494 // C++11 [over.best.ics]p4:
4495 // ... and the constructor or user-defined conversion function is a
4496 // candidate by
4497 // - 13.3.1.3, when the argument is the temporary in the second step
4498 // of a class copy-initialization, or
4499 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4500 // - the second phase of 13.3.1.7 when the initializer list has exactly
4501 // one element that is itself an initializer list, and the target is
4502 // the first parameter of a constructor of class X, and the conversion
4503 // is to X or reference to (possibly cv-qualified X),
4504 // user-defined conversion sequences are not considered.
4505 bool SuppressUserConversions =
4506 SecondStepOfCopyInit ||
4507 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4509
4510 if (Info.ConstructorTmpl)
4512 Info.ConstructorTmpl, Info.FoundDecl,
4513 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4514 /*PartialOverloading=*/false, AllowExplicit);
4515 else {
4516 // C++ [over.match.copy]p1:
4517 // - When initializing a temporary to be bound to the first parameter
4518 // of a constructor [for type T] that takes a reference to possibly
4519 // cv-qualified T as its first argument, called with a single
4520 // argument in the context of direct-initialization, explicit
4521 // conversion functions are also considered.
4522 // FIXME: What if a constructor template instantiates to such a signature?
4523 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4524 Args.size() == 1 &&
4526 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4527 CandidateSet, SuppressUserConversions,
4528 /*PartialOverloading=*/false, AllowExplicit,
4529 AllowExplicitConv);
4530 }
4531 }
4532
4533 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4534 //
4535 // When initializing an object of class type T by constructor
4536 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4537 // from a single expression of class type U, conversion functions of
4538 // U that convert to the non-reference type cv T are candidates.
4539 // Explicit conversion functions are only candidates during
4540 // direct-initialization.
4541 //
4542 // Note: SecondStepOfCopyInit is only ever true in this case when
4543 // evaluating whether to produce a C++98 compatibility warning.
4544 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4545 !RequireActualConstructor && !SecondStepOfCopyInit) {
4546 Expr *Initializer = Args[0];
4547 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4548 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4549 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4550 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4551 NamedDecl *D = *I;
4553 D = D->getUnderlyingDecl();
4554
4555 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4556 CXXConversionDecl *Conv;
4557 if (ConvTemplate)
4558 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4559 else
4560 Conv = cast<CXXConversionDecl>(D);
4561
4562 if (ConvTemplate)
4564 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4565 CandidateSet, AllowExplicit, AllowExplicit,
4566 /*AllowResultConversion*/ false);
4567 else
4568 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4569 DestType, CandidateSet, AllowExplicit,
4570 AllowExplicit,
4571 /*AllowResultConversion*/ false);
4572 }
4573 }
4574 }
4575
4576 // Perform overload resolution and return the result.
4577 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4578}
4579
4580/// Attempt initialization by constructor (C++ [dcl.init]), which
4581/// enumerates the constructors of the initialized entity and performs overload
4582/// resolution to select the best.
4583/// \param DestType The destination class type.
4584/// \param DestArrayType The destination type, which is either DestType or
4585/// a (possibly multidimensional) array of DestType.
4586/// \param IsListInit Is this list-initialization?
4587/// \param IsInitListCopy Is this non-list-initialization resulting from a
4588/// list-initialization from {x} where x is the same
4589/// aggregate type as the entity?
4591 const InitializedEntity &Entity,
4592 const InitializationKind &Kind,
4593 MultiExprArg Args, QualType DestType,
4594 QualType DestArrayType,
4595 InitializationSequence &Sequence,
4596 bool IsListInit = false,
4597 bool IsInitListCopy = false) {
4598 assert(((!IsListInit && !IsInitListCopy) ||
4599 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4600 "IsListInit/IsInitListCopy must come with a single initializer list "
4601 "argument.");
4602 InitListExpr *ILE =
4603 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4604 MultiExprArg UnwrappedArgs =
4605 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4606
4607 // The type we're constructing needs to be complete.
4608 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4609 Sequence.setIncompleteTypeFailure(DestType);
4610 return;
4611 }
4612
4613 bool RequireActualConstructor =
4614 !(Entity.getKind() != InitializedEntity::EK_Base &&
4616 Entity.getKind() !=
4618
4619 bool CopyElisionPossible = false;
4620 auto ElideConstructor = [&] {
4621 // Convert qualifications if necessary.
4622 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4623 if (ILE)
4624 Sequence.RewrapReferenceInitList(DestType, ILE);
4625 };
4626
4627 // C++17 [dcl.init]p17:
4628 // - If the initializer expression is a prvalue and the cv-unqualified
4629 // version of the source type is the same class as the class of the
4630 // destination, the initializer expression is used to initialize the
4631 // destination object.
4632 // Per DR (no number yet), this does not apply when initializing a base
4633 // class or delegating to another constructor from a mem-initializer.
4634 // ObjC++: Lambda captured by the block in the lambda to block conversion
4635 // should avoid copy elision.
4636 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4637 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4638 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4639 if (ILE && !DestType->isAggregateType()) {
4640 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4641 // Make this an elision if this won't call an initializer-list
4642 // constructor. (Always on an aggregate type or check constructors first.)
4643
4644 // This effectively makes our resolution as follows. The parts in angle
4645 // brackets are additions.
4646 // C++17 [over.match.list]p(1.2):
4647 // - If no viable initializer-list constructor is found <and the
4648 // initializer list does not consist of exactly a single element with
4649 // the same cv-unqualified class type as T>, [...]
4650 // C++17 [dcl.init.list]p(3.6):
4651 // - Otherwise, if T is a class type, constructors are considered. The
4652 // applicable constructors are enumerated and the best one is chosen
4653 // through overload resolution. <If no constructor is found and the
4654 // initializer list consists of exactly a single element with the same
4655 // cv-unqualified class type as T, the object is initialized from that
4656 // element (by copy-initialization for copy-list-initialization, or by
4657 // direct-initialization for direct-list-initialization). Otherwise, >
4658 // if a narrowing conversion [...]
4659 assert(!IsInitListCopy &&
4660 "IsInitListCopy only possible with aggregate types");
4661 CopyElisionPossible = true;
4662 } else {
4663 ElideConstructor();
4664 return;
4665 }
4666 }
4667
4668 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4669 // Build the candidate set directly in the initialization sequence
4670 // structure, so that it will persist if we fail.
4671 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4672
4673 // Determine whether we are allowed to call explicit constructors or
4674 // explicit conversion operators.
4675 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4676 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4677
4678 // - Otherwise, if T is a class type, constructors are considered. The
4679 // applicable constructors are enumerated, and the best one is chosen
4680 // through overload resolution.
4681 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4682
4685 bool AsInitializerList = false;
4686
4687 // C++11 [over.match.list]p1, per DR1467:
4688 // When objects of non-aggregate type T are list-initialized, such that
4689 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4690 // according to the rules in this section, overload resolution selects
4691 // the constructor in two phases:
4692 //
4693 // - Initially, the candidate functions are the initializer-list
4694 // constructors of the class T and the argument list consists of the
4695 // initializer list as a single argument.
4696 if (IsListInit) {
4697 AsInitializerList = true;
4698
4699 // If the initializer list has no elements and T has a default constructor,
4700 // the first phase is omitted.
4701 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4703 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4704 CopyInitialization, AllowExplicit,
4705 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4706
4707 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4708 // No initializer list candidate
4709 ElideConstructor();
4710 return;
4711 }
4712 }
4713
4714 // if the initialization is direct-initialization, or if it is
4715 // copy-initialization where the cv-unqualified version of the source type is
4716 // the same as or is derived from the class of the destination type,
4717 // constructors are considered.
4718 if ((Kind.getKind() == InitializationKind::IK_Direct ||
4719 Kind.getKind() == InitializationKind::IK_Copy) &&
4720 Args.size() == 1 &&
4722 Args[0]->getType().getNonReferenceType(),
4723 DestType.getNonReferenceType()))
4724 RequireActualConstructor = true;
4725
4726 // C++11 [over.match.list]p1:
4727 // - If no viable initializer-list constructor is found, overload resolution
4728 // is performed again, where the candidate functions are all the
4729 // constructors of the class T and the argument list consists of the
4730 // elements of the initializer list.
4732 AsInitializerList = false;
4734 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4735 Best, CopyInitialization, AllowExplicit,
4736 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4737 }
4738 if (Result) {
4739 Sequence.SetOverloadFailure(
4742 Result);
4743
4744 if (Result != OR_Deleted)
4745 return;
4746 }
4747
4748 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4749
4750 // In C++17, ResolveConstructorOverload can select a conversion function
4751 // instead of a constructor.
4752 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4753 // Add the user-defined conversion step that calls the conversion function.
4754 QualType ConvType = CD->getConversionType();
4755 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4756 "should not have selected this conversion function");
4757 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4758 HadMultipleCandidates);
4759 if (!S.Context.hasSameType(ConvType, DestType))
4760 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4761 if (IsListInit)
4762 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4763 return;
4764 }
4765
4766 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4767 if (Result != OR_Deleted) {
4768 if (!IsListInit &&
4769 (Kind.getKind() == InitializationKind::IK_Default ||
4770 Kind.getKind() == InitializationKind::IK_Direct) &&
4771 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4772 DestRecordDecl->isAggregate() &&
4773 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4774 !S.isUnevaluatedContext()) {
4775 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4776 << /* Var-in-Record */ 1 << DestRecordDecl;
4777 emitUninitializedExplicitInitFields(S, DestRecordDecl);
4778 }
4779
4780 // C++11 [dcl.init]p6:
4781 // If a program calls for the default initialization of an object
4782 // of a const-qualified type T, T shall be a class type with a
4783 // user-provided default constructor.
4784 // C++ core issue 253 proposal:
4785 // If the implicit default constructor initializes all subobjects, no
4786 // initializer should be required.
4787 // The 253 proposal is for example needed to process libstdc++ headers
4788 // in 5.x.
4789 if (Kind.getKind() == InitializationKind::IK_Default &&
4790 Entity.getType().isConstQualified()) {
4791 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4792 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4794 return;
4795 }
4796 }
4797
4798 // C++11 [over.match.list]p1:
4799 // In copy-list-initialization, if an explicit constructor is chosen, the
4800 // initializer is ill-formed.
4801 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4803 return;
4804 }
4805 }
4806
4807 // [class.copy.elision]p3:
4808 // In some copy-initialization contexts, a two-stage overload resolution
4809 // is performed.
4810 // If the first overload resolution selects a deleted function, we also
4811 // need the initialization sequence to decide whether to perform the second
4812 // overload resolution.
4813 // For deleted functions in other contexts, there is no need to get the
4814 // initialization sequence.
4815 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4816 return;
4817
4818 // Add the constructor initialization step. Any cv-qualification conversion is
4819 // subsumed by the initialization.
4821 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4822 IsListInit | IsInitListCopy, AsInitializerList);
4823}
4824
4826 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4827 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4828 ExprResult *Result = nullptr);
4829
4830/// Attempt to initialize an object of a class type either by
4831/// direct-initialization, or by copy-initialization from an
4832/// expression of the same or derived class type. This corresponds
4833/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4834///
4835/// \param IsAggrListInit Is this non-list-initialization being done as
4836/// part of a list-initialization of an aggregate
4837/// from a single expression of the same or
4838/// derived class type (C++2c [dcl.init.list] p3.2)?
4840 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4841 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4842 bool IsAggrListInit) {
4843 // C++2c [dcl.init.general] p16.6:
4844 // * Otherwise, if the destination type is a class type:
4845 // * If the initializer expression is a prvalue and
4846 // the cv-unqualified version of the source type is the same
4847 // as the destination type, the initializer expression is used
4848 // to initialize the destination object.
4849 // * Otherwise, if the initialization is direct-initialization,
4850 // or if it is copy-initialization where the cv-unqualified
4851 // version of the source type is the same as or is derived from
4852 // the class of the destination type, constructors are considered.
4853 // The applicable constructors are enumerated, and the best one
4854 // is chosen through overload resolution. Then:
4855 // * If overload resolution is successful, the selected
4856 // constructor is called to initialize the object, with
4857 // the initializer expression or expression-list as its
4858 // argument(s).
4859 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
4860 Sequence, /*IsListInit=*/false, IsAggrListInit);
4861
4862 // * Otherwise, if no constructor is viable, the destination type
4863 // is an aggregate class, and the initializer is a parenthesized
4864 // expression-list, the object is initialized as follows. [...]
4865 // Parenthesized initialization of aggregates is a C++20 feature.
4866 if (S.getLangOpts().CPlusPlus20 &&
4867 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4868 Sequence.getFailureKind() ==
4871 (IsAggrListInit || DestType->isAggregateType()))
4872 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4873 /*VerifyOnly=*/true);
4874
4875 // * Otherwise, the initialization is ill-formed.
4876}
4877
4878static bool
4881 QualType &SourceType,
4882 QualType &UnqualifiedSourceType,
4883 QualType UnqualifiedTargetType,
4884 InitializationSequence &Sequence) {
4885 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4886 S.Context.OverloadTy) {
4888 bool HadMultipleCandidates = false;
4889 if (FunctionDecl *Fn
4891 UnqualifiedTargetType,
4892 false, Found,
4893 &HadMultipleCandidates)) {
4895 HadMultipleCandidates);
4896 SourceType = Fn->getType();
4897 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4898 } else if (!UnqualifiedTargetType->isRecordType()) {
4900 return true;
4901 }
4902 }
4903 return false;
4904}
4905
4906static void TryReferenceInitializationCore(Sema &S,
4907 const InitializedEntity &Entity,
4908 const InitializationKind &Kind,
4909 Expr *Initializer,
4910 QualType cv1T1, QualType T1,
4911 Qualifiers T1Quals,
4912 QualType cv2T2, QualType T2,
4913 Qualifiers T2Quals,
4914 InitializationSequence &Sequence,
4915 bool TopLevelOfInitList);
4916
4917static void TryValueInitialization(Sema &S,
4918 const InitializedEntity &Entity,
4919 const InitializationKind &Kind,
4920 InitializationSequence &Sequence,
4921 InitListExpr *InitList = nullptr);
4922
4923/// Attempt list initialization of a reference.
4925 const InitializedEntity &Entity,
4926 const InitializationKind &Kind,
4927 InitListExpr *InitList,
4928 InitializationSequence &Sequence,
4929 bool TreatUnavailableAsInvalid) {
4930 // First, catch C++03 where this isn't possible.
4931 if (!S.getLangOpts().CPlusPlus11) {
4933 return;
4934 }
4935 // Can't reference initialize a compound literal.
4938 return;
4939 }
4940
4941 QualType DestType = Entity.getType();
4942 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4943 Qualifiers T1Quals;
4944 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4945
4946 // Reference initialization via an initializer list works thus:
4947 // If the initializer list consists of a single element that is
4948 // reference-related to the referenced type, bind directly to that element
4949 // (possibly creating temporaries).
4950 // Otherwise, initialize a temporary with the initializer list and
4951 // bind to that.
4952 if (InitList->getNumInits() == 1) {
4953 Expr *Initializer = InitList->getInit(0);
4955 Qualifiers T2Quals;
4956 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4957
4958 // If this fails, creating a temporary wouldn't work either.
4960 T1, Sequence))
4961 return;
4962
4963 SourceLocation DeclLoc = Initializer->getBeginLoc();
4964 Sema::ReferenceCompareResult RefRelationship
4965 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4966 if (RefRelationship >= Sema::Ref_Related) {
4967 // Try to bind the reference here.
4968 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4969 T1Quals, cv2T2, T2, T2Quals, Sequence,
4970 /*TopLevelOfInitList=*/true);
4971 if (Sequence)
4972 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4973 return;
4974 }
4975
4976 // Update the initializer if we've resolved an overloaded function.
4977 if (!Sequence.steps().empty())
4978 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4979 }
4980 // Perform address space compatibility check.
4981 QualType cv1T1IgnoreAS = cv1T1;
4982 if (T1Quals.hasAddressSpace()) {
4983 Qualifiers T2Quals;
4984 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4985 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
4986 Sequence.SetFailed(
4988 return;
4989 }
4990 // Ignore address space of reference type at this point and perform address
4991 // space conversion after the reference binding step.
4992 cv1T1IgnoreAS =
4994 }
4995 // Not reference-related. Create a temporary and bind to that.
4996 InitializedEntity TempEntity =
4998
4999 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
5000 TreatUnavailableAsInvalid);
5001 if (Sequence) {
5002 if (DestType->isRValueReferenceType() ||
5003 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
5004 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
5005 /*BindingTemporary=*/true);
5006 if (S.getLangOpts().CPlusPlus20 &&
5008 DestType->isRValueReferenceType()) {
5009 // C++20 [dcl.init.list]p3.10:
5010 // List-initialization of an object or reference of type T is defined as
5011 // follows:
5012 // ..., unless T is “reference to array of unknown bound of U”, in which
5013 // case the type of the prvalue is the type of x in the declaration U
5014 // x[] H, where H is the initializer list.
5015
5016 // The call to AddReferenceBindingStep above converts the rvalue to an
5017 // xvalue. Convert that xvalue to the incomplete array type.
5019 }
5020 if (T1Quals.hasAddressSpace())
5022 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
5023 } else
5024 Sequence.SetFailed(
5026 }
5027}
5028
5029/// Attempt list initialization (C++0x [dcl.init.list])
5031 const InitializedEntity &Entity,
5032 const InitializationKind &Kind,
5033 InitListExpr *InitList,
5034 InitializationSequence &Sequence,
5035 bool TreatUnavailableAsInvalid) {
5036 QualType DestType = Entity.getType();
5037
5038 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, InitList)) {
5040 return;
5041 }
5042
5043 // C++ doesn't allow scalar initialization with more than one argument.
5044 // But C99 complex numbers are scalars and it makes sense there.
5045 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
5046 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
5048 return;
5049 }
5050 if (DestType->isReferenceType()) {
5051 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
5052 TreatUnavailableAsInvalid);
5053 return;
5054 }
5055
5056 if (DestType->isRecordType() &&
5057 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
5058 Sequence.setIncompleteTypeFailure(DestType);
5059 return;
5060 }
5061
5062 // C++20 [dcl.init.list]p3:
5063 // - If the braced-init-list contains a designated-initializer-list, T shall
5064 // be an aggregate class. [...] Aggregate initialization is performed.
5065 //
5066 // We allow arrays here too in order to support array designators.
5067 //
5068 // FIXME: This check should precede the handling of reference initialization.
5069 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
5070 // as a tentative DR resolution.
5071 bool IsDesignatedInit = InitList->hasDesignatedInit();
5072 if (!DestType->isAggregateType() && IsDesignatedInit) {
5073 Sequence.SetFailed(
5075 return;
5076 }
5077
5078 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
5079 // - If T is an aggregate class and the initializer list has a single element
5080 // of type cv U, where U is T or a class derived from T, the object is
5081 // initialized from that element (by copy-initialization for
5082 // copy-list-initialization, or by direct-initialization for
5083 // direct-list-initialization).
5084 // - Otherwise, if T is a character array and the initializer list has a
5085 // single element that is an appropriately-typed string literal
5086 // (8.5.2 [dcl.init.string]), initialization is performed as described
5087 // in that section.
5088 // - Otherwise, if T is an aggregate, [...] (continue below).
5089 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
5090 !IsDesignatedInit) {
5091 if (DestType->isRecordType() && DestType->isAggregateType()) {
5092 QualType InitType = InitList->getInit(0)->getType();
5093 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
5094 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
5095 InitializationKind SubKind =
5097 ? InitializationKind::CreateDirect(Kind.getLocation(),
5098 InitList->getLBraceLoc(),
5099 InitList->getRBraceLoc())
5100 : Kind;
5101 Expr *InitListAsExpr = InitList;
5103 S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
5104 /*IsAggrListInit=*/true);
5105 return;
5106 }
5107 }
5108 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
5109 Expr *SubInit[1] = {InitList->getInit(0)};
5110
5111 // C++17 [dcl.struct.bind]p1:
5112 // ... If the assignment-expression in the initializer has array type A
5113 // and no ref-qualifier is present, e has type cv A and each element is
5114 // copy-initialized or direct-initialized from the corresponding element
5115 // of the assignment-expression as specified by the form of the
5116 // initializer. ...
5117 //
5118 // This is a special case not following list-initialization.
5119 if (isa<ConstantArrayType>(DestAT) &&
5121 isa<DecompositionDecl>(Entity.getDecl())) {
5122 assert(
5123 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5124 "Deduced to other type?");
5125 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5126 "List-initialize structured bindings but not "
5127 "direct-list-initialization?");
5128 TryArrayCopy(S,
5129 InitializationKind::CreateDirect(Kind.getLocation(),
5130 InitList->getLBraceLoc(),
5131 InitList->getRBraceLoc()),
5132 Entity, SubInit[0], DestType, Sequence,
5133 TreatUnavailableAsInvalid);
5134 if (Sequence)
5135 Sequence.AddUnwrapInitListInitStep(InitList);
5136 return;
5137 }
5138
5139 if (!isa<VariableArrayType>(DestAT) &&
5140 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
5141 InitializationKind SubKind =
5143 ? InitializationKind::CreateDirect(Kind.getLocation(),
5144 InitList->getLBraceLoc(),
5145 InitList->getRBraceLoc())
5146 : Kind;
5147 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5148 /*TopLevelOfInitList*/ true,
5149 TreatUnavailableAsInvalid);
5150
5151 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5152 // the element is not an appropriately-typed string literal, in which
5153 // case we should proceed as in C++11 (below).
5154 if (Sequence) {
5155 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5156 return;
5157 }
5158 }
5159 }
5160 }
5161
5162 // C++11 [dcl.init.list]p3:
5163 // - If T is an aggregate, aggregate initialization is performed.
5164 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5165 (S.getLangOpts().CPlusPlus11 &&
5166 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
5167 if (S.getLangOpts().CPlusPlus11) {
5168 // - Otherwise, if the initializer list has no elements and T is a
5169 // class type with a default constructor, the object is
5170 // value-initialized.
5171 if (InitList->getNumInits() == 0) {
5172 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5173 if (S.LookupDefaultConstructor(RD)) {
5174 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5175 return;
5176 }
5177 }
5178
5179 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5180 // an initializer_list object constructed [...]
5181 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
5182 TreatUnavailableAsInvalid))
5183 return;
5184
5185 // - Otherwise, if T is a class type, constructors are considered.
5186 Expr *InitListAsExpr = InitList;
5187 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
5188 DestType, Sequence, /*InitListSyntax*/true);
5189 } else
5191 return;
5192 }
5193
5194 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5195 InitList->getNumInits() == 1) {
5196 Expr *E = InitList->getInit(0);
5197
5198 // - Otherwise, if T is an enumeration with a fixed underlying type,
5199 // the initializer-list has a single element v, and the initialization
5200 // is direct-list-initialization, the object is initialized with the
5201 // value T(v); if a narrowing conversion is required to convert v to
5202 // the underlying type of T, the program is ill-formed.
5203 if (S.getLangOpts().CPlusPlus17 &&
5204 Kind.getKind() == InitializationKind::IK_DirectList &&
5205 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5206 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
5208 E->getType()->isFloatingType())) {
5209 // There are two ways that T(v) can work when T is an enumeration type.
5210 // If there is either an implicit conversion sequence from v to T or
5211 // a conversion function that can convert from v to T, then we use that.
5212 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5213 // type, it is converted to the enumeration type via its underlying type.
5214 // There is no overlap possible between these two cases (except when the
5215 // source value is already of the destination type), and the first
5216 // case is handled by the general case for single-element lists below.
5218 ICS.setStandard();
5220 if (!E->isPRValue())
5222 // If E is of a floating-point type, then the conversion is ill-formed
5223 // due to narrowing, but go through the motions in order to produce the
5224 // right diagnostic.
5228 ICS.Standard.setFromType(E->getType());
5229 ICS.Standard.setToType(0, E->getType());
5230 ICS.Standard.setToType(1, DestType);
5231 ICS.Standard.setToType(2, DestType);
5232 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
5233 /*TopLevelOfInitList*/true);
5234 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5235 return;
5236 }
5237
5238 // - Otherwise, if the initializer list has a single element of type E
5239 // [...references are handled above...], the object or reference is
5240 // initialized from that element (by copy-initialization for
5241 // copy-list-initialization, or by direct-initialization for
5242 // direct-list-initialization); if a narrowing conversion is required
5243 // to convert the element to T, the program is ill-formed.
5244 //
5245 // Per core-24034, this is direct-initialization if we were performing
5246 // direct-list-initialization and copy-initialization otherwise.
5247 // We can't use InitListChecker for this, because it always performs
5248 // copy-initialization. This only matters if we might use an 'explicit'
5249 // conversion operator, or for the special case conversion of nullptr_t to
5250 // bool, so we only need to handle those cases.
5251 //
5252 // FIXME: Why not do this in all cases?
5253 Expr *Init = InitList->getInit(0);
5254 if (Init->getType()->isRecordType() ||
5255 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5256 InitializationKind SubKind =
5258 ? InitializationKind::CreateDirect(Kind.getLocation(),
5259 InitList->getLBraceLoc(),
5260 InitList->getRBraceLoc())
5261 : Kind;
5262 Expr *SubInit[1] = { Init };
5263 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5264 /*TopLevelOfInitList*/true,
5265 TreatUnavailableAsInvalid);
5266 if (Sequence)
5267 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5268 return;
5269 }
5270 }
5271
5272 InitListChecker CheckInitList(S, Entity, InitList,
5273 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5274 if (CheckInitList.HadError()) {
5276 return;
5277 }
5278
5279 // Add the list initialization step with the built init list.
5280 Sequence.AddListInitializationStep(DestType);
5281}
5282
5283/// Try a reference initialization that involves calling a conversion
5284/// function.
5286 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5287 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5288 InitializationSequence &Sequence) {
5289 QualType DestType = Entity.getType();
5290 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5291 QualType T1 = cv1T1.getUnqualifiedType();
5292 QualType cv2T2 = Initializer->getType();
5293 QualType T2 = cv2T2.getUnqualifiedType();
5294
5295 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5296 "Must have incompatible references when binding via conversion");
5297
5298 // Build the candidate set directly in the initialization sequence
5299 // structure, so that it will persist if we fail.
5300 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5302
5303 // Determine whether we are allowed to call explicit conversion operators.
5304 // Note that none of [over.match.copy], [over.match.conv], nor
5305 // [over.match.ref] permit an explicit constructor to be chosen when
5306 // initializing a reference, not even for direct-initialization.
5307 bool AllowExplicitCtors = false;
5308 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5309
5310 if (AllowRValues && T1->isRecordType() &&
5311 S.isCompleteType(Kind.getLocation(), T1)) {
5312 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5313 if (T1RecordDecl->isInvalidDecl())
5314 return OR_No_Viable_Function;
5315 // The type we're converting to is a class type. Enumerate its constructors
5316 // to see if there is a suitable conversion.
5317 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
5318 auto Info = getConstructorInfo(D);
5319 if (!Info.Constructor)
5320 continue;
5321
5322 if (!Info.Constructor->isInvalidDecl() &&
5323 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5324 if (Info.ConstructorTmpl)
5326 Info.ConstructorTmpl, Info.FoundDecl,
5327 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5328 /*SuppressUserConversions=*/true,
5329 /*PartialOverloading*/ false, AllowExplicitCtors);
5330 else
5332 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
5333 /*SuppressUserConversions=*/true,
5334 /*PartialOverloading*/ false, AllowExplicitCtors);
5335 }
5336 }
5337 }
5338
5339 if (T2->isRecordType() && S.isCompleteType(Kind.getLocation(), T2)) {
5340 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5341 if (T2RecordDecl->isInvalidDecl())
5342 return OR_No_Viable_Function;
5343 // The type we're converting from is a class type, enumerate its conversion
5344 // functions.
5345 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5346 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5347 NamedDecl *D = *I;
5349 if (isa<UsingShadowDecl>(D))
5350 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5351
5352 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5353 CXXConversionDecl *Conv;
5354 if (ConvTemplate)
5355 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5356 else
5357 Conv = cast<CXXConversionDecl>(D);
5358
5359 // If the conversion function doesn't return a reference type,
5360 // it can't be considered for this conversion unless we're allowed to
5361 // consider rvalues.
5362 // FIXME: Do we need to make sure that we only consider conversion
5363 // candidates with reference-compatible results? That might be needed to
5364 // break recursion.
5365 if ((AllowRValues ||
5367 if (ConvTemplate)
5369 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5370 CandidateSet,
5371 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5372 else
5374 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5375 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5376 }
5377 }
5378 }
5379
5380 SourceLocation DeclLoc = Initializer->getBeginLoc();
5381
5382 // Perform overload resolution. If it fails, return the failed result.
5385 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5386 return Result;
5387
5388 FunctionDecl *Function = Best->Function;
5389 // This is the overload that will be used for this initialization step if we
5390 // use this initialization. Mark it as referenced.
5391 Function->setReferenced();
5392
5393 // Compute the returned type and value kind of the conversion.
5394 QualType cv3T3;
5395 if (isa<CXXConversionDecl>(Function))
5396 cv3T3 = Function->getReturnType();
5397 else
5398 cv3T3 = T1;
5399
5401 if (cv3T3->isLValueReferenceType())
5402 VK = VK_LValue;
5403 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5404 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5405 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5406
5407 // Add the user-defined conversion step.
5408 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5409 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5410 HadMultipleCandidates);
5411
5412 // Determine whether we'll need to perform derived-to-base adjustments or
5413 // other conversions.
5415 Sema::ReferenceCompareResult NewRefRelationship =
5416 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5417
5418 // Add the final conversion sequence, if necessary.
5419 if (NewRefRelationship == Sema::Ref_Incompatible) {
5420 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5421 "should not have conversion after constructor");
5422
5424 ICS.setStandard();
5425 ICS.Standard = Best->FinalConversion;
5426 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5427
5428 // Every implicit conversion results in a prvalue, except for a glvalue
5429 // derived-to-base conversion, which we handle below.
5430 cv3T3 = ICS.Standard.getToType(2);
5431 VK = VK_PRValue;
5432 }
5433
5434 // If the converted initializer is a prvalue, its type T4 is adjusted to
5435 // type "cv1 T4" and the temporary materialization conversion is applied.
5436 //
5437 // We adjust the cv-qualifications to match the reference regardless of
5438 // whether we have a prvalue so that the AST records the change. In this
5439 // case, T4 is "cv3 T3".
5440 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5441 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5442 Sequence.AddQualificationConversionStep(cv1T4, VK);
5443 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5444 VK = IsLValueRef ? VK_LValue : VK_XValue;
5445
5446 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5447 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5448 else if (RefConv & Sema::ReferenceConversions::ObjC)
5449 Sequence.AddObjCObjectConversionStep(cv1T1);
5450 else if (RefConv & Sema::ReferenceConversions::Function)
5451 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5452 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5453 if (!S.Context.hasSameType(cv1T4, cv1T1))
5454 Sequence.AddQualificationConversionStep(cv1T1, VK);
5455 }
5456
5457 return OR_Success;
5458}
5459
5460static void CheckCXX98CompatAccessibleCopy(Sema &S,
5461 const InitializedEntity &Entity,
5462 Expr *CurInitExpr);
5463
5464/// Attempt reference initialization (C++0x [dcl.init.ref])
5466 const InitializationKind &Kind,
5468 InitializationSequence &Sequence,
5469 bool TopLevelOfInitList) {
5470 QualType DestType = Entity.getType();
5471 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5472 Qualifiers T1Quals;
5473 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5475 Qualifiers T2Quals;
5476 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5477
5478 // If the initializer is the address of an overloaded function, try
5479 // to resolve the overloaded function. If all goes well, T2 is the
5480 // type of the resulting function.
5482 T1, Sequence))
5483 return;
5484
5485 // Delegate everything else to a subfunction.
5486 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5487 T1Quals, cv2T2, T2, T2Quals, Sequence,
5488 TopLevelOfInitList);
5489}
5490
5491/// Determine whether an expression is a non-referenceable glvalue (one to
5492/// which a reference can never bind). Attempting to bind a reference to
5493/// such a glvalue will always create a temporary.
5495 return E->refersToBitField() || E->refersToVectorElement() ||
5497}
5498
5499/// Reference initialization without resolving overloaded functions.
5500///
5501/// We also can get here in C if we call a builtin which is declared as
5502/// a function with a parameter of reference type (such as __builtin_va_end()).
5504 const InitializedEntity &Entity,
5505 const InitializationKind &Kind,
5507 QualType cv1T1, QualType T1,
5508 Qualifiers T1Quals,
5509 QualType cv2T2, QualType T2,
5510 Qualifiers T2Quals,
5511 InitializationSequence &Sequence,
5512 bool TopLevelOfInitList) {
5513 QualType DestType = Entity.getType();
5514 SourceLocation DeclLoc = Initializer->getBeginLoc();
5515
5516 // Compute some basic properties of the types and the initializer.
5517 bool isLValueRef = DestType->isLValueReferenceType();
5518 bool isRValueRef = !isLValueRef;
5519 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5520
5522 Sema::ReferenceCompareResult RefRelationship =
5523 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5524
5525 // C++0x [dcl.init.ref]p5:
5526 // A reference to type "cv1 T1" is initialized by an expression of type
5527 // "cv2 T2" as follows:
5528 //
5529 // - If the reference is an lvalue reference and the initializer
5530 // expression
5531 // Note the analogous bullet points for rvalue refs to functions. Because
5532 // there are no function rvalues in C++, rvalue refs to functions are treated
5533 // like lvalue refs.
5534 OverloadingResult ConvOvlResult = OR_Success;
5535 bool T1Function = T1->isFunctionType();
5536 if (isLValueRef || T1Function) {
5537 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5538 (RefRelationship == Sema::Ref_Compatible ||
5539 (Kind.isCStyleOrFunctionalCast() &&
5540 RefRelationship == Sema::Ref_Related))) {
5541 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5542 // reference-compatible with "cv2 T2," or
5543 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5544 Sema::ReferenceConversions::ObjC)) {
5545 // If we're converting the pointee, add any qualifiers first;
5546 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5547 if (RefConv & (Sema::ReferenceConversions::Qualification))
5549 S.Context.getQualifiedType(T2, T1Quals),
5550 Initializer->getValueKind());
5551 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5552 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5553 else
5554 Sequence.AddObjCObjectConversionStep(cv1T1);
5555 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5556 // Perform a (possibly multi-level) qualification conversion.
5557 Sequence.AddQualificationConversionStep(cv1T1,
5558 Initializer->getValueKind());
5559 } else if (RefConv & Sema::ReferenceConversions::Function) {
5560 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5561 }
5562
5563 // We only create a temporary here when binding a reference to a
5564 // bit-field or vector element. Those cases are't supposed to be
5565 // handled by this bullet, but the outcome is the same either way.
5566 Sequence.AddReferenceBindingStep(cv1T1, false);
5567 return;
5568 }
5569
5570 // - has a class type (i.e., T2 is a class type), where T1 is not
5571 // reference-related to T2, and can be implicitly converted to an
5572 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5573 // with "cv3 T3" (this conversion is selected by enumerating the
5574 // applicable conversion functions (13.3.1.6) and choosing the best
5575 // one through overload resolution (13.3)),
5576 // If we have an rvalue ref to function type here, the rhs must be
5577 // an rvalue. DR1287 removed the "implicitly" here.
5578 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5579 (isLValueRef || InitCategory.isRValue())) {
5580 if (S.getLangOpts().CPlusPlus) {
5581 // Try conversion functions only for C++.
5582 ConvOvlResult = TryRefInitWithConversionFunction(
5583 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5584 /*IsLValueRef*/ isLValueRef, Sequence);
5585 if (ConvOvlResult == OR_Success)
5586 return;
5587 if (ConvOvlResult != OR_No_Viable_Function)
5588 Sequence.SetOverloadFailure(
5590 ConvOvlResult);
5591 } else {
5592 ConvOvlResult = OR_No_Viable_Function;
5593 }
5594 }
5595 }
5596
5597 // - Otherwise, the reference shall be an lvalue reference to a
5598 // non-volatile const type (i.e., cv1 shall be const), or the reference
5599 // shall be an rvalue reference.
5600 // For address spaces, we interpret this to mean that an addr space
5601 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5602 if (isLValueRef &&
5603 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5604 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5607 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5608 Sequence.SetOverloadFailure(
5610 ConvOvlResult);
5611 else if (!InitCategory.isLValue())
5612 Sequence.SetFailed(
5613 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())
5617 else {
5619 switch (RefRelationship) {
5621 if (Initializer->refersToBitField())
5622 FK = InitializationSequence::
5623 FK_NonConstLValueReferenceBindingToBitfield;
5624 else if (Initializer->refersToVectorElement())
5625 FK = InitializationSequence::
5626 FK_NonConstLValueReferenceBindingToVectorElement;
5627 else if (Initializer->refersToMatrixElement())
5628 FK = InitializationSequence::
5629 FK_NonConstLValueReferenceBindingToMatrixElement;
5630 else
5631 llvm_unreachable("unexpected kind of compatible initializer");
5632 break;
5633 case Sema::Ref_Related:
5635 break;
5637 FK = InitializationSequence::
5638 FK_NonConstLValueReferenceBindingToUnrelated;
5639 break;
5640 }
5641 Sequence.SetFailed(FK);
5642 }
5643 return;
5644 }
5645
5646 // - If the initializer expression
5647 // - is an
5648 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5649 // [1z] rvalue (but not a bit-field) or
5650 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5651 //
5652 // Note: functions are handled above and below rather than here...
5653 if (!T1Function &&
5654 (RefRelationship == Sema::Ref_Compatible ||
5655 (Kind.isCStyleOrFunctionalCast() &&
5656 RefRelationship == Sema::Ref_Related)) &&
5657 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5658 (InitCategory.isPRValue() &&
5659 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5660 T2->isArrayType())))) {
5661 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5662 if (InitCategory.isPRValue() && T2->isRecordType()) {
5663 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5664 // compiler the freedom to perform a copy here or bind to the
5665 // object, while C++0x requires that we bind directly to the
5666 // object. Hence, we always bind to the object without making an
5667 // extra copy. However, in C++03 requires that we check for the
5668 // presence of a suitable copy constructor:
5669 //
5670 // The constructor that would be used to make the copy shall
5671 // be callable whether or not the copy is actually done.
5672 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5673 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5674 else if (S.getLangOpts().CPlusPlus11)
5676 }
5677
5678 // C++1z [dcl.init.ref]/5.2.1.2:
5679 // If the converted initializer is a prvalue, its type T4 is adjusted
5680 // to type "cv1 T4" and the temporary materialization conversion is
5681 // applied.
5682 // Postpone address space conversions to after the temporary materialization
5683 // conversion to allow creating temporaries in the alloca address space.
5684 auto T1QualsIgnoreAS = T1Quals;
5685 auto T2QualsIgnoreAS = T2Quals;
5686 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5687 T1QualsIgnoreAS.removeAddressSpace();
5688 T2QualsIgnoreAS.removeAddressSpace();
5689 }
5690 // Strip the existing ObjC lifetime qualifier from cv2T2 before combining
5691 // with T1's qualifiers.
5692 QualType T2ForQualConv = cv2T2;
5693 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) {
5694 Qualifiers T2BaseQuals =
5695 T2ForQualConv.getQualifiers().withoutObjCLifetime();
5696 T2ForQualConv = S.Context.getQualifiedType(
5697 T2ForQualConv.getUnqualifiedType(), T2BaseQuals);
5698 }
5699 QualType cv1T4 = S.Context.getQualifiedType(T2ForQualConv, T1QualsIgnoreAS);
5700 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5701 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5702 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5703 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5704 // Add addr space conversion if required.
5705 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5706 auto T4Quals = cv1T4.getQualifiers();
5707 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5708 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5709 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5710 cv1T4 = cv1T4WithAS;
5711 }
5712
5713 // In any case, the reference is bound to the resulting glvalue (or to
5714 // an appropriate base class subobject).
5715 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5716 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5717 else if (RefConv & Sema::ReferenceConversions::ObjC)
5718 Sequence.AddObjCObjectConversionStep(cv1T1);
5719 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5720 if (!S.Context.hasSameType(cv1T4, cv1T1))
5721 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5722 }
5723 return;
5724 }
5725
5726 // - has a class type (i.e., T2 is a class type), where T1 is not
5727 // reference-related to T2, and can be implicitly converted to an
5728 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5729 // where "cv1 T1" is reference-compatible with "cv3 T3",
5730 //
5731 // DR1287 removes the "implicitly" here.
5732 if (T2->isRecordType()) {
5733 if (RefRelationship == Sema::Ref_Incompatible) {
5734 ConvOvlResult = TryRefInitWithConversionFunction(
5735 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5736 /*IsLValueRef*/ isLValueRef, Sequence);
5737 if (ConvOvlResult)
5738 Sequence.SetOverloadFailure(
5740 ConvOvlResult);
5741
5742 return;
5743 }
5744
5745 if (RefRelationship == Sema::Ref_Compatible &&
5746 isRValueRef && InitCategory.isLValue()) {
5747 Sequence.SetFailed(
5749 return;
5750 }
5751
5753 return;
5754 }
5755
5756 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5757 // from the initializer expression using the rules for a non-reference
5758 // copy-initialization (8.5). The reference is then bound to the
5759 // temporary. [...]
5760
5761 // Ignore address space of reference type at this point and perform address
5762 // space conversion after the reference binding step.
5763 QualType cv1T1IgnoreAS =
5764 T1Quals.hasAddressSpace()
5766 : cv1T1;
5767
5768 InitializedEntity TempEntity =
5770
5771 // FIXME: Why do we use an implicit conversion here rather than trying
5772 // copy-initialization?
5774 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5775 /*SuppressUserConversions=*/false,
5776 Sema::AllowedExplicit::None,
5777 /*FIXME:InOverloadResolution=*/false,
5778 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5779 /*AllowObjCWritebackConversion=*/false);
5780
5781 if (ICS.isBad()) {
5782 // FIXME: Use the conversion function set stored in ICS to turn
5783 // this into an overloading ambiguity diagnostic. However, we need
5784 // to keep that set as an OverloadCandidateSet rather than as some
5785 // other kind of set.
5786 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5787 Sequence.SetOverloadFailure(
5789 ConvOvlResult);
5790 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5792 else
5794 return;
5795 } else {
5796 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5797 TopLevelOfInitList);
5798 }
5799
5800 // [...] If T1 is reference-related to T2, cv1 must be the
5801 // same cv-qualification as, or greater cv-qualification
5802 // than, cv2; otherwise, the program is ill-formed.
5803 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5804 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5805 if (RefRelationship == Sema::Ref_Related &&
5806 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5807 !T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5809 return;
5810 }
5811
5812 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5813 // reference, the initializer expression shall not be an lvalue.
5814 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5815 InitCategory.isLValue()) {
5816 Sequence.SetFailed(
5818 return;
5819 }
5820
5821 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5822
5823 if (T1Quals.hasAddressSpace()) {
5826 Sequence.SetFailed(
5828 return;
5829 }
5830 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5831 : VK_XValue);
5832 }
5833}
5834
5835/// Attempt character array initialization from a string literal
5836/// (C++ [dcl.init.string], C99 6.7.8).
5838 const InitializedEntity &Entity,
5839 const InitializationKind &Kind,
5841 InitializationSequence &Sequence) {
5842 Sequence.AddStringInitStep(Entity.getType());
5843}
5844
5845/// Attempt value initialization (C++ [dcl.init]p7).
5847 const InitializedEntity &Entity,
5848 const InitializationKind &Kind,
5849 InitializationSequence &Sequence,
5850 InitListExpr *InitList) {
5851 assert((!InitList || InitList->getNumInits() == 0) &&
5852 "Shouldn't use value-init for non-empty init lists");
5853
5854 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5855 //
5856 // To value-initialize an object of type T means:
5857 QualType T = Entity.getType();
5858 assert(!T->isVoidType() && "Cannot value-init void");
5859
5860 // -- if T is an array type, then each element is value-initialized;
5862
5863 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5864 bool NeedZeroInitialization = true;
5865 // C++98:
5866 // -- if T is a class type (clause 9) with a user-declared constructor
5867 // (12.1), then the default constructor for T is called (and the
5868 // initialization is ill-formed if T has no accessible default
5869 // constructor);
5870 // C++11:
5871 // -- if T is a class type (clause 9) with either no default constructor
5872 // (12.1 [class.ctor]) or a default constructor that is user-provided
5873 // or deleted, then the object is default-initialized;
5874 //
5875 // Note that the C++11 rule is the same as the C++98 rule if there are no
5876 // defaulted or deleted constructors, so we just use it unconditionally.
5878 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5879 NeedZeroInitialization = false;
5880
5881 // -- if T is a (possibly cv-qualified) non-union class type without a
5882 // user-provided or deleted default constructor, then the object is
5883 // zero-initialized and, if T has a non-trivial default constructor,
5884 // default-initialized;
5885 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5886 // constructor' part was removed by DR1507.
5887 if (NeedZeroInitialization)
5888 Sequence.AddZeroInitializationStep(Entity.getType());
5889
5890 // C++03:
5891 // -- if T is a non-union class type without a user-declared constructor,
5892 // then every non-static data member and base class component of T is
5893 // value-initialized;
5894 // [...] A program that calls for [...] value-initialization of an
5895 // entity of reference type is ill-formed.
5896 //
5897 // C++11 doesn't need this handling, because value-initialization does not
5898 // occur recursively there, and the implicit default constructor is
5899 // defined as deleted in the problematic cases.
5900 if (!S.getLangOpts().CPlusPlus11 &&
5901 ClassDecl->hasUninitializedReferenceMember()) {
5903 return;
5904 }
5905
5906 // If this is list-value-initialization, pass the empty init list on when
5907 // building the constructor call. This affects the semantics of a few
5908 // things (such as whether an explicit default constructor can be called).
5909 Expr *InitListAsExpr = InitList;
5910 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5911 bool InitListSyntax = InitList;
5912
5913 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5914 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5916 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5917 }
5918
5919 Sequence.AddZeroInitializationStep(Entity.getType());
5920}
5921
5922/// Attempt default initialization (C++ [dcl.init]p6).
5924 const InitializedEntity &Entity,
5925 const InitializationKind &Kind,
5926 InitializationSequence &Sequence) {
5927 assert(Kind.getKind() == InitializationKind::IK_Default);
5928
5929 // C++ [dcl.init]p6:
5930 // To default-initialize an object of type T means:
5931 // - if T is an array type, each element is default-initialized;
5932 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5933
5934 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5935 // constructor for T is called (and the initialization is ill-formed if
5936 // T has no accessible default constructor);
5937 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5938 TryConstructorInitialization(S, Entity, Kind, {}, DestType,
5939 Entity.getType(), Sequence);
5940 return;
5941 }
5942
5943 // - otherwise, no initialization is performed.
5944
5945 // If a program calls for the default initialization of an object of
5946 // a const-qualified type T, T shall be a class type with a user-provided
5947 // default constructor.
5948 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5949 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5951 return;
5952 }
5953
5954 // If the destination type has a lifetime property, zero-initialize it.
5955 if (DestType.getQualifiers().hasObjCLifetime()) {
5956 Sequence.AddZeroInitializationStep(Entity.getType());
5957 return;
5958 }
5959}
5960
5962 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5963 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5964 ExprResult *Result) {
5965 unsigned EntityIndexToProcess = 0;
5966 SmallVector<Expr *, 4> InitExprs;
5967 QualType ResultType;
5968 Expr *ArrayFiller = nullptr;
5969 FieldDecl *InitializedFieldInUnion = nullptr;
5970
5971 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5972 const InitializationKind &SubKind,
5973 Expr *Arg, Expr **InitExpr = nullptr) {
5975 S, SubEntity, SubKind,
5976 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5977
5978 if (IS.Failed()) {
5979 if (!VerifyOnly) {
5980 IS.Diagnose(S, SubEntity, SubKind,
5981 Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5982 } else {
5983 Sequence.SetFailed(
5985 }
5986
5987 return false;
5988 }
5989 if (!VerifyOnly) {
5990 ExprResult ER;
5991 ER = IS.Perform(S, SubEntity, SubKind,
5992 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5993
5994 if (ER.isInvalid())
5995 return false;
5996
5997 if (InitExpr)
5998 *InitExpr = ER.get();
5999 else
6000 InitExprs.push_back(ER.get());
6001 }
6002 return true;
6003 };
6004
6005 if (const ArrayType *AT =
6006 S.getASTContext().getAsArrayType(Entity.getType())) {
6007 uint64_t ArrayLength;
6008 // C++ [dcl.init]p16.5
6009 // if the destination type is an array, the object is initialized as
6010 // follows. Let x1, . . . , xk be the elements of the expression-list. If
6011 // the destination type is an array of unknown bound, it is defined as
6012 // having k elements.
6013 if (const ConstantArrayType *CAT =
6015 ArrayLength = CAT->getZExtSize();
6016 ResultType = Entity.getType();
6017 } else if (const VariableArrayType *VAT =
6019 // Braced-initialization of variable array types is not allowed, even if
6020 // the size is greater than or equal to the number of args, so we don't
6021 // allow them to be initialized via parenthesized aggregate initialization
6022 // either.
6023 const Expr *SE = VAT->getSizeExpr();
6024 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
6025 << SE->getSourceRange();
6026 return;
6027 } else {
6028 assert(Entity.getType()->isIncompleteArrayType());
6029 ArrayLength = Args.size();
6030 }
6031 EntityIndexToProcess = ArrayLength;
6032
6033 // ...the ith array element is copy-initialized with xi for each
6034 // 1 <= i <= k
6035 for (Expr *E : Args) {
6037 S.getASTContext(), EntityIndexToProcess, Entity);
6039 E->getExprLoc(), /*isDirectInit=*/false, E);
6040 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6041 return;
6042 }
6043 // ...and value-initialized for each k < i <= n;
6044 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
6046 S.getASTContext(), Args.size(), Entity);
6048 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6049 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
6050 return;
6051 }
6052
6053 if (ResultType.isNull()) {
6054 ResultType = S.Context.getConstantArrayType(
6055 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
6056 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
6057 }
6058 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
6059 bool IsUnion = RD->isUnion();
6060 if (RD->isInvalidDecl()) {
6061 // Exit early to avoid confusion when processing members.
6062 // We do the same for braced list initialization in
6063 // `CheckStructUnionTypes`.
6064 Sequence.SetFailed(
6066 return;
6067 }
6068
6069 if (!IsUnion) {
6070 for (const CXXBaseSpecifier &Base : RD->bases()) {
6072 S.getASTContext(), &Base, false, &Entity);
6073 if (EntityIndexToProcess < Args.size()) {
6074 // C++ [dcl.init]p16.6.2.2.
6075 // ...the object is initialized is follows. Let e1, ..., en be the
6076 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
6077 // the elements of the expression-list...The element ei is
6078 // copy-initialized with xi for 1 <= i <= k.
6079 Expr *E = Args[EntityIndexToProcess];
6081 E->getExprLoc(), /*isDirectInit=*/false, E);
6082 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6083 return;
6084 } else {
6085 // We've processed all of the args, but there are still base classes
6086 // that have to be initialized.
6087 // C++ [dcl.init]p17.6.2.2
6088 // The remaining elements...otherwise are value initialzed
6090 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
6091 /*IsImplicit=*/true);
6092 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6093 return;
6094 }
6095 EntityIndexToProcess++;
6096 }
6097 }
6098
6099 for (FieldDecl *FD : RD->fields()) {
6100 // Unnamed bitfields should not be initialized at all, either with an arg
6101 // or by default.
6102 if (FD->isUnnamedBitField())
6103 continue;
6104
6105 InitializedEntity SubEntity =
6107
6108 if (EntityIndexToProcess < Args.size()) {
6109 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6110 Expr *E = Args[EntityIndexToProcess];
6111
6112 // Incomplete array types indicate flexible array members. Do not allow
6113 // paren list initializations of structs with these members, as GCC
6114 // doesn't either.
6115 if (FD->getType()->isIncompleteArrayType()) {
6116 if (!VerifyOnly) {
6117 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
6118 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6119 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
6120 }
6121 Sequence.SetFailed(
6123 return;
6124 }
6125
6127 E->getExprLoc(), /*isDirectInit=*/false, E);
6128 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6129 return;
6130
6131 // Unions should have only one initializer expression, so we bail out
6132 // after processing the first field. If there are more initializers then
6133 // it will be caught when we later check whether EntityIndexToProcess is
6134 // less than Args.size();
6135 if (IsUnion) {
6136 InitializedFieldInUnion = FD;
6137 EntityIndexToProcess = 1;
6138 break;
6139 }
6140 } else {
6141 // We've processed all of the args, but there are still members that
6142 // have to be initialized.
6143 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6144 !S.isUnevaluatedContext()) {
6145 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
6146 << /* Var-in-Record */ 0 << FD;
6147 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
6148 }
6149
6150 if (FD->hasInClassInitializer()) {
6151 if (!VerifyOnly) {
6152 // C++ [dcl.init]p16.6.2.2
6153 // The remaining elements are initialized with their default
6154 // member initializers, if any
6156 Kind.getParenOrBraceRange().getEnd(), FD);
6157 if (DIE.isInvalid())
6158 return;
6159 S.checkInitializerLifetime(SubEntity, DIE.get());
6160 InitExprs.push_back(DIE.get());
6161 }
6162 } else {
6163 // C++ [dcl.init]p17.6.2.2
6164 // The remaining elements...otherwise are value initialzed
6165 if (FD->getType()->isReferenceType()) {
6166 Sequence.SetFailed(
6168 if (!VerifyOnly) {
6169 SourceRange SR = Kind.getParenOrBraceRange();
6170 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
6171 << FD->getType() << SR;
6172 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
6173 }
6174 return;
6175 }
6177 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6178 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6179 return;
6180 }
6181 }
6182 EntityIndexToProcess++;
6183 }
6184 ResultType = Entity.getType();
6185 }
6186
6187 // Not all of the args have been processed, so there must've been more args
6188 // than were required to initialize the element.
6189 if (EntityIndexToProcess < Args.size()) {
6191 if (!VerifyOnly) {
6192 QualType T = Entity.getType();
6193 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6194 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6195 Args.back()->getEndLoc());
6196 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6197 << InitKind << ExcessInitSR;
6198 }
6199 return;
6200 }
6201
6202 if (VerifyOnly) {
6204 Sequence.AddParenthesizedListInitStep(Entity.getType());
6205 } else if (Result) {
6206 SourceRange SR = Kind.getParenOrBraceRange();
6207 auto *CPLIE = CXXParenListInitExpr::Create(
6208 S.getASTContext(), InitExprs, ResultType, Args.size(),
6209 Kind.getLocation(), SR.getBegin(), SR.getEnd());
6210 if (ArrayFiller)
6211 CPLIE->setArrayFiller(ArrayFiller);
6212 if (InitializedFieldInUnion)
6213 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6214 *Result = CPLIE;
6215 S.Diag(Kind.getLocation(),
6216 diag::warn_cxx17_compat_aggregate_init_paren_list)
6217 << Kind.getLocation() << SR << ResultType;
6218 }
6219}
6220
6221/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6222/// which enumerates all conversion functions and performs overload resolution
6223/// to select the best.
6225 QualType DestType,
6226 const InitializationKind &Kind,
6228 InitializationSequence &Sequence,
6229 bool TopLevelOfInitList) {
6230 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6231 QualType SourceType = Initializer->getType();
6232 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6233 "Must have a class type to perform a user-defined conversion");
6234
6235 // Build the candidate set directly in the initialization sequence
6236 // structure, so that it will persist if we fail.
6237 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6239 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6240
6241 // Determine whether we are allowed to call explicit constructors or
6242 // explicit conversion operators.
6243 bool AllowExplicit = Kind.AllowExplicit();
6244
6245 if (DestType->isRecordType()) {
6246 // The type we're converting to is a class type. Enumerate its constructors
6247 // to see if there is a suitable conversion.
6248 // Try to complete the type we're converting to.
6249 if (S.isCompleteType(Kind.getLocation(), DestType)) {
6250 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6251 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
6252 auto Info = getConstructorInfo(D);
6253 if (!Info.Constructor)
6254 continue;
6255
6256 if (!Info.Constructor->isInvalidDecl() &&
6257 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6258 if (Info.ConstructorTmpl)
6260 Info.ConstructorTmpl, Info.FoundDecl,
6261 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
6262 /*SuppressUserConversions=*/true,
6263 /*PartialOverloading*/ false, AllowExplicit);
6264 else
6265 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
6266 Initializer, CandidateSet,
6267 /*SuppressUserConversions=*/true,
6268 /*PartialOverloading*/ false, AllowExplicit);
6269 }
6270 }
6271 }
6272 }
6273
6274 SourceLocation DeclLoc = Initializer->getBeginLoc();
6275
6276 if (SourceType->isRecordType()) {
6277 // The type we're converting from is a class type, enumerate its conversion
6278 // functions.
6279
6280 // We can only enumerate the conversion functions for a complete type; if
6281 // the type isn't complete, simply skip this step.
6282 if (S.isCompleteType(DeclLoc, SourceType)) {
6283 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6284 const auto &Conversions =
6285 SourceRecordDecl->getVisibleConversionFunctions();
6286 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6287 NamedDecl *D = *I;
6289 if (isa<UsingShadowDecl>(D))
6290 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6291
6292 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6293 CXXConversionDecl *Conv;
6294 if (ConvTemplate)
6295 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6296 else
6297 Conv = cast<CXXConversionDecl>(D);
6298
6299 if (ConvTemplate)
6301 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
6302 CandidateSet, AllowExplicit, AllowExplicit);
6303 else
6304 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
6305 DestType, CandidateSet, AllowExplicit,
6306 AllowExplicit);
6307 }
6308 }
6309 }
6310
6311 // Perform overload resolution. If it fails, return the failed result.
6314 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
6315 Sequence.SetOverloadFailure(
6317
6318 // [class.copy.elision]p3:
6319 // In some copy-initialization contexts, a two-stage overload resolution
6320 // is performed.
6321 // If the first overload resolution selects a deleted function, we also
6322 // need the initialization sequence to decide whether to perform the second
6323 // overload resolution.
6324 if (!(Result == OR_Deleted &&
6325 Kind.getKind() == InitializationKind::IK_Copy))
6326 return;
6327 }
6328
6329 FunctionDecl *Function = Best->Function;
6330 Function->setReferenced();
6331 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6332
6333 if (isa<CXXConstructorDecl>(Function)) {
6334 // Add the user-defined conversion step. Any cv-qualification conversion is
6335 // subsumed by the initialization. Per DR5, the created temporary is of the
6336 // cv-unqualified type of the destination.
6337 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
6338 DestType.getUnqualifiedType(),
6339 HadMultipleCandidates);
6340
6341 // C++14 and before:
6342 // - if the function is a constructor, the call initializes a temporary
6343 // of the cv-unqualified version of the destination type. The [...]
6344 // temporary [...] is then used to direct-initialize, according to the
6345 // rules above, the object that is the destination of the
6346 // copy-initialization.
6347 // Note that this just performs a simple object copy from the temporary.
6348 //
6349 // C++17:
6350 // - if the function is a constructor, the call is a prvalue of the
6351 // cv-unqualified version of the destination type whose return object
6352 // is initialized by the constructor. The call is used to
6353 // direct-initialize, according to the rules above, the object that
6354 // is the destination of the copy-initialization.
6355 // Therefore we need to do nothing further.
6356 //
6357 // FIXME: Mark this copy as extraneous.
6358 if (!S.getLangOpts().CPlusPlus17)
6359 Sequence.AddFinalCopy(DestType);
6360 else if (DestType.hasQualifiers())
6361 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6362 return;
6363 }
6364
6365 // Add the user-defined conversion step that calls the conversion function.
6366 QualType ConvType = Function->getCallResultType();
6367 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6368 HadMultipleCandidates);
6369
6370 if (ConvType->isRecordType()) {
6371 if (S.getLangOpts().HLSL &&
6372 ConvType.getAddressSpace() == LangAS::hlsl_constant &&
6373 S.Context.hasSameUnqualifiedType(ConvType, DestType)) {
6374 Sequence.AddHLSLBufferConversionStep(ConvType);
6375 return;
6376 }
6377
6378 // The call is used to direct-initialize [...] the object that is the
6379 // destination of the copy-initialization.
6380 //
6381 // In C++17, this does not call a constructor if we enter /17.6.1:
6382 // - If the initializer expression is a prvalue and the cv-unqualified
6383 // version of the source type is the same as the class of the
6384 // destination [... do not make an extra copy]
6385 //
6386 // FIXME: Mark this copy as extraneous.
6387 if (!S.getLangOpts().CPlusPlus17 ||
6388 Function->getReturnType()->isReferenceType() ||
6389 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6390 Sequence.AddFinalCopy(DestType);
6391 else if (!S.Context.hasSameType(ConvType, DestType))
6392 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6393 return;
6394 }
6395
6396 // If the conversion following the call to the conversion function
6397 // is interesting, add it as a separate step.
6398 assert(Best->HasFinalConversion);
6399 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6400 Best->FinalConversion.Third) {
6402 ICS.setStandard();
6403 ICS.Standard = Best->FinalConversion;
6404 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6405 }
6406}
6407
6408/// The non-zero enum values here are indexes into diagnostic alternatives.
6410
6411/// Determines whether this expression is an acceptable ICR source.
6413 bool isAddressOf, bool &isWeakAccess) {
6414 // Skip parens.
6415 e = e->IgnoreParens();
6416
6417 // Skip address-of nodes.
6418 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6419 if (op->getOpcode() == UO_AddrOf)
6420 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6421 isWeakAccess);
6422
6423 // Skip certain casts.
6424 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6425 switch (ce->getCastKind()) {
6426 case CK_Dependent:
6427 case CK_BitCast:
6428 case CK_LValueBitCast:
6429 case CK_NoOp:
6430 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6431
6432 case CK_ArrayToPointerDecay:
6433 return IIK_nonscalar;
6434
6435 case CK_NullToPointer:
6436 return IIK_okay;
6437
6438 default:
6439 break;
6440 }
6441
6442 // If we have a declaration reference, it had better be a local variable.
6443 } else if (isa<DeclRefExpr>(e)) {
6444 // set isWeakAccess to true, to mean that there will be an implicit
6445 // load which requires a cleanup.
6447 isWeakAccess = true;
6448
6449 if (!isAddressOf) return IIK_nonlocal;
6450
6451 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6452 if (!var) return IIK_nonlocal;
6453
6454 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6455
6456 // If we have a conditional operator, check both sides.
6457 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6458 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6459 isWeakAccess))
6460 return iik;
6461
6462 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6463
6464 // These are never scalar.
6465 } else if (isa<ArraySubscriptExpr>(e)) {
6466 return IIK_nonscalar;
6467
6468 // Otherwise, it needs to be a null pointer constant.
6469 } else {
6472 }
6473
6474 return IIK_nonlocal;
6475}
6476
6477/// Check whether the given expression is a valid operand for an
6478/// indirect copy/restore.
6480 assert(src->isPRValue());
6481 bool isWeakAccess = false;
6482 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6483 // If isWeakAccess to true, there will be an implicit
6484 // load which requires a cleanup.
6485 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6487
6488 if (iik == IIK_okay) return;
6489
6490 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6491 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6492 << src->getSourceRange();
6493}
6494
6495/// Determine whether we have compatible array types for the
6496/// purposes of GNU by-copy array initialization.
6497static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6498 const ArrayType *Source) {
6499 // If the source and destination array types are equivalent, we're
6500 // done.
6501 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6502 return true;
6503
6504 // Make sure that the element types are the same.
6505 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6506 return false;
6507
6508 // The only mismatch we allow is when the destination is an
6509 // incomplete array type and the source is a constant array type.
6510 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6511}
6512
6514 InitializationSequence &Sequence,
6515 const InitializedEntity &Entity,
6516 Expr *Initializer) {
6517 bool ArrayDecay = false;
6518 QualType ArgType = Initializer->getType();
6519 QualType ArgPointee;
6520 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6521 ArrayDecay = true;
6522 ArgPointee = ArgArrayType->getElementType();
6523 ArgType = S.Context.getPointerType(ArgPointee);
6524 }
6525
6526 // Handle write-back conversion.
6527 QualType ConvertedArgType;
6528 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6529 ConvertedArgType))
6530 return false;
6531
6532 // We should copy unless we're passing to an argument explicitly
6533 // marked 'out'.
6534 bool ShouldCopy = true;
6535 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6536 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6537
6538 // Do we need an lvalue conversion?
6539 if (ArrayDecay || Initializer->isGLValue()) {
6541 ICS.setStandard();
6543
6544 QualType ResultType;
6545 if (ArrayDecay) {
6547 ResultType = S.Context.getPointerType(ArgPointee);
6548 } else {
6550 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6551 }
6552
6553 Sequence.AddConversionSequenceStep(ICS, ResultType);
6554 }
6555
6556 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6557 return true;
6558}
6559
6561 InitializationSequence &Sequence,
6562 QualType DestType,
6563 Expr *Initializer) {
6564 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6565 (!Initializer->isIntegerConstantExpr(S.Context) &&
6566 !Initializer->getType()->isSamplerT()))
6567 return false;
6568
6569 Sequence.AddOCLSamplerInitStep(DestType);
6570 return true;
6571}
6572
6573static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6574 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6575 return Value && Value->isZero();
6576}
6577
6579 InitializationSequence &Sequence,
6580 QualType DestType,
6581 Expr *Initializer) {
6582 if (!S.getLangOpts().OpenCL)
6583 return false;
6584
6585 //
6586 // OpenCL 1.2 spec, s6.12.10
6587 //
6588 // The event argument can also be used to associate the
6589 // async_work_group_copy with a previous async copy allowing
6590 // an event to be shared by multiple async copies; otherwise
6591 // event should be zero.
6592 //
6593 if (DestType->isEventT() || DestType->isQueueT()) {
6595 return false;
6596
6597 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6598 return true;
6599 }
6600
6601 // We should allow zero initialization for all types defined in the
6602 // cl_intel_device_side_avc_motion_estimation extension, except
6603 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6605 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6606 DestType->isOCLIntelSubgroupAVCType()) {
6607 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6608 DestType->isOCLIntelSubgroupAVCMceResultType())
6609 return false;
6611 return false;
6612
6613 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6614 return true;
6615 }
6616
6617 return false;
6618}
6619
6621 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6622 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6623 : FailedOverloadResult(OR_Success),
6624 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6625 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6626 TreatUnavailableAsInvalid);
6627}
6628
6629/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6630/// address of that function, this returns true. Otherwise, it returns false.
6631static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6632 auto *DRE = dyn_cast<DeclRefExpr>(E);
6633 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6634 return false;
6635
6637 cast<FunctionDecl>(DRE->getDecl()));
6638}
6639
6640/// Determine whether we can perform an elementwise array copy for this kind
6641/// of entity.
6642static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6643 switch (Entity.getKind()) {
6645 // C++ [expr.prim.lambda]p24:
6646 // For array members, the array elements are direct-initialized in
6647 // increasing subscript order.
6648 return true;
6649
6651 // C++ [dcl.decomp]p1:
6652 // [...] each element is copy-initialized or direct-initialized from the
6653 // corresponding element of the assignment-expression [...]
6654 return isa<DecompositionDecl>(Entity.getDecl());
6655
6657 // C++ [class.copy.ctor]p14:
6658 // - if the member is an array, each element is direct-initialized with
6659 // the corresponding subobject of x
6660 return Entity.isImplicitMemberInitializer();
6661
6663 // All the above cases are intended to apply recursively, even though none
6664 // of them actually say that.
6665 if (auto *E = Entity.getParent())
6666 return canPerformArrayCopy(*E);
6667 break;
6668
6669 default:
6670 break;
6671 }
6672
6673 return false;
6674}
6675
6676static const FieldDecl *getConstField(const RecordDecl *RD) {
6677 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6678 for (const FieldDecl *FD : RD->fields()) {
6679 // If the field is a flexible array member, we don't want to consider it
6680 // as a const field because there's no way to initialize the FAM anyway.
6681 const ASTContext &Ctx = FD->getASTContext();
6683 Ctx, FD, FD->getType(),
6684 Ctx.getLangOpts().getStrictFlexArraysLevel(),
6685 /*IgnoreTemplateOrMacroSubstitution=*/true))
6686 continue;
6687
6688 QualType QT = FD->getType();
6689 if (QT.isConstQualified())
6690 return FD;
6691 if (const auto *RD = QT->getAsRecordDecl()) {
6692 if (const FieldDecl *FD = getConstField(RD))
6693 return FD;
6694 }
6695 }
6696 return nullptr;
6697}
6698
6700 const InitializedEntity &Entity,
6701 const InitializationKind &Kind,
6702 MultiExprArg Args,
6703 bool TopLevelOfInitList,
6704 bool TreatUnavailableAsInvalid) {
6705 ASTContext &Context = S.Context;
6706
6707 // Eliminate non-overload placeholder types in the arguments. We
6708 // need to do this before checking whether types are dependent
6709 // because lowering a pseudo-object expression might well give us
6710 // something of dependent type.
6711 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6712 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6713 // FIXME: should we be doing this here?
6714 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6715 if (result.isInvalid()) {
6717 return;
6718 }
6719 Args[I] = result.get();
6720 }
6721
6722 // C++0x [dcl.init]p16:
6723 // The semantics of initializers are as follows. The destination type is
6724 // the type of the object or reference being initialized and the source
6725 // type is the type of the initializer expression. The source type is not
6726 // defined when the initializer is a braced-init-list or when it is a
6727 // parenthesized list of expressions.
6728 QualType DestType = Entity.getType();
6729
6730 if (DestType->isDependentType() ||
6733 return;
6734 }
6735
6736 // Almost everything is a normal sequence.
6738
6739 QualType SourceType;
6740 Expr *Initializer = nullptr;
6741 if (Args.size() == 1) {
6742 Initializer = Args[0];
6743 if (S.getLangOpts().ObjC) {
6745 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6746 Initializer) ||
6748 Args[0] = Initializer;
6749 }
6751 SourceType = Initializer->getType();
6752 }
6753
6754 // - If the initializer is a (non-parenthesized) braced-init-list, the
6755 // object is list-initialized (8.5.4).
6756 if (Kind.getKind() != InitializationKind::IK_Direct) {
6757 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6758 TryListInitialization(S, Entity, Kind, InitList, *this,
6759 TreatUnavailableAsInvalid);
6760 return;
6761 }
6762 }
6763
6764 if (!S.getLangOpts().CPlusPlus &&
6765 Kind.getKind() == InitializationKind::IK_Default) {
6766 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6767 VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6768 if (Rec->hasUninitializedExplicitInitFields()) {
6769 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6770 S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6771 << /* Var-in-Record */ 1 << Rec;
6773 }
6774 }
6775 // If the record has any members which are const (recursively checked),
6776 // then we want to diagnose those as being uninitialized if there is no
6777 // initializer present. However, we only do this for structure types, not
6778 // union types, because an unitialized field in a union is generally
6779 // reasonable, especially in C where unions can be used for type punning.
6780 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6781 if (const FieldDecl *FD = getConstField(Rec)) {
6782 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6783 if (Var->getStorageDuration() == SD_Static ||
6784 Var->getStorageDuration() == SD_Thread)
6785 DiagID = diag::warn_default_init_const_field;
6786
6787 bool EmitCppCompat = !S.Diags.isIgnored(
6788 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6789 Var->getLocation());
6790
6791 S.Diag(Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6792 S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6793 }
6794 }
6795 }
6796 }
6797
6798 // - If the destination type is a reference type, see 8.5.3.
6799 if (DestType->isReferenceType()) {
6800 // C++0x [dcl.init.ref]p1:
6801 // A variable declared to be a T& or T&&, that is, "reference to type T"
6802 // (8.3.2), shall be initialized by an object, or function, of type T or
6803 // by an object that can be converted into a T.
6804 // (Therefore, multiple arguments are not permitted.)
6805 if (Args.size() != 1)
6807 // C++17 [dcl.init.ref]p5:
6808 // A reference [...] is initialized by an expression [...] as follows:
6809 // If the initializer is not an expression, presumably we should reject,
6810 // but the standard fails to actually say so.
6811 else if (isa<InitListExpr>(Args[0]))
6813 else
6814 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6815 TopLevelOfInitList);
6816 return;
6817 }
6818
6819 // - If the initializer is (), the object is value-initialized.
6820 if (Kind.getKind() == InitializationKind::IK_Value ||
6821 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6822 TryValueInitialization(S, Entity, Kind, *this);
6823 return;
6824 }
6825
6826 // Handle default initialization.
6827 if (Kind.getKind() == InitializationKind::IK_Default) {
6828 TryDefaultInitialization(S, Entity, Kind, *this);
6829 return;
6830 }
6831
6832 // - If the destination type is an array of characters, an array of
6833 // char16_t, an array of char32_t, or an array of wchar_t, and the
6834 // initializer is a string literal, see 8.5.2.
6835 // - Otherwise, if the destination type is an array, the program is
6836 // ill-formed.
6837 // - Except in HLSL, where non-decaying array parameters behave like
6838 // non-array types for initialization.
6839 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6840 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6841 if (Initializer && isa<VariableArrayType>(DestAT)) {
6843 return;
6844 }
6845
6846 if (Initializer) {
6847 switch (IsStringInit(Initializer, DestAT, Context)) {
6848 case SIF_None:
6849 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6850 return;
6853 return;
6856 return;
6859 return;
6862 return;
6865 return;
6866 case SIF_Other:
6867 break;
6868 }
6869 }
6870
6871 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(DestAT)) {
6872 QualType SrcType = Entity.getType();
6873 if (SrcType->isArrayParameterType())
6874 SrcType =
6875 cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6876 if (S.Context.hasSameUnqualifiedType(DestType, SrcType)) {
6877 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6878 TreatUnavailableAsInvalid);
6879 return;
6880 }
6881 }
6882
6883 // Some kinds of initialization permit an array to be initialized from
6884 // another array of the same type, and perform elementwise initialization.
6885 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6887 Entity.getType()) &&
6888 canPerformArrayCopy(Entity)) {
6889 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6890 TreatUnavailableAsInvalid);
6891 return;
6892 }
6893
6894 // Note: as an GNU C extension, we allow initialization of an
6895 // array from a compound literal that creates an array of the same
6896 // type, so long as the initializer has no side effects.
6897 if (!S.getLangOpts().CPlusPlus && Initializer &&
6898 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6899 Initializer->getType()->isArrayType()) {
6900 const ArrayType *SourceAT
6901 = Context.getAsArrayType(Initializer->getType());
6902 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6904 else if (Initializer->HasSideEffects(S.Context))
6906 else {
6907 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6908 }
6909 }
6910 // Note: as a GNU C++ extension, we allow list-initialization of a
6911 // class member of array type from a parenthesized initializer list.
6912 else if (S.getLangOpts().CPlusPlus &&
6914 isa_and_nonnull<InitListExpr>(Initializer)) {
6916 *this, TreatUnavailableAsInvalid);
6918 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6919 Kind.getKind() == InitializationKind::IK_Direct)
6920 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6921 /*VerifyOnly=*/true);
6922 else if (DestAT->getElementType()->isCharType())
6924 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6926 else
6928
6929 return;
6930 }
6931
6932 // Determine whether we should consider writeback conversions for
6933 // Objective-C ARC.
6934 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6935 Entity.isParameterKind();
6936
6937 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6938 return;
6939
6940 // We're at the end of the line for C: it's either a write-back conversion
6941 // or it's a C assignment. There's no need to check anything else.
6942 if (!S.getLangOpts().CPlusPlus) {
6943 assert(Initializer && "Initializer must be non-null");
6944 // If allowed, check whether this is an Objective-C writeback conversion.
6945 if (allowObjCWritebackConversion &&
6946 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6947 return;
6948 }
6949
6950 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6951 return;
6952
6953 // Handle initialization in C
6954 AddCAssignmentStep(DestType);
6955 MaybeProduceObjCObject(S, *this, Entity);
6956 return;
6957 }
6958
6959 assert(S.getLangOpts().CPlusPlus);
6960
6961 // - If the destination type is a (possibly cv-qualified) class type:
6962 // (except for HLSL, where user-defined record types do not have
6963 // constructors or conversion functions)
6964 if (DestType->isRecordType() &&
6965 (!S.getLangOpts().HLSL ||
6966 DestType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
6967 // - If the initialization is direct-initialization, or if it is
6968 // copy-initialization where the cv-unqualified version of the
6969 // source type is the same class as, or a derived class of, the
6970 // class of the destination, constructors are considered. [...]
6971 if (Kind.getKind() == InitializationKind::IK_Direct ||
6972 (Kind.getKind() == InitializationKind::IK_Copy &&
6973 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6974 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6975 SourceType, DestType))))) {
6976 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6977 *this, /*IsAggrListInit=*/false);
6978 } else {
6979 // - Otherwise (i.e., for the remaining copy-initialization cases),
6980 // user-defined conversion sequences that can convert from the
6981 // source type to the destination type or (when a conversion
6982 // function is used) to a derived class thereof are enumerated as
6983 // described in 13.3.1.4, and the best one is chosen through
6984 // overload resolution (13.3).
6985 assert(Initializer && "Initializer must be non-null");
6986 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6987 TopLevelOfInitList);
6988 }
6989 return;
6990 }
6991
6992 assert(Args.size() >= 1 && "Zero-argument case handled above");
6993
6994 // For HLSL ext vector types we allow list initialization behavior for C++
6995 // functional cast expressions which look like constructor syntax. This is
6996 // accomplished by converting initialization arguments to InitListExpr.
6997 auto ShouldTryListInitialization = [&]() -> bool {
6998 // Only try list initialization for HLSL.
6999 if (!S.getLangOpts().HLSL)
7000 return false;
7001
7002 bool DestIsVec = DestType->isExtVectorType();
7003 bool DestIsMat = DestType->isConstantMatrixType();
7004
7005 // If the destination type is neither a vector nor a matrix, then don't try
7006 // list initialization.
7007 if (!DestIsVec && !DestIsMat)
7008 return false;
7009
7010 // If there is only a single source argument, then only try list
7011 // initialization if initializing a matrix with a vector or vice versa.
7012 if (Args.size() == 1) {
7013 assert(!SourceType.isNull() &&
7014 "Source QualType should not be null when arg size is exactly 1");
7015 bool SourceIsVec = SourceType->isExtVectorType();
7016 bool SourceIsMat = SourceType->isConstantMatrixType();
7017
7018 if (DestIsMat && !SourceIsVec)
7019 return false;
7020 if (DestIsVec && !SourceIsMat)
7021 return false;
7022 }
7023
7024 // Try list initialization if the source type is null or if the
7025 // destination and source types differ.
7026 return SourceType.isNull() ||
7027 !Context.hasSameUnqualifiedType(SourceType, DestType);
7028 };
7029 if (ShouldTryListInitialization()) {
7030 InitListExpr *ILE = new (Context)
7031 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
7032 Args.back()->getEndLoc(), /*isExplicit=*/false);
7033 ILE->setType(DestType);
7034 Args[0] = ILE;
7035 TryListInitialization(S, Entity, Kind, ILE, *this,
7036 TreatUnavailableAsInvalid);
7037 return;
7038 }
7039
7040 // The remaining cases all need a source type.
7041 if (Args.size() > 1) {
7043 return;
7044 } else if (isa<InitListExpr>(Args[0])) {
7046 return;
7047 }
7048
7049 // - Otherwise, if the source type is a (possibly cv-qualified) class
7050 // type, conversion functions are considered.
7051 // (except for HLSL, where user-defined record types do not have
7052 // constructors or conversion functions).
7053 if (!SourceType.isNull() && SourceType->isRecordType() &&
7054 (!S.getLangOpts().HLSL ||
7055 SourceType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
7056 assert(Initializer && "Initializer must be non-null");
7057 // For a conversion to _Atomic(T) from either T or a class type derived
7058 // from T, initialize the T object then convert to _Atomic type.
7059 bool NeedAtomicConversion = false;
7060 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
7061 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
7062 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
7063 Atomic->getValueType())) {
7064 DestType = Atomic->getValueType();
7065 NeedAtomicConversion = true;
7066 }
7067 }
7068
7069 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
7070 TopLevelOfInitList);
7071 MaybeProduceObjCObject(S, *this, Entity);
7072 if (!Failed() && NeedAtomicConversion)
7074 return;
7075 }
7076
7077 // - Otherwise, if the initialization is direct-initialization, the source
7078 // type is std::nullptr_t, and the destination type is bool, the initial
7079 // value of the object being initialized is false.
7080 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
7081 DestType->isBooleanType() &&
7082 Kind.getKind() == InitializationKind::IK_Direct) {
7085 Initializer->isGLValue()),
7086 DestType);
7087 return;
7088 }
7089
7090 // - Otherwise, the initial value of the object being initialized is the
7091 // (possibly converted) value of the initializer expression. Standard
7092 // conversions (Clause 4) will be used, if necessary, to convert the
7093 // initializer expression to the cv-unqualified version of the
7094 // destination type; no user-defined conversions are considered.
7095
7097 = S.TryImplicitConversion(Initializer, DestType,
7098 /*SuppressUserConversions*/true,
7099 Sema::AllowedExplicit::None,
7100 /*InOverloadResolution*/ false,
7101 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
7102 allowObjCWritebackConversion);
7103
7104 if (ICS.isStandard() &&
7106 // Objective-C ARC writeback conversion.
7107
7108 // We should copy unless we're passing to an argument explicitly
7109 // marked 'out'.
7110 bool ShouldCopy = true;
7111 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
7112 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
7113
7114 // If there was an lvalue adjustment, add it as a separate conversion.
7115 if (ICS.Standard.First == ICK_Array_To_Pointer ||
7118 LvalueICS.setStandard();
7120 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
7121 LvalueICS.Standard.First = ICS.Standard.First;
7122 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
7123 }
7124
7125 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
7126 } else if (ICS.isBad()) {
7128 Initializer->getType() == Context.OverloadTy &&
7130 /*Complain=*/false, Found))
7132 else if (Initializer->getType()->isFunctionType() &&
7135 else
7137 } else {
7138 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
7139
7140 MaybeProduceObjCObject(S, *this, Entity);
7141 }
7142}
7143
7145 for (auto &S : Steps)
7146 S.Destroy();
7147}
7148
7149//===----------------------------------------------------------------------===//
7150// Perform initialization
7151//===----------------------------------------------------------------------===//
7153 bool Diagnose = false) {
7154 switch(Entity.getKind()) {
7161
7163 if (Entity.getDecl() &&
7166
7168
7170 if (Entity.getDecl() &&
7173
7174 return !Diagnose ? AssignmentAction::Passing
7176
7178 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7180
7183 // FIXME: Can we tell apart casting vs. converting?
7185
7187 // This is really initialization, but refer to it as conversion for
7188 // consistency with CheckConvertedConstantExpression.
7190
7203 }
7204
7205 llvm_unreachable("Invalid EntityKind!");
7206}
7207
7208/// Whether we should bind a created object as a temporary when
7209/// initializing the given entity.
7242
7243/// Whether the given entity, when initialized with an object
7244/// created for that initialization, requires destruction.
7277
7278/// Get the location at which initialization diagnostics should appear.
7317
7318/// Make a (potentially elidable) temporary copy of the object
7319/// provided by the given initializer by calling the appropriate copy
7320/// constructor.
7321///
7322/// \param S The Sema object used for type-checking.
7323///
7324/// \param T The type of the temporary object, which must either be
7325/// the type of the initializer expression or a superclass thereof.
7326///
7327/// \param Entity The entity being initialized.
7328///
7329/// \param CurInit The initializer expression.
7330///
7331/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7332/// is permitted in C++03 (but not C++0x) when binding a reference to
7333/// an rvalue.
7334///
7335/// \returns An expression that copies the initializer expression into
7336/// a temporary object, or an error expression if a copy could not be
7337/// created.
7339 QualType T,
7340 const InitializedEntity &Entity,
7341 ExprResult CurInit,
7342 bool IsExtraneousCopy) {
7343 if (CurInit.isInvalid())
7344 return CurInit;
7345 // Determine which class type we're copying to.
7346 Expr *CurInitExpr = (Expr *)CurInit.get();
7347 auto *Class = T->getAsCXXRecordDecl();
7348 if (!Class)
7349 return CurInit;
7350
7351 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
7352
7353 // Make sure that the type we are copying is complete.
7354 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
7355 return CurInit;
7356
7357 // Perform overload resolution using the class's constructors. Per
7358 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7359 // is direct-initialization.
7362
7365 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
7366 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7367 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7368 /*RequireActualConstructor=*/false,
7369 /*SecondStepOfCopyInit=*/true)) {
7370 case OR_Success:
7371 break;
7372
7374 CandidateSet.NoteCandidates(
7376 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
7377 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7378 : diag::err_temp_copy_no_viable)
7379 << (int)Entity.getKind() << CurInitExpr->getType()
7380 << CurInitExpr->getSourceRange()),
7381 S, OCD_AllCandidates, CurInitExpr);
7382 if (!IsExtraneousCopy || S.isSFINAEContext())
7383 return ExprError();
7384 return CurInit;
7385
7386 case OR_Ambiguous:
7387 CandidateSet.NoteCandidates(
7388 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
7389 << (int)Entity.getKind()
7390 << CurInitExpr->getType()
7391 << CurInitExpr->getSourceRange()),
7392 S, OCD_AmbiguousCandidates, CurInitExpr);
7393 return ExprError();
7394
7395 case OR_Deleted:
7396 S.Diag(Loc, diag::err_temp_copy_deleted)
7397 << (int)Entity.getKind() << CurInitExpr->getType()
7398 << CurInitExpr->getSourceRange();
7399 S.NoteDeletedFunction(Best->Function);
7400 return ExprError();
7401 }
7402
7403 bool HadMultipleCandidates = CandidateSet.size() > 1;
7404
7406 SmallVector<Expr*, 8> ConstructorArgs;
7407 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7408
7409 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7410 IsExtraneousCopy);
7411
7412 if (IsExtraneousCopy) {
7413 // If this is a totally extraneous copy for C++03 reference
7414 // binding purposes, just return the original initialization
7415 // expression. We don't generate an (elided) copy operation here
7416 // because doing so would require us to pass down a flag to avoid
7417 // infinite recursion, where each step adds another extraneous,
7418 // elidable copy.
7419
7420 // Instantiate the default arguments of any extra parameters in
7421 // the selected copy constructor, as if we were going to create a
7422 // proper call to the copy constructor.
7423 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7424 ParmVarDecl *Parm = Constructor->getParamDecl(I);
7425 if (S.RequireCompleteType(Loc, Parm->getType(),
7426 diag::err_call_incomplete_argument))
7427 break;
7428
7429 // Build the default argument expression; we don't actually care
7430 // if this succeeds or not, because this routine will complain
7431 // if there was a problem.
7432 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7433 }
7434
7435 return CurInitExpr;
7436 }
7437
7438 // Determine the arguments required to actually perform the
7439 // constructor call (we might have derived-to-base conversions, or
7440 // the copy constructor may have default arguments).
7441 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7442 ConstructorArgs))
7443 return ExprError();
7444
7445 // C++0x [class.copy]p32:
7446 // When certain criteria are met, an implementation is allowed to
7447 // omit the copy/move construction of a class object, even if the
7448 // copy/move constructor and/or destructor for the object have
7449 // side effects. [...]
7450 // - when a temporary class object that has not been bound to a
7451 // reference (12.2) would be copied/moved to a class object
7452 // with the same cv-unqualified type, the copy/move operation
7453 // can be omitted by constructing the temporary object
7454 // directly into the target of the omitted copy/move
7455 //
7456 // Note that the other three bullets are handled elsewhere. Copy
7457 // elision for return statements and throw expressions are handled as part
7458 // of constructor initialization, while copy elision for exception handlers
7459 // is handled by the run-time.
7460 //
7461 // FIXME: If the function parameter is not the same type as the temporary, we
7462 // should still be able to elide the copy, but we don't have a way to
7463 // represent in the AST how much should be elided in this case.
7464 bool Elidable =
7465 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7467 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7468 CurInitExpr->getType());
7469
7470 // Actually perform the constructor call.
7471 CurInit = S.BuildCXXConstructExpr(
7472 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7473 HadMultipleCandidates,
7474 /*ListInit*/ false,
7475 /*StdInitListInit*/ false,
7476 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7477
7478 // If we're supposed to bind temporaries, do so.
7479 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7480 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7481 return CurInit;
7482}
7483
7484/// Check whether elidable copy construction for binding a reference to
7485/// a temporary would have succeeded if we were building in C++98 mode, for
7486/// -Wc++98-compat.
7488 const InitializedEntity &Entity,
7489 Expr *CurInitExpr) {
7490 assert(S.getLangOpts().CPlusPlus11);
7491
7492 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7493 if (!Record)
7494 return;
7495
7496 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7497 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7498 return;
7499
7500 // Find constructors which would have been considered.
7503
7504 // Perform overload resolution.
7507 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7508 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7509 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7510 /*RequireActualConstructor=*/false,
7511 /*SecondStepOfCopyInit=*/true);
7512
7513 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7514 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7515 << CurInitExpr->getSourceRange();
7516
7517 switch (OR) {
7518 case OR_Success:
7519 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7520 Best->FoundDecl, Entity, Diag);
7521 // FIXME: Check default arguments as far as that's possible.
7522 break;
7523
7525 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7526 OCD_AllCandidates, CurInitExpr);
7527 break;
7528
7529 case OR_Ambiguous:
7530 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7531 OCD_AmbiguousCandidates, CurInitExpr);
7532 break;
7533
7534 case OR_Deleted:
7535 S.Diag(Loc, Diag);
7536 S.NoteDeletedFunction(Best->Function);
7537 break;
7538 }
7539}
7540
7541void InitializationSequence::PrintInitLocationNote(Sema &S,
7542 const InitializedEntity &Entity) {
7543 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7544 if (Entity.getDecl()->getLocation().isInvalid())
7545 return;
7546
7547 if (Entity.getDecl()->getDeclName())
7548 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7549 << Entity.getDecl()->getDeclName();
7550 else
7551 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7552 }
7553 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7554 Entity.getMethodDecl())
7555 S.Diag(Entity.getMethodDecl()->getLocation(),
7556 diag::note_method_return_type_change)
7557 << Entity.getMethodDecl()->getDeclName();
7558}
7559
7560/// Returns true if the parameters describe a constructor initialization of
7561/// an explicit temporary object, e.g. "Point(x, y)".
7562static bool isExplicitTemporary(const InitializedEntity &Entity,
7563 const InitializationKind &Kind,
7564 unsigned NumArgs) {
7565 switch (Entity.getKind()) {
7569 break;
7570 default:
7571 return false;
7572 }
7573
7574 switch (Kind.getKind()) {
7576 return true;
7577 // FIXME: Hack to work around cast weirdness.
7580 return NumArgs != 1;
7581 default:
7582 return false;
7583 }
7584}
7585
7586static ExprResult
7588 const InitializedEntity &Entity,
7589 const InitializationKind &Kind,
7590 MultiExprArg Args,
7591 const InitializationSequence::Step& Step,
7592 bool &ConstructorInitRequiresZeroInit,
7593 bool IsListInitialization,
7594 bool IsStdInitListInitialization,
7595 SourceLocation LBraceLoc,
7596 SourceLocation RBraceLoc) {
7597 unsigned NumArgs = Args.size();
7600 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7601
7602 // Build a call to the selected constructor.
7603 SmallVector<Expr*, 8> ConstructorArgs;
7604 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7605 ? Kind.getEqualLoc()
7606 : Kind.getLocation();
7607
7608 if (Kind.getKind() == InitializationKind::IK_Default) {
7609 // Force even a trivial, implicit default constructor to be
7610 // semantically checked. We do this explicitly because we don't build
7611 // the definition for completely trivial constructors.
7612 assert(Constructor->getParent() && "No parent class for constructor.");
7613 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7614 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7615 S.runWithSufficientStackSpace(Loc, [&] {
7617 });
7618 }
7619 }
7620
7621 ExprResult CurInit((Expr *)nullptr);
7622
7623 // C++ [over.match.copy]p1:
7624 // - When initializing a temporary to be bound to the first parameter
7625 // of a constructor that takes a reference to possibly cv-qualified
7626 // T as its first argument, called with a single argument in the
7627 // context of direct-initialization, explicit conversion functions
7628 // are also considered.
7629 bool AllowExplicitConv =
7630 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7633
7634 // A smart pointer constructed from a nullable pointer is nullable.
7635 if (NumArgs == 1 && !Kind.isExplicitCast())
7637 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7638
7639 // Determine the arguments required to actually perform the constructor
7640 // call.
7641 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7642 ConstructorArgs, AllowExplicitConv,
7643 IsListInitialization))
7644 return ExprError();
7645
7646 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7647 // An explicitly-constructed temporary, e.g., X(1, 2).
7648 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7649 return ExprError();
7650
7651 if (Kind.getKind() == InitializationKind::IK_Value &&
7652 Constructor->isImplicit()) {
7653 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7654 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7655 unsigned I = 0;
7656 for (const FieldDecl *FD : RD->fields()) {
7657 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7658 !S.isUnevaluatedContext()) {
7659 S.Diag(Loc, diag::warn_field_requires_explicit_init)
7660 << /* Var-in-Record */ 0 << FD;
7661 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
7662 }
7663 ++I;
7664 }
7665 }
7666 }
7667
7668 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7669 if (!TSInfo)
7670 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7671 SourceRange ParenOrBraceRange =
7672 (Kind.getKind() == InitializationKind::IK_DirectList)
7673 ? SourceRange(LBraceLoc, RBraceLoc)
7674 : Kind.getParenOrBraceRange();
7675
7676 CXXConstructorDecl *CalleeDecl = Constructor;
7677 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7678 Step.Function.FoundDecl.getDecl())) {
7679 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7680 }
7681 S.MarkFunctionReferenced(Loc, CalleeDecl);
7682
7683 CurInit = S.CheckForImmediateInvocation(
7685 S.Context, CalleeDecl,
7686 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7687 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7688 IsListInitialization, IsStdInitListInitialization,
7689 ConstructorInitRequiresZeroInit),
7690 CalleeDecl);
7691 } else {
7693
7694 if (Entity.getKind() == InitializedEntity::EK_Base) {
7695 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7698 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7699 ConstructKind = CXXConstructionKind::Delegating;
7700 }
7701
7702 // Only get the parenthesis or brace range if it is a list initialization or
7703 // direct construction.
7704 SourceRange ParenOrBraceRange;
7705 if (IsListInitialization)
7706 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7707 else if (Kind.getKind() == InitializationKind::IK_Direct)
7708 ParenOrBraceRange = Kind.getParenOrBraceRange();
7709
7710 // If the entity allows NRVO, mark the construction as elidable
7711 // unconditionally.
7712 if (Entity.allowsNRVO())
7713 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7714 Step.Function.FoundDecl,
7715 Constructor, /*Elidable=*/true,
7716 ConstructorArgs,
7717 HadMultipleCandidates,
7718 IsListInitialization,
7719 IsStdInitListInitialization,
7720 ConstructorInitRequiresZeroInit,
7721 ConstructKind,
7722 ParenOrBraceRange);
7723 else
7724 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7725 Step.Function.FoundDecl,
7727 ConstructorArgs,
7728 HadMultipleCandidates,
7729 IsListInitialization,
7730 IsStdInitListInitialization,
7731 ConstructorInitRequiresZeroInit,
7732 ConstructKind,
7733 ParenOrBraceRange);
7734 }
7735 if (CurInit.isInvalid())
7736 return ExprError();
7737
7738 // Only check access if all of that succeeded.
7741 return ExprError();
7742
7743 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7745 return ExprError();
7746
7747 if (shouldBindAsTemporary(Entity))
7748 CurInit = S.MaybeBindToTemporary(CurInit.get());
7749
7750 return CurInit;
7751}
7752
7754 Expr *Init) {
7755 return sema::checkInitLifetime(*this, Entity, Init);
7756}
7757
7758static void DiagnoseNarrowingInInitList(Sema &S,
7759 const ImplicitConversionSequence &ICS,
7760 QualType PreNarrowingType,
7761 QualType EntityType,
7762 const Expr *PostInit);
7763
7764static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7765 QualType ToType, Expr *Init);
7766
7767/// Provide warnings when std::move is used on construction.
7768static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7769 bool IsReturnStmt) {
7770 if (!InitExpr)
7771 return;
7772
7774 return;
7775
7776 QualType DestType = InitExpr->getType();
7777 if (!DestType->isRecordType())
7778 return;
7779
7780 unsigned DiagID = 0;
7781 if (IsReturnStmt) {
7782 const CXXConstructExpr *CCE =
7783 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7784 if (!CCE || CCE->getNumArgs() != 1)
7785 return;
7786
7788 return;
7789
7790 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7791 }
7792
7793 // Find the std::move call and get the argument.
7794 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7795 if (!CE || !CE->isCallToStdMove())
7796 return;
7797
7798 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7799
7800 if (IsReturnStmt) {
7801 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7802 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7803 return;
7804
7805 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7806 if (!VD || !VD->hasLocalStorage())
7807 return;
7808
7809 // __block variables are not moved implicitly.
7810 if (VD->hasAttr<BlocksAttr>())
7811 return;
7812
7813 QualType SourceType = VD->getType();
7814 if (!SourceType->isRecordType())
7815 return;
7816
7817 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7818 return;
7819 }
7820
7821 // If we're returning a function parameter, copy elision
7822 // is not possible.
7823 if (isa<ParmVarDecl>(VD))
7824 DiagID = diag::warn_redundant_move_on_return;
7825 else
7826 DiagID = diag::warn_pessimizing_move_on_return;
7827 } else {
7828 DiagID = diag::warn_pessimizing_move_on_initialization;
7829 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7830 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7831 return;
7832 }
7833
7834 S.Diag(CE->getBeginLoc(), DiagID);
7835
7836 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7837 // is within a macro.
7838 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7839 if (CallBegin.isMacroID())
7840 return;
7841 SourceLocation RParen = CE->getRParenLoc();
7842 if (RParen.isMacroID())
7843 return;
7844 SourceLocation LParen;
7845 SourceLocation ArgLoc = Arg->getBeginLoc();
7846
7847 // Special testing for the argument location. Since the fix-it needs the
7848 // location right before the argument, the argument location can be in a
7849 // macro only if it is at the beginning of the macro.
7850 while (ArgLoc.isMacroID() &&
7853 }
7854
7855 if (LParen.isMacroID())
7856 return;
7857
7858 LParen = ArgLoc.getLocWithOffset(-1);
7859
7860 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7861 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7862 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7863}
7864
7865static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7866 // Check to see if we are dereferencing a null pointer. If so, this is
7867 // undefined behavior, so warn about it. This only handles the pattern
7868 // "*null", which is a very syntactic check.
7869 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7870 if (UO->getOpcode() == UO_Deref &&
7871 UO->getSubExpr()->IgnoreParenCasts()->
7872 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7873 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7874 S.PDiag(diag::warn_binding_null_to_reference)
7875 << UO->getSubExpr()->getSourceRange());
7876 }
7877}
7878
7881 bool BoundToLvalueReference) {
7882 auto MTE = new (Context)
7883 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7884
7885 // Order an ExprWithCleanups for lifetime marks.
7886 //
7887 // TODO: It'll be good to have a single place to check the access of the
7888 // destructor and generate ExprWithCleanups for various uses. Currently these
7889 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7890 // but there may be a chance to merge them.
7891 Cleanup.setExprNeedsCleanups(false);
7894 return MTE;
7895}
7896
7898 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7899 // same rule, but C99 is broken without this behavior and so we treat the
7900 // change as applying to all C language modes.
7901 // FIXME: This means that AST consumers need to deal with "prvalues" that
7902 // denote materialized temporaries. Maybe we should add another ValueKind
7903 // for "xvalue pretending to be a prvalue" for C++98 support.
7904 if (!E->isPRValue() ||
7906 return E;
7907
7908 // C++1z [conv.rval]/1: T shall be a complete type.
7909 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7910 // If so, we should check for a non-abstract class type here too.
7911 QualType T = E->getType();
7912 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7913 return ExprError();
7914
7915 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7916}
7917
7921
7922 CastKind CK = CK_NoOp;
7923
7924 if (VK == VK_PRValue) {
7925 auto PointeeTy = Ty->getPointeeType();
7926 auto ExprPointeeTy = E->getType()->getPointeeType();
7927 if (!PointeeTy.isNull() &&
7928 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7929 CK = CK_AddressSpaceConversion;
7930 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7931 CK = CK_AddressSpaceConversion;
7932 }
7933
7934 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7935}
7936
7938 const InitializedEntity &Entity,
7939 const InitializationKind &Kind,
7940 MultiExprArg Args,
7941 QualType *ResultType) {
7942 if (Failed()) {
7943 Diagnose(S, Entity, Kind, Args);
7944 return ExprError();
7945 }
7946 if (!ZeroInitializationFixit.empty()) {
7947 const Decl *D = Entity.getDecl();
7948 const auto *VD = dyn_cast_or_null<VarDecl>(D);
7949 QualType DestType = Entity.getType();
7950
7951 // The initialization would have succeeded with this fixit. Since the fixit
7952 // is on the error, we need to build a valid AST in this case, so this isn't
7953 // handled in the Failed() branch above.
7954 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7955 // Use a more useful diagnostic for constexpr variables.
7956 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7957 << VD
7958 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7959 ZeroInitializationFixit);
7960 } else {
7961 unsigned DiagID = diag::err_default_init_const;
7962 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7963 DiagID = diag::ext_default_init_const;
7964
7965 S.Diag(Kind.getLocation(), DiagID)
7966 << DestType << DestType->isRecordType()
7967 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7968 ZeroInitializationFixit);
7969 }
7970 }
7971
7972 if (getKind() == DependentSequence) {
7973 // If the declaration is a non-dependent, incomplete array type
7974 // that has an initializer, then its type will be completed once
7975 // the initializer is instantiated.
7976 if (ResultType && !Entity.getType()->isDependentType() &&
7977 Args.size() == 1) {
7978 QualType DeclType = Entity.getType();
7979 if (const IncompleteArrayType *ArrayT
7980 = S.Context.getAsIncompleteArrayType(DeclType)) {
7981 // FIXME: We don't currently have the ability to accurately
7982 // compute the length of an initializer list without
7983 // performing full type-checking of the initializer list
7984 // (since we have to determine where braces are implicitly
7985 // introduced and such). So, we fall back to making the array
7986 // type a dependently-sized array type with no specified
7987 // bound.
7988 if (isa<InitListExpr>((Expr *)Args[0]))
7989 *ResultType = S.Context.getDependentSizedArrayType(
7990 ArrayT->getElementType(),
7991 /*NumElts=*/nullptr, ArrayT->getSizeModifier(),
7992 ArrayT->getIndexTypeCVRQualifiers());
7993 }
7994 }
7995 if (Kind.getKind() == InitializationKind::IK_Direct &&
7996 !Kind.isExplicitCast()) {
7997 // Rebuild the ParenListExpr.
7998 SourceRange ParenRange = Kind.getParenOrBraceRange();
7999 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8000 Args);
8001 }
8002 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8003 Kind.isExplicitCast() ||
8004 Kind.getKind() == InitializationKind::IK_DirectList);
8005 return ExprResult(Args[0]);
8006 }
8007
8008 // No steps means no initialization.
8009 if (Steps.empty())
8010 return ExprResult((Expr *)nullptr);
8011
8012 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8013 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8014 !Entity.isParamOrTemplateParamKind()) {
8015 // Produce a C++98 compatibility warning if we are initializing a reference
8016 // from an initializer list. For parameters, we produce a better warning
8017 // elsewhere.
8018 Expr *Init = Args[0];
8019 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8020 << Init->getSourceRange();
8021 }
8022
8023 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8024 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8025 // Produce a Microsoft compatibility warning when initializing from a
8026 // predefined expression since MSVC treats predefined expressions as string
8027 // literals.
8028 Expr *Init = Args[0];
8029 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8030 }
8031
8032 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8033 QualType ETy = Entity.getType();
8034 bool HasGlobalAS = ETy.hasAddressSpace() &&
8036
8037 if (S.getLangOpts().OpenCLVersion >= 200 &&
8038 ETy->isAtomicType() && !HasGlobalAS &&
8039 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8040 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8041 << 1
8042 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8043 return ExprError();
8044 }
8045
8046 QualType DestType = Entity.getType().getNonReferenceType();
8047 // FIXME: Ugly hack around the fact that Entity.getType() is not
8048 // the same as Entity.getDecl()->getType() in cases involving type merging,
8049 // and we want latter when it makes sense.
8050 if (ResultType)
8051 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8052 Entity.getType();
8053
8054 ExprResult CurInit((Expr *)nullptr);
8055 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8056
8057 // HLSL allows vector/matrix initialization to function like list
8058 // initialization, but use the syntax of a C++-like constructor.
8059 bool IsHLSLVectorOrMatrixInit =
8060 S.getLangOpts().HLSL &&
8061 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
8062 isa<InitListExpr>(Args[0]);
8063 (void)IsHLSLVectorOrMatrixInit;
8064
8065 // For initialization steps that start with a single initializer,
8066 // grab the only argument out the Args and place it into the "current"
8067 // initializer.
8068 switch (Steps.front().Kind) {
8073 case SK_BindReference:
8075 case SK_FinalCopy:
8077 case SK_UserConversion:
8086 case SK_UnwrapInitList:
8087 case SK_RewrapInitList:
8088 case SK_CAssignment:
8089 case SK_StringInit:
8091 case SK_ArrayLoopIndex:
8092 case SK_ArrayLoopInit:
8093 case SK_ArrayInit:
8094 case SK_GNUArrayInit:
8100 case SK_OCLSamplerInit:
8103 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
8104 CurInit = Args[0];
8105 if (!CurInit.get()) return ExprError();
8106 break;
8107 }
8108
8114 break;
8115 }
8116
8117 // Promote from an unevaluated context to an unevaluated list context in
8118 // C++11 list-initialization; we need to instantiate entities usable in
8119 // constant expressions here in order to perform narrowing checks =(
8122 isa_and_nonnull<InitListExpr>(CurInit.get()));
8123
8124 // C++ [class.abstract]p2:
8125 // no objects of an abstract class can be created except as subobjects
8126 // of a class derived from it
8127 auto checkAbstractType = [&](QualType T) -> bool {
8128 if (Entity.getKind() == InitializedEntity::EK_Base ||
8130 return false;
8131 return S.RequireNonAbstractType(Kind.getLocation(), T,
8132 diag::err_allocation_of_abstract_type);
8133 };
8134
8135 // Walk through the computed steps for the initialization sequence,
8136 // performing the specified conversions along the way.
8137 bool ConstructorInitRequiresZeroInit = false;
8138 for (step_iterator Step = step_begin(), StepEnd = step_end();
8139 Step != StepEnd; ++Step) {
8140 if (CurInit.isInvalid())
8141 return ExprError();
8142
8143 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8144
8145 switch (Step->Kind) {
8147 // Overload resolution determined which function invoke; update the
8148 // initializer to reflect that choice.
8150 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8151 return ExprError();
8152 CurInit = S.FixOverloadedFunctionReference(CurInit,
8155 // We might get back another placeholder expression if we resolved to a
8156 // builtin.
8157 if (!CurInit.isInvalid())
8158 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8159 break;
8160
8164 // We have a derived-to-base cast that produces either an rvalue or an
8165 // lvalue. Perform that cast.
8166
8167 CXXCastPath BasePath;
8168
8169 // Casts to inaccessible base classes are allowed with C-style casts.
8170 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8172 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8173 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8174 return ExprError();
8175
8178 ? VK_LValue
8180 : VK_PRValue);
8182 CK_DerivedToBase, CurInit.get(),
8183 &BasePath, VK, FPOptionsOverride());
8184 break;
8185 }
8186
8187 case SK_BindReference:
8188 // Reference binding does not have any corresponding ASTs.
8189
8190 // Check exception specifications
8191 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8192 return ExprError();
8193
8194 // We don't check for e.g. function pointers here, since address
8195 // availability checks should only occur when the function first decays
8196 // into a pointer or reference.
8197 if (CurInit.get()->getType()->isFunctionProtoType()) {
8198 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8199 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8200 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8201 DRE->getBeginLoc()))
8202 return ExprError();
8203 }
8204 }
8205 }
8206
8207 CheckForNullPointerDereference(S, CurInit.get());
8208 break;
8209
8211 // Make sure the "temporary" is actually an rvalue.
8212 assert(CurInit.get()->isPRValue() && "not a temporary");
8213
8214 // Check exception specifications
8215 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8216 return ExprError();
8217
8218 QualType MTETy = Step->Type;
8219
8220 // When this is an incomplete array type (such as when this is
8221 // initializing an array of unknown bounds from an init list), use THAT
8222 // type instead so that we propagate the array bounds.
8223 if (MTETy->isIncompleteArrayType() &&
8224 !CurInit.get()->getType()->isIncompleteArrayType() &&
8227 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8228 MTETy = CurInit.get()->getType();
8229
8230 // Materialize the temporary into memory.
8232 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8233 CurInit = MTE;
8234
8235 // If we're extending this temporary to automatic storage duration -- we
8236 // need to register its cleanup during the full-expression's cleanups.
8237 if (MTE->getStorageDuration() == SD_Automatic &&
8238 MTE->getType().isDestructedType())
8240 break;
8241 }
8242
8243 case SK_FinalCopy:
8244 if (checkAbstractType(Step->Type))
8245 return ExprError();
8246
8247 // If the overall initialization is initializing a temporary, we already
8248 // bound our argument if it was necessary to do so. If not (if we're
8249 // ultimately initializing a non-temporary), our argument needs to be
8250 // bound since it's initializing a function parameter.
8251 // FIXME: This is a mess. Rationalize temporary destruction.
8252 if (!shouldBindAsTemporary(Entity))
8253 CurInit = S.MaybeBindToTemporary(CurInit.get());
8254 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8255 /*IsExtraneousCopy=*/false);
8256 break;
8257
8259 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8260 /*IsExtraneousCopy=*/true);
8261 break;
8262
8263 case SK_UserConversion: {
8264 // We have a user-defined conversion that invokes either a constructor
8265 // or a conversion function.
8269 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8270 bool CreatedObject = false;
8271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8272 // Build a call to the selected constructor.
8273 SmallVector<Expr*, 8> ConstructorArgs;
8274 SourceLocation Loc = CurInit.get()->getBeginLoc();
8275
8276 // Determine the arguments required to actually perform the constructor
8277 // call.
8278 Expr *Arg = CurInit.get();
8280 MultiExprArg(&Arg, 1), Loc,
8281 ConstructorArgs))
8282 return ExprError();
8283
8284 // Build an expression that constructs a temporary.
8285 CurInit = S.BuildCXXConstructExpr(
8286 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8287 HadMultipleCandidates,
8288 /*ListInit*/ false,
8289 /*StdInitListInit*/ false,
8290 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8291 if (CurInit.isInvalid())
8292 return ExprError();
8293
8294 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8295 Entity);
8296 if (S.DiagnoseUseOfOverloadedDecl(Constructor, Kind.getLocation()))
8297 return ExprError();
8298
8299 CastKind = CK_ConstructorConversion;
8300 CreatedObject = true;
8301 } else {
8302 // Build a call to the conversion function.
8304 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8305 FoundFn);
8306 if (S.DiagnoseUseOfOverloadedDecl(Conversion, Kind.getLocation()))
8307 return ExprError();
8308
8309 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8310 HadMultipleCandidates);
8311 if (CurInit.isInvalid())
8312 return ExprError();
8313
8314 CastKind = CK_UserDefinedConversion;
8315 CreatedObject = Conversion->getReturnType()->isRecordType();
8316 }
8317
8318 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8319 return ExprError();
8320
8321 CurInit = ImplicitCastExpr::Create(
8322 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8323 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8324
8325 if (shouldBindAsTemporary(Entity))
8326 // The overall entity is temporary, so this expression should be
8327 // destroyed at the end of its full-expression.
8328 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8329 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8330 // The object outlasts the full-expression, but we need to prepare for
8331 // a destructor being run on it.
8332 // FIXME: It makes no sense to do this here. This should happen
8333 // regardless of how we initialized the entity.
8334 QualType T = CurInit.get()->getType();
8335 if (auto *Record = T->castAsCXXRecordDecl()) {
8338 S.PDiag(diag::err_access_dtor_temp) << T);
8340 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8341 return ExprError();
8342 }
8343 }
8344 break;
8345 }
8346
8350 // Perform a qualification conversion; these can never go wrong.
8353 ? VK_LValue
8355 : VK_PRValue);
8356 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8357 break;
8358 }
8359
8361 assert(CurInit.get()->isLValue() &&
8362 "function reference should be lvalue");
8363 CurInit =
8364 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8365 break;
8366
8367 case SK_AtomicConversion: {
8368 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8369 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8370 CK_NonAtomicToAtomic, VK_PRValue);
8371 break;
8372 }
8373
8376 if (const auto *FromPtrType =
8377 CurInit.get()->getType()->getAs<PointerType>()) {
8378 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8379 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8380 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8381 // Do not check static casts here because they are checked earlier
8382 // in Sema::ActOnCXXNamedCast()
8383 if (!Kind.isStaticCast()) {
8384 S.Diag(CurInit.get()->getExprLoc(),
8385 diag::warn_noderef_to_dereferenceable_pointer)
8386 << CurInit.get()->getSourceRange();
8387 }
8388 }
8389 }
8390 }
8391 Expr *Init = CurInit.get();
8393 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8394 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8395 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8397 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8398 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
8399 if (CurInitExprRes.isInvalid())
8400 return ExprError();
8401
8403
8404 CurInit = CurInitExprRes;
8405
8407 S.getLangOpts().CPlusPlus)
8408 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8409 CurInit.get());
8410
8411 break;
8412 }
8413
8414 case SK_ListInitialization: {
8415 if (checkAbstractType(Step->Type))
8416 return ExprError();
8417
8418 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8419 // If we're not initializing the top-level entity, we need to create an
8420 // InitializeTemporary entity for our target type.
8421 QualType Ty = Step->Type;
8422 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8423 InitializedEntity InitEntity =
8424 IsTemporary ? InitializedEntity::InitializeTemporary(Ty) : Entity;
8425 InitListChecker PerformInitList(S, InitEntity,
8426 InitList, Ty, /*VerifyOnly=*/false,
8427 /*TreatUnavailableAsInvalid=*/false);
8428 if (PerformInitList.HadError())
8429 return ExprError();
8430
8431 // Hack: We must update *ResultType if available in order to set the
8432 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8433 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8434 if (ResultType &&
8435 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8436 if ((*ResultType)->isRValueReferenceType())
8438 else if ((*ResultType)->isLValueReferenceType())
8440 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8441 *ResultType = Ty;
8442 }
8443
8444 InitListExpr *StructuredInitList =
8445 PerformInitList.getFullyStructuredList();
8446 CurInit = shouldBindAsTemporary(InitEntity)
8447 ? S.MaybeBindToTemporary(StructuredInitList)
8448 : StructuredInitList;
8449 break;
8450 }
8451
8453 if (checkAbstractType(Step->Type))
8454 return ExprError();
8455
8456 // When an initializer list is passed for a parameter of type "reference
8457 // to object", we don't get an EK_Temporary entity, but instead an
8458 // EK_Parameter entity with reference type.
8459 // FIXME: This is a hack. What we really should do is create a user
8460 // conversion step for this case, but this makes it considerably more
8461 // complicated. For now, this will do.
8463 Entity.getType().getNonReferenceType());
8464 bool UseTemporary = Entity.getType()->isReferenceType();
8465 assert(Args.size() == 1 && "expected a single argument for list init");
8466 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8467 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8468 << InitList->getSourceRange();
8469 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8470 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8471 Entity,
8472 Kind, Arg, *Step,
8473 ConstructorInitRequiresZeroInit,
8474 /*IsListInitialization*/true,
8475 /*IsStdInitListInit*/false,
8476 InitList->getLBraceLoc(),
8477 InitList->getRBraceLoc());
8478 break;
8479 }
8480
8481 case SK_UnwrapInitList:
8482 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8483 break;
8484
8485 case SK_RewrapInitList: {
8486 Expr *E = CurInit.get();
8488 InitListExpr *ILE = new (S.Context)
8489 InitListExpr(S.Context, Syntactic->getLBraceLoc(), E,
8490 Syntactic->getRBraceLoc(), Syntactic->isExplicit());
8491 ILE->setSyntacticForm(Syntactic);
8492 ILE->setType(E->getType());
8493 ILE->setValueKind(E->getValueKind());
8494 CurInit = ILE;
8495 break;
8496 }
8497
8500 if (checkAbstractType(Step->Type))
8501 return ExprError();
8502
8503 // When an initializer list is passed for a parameter of type "reference
8504 // to object", we don't get an EK_Temporary entity, but instead an
8505 // EK_Parameter entity with reference type.
8506 // FIXME: This is a hack. What we really should do is create a user
8507 // conversion step for this case, but this makes it considerably more
8508 // complicated. For now, this will do.
8510 Entity.getType().getNonReferenceType());
8511 bool UseTemporary = Entity.getType()->isReferenceType();
8512 bool IsStdInitListInit =
8514 Expr *Source = CurInit.get();
8515 SourceRange Range = Kind.hasParenOrBraceRange()
8516 ? Kind.getParenOrBraceRange()
8517 : SourceRange();
8519 S, UseTemporary ? TempEntity : Entity, Kind,
8520 Source ? MultiExprArg(Source) : Args, *Step,
8521 ConstructorInitRequiresZeroInit,
8522 /*IsListInitialization*/ IsStdInitListInit,
8523 /*IsStdInitListInitialization*/ IsStdInitListInit,
8524 /*LBraceLoc*/ Range.getBegin(),
8525 /*RBraceLoc*/ Range.getEnd());
8526 break;
8527 }
8528
8529 case SK_ZeroInitialization: {
8530 step_iterator NextStep = Step;
8531 ++NextStep;
8532 if (NextStep != StepEnd &&
8533 (NextStep->Kind == SK_ConstructorInitialization ||
8534 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8535 // The need for zero-initialization is recorded directly into
8536 // the call to the object's constructor within the next step.
8537 ConstructorInitRequiresZeroInit = true;
8538 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8539 S.getLangOpts().CPlusPlus &&
8540 !Kind.isImplicitValueInit()) {
8541 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8542 if (!TSInfo)
8544 Kind.getRange().getBegin());
8545
8546 CurInit = new (S.Context) CXXScalarValueInitExpr(
8547 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8548 Kind.getRange().getEnd());
8549 } else {
8550 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8551 // Note the return value isn't used to return a ExprError() when
8552 // initialization fails . For struct initialization allows all field
8553 // assignments to be checked rather than bailing on the first error.
8554 S.BoundsSafetyCheckInitialization(Entity, Kind,
8556 Step->Type, CurInit.get());
8557 }
8558 break;
8559 }
8560
8561 case SK_CAssignment: {
8562 QualType SourceType = CurInit.get()->getType();
8563 Expr *Init = CurInit.get();
8564
8565 // Save off the initial CurInit in case we need to emit a diagnostic
8566 ExprResult InitialCurInit = Init;
8569 Step->Type, Result, true,
8571 if (Result.isInvalid())
8572 return ExprError();
8573 CurInit = Result;
8574
8575 // If this is a call, allow conversion to a transparent union.
8576 ExprResult CurInitExprRes = CurInit;
8577 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8579 Step->Type, CurInitExprRes) == AssignConvertType::Compatible)
8581 if (CurInitExprRes.isInvalid())
8582 return ExprError();
8583 CurInit = CurInitExprRes;
8584
8585 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8586 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8587 CurInit.get());
8588
8589 // C23 6.7.1p6: If an object or subobject declared with storage-class
8590 // specifier constexpr has pointer, integer, or arithmetic type, any
8591 // explicit initializer value for it shall be null, an integer
8592 // constant expression, or an arithmetic constant expression,
8593 // respectively.
8595 if (Entity.getType()->getAs<PointerType>() &&
8596 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8597 (ER.Val.isLValue() && !ER.Val.isNullPointer())) {
8598 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8599 return ExprError();
8600 }
8601 }
8602
8603 // Note the return value isn't used to return a ExprError() when
8604 // initialization fails. For struct initialization this allows all field
8605 // assignments to be checked rather than bailing on the first error.
8606 S.BoundsSafetyCheckInitialization(Entity, Kind,
8607 getAssignmentAction(Entity, true),
8608 Step->Type, InitialCurInit.get());
8609
8610 bool Complained;
8611 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8612 Step->Type, SourceType,
8613 InitialCurInit.get(),
8614 getAssignmentAction(Entity, true),
8615 &Complained)) {
8616 PrintInitLocationNote(S, Entity);
8617 return ExprError();
8618 } else if (Complained)
8619 PrintInitLocationNote(S, Entity);
8620 break;
8621 }
8622
8623 case SK_StringInit: {
8624 QualType Ty = Step->Type;
8625 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8626 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8627 S.Context.getAsArrayType(Ty), S, Entity,
8628 S.getLangOpts().C23 &&
8630 break;
8631 }
8632
8634 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8635 CK_ObjCObjectLValueCast,
8636 CurInit.get()->getValueKind());
8637 break;
8638
8639 case SK_ArrayLoopIndex: {
8640 Expr *Cur = CurInit.get();
8641 Expr *BaseExpr = new (S.Context)
8642 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8643 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8644 Expr *IndexExpr =
8647 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8648 ArrayLoopCommonExprs.push_back(BaseExpr);
8649 break;
8650 }
8651
8652 case SK_ArrayLoopInit: {
8653 assert(!ArrayLoopCommonExprs.empty() &&
8654 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8655 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8656 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8657 CurInit.get());
8658 break;
8659 }
8660
8661 case SK_GNUArrayInit:
8662 // Okay: we checked everything before creating this step. Note that
8663 // this is a GNU extension.
8664 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8665 << Step->Type << CurInit.get()->getType()
8666 << CurInit.get()->getSourceRange();
8668 [[fallthrough]];
8669 case SK_ArrayInit:
8670 // If the destination type is an incomplete array type, update the
8671 // type accordingly.
8672 if (ResultType) {
8673 if (const IncompleteArrayType *IncompleteDest
8675 if (const ConstantArrayType *ConstantSource
8676 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8677 *ResultType = S.Context.getConstantArrayType(
8678 IncompleteDest->getElementType(), ConstantSource->getSize(),
8679 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8680 }
8681 }
8682 }
8683 break;
8684
8686 // Okay: we checked everything before creating this step. Note that
8687 // this is a GNU extension.
8688 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8689 << CurInit.get()->getSourceRange();
8690 break;
8691
8694 checkIndirectCopyRestoreSource(S, CurInit.get());
8695 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8696 CurInit.get(), Step->Type,
8698 break;
8699
8701 CurInit = ImplicitCastExpr::Create(
8702 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8704 break;
8705
8706 case SK_StdInitializerList: {
8707 S.Diag(CurInit.get()->getExprLoc(),
8708 diag::warn_cxx98_compat_initializer_list_init)
8709 << CurInit.get()->getSourceRange();
8710
8711 // Materialize the temporary into memory.
8713 CurInit.get()->getType(), CurInit.get(),
8714 /*BoundToLvalueReference=*/false);
8715
8716 // Wrap it in a construction of a std::initializer_list<T>.
8717 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8718
8719 if (!Step->Type->isDependentType()) {
8720 QualType ElementType;
8721 [[maybe_unused]] bool IsStdInitializerList =
8722 S.isStdInitializerList(Step->Type, &ElementType);
8723 assert(IsStdInitializerList &&
8724 "StdInitializerList step to non-std::initializer_list");
8725 const auto *Record = Step->Type->castAsCXXRecordDecl();
8726 assert(Record->isCompleteDefinition() &&
8727 "std::initializer_list should have already be "
8728 "complete/instantiated by this point");
8729
8730 auto InvalidType = [&] {
8731 S.Diag(Record->getLocation(),
8732 diag::err_std_initializer_list_malformed)
8734 return ExprError();
8735 };
8736
8737 if (Record->isUnion() || Record->getNumBases() != 0 ||
8738 Record->isPolymorphic())
8739 return InvalidType();
8740
8741 RecordDecl::field_iterator Field = Record->field_begin();
8742 if (Field == Record->field_end())
8743 return InvalidType();
8744
8745 // Start pointer
8746 if (!Field->getType()->isPointerType() ||
8747 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8748 ElementType.withConst()))
8749 return InvalidType();
8750
8751 if (++Field == Record->field_end())
8752 return InvalidType();
8753
8754 // Size or end pointer
8755 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8756 if (!S.Context.hasSameType(PT->getPointeeType(),
8757 ElementType.withConst()))
8758 return InvalidType();
8759 } else {
8760 if (Field->isBitField() ||
8761 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8762 return InvalidType();
8763 }
8764
8765 if (++Field != Record->field_end())
8766 return InvalidType();
8767 }
8768
8769 // Bind the result, in case the library has given initializer_list a
8770 // non-trivial destructor.
8771 if (shouldBindAsTemporary(Entity))
8772 CurInit = S.MaybeBindToTemporary(CurInit.get());
8773 break;
8774 }
8775
8776 case SK_OCLSamplerInit: {
8777 // Sampler initialization have 5 cases:
8778 // 1. function argument passing
8779 // 1a. argument is a file-scope variable
8780 // 1b. argument is a function-scope variable
8781 // 1c. argument is one of caller function's parameters
8782 // 2. variable initialization
8783 // 2a. initializing a file-scope variable
8784 // 2b. initializing a function-scope variable
8785 //
8786 // For file-scope variables, since they cannot be initialized by function
8787 // call of __translate_sampler_initializer in LLVM IR, their references
8788 // need to be replaced by a cast from their literal initializers to
8789 // sampler type. Since sampler variables can only be used in function
8790 // calls as arguments, we only need to replace them when handling the
8791 // argument passing.
8792 assert(Step->Type->isSamplerT() &&
8793 "Sampler initialization on non-sampler type.");
8794 Expr *Init = CurInit.get()->IgnoreParens();
8795 QualType SourceType = Init->getType();
8796 // Case 1
8797 if (Entity.isParameterKind()) {
8798 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8799 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8800 << SourceType;
8801 break;
8802 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8803 auto Var = cast<VarDecl>(DRE->getDecl());
8804 // Case 1b and 1c
8805 // No cast from integer to sampler is needed.
8806 if (!Var->hasGlobalStorage()) {
8807 CurInit = ImplicitCastExpr::Create(
8808 S.Context, Step->Type, CK_LValueToRValue, Init,
8809 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8810 break;
8811 }
8812 // Case 1a
8813 // For function call with a file-scope sampler variable as argument,
8814 // get the integer literal.
8815 // Do not diagnose if the file-scope variable does not have initializer
8816 // since this has already been diagnosed when parsing the variable
8817 // declaration.
8818 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8819 break;
8820 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8821 Var->getInit()))->getSubExpr();
8822 SourceType = Init->getType();
8823 }
8824 } else {
8825 // Case 2
8826 // Check initializer is 32 bit integer constant.
8827 // If the initializer is taken from global variable, do not diagnose since
8828 // this has already been done when parsing the variable declaration.
8829 if (!Init->isConstantInitializer(S.Context))
8830 break;
8831
8832 if (!SourceType->isIntegerType() ||
8833 32 != S.Context.getIntWidth(SourceType)) {
8834 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8835 << SourceType;
8836 break;
8837 }
8838
8839 Expr::EvalResult EVResult;
8840 Init->EvaluateAsInt(EVResult, S.Context);
8841 llvm::APSInt Result = EVResult.Val.getInt();
8842 const uint64_t SamplerValue = Result.getLimitedValue();
8843 // 32-bit value of sampler's initializer is interpreted as
8844 // bit-field with the following structure:
8845 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8846 // |31 6|5 4|3 1| 0|
8847 // This structure corresponds to enum values of sampler properties
8848 // defined in SPIR spec v1.2 and also opencl-c.h
8849 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8850 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8851 if (FilterMode != 1 && FilterMode != 2 &&
8853 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8854 S.Diag(Kind.getLocation(),
8855 diag::warn_sampler_initializer_invalid_bits)
8856 << "Filter Mode";
8857 if (AddressingMode > 4)
8858 S.Diag(Kind.getLocation(),
8859 diag::warn_sampler_initializer_invalid_bits)
8860 << "Addressing Mode";
8861 }
8862
8863 // Cases 1a, 2a and 2b
8864 // Insert cast from integer to sampler.
8866 CK_IntToOCLSampler);
8867 break;
8868 }
8869 case SK_OCLZeroOpaqueType: {
8870 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8872 "Wrong type for initialization of OpenCL opaque type.");
8873
8874 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8875 CK_ZeroToOCLOpaqueType,
8876 CurInit.get()->getValueKind());
8877 break;
8878 }
8880 CurInit = nullptr;
8881 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8882 /*VerifyOnly=*/false, &CurInit);
8883 if (CurInit.get() && ResultType)
8884 *ResultType = CurInit.get()->getType();
8885 if (shouldBindAsTemporary(Entity))
8886 CurInit = S.MaybeBindToTemporary(CurInit.get());
8887 break;
8888 }
8890 CurInit = ImplicitCastExpr::Create(
8891 S.Context, Step->Type.getLocalUnqualifiedType(), CK_LValueToRValue,
8892 CurInit.get(),
8893 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8894 break;
8895 }
8896 }
8897 }
8898
8899 Expr *Init = CurInit.get();
8900 if (!Init)
8901 return ExprError();
8902
8903 // Check whether the initializer has a shorter lifetime than the initialized
8904 // entity, and if not, either lifetime-extend or warn as appropriate.
8905 S.checkInitializerLifetime(Entity, Init);
8906
8907 // Diagnose non-fatal problems with the completed initialization.
8908 if (InitializedEntity::EntityKind EK = Entity.getKind();
8911 cast<FieldDecl>(Entity.getDecl())->isBitField())
8912 S.CheckBitFieldInitialization(Kind.getLocation(),
8913 cast<FieldDecl>(Entity.getDecl()), Init);
8914
8915 // Check for std::move on construction.
8918
8919 return Init;
8920}
8921
8922/// Somewhere within T there is an uninitialized reference subobject.
8923/// Dig it out and diagnose it.
8925 QualType T) {
8926 if (T->isReferenceType()) {
8927 S.Diag(Loc, diag::err_reference_without_init)
8928 << T.getNonReferenceType();
8929 return true;
8930 }
8931
8932 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8933 if (!RD || !RD->hasUninitializedReferenceMember())
8934 return false;
8935
8936 for (const auto *FI : RD->fields()) {
8937 if (FI->isUnnamedBitField())
8938 continue;
8939
8940 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8941 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8942 return true;
8943 }
8944 }
8945
8946 for (const auto &BI : RD->bases()) {
8947 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8948 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8949 return true;
8950 }
8951 }
8952
8953 return false;
8954}
8955
8956
8957//===----------------------------------------------------------------------===//
8958// Diagnose initialization failures
8959//===----------------------------------------------------------------------===//
8960
8961/// Emit notes associated with an initialization that failed due to a
8962/// "simple" conversion failure.
8963static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8964 Expr *op) {
8965 QualType destType = entity.getType();
8966 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8968
8969 // Emit a possible note about the conversion failing because the
8970 // operand is a message send with a related result type.
8972
8973 // Emit a possible note about a return failing because we're
8974 // expecting a related result type.
8975 if (entity.getKind() == InitializedEntity::EK_Result)
8977 }
8978 QualType fromType = op->getType();
8979 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8980 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8981 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8982 auto *destDecl = destType->getPointeeCXXRecordDecl();
8983 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8984 destDecl->getDeclKind() == Decl::CXXRecord &&
8985 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8986 !fromDecl->hasDefinition() &&
8987 destPointeeType.getQualifiers().compatiblyIncludes(
8988 fromPointeeType.getQualifiers(), S.getASTContext()))
8989 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8990 << S.getASTContext().getCanonicalTagType(fromDecl)
8991 << S.getASTContext().getCanonicalTagType(destDecl);
8992}
8993
8994static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8995 InitListExpr *InitList) {
8996 QualType DestType = Entity.getType();
8997
8998 QualType E;
8999 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9001 E.withConst(),
9002 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9003 InitList->getNumInits()),
9005 InitializedEntity HiddenArray =
9007 return diagnoseListInit(S, HiddenArray, InitList);
9008 }
9009
9010 if (DestType->isReferenceType()) {
9011 // A list-initialization failure for a reference means that we tried to
9012 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9013 // inner initialization failed.
9014 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9016 SourceLocation Loc = InitList->getBeginLoc();
9017 if (auto *D = Entity.getDecl())
9018 Loc = D->getLocation();
9019 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9020 return;
9021 }
9022
9023 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9024 /*VerifyOnly=*/false,
9025 /*TreatUnavailableAsInvalid=*/false);
9026 assert(DiagnoseInitList.HadError() &&
9027 "Inconsistent init list check result.");
9028}
9029
9031 const InitializedEntity &Entity,
9032 const InitializationKind &Kind,
9033 ArrayRef<Expr *> Args) {
9034 if (!Failed())
9035 return false;
9036
9037 QualType DestType = Entity.getType();
9038
9039 // When we want to diagnose only one element of a braced-init-list,
9040 // we need to factor it out.
9041 Expr *OnlyArg;
9042 if (Args.size() == 1) {
9043 auto *List = dyn_cast<InitListExpr>(Args[0]);
9044 if (List && List->getNumInits() == 1)
9045 OnlyArg = List->getInit(0);
9046 else
9047 OnlyArg = Args[0];
9048
9049 if (OnlyArg->getType() == S.Context.OverloadTy) {
9052 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
9053 Found)) {
9054 if (Expr *Resolved =
9055 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
9056 OnlyArg = Resolved;
9057 }
9058 }
9059 }
9060 else
9061 OnlyArg = nullptr;
9062
9063 switch (Failure) {
9065 // FIXME: Customize for the initialized entity?
9066 if (Args.empty()) {
9067 // Dig out the reference subobject which is uninitialized and diagnose it.
9068 // If this is value-initialization, this could be nested some way within
9069 // the target type.
9070 assert(Kind.getKind() == InitializationKind::IK_Value ||
9071 DestType->isReferenceType());
9072 bool Diagnosed =
9073 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9074 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9075 (void)Diagnosed;
9076 } else // FIXME: diagnostic below could be better!
9077 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9078 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9079 break;
9081 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9082 << 1 << Entity.getType() << Args[0]->getSourceRange();
9083 break;
9084
9086 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9087 break;
9089 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9090 break;
9092 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9093 break;
9095 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9096 break;
9098 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9099 break;
9101 S.Diag(Kind.getLocation(),
9102 diag::err_array_init_incompat_wide_string_into_wchar);
9103 break;
9105 S.Diag(Kind.getLocation(),
9106 diag::err_array_init_plain_string_into_char8_t);
9107 S.Diag(Args.front()->getBeginLoc(),
9108 diag::note_array_init_plain_string_into_char8_t)
9109 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9110 break;
9112 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9113 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9114 break;
9117 S.Diag(Kind.getLocation(),
9118 (Failure == FK_ArrayTypeMismatch
9119 ? diag::err_array_init_different_type
9120 : diag::err_array_init_non_constant_array))
9121 << DestType.getNonReferenceType()
9122 << OnlyArg->getType()
9123 << Args[0]->getSourceRange();
9124 break;
9125
9127 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9128 << Args[0]->getSourceRange();
9129 break;
9130
9134 DestType.getNonReferenceType(),
9135 true,
9136 Found);
9137 break;
9138 }
9139
9141 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9142 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9143 OnlyArg->getBeginLoc());
9144 break;
9145 }
9146
9149 switch (FailedOverloadResult) {
9150 case OR_Ambiguous:
9151
9152 FailedCandidateSet.NoteCandidates(
9154 Kind.getLocation(),
9156 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9157 << OnlyArg->getType() << DestType
9158 << Args[0]->getSourceRange())
9159 : (S.PDiag(diag::err_ref_init_ambiguous)
9160 << DestType << OnlyArg->getType()
9161 << Args[0]->getSourceRange())),
9162 S, OCD_AmbiguousCandidates, Args);
9163 break;
9164
9165 case OR_No_Viable_Function: {
9166 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9167 if (!S.RequireCompleteType(Kind.getLocation(),
9168 DestType.getNonReferenceType(),
9169 diag::err_typecheck_nonviable_condition_incomplete,
9170 OnlyArg->getType(), Args[0]->getSourceRange()))
9171 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9172 << (Entity.getKind() == InitializedEntity::EK_Result)
9173 << OnlyArg->getType() << Args[0]->getSourceRange()
9174 << DestType.getNonReferenceType();
9175
9176 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9177 break;
9178 }
9179 case OR_Deleted: {
9182 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9183
9184 StringLiteral *Msg = Best->Function->getDeletedMessage();
9185 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9186 << OnlyArg->getType() << DestType.getNonReferenceType()
9187 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9188 << Args[0]->getSourceRange();
9189 if (Ovl == OR_Deleted) {
9190 S.NoteDeletedFunction(Best->Function);
9191 } else {
9192 llvm_unreachable("Inconsistent overload resolution?");
9193 }
9194 break;
9195 }
9196
9197 case OR_Success:
9198 llvm_unreachable("Conversion did not fail!");
9199 }
9200 break;
9201
9203 if (isa<InitListExpr>(Args[0])) {
9204 S.Diag(Kind.getLocation(),
9205 diag::err_lvalue_reference_bind_to_initlist)
9207 << DestType.getNonReferenceType()
9208 << Args[0]->getSourceRange();
9209 break;
9210 }
9211 [[fallthrough]];
9212
9214 S.Diag(Kind.getLocation(),
9216 ? diag::err_lvalue_reference_bind_to_temporary
9217 : diag::err_lvalue_reference_bind_to_unrelated)
9219 << DestType.getNonReferenceType()
9220 << OnlyArg->getType()
9221 << Args[0]->getSourceRange();
9222 break;
9223
9225 // We don't necessarily have an unambiguous source bit-field.
9226 FieldDecl *BitField = Args[0]->getSourceBitField();
9227 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9228 << DestType.isVolatileQualified()
9229 << (BitField ? BitField->getDeclName() : DeclarationName())
9230 << (BitField != nullptr)
9231 << Args[0]->getSourceRange();
9232 if (BitField)
9233 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9234 break;
9235 }
9236
9238 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9239 << DestType.isVolatileQualified()
9240 << Args[0]->getSourceRange();
9241 break;
9242
9244 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9245 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9246 break;
9247
9249 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9250 << DestType.getNonReferenceType() << OnlyArg->getType()
9251 << Args[0]->getSourceRange();
9252 break;
9253
9255 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9256 << DestType << Args[0]->getSourceRange();
9257 break;
9258
9260 QualType SourceType = OnlyArg->getType();
9261 QualType NonRefType = DestType.getNonReferenceType();
9262 Qualifiers DroppedQualifiers =
9263 SourceType.getQualifiers() - NonRefType.getQualifiers();
9264
9265 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9266 SourceType.getQualifiers(), S.getASTContext()))
9267 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9268 << NonRefType << SourceType << 1 /*addr space*/
9269 << Args[0]->getSourceRange();
9270 else if (DroppedQualifiers.hasQualifiers())
9271 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9272 << NonRefType << SourceType << 0 /*cv quals*/
9273 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9274 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9275 else
9276 // FIXME: Consider decomposing the type and explaining which qualifiers
9277 // were dropped where, or on which level a 'const' is missing, etc.
9278 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9279 << NonRefType << SourceType << 2 /*incompatible quals*/
9280 << Args[0]->getSourceRange();
9281 break;
9282 }
9283
9285 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9286 << DestType.getNonReferenceType()
9287 << DestType.getNonReferenceType()->isIncompleteType()
9288 << OnlyArg->isLValue()
9289 << OnlyArg->getType()
9290 << Args[0]->getSourceRange();
9291 emitBadConversionNotes(S, Entity, Args[0]);
9292 break;
9293
9294 case FK_ConversionFailed: {
9295 QualType FromType = OnlyArg->getType();
9296 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op
9297 // type, although this is almost always an error and we advise against it.
9298 if (FromType == S.Context.AMDGPUFeaturePredicateTy &&
9299 DestType == S.Context.getLogicalOperationType()) {
9300 S.Diag(OnlyArg->getExprLoc(),
9301 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
9302 << OnlyArg << DestType;
9303 break;
9304 }
9305 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9306 << (int)Entity.getKind()
9307 << DestType
9308 << OnlyArg->isLValue()
9309 << FromType
9310 << Args[0]->getSourceRange();
9311 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9312 S.Diag(Kind.getLocation(), PDiag);
9313 emitBadConversionNotes(S, Entity, Args[0]);
9314 break;
9315 }
9316
9318 // No-op. This error has already been reported.
9319 break;
9320
9322 SourceRange R;
9323
9324 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9325 if (InitList && InitList->getNumInits() >= 1) {
9326 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9327 } else {
9328 assert(Args.size() > 1 && "Expected multiple initializers!");
9329 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9330 }
9331
9332 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9333 if (Kind.isCStyleOrFunctionalCast())
9334 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9335 << R;
9336 else
9337 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9338 << /*scalar=*/3 << R;
9339 break;
9340 }
9341
9343 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9344 << 0 << Entity.getType() << Args[0]->getSourceRange();
9345 break;
9346
9348 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9349 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9350 break;
9351
9353 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9354 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9355 break;
9356
9359 SourceRange ArgsRange;
9360 if (Args.size())
9361 ArgsRange =
9362 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9363
9364 if (Failure == FK_ListConstructorOverloadFailed) {
9365 assert(Args.size() == 1 &&
9366 "List construction from other than 1 argument.");
9367 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9368 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9369 }
9370
9371 // FIXME: Using "DestType" for the entity we're printing is probably
9372 // bad.
9373 switch (FailedOverloadResult) {
9374 case OR_Ambiguous:
9375 FailedCandidateSet.NoteCandidates(
9376 PartialDiagnosticAt(Kind.getLocation(),
9377 S.PDiag(diag::err_ovl_ambiguous_init)
9378 << DestType << ArgsRange),
9379 S, OCD_AmbiguousCandidates, Args);
9380 break;
9381
9383 if (Kind.getKind() == InitializationKind::IK_Default &&
9384 (Entity.getKind() == InitializedEntity::EK_Base ||
9388 // This is implicit default initialization of a member or
9389 // base within a constructor. If no viable function was
9390 // found, notify the user that they need to explicitly
9391 // initialize this base/member.
9394 const CXXRecordDecl *InheritedFrom = nullptr;
9395 if (auto Inherited = Constructor->getInheritedConstructor())
9396 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9397 if (Entity.getKind() == InitializedEntity::EK_Base) {
9398 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9399 << (InheritedFrom ? 2
9400 : Constructor->isImplicit() ? 1
9401 : 0)
9402 << S.Context.getCanonicalTagType(Constructor->getParent())
9403 << /*base=*/0 << Entity.getType() << InheritedFrom;
9404
9405 auto *BaseDecl =
9407 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9408 << S.Context.getCanonicalTagType(BaseDecl);
9409 } else {
9410 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9411 << (InheritedFrom ? 2
9412 : Constructor->isImplicit() ? 1
9413 : 0)
9414 << S.Context.getCanonicalTagType(Constructor->getParent())
9415 << /*member=*/1 << Entity.getName() << InheritedFrom;
9416 S.Diag(Entity.getDecl()->getLocation(),
9417 diag::note_member_declared_at);
9418
9419 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9420 S.Diag(Record->getDecl()->getLocation(), diag::note_previous_decl)
9421 << S.Context.getCanonicalTagType(Record->getDecl());
9422 }
9423 break;
9424 }
9425
9426 FailedCandidateSet.NoteCandidates(
9428 Kind.getLocation(),
9429 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9430 << DestType << ArgsRange),
9431 S, OCD_AllCandidates, Args);
9432 break;
9433
9434 case OR_Deleted: {
9437 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9438 if (Ovl != OR_Deleted) {
9439 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9440 << DestType << ArgsRange;
9441 llvm_unreachable("Inconsistent overload resolution?");
9442 break;
9443 }
9444
9445 // If this is a defaulted or implicitly-declared function, then
9446 // it was implicitly deleted. Make it clear that the deletion was
9447 // implicit.
9448 if (S.isImplicitlyDeleted(Best->Function))
9449 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9450 << cast<CXXMethodDecl>(Best->Function)->getSpecialMemberKind()
9451 << DestType << ArgsRange;
9452 else {
9453 StringLiteral *Msg = Best->Function->getDeletedMessage();
9454 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9455 << DestType << (Msg != nullptr)
9456 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9457 }
9458
9459 // If it's a default constructed member, but it's not in the
9460 // constructor's initializer list, explicitly note where the member is
9461 // declared so the user can see which member is erroneously initialized
9462 // with a deleted default constructor.
9463 if (Kind.getKind() == InitializationKind::IK_Default &&
9466 S.Diag(Entity.getDecl()->getLocation(),
9467 diag::note_default_constructed_field)
9468 << Entity.getDecl();
9469 }
9470 S.NoteDeletedFunction(Best->Function);
9471 break;
9472 }
9473
9474 case OR_Success:
9475 llvm_unreachable("Conversion did not fail!");
9476 }
9477 }
9478 break;
9479
9481 if (Entity.getKind() == InitializedEntity::EK_Member &&
9483 // This is implicit default-initialization of a const member in
9484 // a constructor. Complain that it needs to be explicitly
9485 // initialized.
9487 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9488 << (Constructor->getInheritedConstructor() ? 2
9489 : Constructor->isImplicit() ? 1
9490 : 0)
9491 << S.Context.getCanonicalTagType(Constructor->getParent())
9492 << /*const=*/1 << Entity.getName();
9493 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9494 << Entity.getName();
9495 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9496 VD && VD->isConstexpr()) {
9497 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9498 << VD;
9499 } else {
9500 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9501 << DestType << DestType->isRecordType();
9502 }
9503 break;
9504
9505 case FK_Incomplete:
9506 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9507 diag::err_init_incomplete_type);
9508 break;
9509
9511 // Run the init list checker again to emit diagnostics.
9512 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9513 diagnoseListInit(S, Entity, InitList);
9514 break;
9515 }
9516
9517 case FK_PlaceholderType: {
9518 // FIXME: Already diagnosed!
9519 break;
9520 }
9521
9523 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9524 // allows us to diagnose the failure when it happens in the
9525 // TryListInitialization call instead of delaying the diagnosis, which is
9526 // beneficial because the flattening is also expensive.
9527 break;
9528 }
9529
9531 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9532 << Args[0]->getSourceRange();
9535 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9536 (void)Ovl;
9537 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9538 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9539 S.Diag(CtorDecl->getLocation(),
9540 diag::note_explicit_ctor_deduction_guide_here) << false;
9541 break;
9542 }
9543
9545 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9546 /*VerifyOnly=*/false);
9547 break;
9548
9550 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9551 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9552 << Entity.getType() << InitList->getSourceRange();
9553 break;
9554 }
9555
9556 PrintInitLocationNote(S, Entity);
9557 return true;
9558}
9559
9560void InitializationSequence::dump(raw_ostream &OS) const {
9561 switch (SequenceKind) {
9562 case FailedSequence: {
9563 OS << "Failed sequence: ";
9564 switch (Failure) {
9566 OS << "too many initializers for reference";
9567 break;
9568
9570 OS << "parenthesized list init for reference";
9571 break;
9572
9574 OS << "array requires initializer list";
9575 break;
9576
9578 OS << "address of unaddressable function was taken";
9579 break;
9580
9582 OS << "array requires initializer list or string literal";
9583 break;
9584
9586 OS << "array requires initializer list or wide string literal";
9587 break;
9588
9590 OS << "narrow string into wide char array";
9591 break;
9592
9594 OS << "wide string into char array";
9595 break;
9596
9598 OS << "incompatible wide string into wide char array";
9599 break;
9600
9602 OS << "plain string literal into char8_t array";
9603 break;
9604
9606 OS << "u8 string literal into char array";
9607 break;
9608
9610 OS << "array type mismatch";
9611 break;
9612
9614 OS << "non-constant array initializer";
9615 break;
9616
9618 OS << "address of overloaded function failed";
9619 break;
9620
9622 OS << "overload resolution for reference initialization failed";
9623 break;
9624
9626 OS << "non-const lvalue reference bound to temporary";
9627 break;
9628
9630 OS << "non-const lvalue reference bound to bit-field";
9631 break;
9632
9634 OS << "non-const lvalue reference bound to vector element";
9635 break;
9636
9638 OS << "non-const lvalue reference bound to matrix element";
9639 break;
9640
9642 OS << "non-const lvalue reference bound to unrelated type";
9643 break;
9644
9646 OS << "rvalue reference bound to an lvalue";
9647 break;
9648
9650 OS << "reference initialization drops qualifiers";
9651 break;
9652
9654 OS << "reference with mismatching address space bound to temporary";
9655 break;
9656
9658 OS << "reference initialization failed";
9659 break;
9660
9662 OS << "conversion failed";
9663 break;
9664
9666 OS << "conversion from property failed";
9667 break;
9668
9670 OS << "too many initializers for scalar";
9671 break;
9672
9674 OS << "parenthesized list init for reference";
9675 break;
9676
9678 OS << "referencing binding to initializer list";
9679 break;
9680
9682 OS << "initializer list for non-aggregate, non-scalar type";
9683 break;
9684
9686 OS << "overloading failed for user-defined conversion";
9687 break;
9688
9690 OS << "constructor overloading failed";
9691 break;
9692
9694 OS << "default initialization of a const variable";
9695 break;
9696
9697 case FK_Incomplete:
9698 OS << "initialization of incomplete type";
9699 break;
9700
9702 OS << "list initialization checker failure";
9703 break;
9704
9706 OS << "variable length array has an initializer";
9707 break;
9708
9709 case FK_PlaceholderType:
9710 OS << "initializer expression isn't contextually valid";
9711 break;
9712
9714 OS << "list constructor overloading failed";
9715 break;
9716
9718 OS << "list copy initialization chose explicit constructor";
9719 break;
9720
9722 OS << "parenthesized list initialization failed";
9723 break;
9724
9726 OS << "designated initializer for non-aggregate type";
9727 break;
9728
9730 OS << "HLSL initialization list flattening failed";
9731 break;
9732 }
9733 OS << '\n';
9734 return;
9735 }
9736
9737 case DependentSequence:
9738 OS << "Dependent sequence\n";
9739 return;
9740
9741 case NormalSequence:
9742 OS << "Normal sequence: ";
9743 break;
9744 }
9745
9746 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9747 if (S != step_begin()) {
9748 OS << " -> ";
9749 }
9750
9751 switch (S->Kind) {
9753 OS << "resolve address of overloaded function";
9754 break;
9755
9757 OS << "derived-to-base (prvalue)";
9758 break;
9759
9761 OS << "derived-to-base (xvalue)";
9762 break;
9763
9765 OS << "derived-to-base (lvalue)";
9766 break;
9767
9768 case SK_BindReference:
9769 OS << "bind reference to lvalue";
9770 break;
9771
9773 OS << "bind reference to a temporary";
9774 break;
9775
9776 case SK_FinalCopy:
9777 OS << "final copy in class direct-initialization";
9778 break;
9779
9781 OS << "extraneous C++03 copy to temporary";
9782 break;
9783
9784 case SK_UserConversion:
9785 OS << "user-defined conversion via " << *S->Function.Function;
9786 break;
9787
9789 OS << "qualification conversion (prvalue)";
9790 break;
9791
9793 OS << "qualification conversion (xvalue)";
9794 break;
9795
9797 OS << "qualification conversion (lvalue)";
9798 break;
9799
9801 OS << "function reference conversion";
9802 break;
9803
9805 OS << "non-atomic-to-atomic conversion";
9806 break;
9807
9809 OS << "implicit conversion sequence (";
9810 S->ICS->dump(); // FIXME: use OS
9811 OS << ")";
9812 break;
9813
9815 OS << "implicit conversion sequence with narrowing prohibited (";
9816 S->ICS->dump(); // FIXME: use OS
9817 OS << ")";
9818 break;
9819
9821 OS << "list aggregate initialization";
9822 break;
9823
9824 case SK_UnwrapInitList:
9825 OS << "unwrap reference initializer list";
9826 break;
9827
9828 case SK_RewrapInitList:
9829 OS << "rewrap reference initializer list";
9830 break;
9831
9833 OS << "constructor initialization";
9834 break;
9835
9837 OS << "list initialization via constructor";
9838 break;
9839
9841 OS << "zero initialization";
9842 break;
9843
9844 case SK_CAssignment:
9845 OS << "C assignment";
9846 break;
9847
9848 case SK_StringInit:
9849 OS << "string initialization";
9850 break;
9851
9853 OS << "Objective-C object conversion";
9854 break;
9855
9856 case SK_ArrayLoopIndex:
9857 OS << "indexing for array initialization loop";
9858 break;
9859
9860 case SK_ArrayLoopInit:
9861 OS << "array initialization loop";
9862 break;
9863
9864 case SK_ArrayInit:
9865 OS << "array initialization";
9866 break;
9867
9868 case SK_GNUArrayInit:
9869 OS << "array initialization (GNU extension)";
9870 break;
9871
9873 OS << "parenthesized array initialization";
9874 break;
9875
9877 OS << "pass by indirect copy and restore";
9878 break;
9879
9881 OS << "pass by indirect restore";
9882 break;
9883
9885 OS << "Objective-C object retension";
9886 break;
9887
9889 OS << "std::initializer_list from initializer list";
9890 break;
9891
9893 OS << "list initialization from std::initializer_list";
9894 break;
9895
9896 case SK_OCLSamplerInit:
9897 OS << "OpenCL sampler_t from integer constant";
9898 break;
9899
9901 OS << "OpenCL opaque type from zero";
9902 break;
9903
9905 OS << "initialization from a parenthesized list of values";
9906 break;
9907
9909 OS << "HLSL buffer conversion";
9910 break;
9911 }
9912
9913 OS << " [" << S->Type << ']';
9914 }
9915
9916 OS << '\n';
9917}
9918
9920 dump(llvm::errs());
9921}
9922
9924 const ImplicitConversionSequence &ICS,
9925 QualType PreNarrowingType,
9926 QualType EntityType,
9927 const Expr *PostInit) {
9928 const StandardConversionSequence *SCS = nullptr;
9929 switch (ICS.getKind()) {
9931 SCS = &ICS.Standard;
9932 break;
9934 SCS = &ICS.UserDefined.After;
9935 break;
9940 return;
9941 }
9942
9943 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9944 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9945 unsigned DiagID;
9946 auto &L = S.getLangOpts();
9947 if (L.CPlusPlus11 && !L.HLSL &&
9948 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9949 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9950 else
9951 DiagID = WarnDiagID;
9952 return S.Diag(PostInit->getBeginLoc(), DiagID)
9953 << PostInit->getSourceRange();
9954 };
9955
9956 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9957 APValue ConstantValue;
9958 QualType ConstantType;
9959 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9960 ConstantType)) {
9961 case NK_Not_Narrowing:
9963 // No narrowing occurred.
9964 return;
9965
9966 case NK_Type_Narrowing: {
9967 // This was a floating-to-integer conversion, which is always considered a
9968 // narrowing conversion even if the value is a constant and can be
9969 // represented exactly as an integer.
9970 QualType T = EntityType.getNonReferenceType();
9971 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9972 diag::ext_init_list_type_narrowing_const_reference,
9973 diag::warn_init_list_type_narrowing)
9974 << PreNarrowingType.getLocalUnqualifiedType()
9975 << T.getLocalUnqualifiedType();
9976 break;
9977 }
9978
9979 case NK_Constant_Narrowing: {
9980 // A constant value was narrowed.
9981 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9982 diag::ext_init_list_constant_narrowing,
9983 diag::ext_init_list_constant_narrowing_const_reference,
9984 diag::warn_init_list_constant_narrowing)
9985 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9987 break;
9988 }
9989
9990 case NK_Variable_Narrowing: {
9991 // A variable's value may have been narrowed.
9992 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9993 diag::ext_init_list_variable_narrowing,
9994 diag::ext_init_list_variable_narrowing_const_reference,
9995 diag::warn_init_list_variable_narrowing)
9996 << PreNarrowingType.getLocalUnqualifiedType()
9998 break;
9999 }
10000 }
10001
10002 SmallString<128> StaticCast;
10003 llvm::raw_svector_ostream OS(StaticCast);
10004 OS << "static_cast<";
10005 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10006 // It's important to use the typedef's name if there is one so that the
10007 // fixit doesn't break code using types like int64_t.
10008 //
10009 // FIXME: This will break if the typedef requires qualification. But
10010 // getQualifiedNameAsString() includes non-machine-parsable components.
10011 OS << *TT->getDecl();
10012 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10013 OS << BT->getName(S.getLangOpts());
10014 else {
10015 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10016 // with a broken cast.
10017 return;
10018 }
10019 OS << ">(";
10020 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10021 << PostInit->getSourceRange()
10022 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10024 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10025}
10026
10028 QualType ToType, Expr *Init) {
10029 assert(S.getLangOpts().C23);
10031 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10032 Sema::AllowedExplicit::None,
10033 /*InOverloadResolution*/ false,
10034 /*CStyle*/ false,
10035 /*AllowObjCWritebackConversion=*/false);
10036
10037 if (!ICS.isStandard())
10038 return;
10039
10040 APValue Value;
10041 QualType PreNarrowingType;
10042 // Reuse C++ narrowing check.
10043 switch (ICS.Standard.getNarrowingKind(
10044 S.Context, Init, Value, PreNarrowingType,
10045 /*IgnoreFloatToIntegralConversion*/ false)) {
10046 // The value doesn't fit.
10048 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10049 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10050 return;
10051
10052 // Conversion to a narrower type.
10053 case NK_Type_Narrowing:
10054 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10055 << ToType << FromType;
10056 return;
10057
10058 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10059 // not really interested in these cases.
10062 case NK_Not_Narrowing:
10063 return;
10064 }
10065 llvm_unreachable("unhandled case in switch");
10066}
10067
10069 Sema &SemaRef, QualType &TT) {
10070 assert(SemaRef.getLangOpts().C23);
10071 // character that string literal contains fits into TT - target type.
10072 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10073 QualType CharType = AT->getElementType();
10074 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10075 bool isUnsigned = CharType->isUnsignedIntegerType();
10076 llvm::APSInt Value(BitWidth, isUnsigned);
10077 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10078 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10079 Value = C;
10080 if (Value != C) {
10081 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10082 diag::err_c23_constexpr_init_not_representable)
10083 << C << CharType;
10084 return;
10085 }
10086 }
10087}
10088
10089//===----------------------------------------------------------------------===//
10090// Initialization helper functions
10091//===----------------------------------------------------------------------===//
10092bool
10094 ExprResult Init) {
10095 if (Init.isInvalid())
10096 return false;
10097
10098 Expr *InitE = Init.get();
10099 assert(InitE && "No initialization expression");
10100
10101 InitializationKind Kind =
10103 InitializationSequence Seq(*this, Entity, Kind, InitE);
10104 return !Seq.Failed();
10105}
10106
10109 SourceLocation EqualLoc,
10111 bool TopLevelOfInitList,
10112 bool AllowExplicit) {
10113 if (Init.isInvalid())
10114 return ExprError();
10115
10116 Expr *InitE = Init.get();
10117 assert(InitE && "No initialization expression?");
10118
10119 if (EqualLoc.isInvalid())
10120 EqualLoc = InitE->getBeginLoc();
10121
10122 if (Entity.getType().getDesugaredType(Context) ==
10123 Context.AMDGPUFeaturePredicateTy &&
10124 Entity.getDecl()) {
10125 Diag(EqualLoc, diag::err_amdgcn_predicate_type_is_not_constructible)
10126 << Entity.getDecl();
10127 return ExprError();
10128 }
10129
10131 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10132 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10133
10134 // Prevent infinite recursion when performing parameter copy-initialization.
10135 const bool ShouldTrackCopy =
10136 Entity.isParameterKind() && Seq.isConstructorInitialization();
10137 if (ShouldTrackCopy) {
10138 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10139 Seq.SetOverloadFailure(
10142
10143 // Try to give a meaningful diagnostic note for the problematic
10144 // constructor.
10145 const auto LastStep = Seq.step_end() - 1;
10146 assert(LastStep->Kind ==
10148 const FunctionDecl *Function = LastStep->Function.Function;
10149 auto Candidate =
10150 llvm::find_if(Seq.getFailedCandidateSet(),
10151 [Function](const OverloadCandidate &Candidate) -> bool {
10152 return Candidate.Viable &&
10153 Candidate.Function == Function &&
10154 Candidate.Conversions.size() > 0;
10155 });
10156 if (Candidate != Seq.getFailedCandidateSet().end() &&
10157 Function->getNumParams() > 0) {
10158 Candidate->Viable = false;
10161 InitE,
10162 Function->getParamDecl(0)->getType());
10163 }
10164 }
10165 CurrentParameterCopyTypes.push_back(Entity.getType());
10166 }
10167
10168 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10169
10170 if (ShouldTrackCopy)
10171 CurrentParameterCopyTypes.pop_back();
10172
10173 return Result;
10174}
10175
10176/// Determine whether RD is, or is derived from, a specialization of CTD.
10178 ClassTemplateDecl *CTD) {
10179 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10180 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10181 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10182 };
10183 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10184}
10185
10187 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10188 const InitializationKind &Kind, MultiExprArg Inits) {
10189 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10190 TSInfo->getType()->getContainedDeducedType());
10191 assert(DeducedTST && "not a deduced template specialization type");
10192
10193 auto TemplateName = DeducedTST->getTemplateName();
10195 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10196
10197 // We can only perform deduction for class templates or alias templates.
10198 auto *Template =
10199 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10200 TemplateDecl *LookupTemplateDecl = Template;
10201 if (!Template) {
10202 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10204 DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
10205 LookupTemplateDecl = AliasTemplate;
10206 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10207 ->getUnderlyingType()
10208 .getCanonicalType();
10209 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10210 // of the form
10211 // [typename] [nested-name-specifier] [template] simple-template-id
10212 if (const auto *TST =
10213 UnderlyingType->getAs<TemplateSpecializationType>()) {
10214 Template = dyn_cast_or_null<ClassTemplateDecl>(
10215 TST->getTemplateName().getAsTemplateDecl());
10216 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10217 // Cases where template arguments in the RHS of the alias are not
10218 // dependent. e.g.
10219 // using AliasFoo = Foo<bool>;
10220 if (const auto *CTSD =
10221 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
10222 Template = CTSD->getSpecializedTemplate();
10223 }
10224 }
10225 }
10226 if (!Template) {
10227 Diag(Kind.getLocation(),
10228 diag::err_deduced_non_class_or_alias_template_specialization_type)
10230 if (auto *TD = TemplateName.getAsTemplateDecl())
10232 return QualType();
10233 }
10234
10235 // Can't deduce from dependent arguments.
10237 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10238 diag::warn_cxx14_compat_class_template_argument_deduction)
10239 << TSInfo->getTypeLoc().getSourceRange() << 0;
10240 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10241 }
10242
10243 // FIXME: Perform "exact type" matching first, per CWG discussion?
10244 // Or implement this via an implied 'T(T) -> T' deduction guide?
10245
10246 // Look up deduction guides, including those synthesized from constructors.
10247 //
10248 // C++1z [over.match.class.deduct]p1:
10249 // A set of functions and function templates is formed comprising:
10250 // - For each constructor of the class template designated by the
10251 // template-name, a function template [...]
10252 // - For each deduction-guide, a function or function template [...]
10253 DeclarationNameInfo NameInfo(
10254 Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),
10255 TSInfo->getTypeLoc().getEndLoc());
10256 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10257 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10258
10259 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10260 // clear on this, but they're not found by name so access does not apply.
10261 Guides.suppressDiagnostics();
10262
10263 // Figure out if this is list-initialization.
10265 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10266 ? dyn_cast<InitListExpr>(Inits[0])
10267 : nullptr;
10268
10269 // C++1z [over.match.class.deduct]p1:
10270 // Initialization and overload resolution are performed as described in
10271 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10272 // (as appropriate for the type of initialization performed) for an object
10273 // of a hypothetical class type, where the selected functions and function
10274 // templates are considered to be the constructors of that class type
10275 //
10276 // Since we know we're initializing a class type of a type unrelated to that
10277 // of the initializer, this reduces to something fairly reasonable.
10278 OverloadCandidateSet Candidates(Kind.getLocation(),
10281
10282 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10283
10284 // Return true if the candidate is added successfully, false otherwise.
10285 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10287 DeclAccessPair FoundDecl,
10288 bool OnlyListConstructors,
10289 bool AllowAggregateDeductionCandidate) {
10290 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10291 // For copy-initialization, the candidate functions are all the
10292 // converting constructors (12.3.1) of that class.
10293 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10294 // The converting constructors of T are candidate functions.
10295 if (!AllowExplicit) {
10296 // Overload resolution checks whether the deduction guide is declared
10297 // explicit for us.
10298
10299 // When looking for a converting constructor, deduction guides that
10300 // could never be called with one argument are not interesting to
10301 // check or note.
10302 if (GD->getMinRequiredArguments() > 1 ||
10303 (GD->getNumParams() == 0 && !GD->isVariadic()))
10304 return;
10305 }
10306
10307 // C++ [over.match.list]p1.1: (first phase list initialization)
10308 // Initially, the candidate functions are the initializer-list
10309 // constructors of the class T
10310 if (OnlyListConstructors && !isInitListConstructor(GD))
10311 return;
10312
10313 if (!AllowAggregateDeductionCandidate &&
10314 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10315 return;
10316
10317 // C++ [over.match.list]p1.2: (second phase list initialization)
10318 // the candidate functions are all the constructors of the class T
10319 // C++ [over.match.ctor]p1: (all other cases)
10320 // the candidate functions are all the constructors of the class of
10321 // the object being initialized
10322
10323 // C++ [over.best.ics]p4:
10324 // When [...] the constructor [...] is a candidate by
10325 // - [over.match.copy] (in all cases)
10326 if (TD) {
10327
10328 // As template candidates are not deduced immediately,
10329 // persist the array in the overload set.
10330 MutableArrayRef<Expr *> TmpInits =
10331 Candidates.getPersistentArgsArray(Inits.size());
10332
10333 for (auto [I, E] : llvm::enumerate(Inits)) {
10334 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10335 TmpInits[I] = DI->getInit();
10336 else
10337 TmpInits[I] = E;
10338 }
10339
10341 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10342 /*SuppressUserConversions=*/false,
10343 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10344 /*PO=*/{}, AllowAggregateDeductionCandidate);
10345 } else {
10346 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10347 /*SuppressUserConversions=*/false,
10348 /*PartialOverloading=*/false, AllowExplicit);
10349 }
10350 };
10351
10352 bool FoundDeductionGuide = false;
10353
10354 auto TryToResolveOverload =
10355 [&](bool OnlyListConstructors) -> OverloadingResult {
10357 bool HasAnyDeductionGuide = false;
10358
10359 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10360 auto *Pattern = Template;
10361 while (Pattern->getInstantiatedFromMemberTemplate()) {
10362 if (Pattern->isMemberSpecialization())
10363 break;
10364 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10365 }
10366
10367 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10368 if (!(RD->getDefinition() && RD->isAggregate()))
10369 return;
10370 QualType Ty = Context.getCanonicalTagType(RD);
10371 SmallVector<QualType, 8> ElementTypes;
10372
10373 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10374 if (!CheckInitList.HadError()) {
10375 // C++ [over.match.class.deduct]p1.8:
10376 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10377 // rvalue reference to the declared type of e_i and
10378 // C++ [over.match.class.deduct]p1.9:
10379 // if e_i is of array type and x_i is a string-literal, T_i is an
10380 // lvalue reference to the const-qualified declared type of e_i and
10381 // C++ [over.match.class.deduct]p1.10:
10382 // otherwise, T_i is the declared type of e_i
10383 for (int I = 0, E = ListInit->getNumInits();
10384 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10385 if (ElementTypes[I]->isArrayType()) {
10387 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10388 else if (isa<StringLiteral>(
10389 ListInit->getInit(I)->IgnoreParenImpCasts()))
10390 ElementTypes[I] =
10391 Context.getLValueReferenceType(ElementTypes[I].withConst());
10392 }
10393
10394 if (CXXDeductionGuideDecl *GD =
10396 LookupTemplateDecl, ElementTypes,
10397 TSInfo->getTypeLoc().getEndLoc())) {
10398 auto *TD = GD->getDescribedFunctionTemplate();
10399 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10400 OnlyListConstructors,
10401 /*AllowAggregateDeductionCandidate=*/true);
10402 HasAnyDeductionGuide = true;
10403 }
10404 }
10405 };
10406
10407 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10408 NamedDecl *D = (*I)->getUnderlyingDecl();
10409 if (D->isInvalidDecl())
10410 continue;
10411
10412 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10413 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10414 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10415 if (!GD)
10416 continue;
10417
10418 if (!GD->isImplicit())
10419 HasAnyDeductionGuide = true;
10420
10421 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10422 /*AllowAggregateDeductionCandidate=*/false);
10423 }
10424
10425 // C++ [over.match.class.deduct]p1.4:
10426 // if C is defined and its definition satisfies the conditions for an
10427 // aggregate class ([dcl.init.aggr]) with the assumption that any
10428 // dependent base class has no virtual functions and no virtual base
10429 // classes, and the initializer is a non-empty braced-init-list or
10430 // parenthesized expression-list, and there are no deduction-guides for
10431 // C, the set contains an additional function template, called the
10432 // aggregate deduction candidate, defined as follows.
10433 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10434 if (ListInit && ListInit->getNumInits()) {
10435 SynthesizeAggrGuide(ListInit);
10436 } else if (Inits.size()) { // parenthesized expression-list
10437 // Inits are expressions inside the parentheses. We don't have
10438 // the parentheses source locations, use the begin/end of Inits as the
10439 // best heuristic.
10440 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10441 Inits, Inits.back()->getEndLoc(),
10442 /*isExplicit=*/false);
10443 SynthesizeAggrGuide(&TempListInit);
10444 }
10445 }
10446
10447 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10448
10449 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10450 };
10451
10453
10454 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10455 // try initializer-list constructors.
10456 if (ListInit) {
10457 bool TryListConstructors = true;
10458
10459 // Try list constructors unless the list is empty and the class has one or
10460 // more default constructors, in which case those constructors win.
10461 if (!ListInit->getNumInits()) {
10462 for (NamedDecl *D : Guides) {
10463 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10464 if (FD && FD->getMinRequiredArguments() == 0) {
10465 TryListConstructors = false;
10466 break;
10467 }
10468 }
10469 } else if (ListInit->getNumInits() == 1) {
10470 // C++ [over.match.class.deduct]:
10471 // As an exception, the first phase in [over.match.list] (considering
10472 // initializer-list constructors) is omitted if the initializer list
10473 // consists of a single expression of type cv U, where U is a
10474 // specialization of C or a class derived from a specialization of C.
10475 Expr *E = ListInit->getInit(0);
10476 auto *RD = E->getType()->getAsCXXRecordDecl();
10477 if (!isa<InitListExpr>(E) && RD &&
10478 isCompleteType(Kind.getLocation(), E->getType()) &&
10480 TryListConstructors = false;
10481 }
10482
10483 if (TryListConstructors)
10484 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10485 // Then unwrap the initializer list and try again considering all
10486 // constructors.
10487 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10488 }
10489
10490 // If list-initialization fails, or if we're doing any other kind of
10491 // initialization, we (eventually) consider constructors.
10493 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10494
10495 switch (Result) {
10496 case OR_Ambiguous:
10497 // FIXME: For list-initialization candidates, it'd usually be better to
10498 // list why they were not viable when given the initializer list itself as
10499 // an argument.
10500 Candidates.NoteCandidates(
10502 Kind.getLocation(),
10503 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10504 << TemplateName),
10506 return QualType();
10507
10508 case OR_No_Viable_Function: {
10509 CXXRecordDecl *Primary =
10510 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10511 bool Complete = isCompleteType(Kind.getLocation(),
10512 Context.getCanonicalTagType(Primary));
10513 Candidates.NoteCandidates(
10515 Kind.getLocation(),
10516 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10517 : diag::err_deduced_class_template_incomplete)
10518 << TemplateName << !Guides.empty()),
10519 *this, OCD_AllCandidates, Inits);
10520 return QualType();
10521 }
10522
10523 case OR_Deleted: {
10524 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10525 // like we ever get here; attempts to trigger this seem to yield a
10526 // generic c'all to deleted function' diagnostic instead.
10527 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10528 << TemplateName;
10529 NoteDeletedFunction(Best->Function);
10530 return QualType();
10531 }
10532
10533 case OR_Success:
10534 // C++ [over.match.list]p1:
10535 // In copy-list-initialization, if an explicit constructor is chosen, the
10536 // initialization is ill-formed.
10537 if (Kind.isCopyInit() && ListInit &&
10538 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10539 bool IsDeductionGuide = !Best->Function->isImplicit();
10540 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10541 << TemplateName << IsDeductionGuide;
10542 Diag(Best->Function->getLocation(),
10543 diag::note_explicit_ctor_deduction_guide_here)
10544 << IsDeductionGuide;
10545 return QualType();
10546 }
10547
10548 // Make sure we didn't select an unusable deduction guide, and mark it
10549 // as referenced.
10550 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
10551 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10552 break;
10553 }
10554
10555 // C++ [dcl.type.class.deduct]p1:
10556 // The placeholder is replaced by the return type of the function selected
10557 // by overload resolution for class template deduction.
10558 QualType DeducedType =
10559 SubstAutoTypeSourceInfo(TSInfo, Best->Function->getReturnType())
10560 ->getType();
10561 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10562 diag::warn_cxx14_compat_class_template_argument_deduction)
10563 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10564
10565 // Warn if CTAD was used on a type that does not have any user-defined
10566 // deduction guides.
10567 if (!FoundDeductionGuide) {
10568 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10569 diag::warn_ctad_maybe_unsupported)
10570 << TemplateName;
10571 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10572 }
10573
10574 return DeducedType;
10575}
Defines the clang::ASTContext interface.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
static bool isRValueRef(QualType ParamType)
Definition Consumed.cpp:178
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
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.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition SemaExpr.cpp:566
This file declares semantic analysis for HLSL constructs.
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
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:175
static void updateGNUCompoundLiteralRValue(Expr *E)
Fix a compound literal initializing an array so it's correctly marked as an rvalue.
Definition SemaInit.cpp:187
static bool initializingConstexprVariable(const InitializedEntity &Entity)
Definition SemaInit.cpp:196
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.
static bool shouldDestroyEntity(const InitializedEntity &Entity)
Whether the given entity, when initialized with an object created for that initialization,...
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
static bool hasAnyDesignatedInits(const InitListExpr *IL)
static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer)
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
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...
static void TryOrBuildParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args, InitializationSequence &Sequence, bool VerifyOnly, ExprResult *Result=nullptr)
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S, const InitializedEntity &Entity, bool CheckC23ConstexprInit=false)
Definition SemaInit.cpp:214
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, Sema &SemaRef, QualType &TT)
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 ...
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, ClassTemplateDecl *CTD)
Determine whether RD is, or is derived from, a specialization of CTD.
static bool canInitializeArrayWithEmbedDataString(ArrayRef< Expr * > ExprList, const InitializedEntity &Entity, ASTContext &Context)
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...
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:74
static void TryArrayCopy(Sema &S, const InitializationKind &Kind, const InitializedEntity &Entity, Expr *Initializer, QualType DestType, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Initialize an array from another array.
static bool isInitializedStructuredList(const InitListExpr *StructuredList)
StringInitFailureKind
Definition SemaInit.cpp:60
@ SIF_None
Definition SemaInit.cpp:61
@ SIF_PlainStringIntoUTF8Char
Definition SemaInit.cpp:66
@ SIF_IncompatWideStringIntoWideChar
Definition SemaInit.cpp:64
@ SIF_UTF8StringIntoPlainChar
Definition SemaInit.cpp:65
@ SIF_NarrowStringIntoWideChar
Definition SemaInit.cpp:62
@ SIF_Other
Definition SemaInit.cpp:67
@ SIF_WideStringIntoChar
Definition SemaInit.cpp:63
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
static ExprResult CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value)
Check that the given Index expression is a valid array designator value.
static bool canPerformArrayCopy(const InitializedEntity &Entity)
Determine whether we can perform an elementwise array copy for this kind of entity.
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, bool TopLevelOfInitList)
Reference initialization without resolving overloaded functions.
static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, QualType ToType, Expr *Init)
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...
static void TryValueInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence, InitListExpr *InitList=nullptr)
Attempt value initialization (C++ [dcl.init]p7).
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...
static OverloadingResult ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, MultiExprArg Args, OverloadCandidateSet &CandidateSet, QualType DestType, DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, bool IsListInit, bool RequireActualConstructor, bool SecondStepOfCopyInit=false)
static AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
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])
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],...
static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, Sema &SemaRef)
Check if the type of a class element has an accessible destructor, and marks it referenced.
static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt reference initialization (C++0x [dcl.init.ref])
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
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...
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,...
static bool isNonReferenceableGLValue(Expr *E)
Determine whether an expression is a non-referenceable glvalue (one to which a reference can never bi...
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
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:50
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
static OverloadingResult TryRefInitWithConversionFunction(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, bool AllowRValues, bool IsLValueRef, InitializationSequence &Sequence)
Try a reference initialization that involves calling a conversion function.
void emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R)
Definition SemaInit.cpp:310
static void TryConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, QualType DestArrayType, InitializationSequence &Sequence, bool IsListInit=false, bool IsInitListCopy=false)
Attempt initialization by constructor (C++ [dcl.init]), which enumerates the constructors of the init...
static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, Expr *op)
Emit notes associated with an initialization that failed due to a "simple" conversion failure.
static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity)
Determine whether Entity is an entity for which it is idiomatic to elide the braces in aggregate init...
static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity.
static void TryConstructorOrParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, InitializationSequence &Sequence, bool IsAggrListInit)
Attempt to initialize an object of a class type either by direct-initialization, or by copy-initializ...
static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx)
static const FieldDecl * getConstField(const RecordDecl *RD)
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
@ IIK_okay
@ IIK_nonlocal
@ IIK_nonscalar
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)
static void TryReferenceListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization of a reference.
static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, const ConstructorInfo &Info)
Determine if the constructor has the signature of a copy or move constructor for the type T of the cl...
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
This file declares semantic analysis for Objective-C.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:511
bool isLValue() const
Definition APValue.h:493
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:991
bool isNullPointer() const
Definition APValue.cpp:1054
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
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.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:985
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType OverloadTy
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType OCLSamplerTy
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:947
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6071
Represents a loop initializing the elements of an array.
Definition Expr.h:6018
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
QualType getElementType() const
Definition TypeBase.h:3848
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3292
Represents a base class of a C++ class.
Definition DeclCXX.h:146
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2641
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2881
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2718
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2976
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3012
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:2000
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2292
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2040
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasUninitializedReferenceMember() const
Whether this class or any of its subobjects has any members of reference type which would make value-...
Definition DeclCXX.h:1167
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1406
CXXBaseSpecifier * base_class_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:517
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition DeclCXX.h:605
base_class_range bases()
Definition DeclCXX.h:608
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1989
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1568
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
llvm::iterator_range< base_class_iterator > base_class_range
Definition DeclCXX.h:604
bool forallBases(ForallBasesCallback BaseMatches) const
Determines if the given callback holds for all the direct or indirect base classes of this type.
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2200
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:804
static CXXTemporaryObjectExpr * Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI, ArrayRef< Expr * > Args, SourceRange ParenOrBraceRange, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization)
Definition ExprCXX.cpp:1179
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
SourceLocation getBeginLoc() const
Definition Expr.h:3321
bool isCallToStdMove() const
Definition Expr.cpp:3676
Expr * getCallee()
Definition Expr.h:3134
SourceLocation getRParenLoc() const
Definition Expr.h:3318
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3720
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
Declaration of a class template.
void setExprNeedsCleanups(bool SideEffects)
Definition CleanupInfo.h:28
ConditionalOperator - The ?
Definition Expr.h:4435
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3950
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4523
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
DeclContextLookupResult lookup_result
Definition DeclBase.h:2607
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...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2403
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1494
ValueDecl * getDecl()
Definition Expr.h:1358
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
static bool isFlexibleArrayMemberLike(const ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
Definition DeclBase.cpp:463
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:585
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:832
Represents a single C99 designator.
Definition Expr.h:5644
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:5806
void setFieldDecl(FieldDecl *FD)
Definition Expr.h:5742
FieldDecl * getFieldDecl() const
Definition Expr.h:5735
SourceLocation getFieldLoc() const
Definition Expr.h:5752
const IdentifierInfo * getFieldName() const
Definition Expr.cpp:4822
SourceLocation getDotLoc() const
Definition Expr.h:5747
SourceLocation getLBracketLoc() const
Definition Expr.h:5788
Represents a C99 designated initializer expression.
Definition Expr.h:5601
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition Expr.h:5861
Expr * getArrayRangeEnd(const Designator &D) const
Definition Expr.cpp:4931
Expr * getSubExpr(unsigned Idx) const
Definition Expr.h:5883
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition Expr.h:5865
Expr * getArrayRangeStart(const Designator &D) const
Definition Expr.cpp:4926
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:4938
MutableArrayRef< Designator > designators()
Definition Expr.h:5834
Expr * getArrayIndex(const Designator &D) const
Definition Expr.cpp:4921
Designator * getDesignator(unsigned Idx)
Definition Expr.h:5842
Expr * getInit() const
Retrieve the initializer value.
Definition Expr.h:5869
unsigned size() const
Returns the number of designators in this initializer.
Definition Expr.h:5831
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:4900
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4917
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition Expr.h:5856
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition Expr.h:5881
static DesignatedInitExpr * Create(const ASTContext &C, ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition Expr.cpp:4863
InitListExpr * getUpdater() const
Definition Expr.h:5986
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:221
const Designator & getDesignator(unsigned Idx) const
Definition Designator.h:232
unsigned getNumDesignators() const
Definition Designator.h:231
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
SourceLocation getFieldLoc() const
Definition Designator.h:133
SourceLocation getDotLoc() const
Definition Designator.h:128
Expr * getArrayRangeStart() const
Definition Designator.h:194
bool isArrayDesignator() const
Definition Designator.h:108
SourceLocation getLBracketLoc() const
Definition Designator.h:167
bool isArrayRangeDesignator() const
Definition Designator.h:109
bool isFieldDesignator() const
Definition Designator.h:107
SourceLocation getRBracketLoc() const
Definition Designator.h:174
SourceLocation getEllipsisLoc() const
Definition Designator.h:204
Expr * getArrayRangeEnd() const
Definition Designator.h:199
const IdentifierInfo * getFieldDecl() const
Definition Designator.h:123
Expr * getArrayIndex() const
Definition Designator.h:162
static Designator CreateFieldDesignator(const IdentifierInfo *FieldName, SourceLocation DotLoc, SourceLocation FieldLoc)
Creates a field designator.
Definition Designator.h:115
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:972
Represents a reference to emded data.
Definition Expr.h:5179
StringLiteral * getDataStringLiteral() const
Definition Expr.h:5196
EmbedDataStorage * getData() const
Definition Expr.h:5198
SourceLocation getLocation() const
Definition Expr.h:5192
size_t getDataElementCount() const
Definition Expr.h:5201
RAII object that enters a new expression evaluation context.
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4373
The return type of classify().
Definition Expr.h:340
bool isLValue() const
Definition Expr.h:391
bool isPRValue() const
Definition Expr.h:394
bool isXValue() const
Definition Expr.h:392
bool isRValue() const
Definition Expr.h:395
This represents one expression.
Definition Expr.h:113
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition Expr.cpp:4319
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3111
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
bool isPRValue() const
Definition Expr.h:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3372
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:851
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:855
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
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:3722
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3103
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:3286
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:4104
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:465
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToMatrixElement() const
Returns whether this expression refers to a matrix element.
Definition Expr.h:518
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:480
QualType getType() const
Definition Expr.h:145
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3475
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4890
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3380
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3401
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3891
QualType getReturnType() const
Definition Decl.h:2976
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2667
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3870
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
One of these records is kept for each identifier that is lexed.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2103
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:623
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:674
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:678
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:828
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6107
Represents a C array with an unspecified size.
Definition TypeBase.h:4023
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3602
chain_iterator chain_end() const
Definition Decl.h:3625
chain_iterator chain_begin() const
Definition Decl.h:3624
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition Decl.h:3621
Describes an C or C++ initializer list.
Definition Expr.h:5352
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition Expr.h:5465
void setSyntacticForm(InitListExpr *Init)
Definition Expr.h:5526
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition Expr.h:5427
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5468
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2495
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition Expr.cpp:2455
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5479
unsigned getNumInits() const
Definition Expr.h:5385
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2529
void setInit(unsigned Init, Expr *expr)
Definition Expr.h:5417
SourceLocation getLBraceLoc() const
Definition Expr.h:5510
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:2459
void setArrayFiller(Expr *filler)
Definition Expr.cpp:2471
InitListExpr * getSyntacticForm() const
Definition Expr.h:5522
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5455
bool isExplicit() const
Definition Expr.h:5495
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5389
SourceLocation getRBraceLoc() const
Definition Expr.h:5512
InitListExpr * getSemanticForm() const
Definition Expr.h:5516
const Expr * getInit(unsigned Init) const
Definition Expr.h:5407
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition Expr.cpp:2518
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2547
void setInitializedFieldInUnion(FieldDecl *FD)
Definition Expr.h:5485
bool isSyntacticForm() const
Definition Expr.h:5519
void setRBraceLoc(SourceLocation Loc)
Definition Expr.h:5513
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
void sawArrayRangeDesignator(bool ARD=true)
Definition Expr.h:5536
Expr ** getInits()
Retrieve the set of initializers.
Definition Expr.h:5398
Describes the kind of initialization being performed, along with location information for tokens rela...
@ IK_DirectList
Direct list-initialization.
@ IK_Value
Value initialization.
@ IK_Direct
Direct initialization.
@ IK_Copy
Copy initialization.
@ IK_Default
Default initialization.
InitKind getKind() const
Determine the initialization kind.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
A single step in the initialization sequence.
StepKind Kind
The kind of conversion or initialization step we are taking.
InitListExpr * WrappingSyntacticList
When Kind = SK_RewrapInitList, the syntactic form of the wrapping list.
ImplicitConversionSequence * ICS
When Kind = SK_ConversionSequence, the implicit conversion sequence.
struct F Function
When Kind == SK_ResolvedOverloadedFunction or Kind == SK_UserConversion, the function that the expres...
Describes the sequence of initializations required to initialize a given object or reference with a s...
step_iterator step_begin() const
void AddListInitializationStep(QualType T)
Add a list-initialization step.
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.
void AddStringInitStep(QualType T)
Add a string init step.
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
@ SK_StdInitializerListConstructorCall
Perform initialization via a constructor taking a single std::initializer_list argument.
@ SK_AtomicConversion
Perform a conversion adding _Atomic to a type.
@ SK_ObjCObjectConversion
An initialization that "converts" an Objective-C object (not a point to an object) to another Objecti...
@ SK_GNUArrayInit
Array initialization (from an array rvalue) as a GNU extension.
@ SK_CastDerivedToBaseLValue
Perform a derived-to-base cast, producing an lvalue.
@ SK_ProduceObjCObject
Produce an Objective-C object pointer.
@ SK_FunctionReferenceConversion
Perform a function reference conversion, see [dcl.init.ref]p4.
@ SK_BindReference
Reference binding to an lvalue.
@ SK_ArrayLoopInit
Array initialization by elementwise copy.
@ SK_ConstructorInitialization
Perform initialization via a constructor.
@ SK_OCLSamplerInit
Initialize an OpenCL sampler from an integer.
@ SK_StringInit
Initialization by string.
@ SK_ZeroInitialization
Zero-initialize the object.
@ SK_CastDerivedToBaseXValue
Perform a derived-to-base cast, producing an xvalue.
@ SK_QualificationConversionXValue
Perform a qualification conversion, producing an xvalue.
@ SK_UserConversion
Perform a user-defined conversion, either via a conversion function or via a constructor.
@ SK_CastDerivedToBasePRValue
Perform a derived-to-base cast, producing an rvalue.
@ SK_BindReferenceToTemporary
Reference binding to a temporary.
@ SK_PassByIndirectRestore
Pass an object by indirect restore.
@ SK_ParenthesizedArrayInit
Array initialization from a parenthesized initializer list.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
@ SK_ArrayInit
Array initialization (from an array rvalue).
@ SK_ExtraneousCopyToTemporary
An optional copy of a temporary object to another temporary object, which is permitted (but not requi...
@ SK_ArrayLoopIndex
Array indexing for initialization by elementwise copy.
@ SK_ConversionSequenceNoNarrowing
Perform an implicit conversion sequence without narrowing.
@ SK_RewrapInitList
Rewrap the single-element initializer list for a reference.
@ SK_ConstructorInitializationFromList
Perform initialization via a constructor, taking arguments from a single InitListExpr.
@ SK_PassByIndirectCopyRestore
Pass an object by indirect copy-and-restore.
@ SK_ResolveAddressOfOverloadedFunction
Resolve the address of an overloaded function to a specific function declaration.
@ SK_UnwrapInitList
Unwrap the single-element initializer list for a reference.
@ SK_FinalCopy
Direct-initialization from a reference-related object in the final stage of class copy-initialization...
@ SK_QualificationConversionLValue
Perform a qualification conversion, producing an lvalue.
@ SK_StdInitializerList
Construct a std::initializer_list from an initializer list.
@ SK_QualificationConversionPRValue
Perform a qualification conversion, producing a prvalue.
@ SK_ConversionSequence
Perform an implicit conversion sequence.
@ SK_ListInitialization
Perform list-initialization without a constructor.
@ SK_OCLZeroOpaqueType
Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero.
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...
void AddHLSLBufferConversionStep(QualType T)
void SetZeroInitializationFixit(const std::string &Fixit, SourceLocation L)
Call for initializations are invalid but that would be valid zero initialzations if Fixit was applied...
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...
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
FailureKind getFailureKind() const
Determine why initialization failed.
void InitializeFrom(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
void AddParenthesizedListInitStep(QualType T)
void SetFailed(FailureKind Failure)
Note that this initialization sequence failed.
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
void AddUnwrapInitListInitStep(InitListExpr *Syntactic)
Only used when initializing structured bindings from an array with direct-list-initialization.
void AddOCLZeroOpaqueTypeStep(QualType T)
Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.) from a zero constant.
void AddFinalCopy(QualType T)
Add a new step that makes a copy of the input to an object of the given type, as the final step in cl...
OverloadingResult getFailedOverloadResult() const
Get the overloading result, for when the initialization sequence failed due to a bad overload.
void setSequenceKind(enum SequenceKind SK)
Set the kind of sequence computed.
void AddObjCObjectConversionStep(QualType T)
Add an Objective-C object conversion step, which is always a no-op.
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
void AddExtraneousCopyToTemporary(QualType T)
Add a new step that makes an extraneous copy of the input to a temporary of the same class type.
void setIncompleteTypeFailure(QualType IncompleteType)
Note that this initialization sequence failed due to an incomplete type.
void AddOCLSamplerInitStep(QualType T)
Add a step to initialize an OpenCL sampler from an integer constant.
void AddCAssignmentStep(QualType T)
Add a C assignment step.
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
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...
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
bool Failed() const
Determine whether the initialization sequence is invalid.
void AddAtomicConversionStep(QualType Ty)
Add a new step that performs conversion from non-atomic to atomic type.
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
enum SequenceKind getKind() const
Determine the kind of initialization sequence computed.
SequenceKind
Describes the kind of initialization sequence computed.
@ NormalSequence
A normal sequence.
@ FailedSequence
A failed initialization sequence.
@ DependentSequence
A dependent initialization, which could not be type-checked due to the presence of dependent types or...
void AddReferenceBindingStep(QualType T, bool BindingTemporary)
Add a new step binding a reference to an object.
FailureKind
Describes why initialization failed.
@ FK_UserConversionOverloadFailed
Overloading for a user-defined conversion failed.
@ FK_NarrowStringIntoWideCharArray
Initializing a wide char array with narrow string literal.
@ FK_ArrayTypeMismatch
Array type mismatch.
@ FK_ParenthesizedListInitForReference
Reference initialized from a parenthesized initializer list.
@ FK_NonConstLValueReferenceBindingToVectorElement
Non-const lvalue reference binding to a vector element.
@ FK_ReferenceInitDropsQualifiers
Reference binding drops qualifiers.
@ FK_InitListBadDestinationType
Initialization of some unused destination type with an initializer list.
@ FK_ConversionFromPropertyFailed
Implicit conversion failed.
@ FK_NonConstLValueReferenceBindingToUnrelated
Non-const lvalue reference binding to an lvalue of unrelated type.
@ FK_ListConstructorOverloadFailed
Overloading for list-initialization by constructor failed.
@ FK_ReferenceInitFailed
Reference binding failed.
@ FK_ArrayNeedsInitList
Array must be initialized with an initializer list.
@ FK_PlainStringIntoUTF8Char
Initializing char8_t array with plain string literal.
@ FK_NonConstantArrayInit
Non-constant array initializer.
@ FK_NonConstLValueReferenceBindingToTemporary
Non-const lvalue reference binding to a temporary.
@ FK_ConversionFailed
Implicit conversion failed.
@ FK_ArrayNeedsInitListOrStringLiteral
Array must be initialized with an initializer list or a string literal.
@ FK_ParenthesizedListInitForScalar
Scalar initialized from a parenthesized initializer list.
@ FK_HLSLInitListFlatteningFailed
HLSL initialization list flattening failed.
@ FK_PlaceholderType
Initializer has a placeholder type which cannot be resolved by initialization.
@ FK_IncompatWideStringIntoWideChar
Initializing wide char array with incompatible wide string literal.
@ FK_NonConstLValueReferenceBindingToMatrixElement
Non-const lvalue reference binding to a matrix element.
@ FK_TooManyInitsForReference
Too many initializers provided for a reference.
@ FK_NonConstLValueReferenceBindingToBitfield
Non-const lvalue reference binding to a bit-field.
@ FK_ReferenceAddrspaceMismatchTemporary
Reference with mismatching address space binding to temporary.
@ FK_ListInitializationFailed
List initialization failed at some point.
@ FK_TooManyInitsForScalar
Too many initializers for scalar.
@ FK_AddressOfOverloadFailed
Cannot resolve the address of an overloaded function.
@ FK_VariableLengthArrayHasInitializer
Variable-length array must not have an initializer.
@ FK_ArrayNeedsInitListOrWideStringLiteral
Array must be initialized with an initializer list or a wide string literal.
@ FK_RValueReferenceBindingToLValue
Rvalue reference binding to an lvalue.
@ FK_Incomplete
Initialization of an incomplete type.
@ FK_WideStringIntoCharArray
Initializing char array with wide string literal.
@ FK_ExplicitConstructor
List-copy-initialization chose an explicit constructor.
@ FK_ReferenceInitOverloadFailed
Overloading due to reference initialization failed.
@ FK_ConstructorOverloadFailed
Overloading for initialization by constructor failed.
@ FK_ReferenceBindingToInitList
Reference initialization from an initializer list.
@ FK_DefaultInitOfConst
Default-initialization of a 'const' object.
@ FK_ParenthesizedListInitFailed
Parenthesized list initialization failed at some point.
@ FK_AddressOfUnaddressableFunction
Trying to take the address of a function that doesn't support having its address taken.
@ FK_UTF8StringIntoPlainChar
Initializing char array with UTF-8 string literal.
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init....
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
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...
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
SmallVectorImpl< Step >::const_iterator step_iterator
OverloadCandidateSet & getFailedCandidateSet()
Retrieve a reference to the candidate set when overload resolution fails.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
VD Variable
When Kind == EK_Variable, EK_Member, EK_Binding, or EK_TemplateParameter, the variable,...
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a member subobject.
EntityKind getKind() const
Determine the kind of initialization.
DeclarationName getName() const
Retrieve the name of the entity being initialized.
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
bool isImplicitMemberInitializer() const
Is this the implicit initialization of a member of a class from a defaulted constructor?
const InitializedEntity * getParent() const
Retrieve the parent of the entity being initialized, when the initialization itself is occurring with...
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
bool isParameterConsumed() const
Determine whether this initialization consumes the parameter.
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
unsigned getElementIndex() const
If this is an array, vector, or complex number element, get the element's index.
void setElementIndex(unsigned Index)
If this is already the initializer for an array or vector element, sets the element index.
SourceLocation getCaptureLoc() const
Determine the location of the capture when initializing field from a captured variable in a lambda.
bool isParamOrTemplateParamKind() const
llvm::PointerIntPair< const CXXBaseSpecifier *, 1 > Base
When Kind == EK_Base, the base specifier that provides the base class.
bool allowsNRVO() const
Determine whether this initialization allows the named return value optimization, which also applies ...
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
EntityKind
Specifies the kind of entity being initialized.
@ EK_Variable
The entity being initialized is a variable.
@ EK_Temporary
The entity being initialized is a temporary object.
@ EK_Binding
The entity being initialized is a structured binding of a decomposition declaration.
@ EK_BlockElement
The entity being initialized is a field of block descriptor for the copied-in c++ object.
@ EK_MatrixElement
The entity being initialized is an element of a matrix.
@ EK_Parameter_CF_Audited
The entity being initialized is a function parameter; function is member of group of audited CF APIs.
@ EK_LambdaToBlockConversionBlockElement
The entity being initialized is a field of block descriptor for the copied-in lambda object that's us...
@ EK_Member
The entity being initialized is a non-static data member subobject.
@ EK_Base
The entity being initialized is a base member subobject.
@ EK_Result
The entity being initialized is the result of a function call.
@ EK_TemplateParameter
The entity being initialized is a non-type template parameter.
@ EK_StmtExprResult
The entity being initialized is the result of a statement expression.
@ EK_ParenAggInitMember
The entity being initialized is a non-static data member subobject of an object initialized via paren...
@ EK_VectorElement
The entity being initialized is an element of a vector.
@ EK_New
The entity being initialized is an object (or array of objects) allocated via new.
@ EK_CompoundLiteralInit
The entity being initialized is the initializer for a compound literal.
@ EK_Parameter
The entity being initialized is a function parameter.
@ EK_Delegating
The initialization is being done by a delegating constructor.
@ EK_ComplexElement
The entity being initialized is the real or imaginary part of a complex number.
@ EK_ArrayElement
The entity being initialized is an element of an array.
@ EK_LambdaCapture
The entity being initialized is the field that captures a variable in a lambda.
@ EK_Exception
The entity being initialized is an exception object that is being thrown.
@ EK_RelatedResult
The entity being implicitly initialized back to the formal result type.
static InitializedEntity InitializeMemberFromParenAggInit(FieldDecl *Member)
Create the initialization entity for a member subobject initialized via parenthesized aggregate init.
SourceLocation getThrowLoc() const
Determine the location of the 'throw' keyword when initializing an exception object.
unsigned Index
When Kind == EK_ArrayElement, EK_VectorElement, EK_MatrixElement, or EK_ComplexElement,...
bool isVariableLengthArrayNew() const
Determine whether this is an array new with an unknown bound.
llvm::PointerIntPair< ParmVarDecl *, 1 > Parameter
When Kind == EK_Parameter, the ParmVarDecl, with the integer indicating whether the parameter is "con...
const CXXBaseSpecifier * getBaseSpecifier() const
Retrieve the base specifier.
SourceLocation getReturnLoc() const
Determine the location of the 'return' keyword when initializing the result of a function call.
TypeSourceInfo * getTypeSourceInfo() const
Retrieve complete type-source information for the object being constructed, if known.
ObjCMethodDecl * getMethodDecl() const
Retrieve the ObjectiveC method being initialized.
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3731
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1075
Represents the results of name lookup.
Definition Lookup.h:147
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4973
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4998
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4451
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4465
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
Represent a C++ namespace.
Definition Decl.h:593
Represents a place-holder for an object not to be initialized by anything.
Definition Expr.h:5927
QualType getEncodedType() const
Definition ExprObjC.h:459
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition ExprObjC.h:1614
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1161
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition Overload.h:1487
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1409
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1182
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1177
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
CandidateSetKind getKind() const
Definition Overload.h:1350
Represents a parameter to a function.
Definition Decl.h:1820
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8585
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8590
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3718
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
QualType withConst() const
Definition TypeBase.h:1175
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8501
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8627
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8541
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8686
QualType getCanonicalType() const
Definition TypeBase.h:8553
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8595
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8574
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8622
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
bool hasConst() const
Definition TypeBase.h:458
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition TypeBase.h:647
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasAddressSpace() const
Definition TypeBase.h:571
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:709
Qualifiers withoutAddressSpace() const
Definition TypeBase.h:539
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:436
bool hasVolatile() const
Definition TypeBase.h:468
bool hasObjCLifetime() const
Definition TypeBase.h:545
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:534
LangAS getAddressSpace() const
Definition TypeBase.h:572
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3749
Represents a struct/union/class.
Definition Decl.h:4460
field_iterator field_end() const
Definition Decl.h:4666
field_range fields() const
Definition Decl.h:4663
bool isRandomized() const
Definition Decl.h:4618
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4644
bool hasUninitializedExplicitInitFields() const
Definition Decl.h:4586
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
bool field_empty() const
Definition Decl.h:4671
field_iterator field_begin() const
Definition Decl.cpp:5339
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
bool isSpelledAsLValue() const
Definition TypeBase.h:3700
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool transformInitList(const InitializedEntity &Entity, InitListExpr *Init)
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9370
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9378
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:169
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, 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 ...
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10444
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10447
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10453
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10451
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
Preprocessor & getPreprocessor() const
Definition Sema.h:934
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6965
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2079
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:6977
ASTContext & Context
Definition Sema.h:1304
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:701
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:228
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...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition Sema.h:1516
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....
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:764
ASTContext & getASTContext() const
Definition Sema.h:935
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:777
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition Sema.h:9056
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition Sema.h:928
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, 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...
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
SemaHLSL & HLSL()
Definition Sema.h:1481
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:79
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7001
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10472
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8217
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8084
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7013
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1444
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8209
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14055
SourceManager & getSourceManager() const
Definition Sema.h:933
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity, const InitializationKind &Kind, AssignmentAction Action, QualType LHSType, Expr *RHSExpr)
Perform Bounds Safety Semantic checks for initializing a Bounds Safety pointer.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13798
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15594
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
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,...
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:127
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6776
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
SourceManager & SourceMgr
Definition Sema.h:1307
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
DiagnosticsEngine & Diags
Definition Sema.h:1306
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:929
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
friend class InitializationSequence
Definition Sema.h:1586
CXXDeductionGuideDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:646
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...
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,...
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the beginning of the immediate macro expansion.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false, bool AllowRelaxedEval=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
QualType getToType(unsigned Idx) const
Definition Overload.h:411
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1819
unsigned getLength() const
Definition Expr.h:1944
StringLiteralKind getKind() const
Definition Expr.h:1948
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
Definition Expr.h:1920
StringRef getString() const
Definition Expr.h:1887
bool isUnion() const
Definition Decl.h:4063
bool isBigEndian() const
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isDependent() const
Determines whether this is a dependent template name.
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8472
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8483
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9110
bool isBooleanType() const
Definition TypeBase.h:9247
bool isMFloat8Type() const
Definition TypeBase.h:9135
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9297
bool isIncompleteArrayType() const
Definition TypeBase.h:8845
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
bool isRValueReferenceType() const
Definition TypeBase.h:8770
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8837
bool isCharType() const
Definition Type.cpp:2223
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isConstantMatrixType() const
Definition TypeBase.h:8905
bool isArrayParameterType() const
Definition TypeBase.h:8853
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9154
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9404
bool isReferenceType() const
Definition TypeBase.h:8762
bool isEnumeralType() const
Definition TypeBase.h:8869
bool isScalarType() const
Definition TypeBase.h:9216
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1984
bool isChar8Type() const
Definition Type.cpp:2239
bool isSizelessBuiltinType() const
Definition Type.cpp:2655
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isExtVectorType() const
Definition TypeBase.h:8881
bool isOCLIntelSubgroupAVCType() const
Definition TypeBase.h:9023
bool isLValueReferenceType() const
Definition TypeBase.h:8766
bool isOpenCLSpecificType() const
Definition TypeBase.h:9038
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2535
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8873
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2139
bool isQueueT() const
Definition TypeBase.h:8994
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9290
bool isAtomicType() const
Definition TypeBase.h:8930
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8901
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isObjCObjectType() const
Definition TypeBase.h:8921
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9390
bool isEventT() const
Definition TypeBase.h:8986
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2559
bool isFunctionType() const
Definition TypeBase.h:8734
bool isObjCObjectPointerType() const
Definition TypeBase.h:8917
bool isVectorType() const
Definition TypeBase.h:8877
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isFloatingType() const
Definition Type.cpp:2421
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:2364
bool isSamplerT() const
Definition TypeBase.h:8982
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9337
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9147
bool isRecordType() const
Definition TypeBase.h:8865
bool isObjCRetainableType() const
Definition Type.cpp:5468
bool isUnionType() const
Definition Type.cpp:755
DeclClass * getCorrectionDeclAs() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
const Expr * getInit() const
Definition Decl.h:1392
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1191
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1251
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4080
Represents a GCC generic vector type.
Definition TypeBase.h:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
VectorKind getVectorKind() const
Definition TypeBase.h:4309
QualType getElementType() const
Definition TypeBase.h:4303
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
void checkInitLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ ovl_fail_bad_conversion
Definition Overload.h:863
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
CXXConstructionKind
Definition ExprCXX.h:1544
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:341
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:340
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ Template
We are parsing a template declaration.
Definition Parser.h:81
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:683
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:685
ExprResult ExprError()
Definition Ownership.h:265
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:217
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
Expr * IgnoreParensSingleStep(Expr *E)
Definition IgnoreExpr.h:157
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1520
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2252
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:432
@ Implicit
An implicit conversion.
Definition Sema.h:434
@ CStyleCast
A C-style cast.
Definition Sema.h:436
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:440
@ FunctionalCast
A functional-style cast.
Definition Sema.h:438
unsigned long uint64_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
CXXConstructorDecl * Constructor
Definition Overload.h:1512
DeclAccessPair FoundDecl
Definition Overload.h:1511
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:934
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1016
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:957
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:964
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6887
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6855
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6893
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6910
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:507