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 (Entity.getType()->isIntegerType() ||
567 Entity.getType()->isRealFloatingType())) {
568 unsigned ArrIndex = Entity.getElementIndex();
569 auto *AType =
570 SemaRef.Context.getAsArrayType(Entity.getParent()->getType());
571 assert(AType && "expected array type when initializing array");
572 ElsCount = Embed->getDataElementCount();
573 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
574 ElsCount = std::min(CAType->getSize().getZExtValue() - ArrIndex,
575 ElsCount - CurEmbedIndex);
576 if (ElsCount == Embed->getDataElementCount()) {
577 CurEmbed = nullptr;
578 CurEmbedIndex = 0;
579 return Embed;
580 }
581 }
582
583 Result = new (SemaRef.Context)
584 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
585 CurEmbedIndex, ElsCount);
586 CurEmbedIndex += ElsCount;
587 if (CurEmbedIndex >= Embed->getDataElementCount()) {
588 CurEmbed = nullptr;
589 CurEmbedIndex = 0;
590 }
591 return Result;
592 }
593
594public:
595 InitListChecker(
596 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
597 bool VerifyOnly, bool TreatUnavailableAsInvalid,
598 bool InOverloadResolution = false,
599 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
600 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
601 QualType &T,
602 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
603 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
604 /*TreatUnavailableAsInvalid=*/false,
605 /*InOverloadResolution=*/false,
606 &AggrDeductionCandidateParamTypes) {}
607
608 bool HadError() { return hadError; }
609
610 // Retrieves the fully-structured initializer list used for
611 // semantic analysis and code generation.
612 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
613};
614
615} // end anonymous namespace
616
617ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
618 const InitializedEntity &Entity) {
620 true);
621 MultiExprArg SubInit;
622 Expr *InitExpr;
623 InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc,
624 /*isExplicit=*/false);
625
626 // C++ [dcl.init.aggr]p7:
627 // If there are fewer initializer-clauses in the list than there are
628 // members in the aggregate, then each member not explicitly initialized
629 // ...
630 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
632 if (EmptyInitList) {
633 // C++1y / DR1070:
634 // shall be initialized [...] from an empty initializer list.
635 //
636 // We apply the resolution of this DR to C++11 but not C++98, since C++98
637 // does not have useful semantics for initialization from an init list.
638 // We treat this as copy-initialization, because aggregate initialization
639 // always performs copy-initialization on its elements.
640 //
641 // Only do this if we're initializing a class type, to avoid filling in
642 // the initializer list where possible.
643 InitExpr = VerifyOnly ? &DummyInitList
644 : new (SemaRef.Context)
645 InitListExpr(SemaRef.Context, Loc, {}, Loc,
646 /*isExplicit=*/false);
647 InitExpr->setType(SemaRef.Context.VoidTy);
648 SubInit = InitExpr;
650 } else {
651 // C++03:
652 // shall be value-initialized.
653 }
654
655 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
656 // HACK: libstdc++ prior to 4.9 marks the vector default constructor
657 // as explicit in _GLIBCXX_DEBUG mode, so recover using the C++03 logic
658 // in that case. stlport does so too.
659 // Look for std::__debug for libstdc++, and for std:: for stlport.
660 // This is effectively a compiler-side implementation of LWG2193.
661 if (!InitSeq && EmptyInitList &&
662 InitSeq.getFailureKind() ==
664 SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2014'04'22)) {
667 InitSeq.getFailedCandidateSet()
668 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
669 (void)O;
670 assert(O == OR_Success && "Inconsistent overload resolution");
671 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
672 CXXRecordDecl *R = CtorDecl->getParent();
673
674 if (CtorDecl->getMinRequiredArguments() == 0 &&
675 CtorDecl->isExplicit() && R->getDeclName() &&
676 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
677 bool IsInStd = false;
678 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
679 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
681 IsInStd = true;
682 }
683
684 if (IsInStd &&
685 llvm::StringSwitch<bool>(R->getName())
686 .Cases({"basic_string", "deque", "forward_list"}, true)
687 .Cases({"list", "map", "multimap", "multiset"}, true)
688 .Cases({"priority_queue", "queue", "set", "stack"}, true)
689 .Cases({"unordered_map", "unordered_set", "vector"}, true)
690 .Default(false)) {
691 InitSeq.InitializeFrom(
692 SemaRef, Entity,
693 InitializationKind::CreateValue(Loc, Loc, Loc, true),
694 MultiExprArg(), /*TopLevelOfInitList=*/false,
695 TreatUnavailableAsInvalid);
696 // Emit a warning for this. System header warnings aren't shown
697 // by default, but people working on system headers should see it.
698 if (!VerifyOnly) {
699 SemaRef.Diag(CtorDecl->getLocation(),
700 diag::warn_invalid_initializer_from_system_header);
702 SemaRef.Diag(Entity.getDecl()->getLocation(),
703 diag::note_used_in_initialization_here);
704 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
705 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
706 }
707 }
708 }
709 }
710 if (!InitSeq) {
711 if (!VerifyOnly) {
712 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
714 SemaRef.Diag(Entity.getDecl()->getLocation(),
715 diag::note_in_omitted_aggregate_initializer)
716 << /*field*/1 << Entity.getDecl();
717 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
718 bool IsTrailingArrayNewMember =
719 Entity.getParent() &&
721 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
722 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
723 << Entity.getElementIndex();
724 }
725 }
726 hadError = true;
727 return ExprError();
728 }
729
730 return VerifyOnly ? ExprResult()
731 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
732}
733
734void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
735 SourceLocation Loc) {
736 // If we're building a fully-structured list, we'll check this at the end
737 // once we know which elements are actually initialized. Otherwise, we know
738 // that there are no designators so we can just check now.
739 if (FullyStructuredList)
740 return;
741 PerformEmptyInit(Loc, Entity);
742}
743
744void InitListChecker::FillInEmptyInitForBase(
745 unsigned Init, const CXXBaseSpecifier &Base,
746 const InitializedEntity &ParentEntity, InitListExpr *ILE,
747 bool &RequiresSecondPass, bool FillWithNoInit) {
749 SemaRef.Context, &Base, false, &ParentEntity);
750
751 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
752 ExprResult BaseInit = FillWithNoInit
753 ? new (SemaRef.Context) NoInitExpr(Base.getType())
754 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
755 if (BaseInit.isInvalid()) {
756 hadError = true;
757 return;
758 }
759
760 if (!VerifyOnly) {
761 assert(Init < ILE->getNumInits() && "should have been expanded");
762 ILE->setInit(Init, BaseInit.getAs<Expr>());
763 }
764 } else if (InitListExpr *InnerILE =
765 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
766 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
767 ILE, Init, FillWithNoInit);
768 } else if (DesignatedInitUpdateExpr *InnerDIUE =
769 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
770 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
771 RequiresSecondPass, ILE, Init,
772 /*FillWithNoInit =*/true);
773 }
774}
775
776void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
777 const InitializedEntity &ParentEntity,
778 InitListExpr *ILE,
779 bool &RequiresSecondPass,
780 bool FillWithNoInit) {
781 SourceLocation Loc = ILE->getEndLoc();
782 unsigned NumInits = ILE->getNumInits();
783 InitializedEntity MemberEntity
784 = InitializedEntity::InitializeMember(Field, &ParentEntity);
785
786 if (Init >= NumInits || !ILE->getInit(Init)) {
787 if (const RecordType *RType = ILE->getType()->getAsCanonical<RecordType>())
788 if (!RType->getDecl()->isUnion())
789 assert((Init < NumInits || VerifyOnly) &&
790 "This ILE should have been expanded");
791
792 if (FillWithNoInit) {
793 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
794 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
795 if (Init < NumInits)
796 ILE->setInit(Init, Filler);
797 else
798 ILE->updateInit(SemaRef.Context, Init, Filler);
799 return;
800 }
801
802 if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>() &&
803 !SemaRef.isUnevaluatedContext()) {
804 SemaRef.Diag(ILE->getExprLoc(), diag::warn_field_requires_explicit_init)
805 << /* Var-in-Record */ 0 << Field;
806 SemaRef.Diag(Field->getLocation(), diag::note_entity_declared_at)
807 << Field;
808 }
809
810 // C++1y [dcl.init.aggr]p7:
811 // If there are fewer initializer-clauses in the list than there are
812 // members in the aggregate, then each member not explicitly initialized
813 // shall be initialized from its brace-or-equal-initializer [...]
814 if (Field->hasInClassInitializer()) {
815 if (VerifyOnly)
816 return;
817
818 // A default member initializer used in aggregate initialization is part
819 // of the full-expression containing the aggregate initialization. Do not
820 // create or finish a separate expression evaluation context here.
821 ExprResult DIE =
822 SemaRef.BuildCXXAggregateDefaultInitExpr(Loc, Field, MemberEntity);
823 if (DIE.isInvalid()) {
824 hadError = true;
825 return;
826 }
827 if (Init < NumInits)
828 ILE->setInit(Init, DIE.get());
829 else {
830 ILE->updateInit(SemaRef.Context, Init, DIE.get());
831 RequiresSecondPass = true;
832 }
833 return;
834 }
835
836 if (Field->getType()->isReferenceType()) {
837 if (!VerifyOnly) {
838 // C++ [dcl.init.aggr]p9:
839 // If an incomplete or empty initializer-list leaves a
840 // member of reference type uninitialized, the program is
841 // ill-formed.
842 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
843 << Field->getType()
844 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
845 ->getSourceRange();
846 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
847 }
848 hadError = true;
849 return;
850 }
851
852 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
853 if (MemberInit.isInvalid()) {
854 hadError = true;
855 return;
856 }
857
858 if (hadError || VerifyOnly) {
859 // Do nothing
860 } else if (Init < NumInits) {
861 ILE->setInit(Init, MemberInit.getAs<Expr>());
862 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
863 // Empty initialization requires a constructor call, so
864 // extend the initializer list to include the constructor
865 // call and make a note that we'll need to take another pass
866 // through the initializer list.
867 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
868 RequiresSecondPass = true;
869 }
870 } else if (InitListExpr *InnerILE
871 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
872 FillInEmptyInitializations(MemberEntity, InnerILE,
873 RequiresSecondPass, ILE, Init, FillWithNoInit);
874 } else if (DesignatedInitUpdateExpr *InnerDIUE =
875 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
876 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
877 RequiresSecondPass, ILE, Init,
878 /*FillWithNoInit =*/true);
879 }
880}
881
882/// Recursively replaces NULL values within the given initializer list
883/// with expressions that perform value-initialization of the
884/// appropriate type, and finish off the InitListExpr formation.
885void
886InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
887 InitListExpr *ILE,
888 bool &RequiresSecondPass,
889 InitListExpr *OuterILE,
890 unsigned OuterIndex,
891 bool FillWithNoInit) {
892 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
893 "Should not have void type");
894
895 // We don't need to do any checks when just filling NoInitExprs; that can't
896 // fail.
897 if (FillWithNoInit && VerifyOnly)
898 return;
899
900 // If this is a nested initializer list, we might have changed its contents
901 // (and therefore some of its properties, such as instantiation-dependence)
902 // while filling it in. Inform the outer initializer list so that its state
903 // can be updated to match.
904 // FIXME: We should fully build the inner initializers before constructing
905 // the outer InitListExpr instead of mutating AST nodes after they have
906 // been used as subexpressions of other nodes.
907 struct UpdateOuterILEWithUpdatedInit {
908 InitListExpr *Outer;
909 unsigned OuterIndex;
910 ~UpdateOuterILEWithUpdatedInit() {
911 if (Outer)
912 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
913 }
914 } UpdateOuterRAII = {OuterILE, OuterIndex};
915
916 // A transparent ILE is not performing aggregate initialization and should
917 // not be filled in.
918 if (ILE->isTransparent())
919 return;
920
921 if (const auto *RDecl = ILE->getType()->getAsRecordDecl()) {
922 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
923 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,
924 RequiresSecondPass, FillWithNoInit);
925 } else {
926 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
927 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
928 "We should have computed initialized fields already");
929 // The fields beyond ILE->getNumInits() are default initialized, so in
930 // order to leave them uninitialized, the ILE is expanded and the extra
931 // fields are then filled with NoInitExpr.
932 unsigned NumElems = numStructUnionElements(ILE->getType());
933 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
934 ++NumElems;
935 if (!VerifyOnly && ILE->getNumInits() < NumElems)
936 ILE->resizeInits(SemaRef.Context, NumElems);
937
938 unsigned Init = 0;
939
940 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
941 for (auto &Base : CXXRD->bases()) {
942 if (hadError)
943 return;
944
945 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
946 FillWithNoInit);
947 ++Init;
948 }
949 }
950
951 for (auto *Field : RDecl->fields()) {
952 if (Field->isUnnamedBitField())
953 continue;
954
955 if (hadError)
956 return;
957
958 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
959 FillWithNoInit);
960 if (hadError)
961 return;
962
963 ++Init;
964
965 // Only look at the first initialization of a union.
966 if (RDecl->isUnion())
967 break;
968 }
969 }
970
971 return;
972 }
973
974 QualType ElementType;
975
976 InitializedEntity ElementEntity = Entity;
977 unsigned NumInits = ILE->getNumInits();
978 uint64_t NumElements = NumInits;
979 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
980 ElementType = AType->getElementType();
981 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
982 NumElements = CAType->getZExtSize();
983 // For an array new with an unknown bound, ask for one additional element
984 // in order to populate the array filler.
985 if (Entity.isVariableLengthArrayNew())
986 ++NumElements;
987 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
988 0, Entity);
989 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
990 ElementType = VType->getElementType();
991 NumElements = VType->getNumElements();
992 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
993 0, Entity);
994 } else
995 ElementType = ILE->getType();
996
997 bool SkipEmptyInitChecks = false;
998 for (uint64_t Init = 0; Init != NumElements; ++Init) {
999 if (hadError)
1000 return;
1001
1002 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
1003 ElementEntity.getKind() == InitializedEntity::EK_VectorElement ||
1005 ElementEntity.setElementIndex(Init);
1006
1007 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
1008 return;
1009
1010 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
1011 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
1012 ILE->setInit(Init, ILE->getArrayFiller());
1013 else if (!InitExpr && !ILE->hasArrayFiller()) {
1014 // In VerifyOnly mode, there's no point performing empty initialization
1015 // more than once.
1016 if (SkipEmptyInitChecks)
1017 continue;
1018
1019 Expr *Filler = nullptr;
1020
1021 if (FillWithNoInit)
1022 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
1023 else {
1024 ExprResult ElementInit =
1025 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
1026 if (ElementInit.isInvalid()) {
1027 hadError = true;
1028 return;
1029 }
1030
1031 Filler = ElementInit.getAs<Expr>();
1032 }
1033
1034 if (hadError) {
1035 // Do nothing
1036 } else if (VerifyOnly) {
1037 SkipEmptyInitChecks = true;
1038 } else if (Init < NumInits) {
1039 // For arrays, just set the expression used for value-initialization
1040 // of the "holes" in the array.
1041 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
1042 ILE->setArrayFiller(Filler);
1043 else
1044 ILE->setInit(Init, Filler);
1045 } else {
1046 // For arrays, just set the expression used for value-initialization
1047 // of the rest of elements and exit.
1048 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
1049 ILE->setArrayFiller(Filler);
1050 return;
1051 }
1052
1053 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
1054 // Empty initialization requires a constructor call, so
1055 // extend the initializer list to include the constructor
1056 // call and make a note that we'll need to take another pass
1057 // through the initializer list.
1058 ILE->updateInit(SemaRef.Context, Init, Filler);
1059 RequiresSecondPass = true;
1060 }
1061 }
1062 } else if (InitListExpr *InnerILE
1063 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
1064 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
1065 ILE, Init, FillWithNoInit);
1066 } else if (DesignatedInitUpdateExpr *InnerDIUE =
1067 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
1068 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1069 RequiresSecondPass, ILE, Init,
1070 /*FillWithNoInit =*/true);
1071 }
1072 }
1073}
1074
1075static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1076 for (const Stmt *Init : *IL)
1077 if (isa_and_nonnull<DesignatedInitExpr>(Init))
1078 return true;
1079 return false;
1080}
1081
1082InitListChecker::InitListChecker(
1083 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1084 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1085 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1086 : SemaRef(S), VerifyOnly(VerifyOnly),
1087 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1088 InOverloadResolution(InOverloadResolution),
1089 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1090 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1091 FullyStructuredList = createInitListExpr(
1092 T, IL->getSourceRange(), IL->getNumInits(), IL->isExplicit());
1093
1094 // FIXME: Check that IL isn't already the semantic form of some other
1095 // InitListExpr. If it is, we'd create a broken AST.
1096 if (!VerifyOnly)
1097 FullyStructuredList->setSyntacticForm(IL);
1098 }
1099
1100 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1101 /*TopLevelObject=*/true);
1102
1103 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1104 bool RequiresSecondPass = false;
1105 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1106 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1107 if (RequiresSecondPass && !hadError)
1108 FillInEmptyInitializations(Entity, FullyStructuredList,
1109 RequiresSecondPass, nullptr, 0);
1110 }
1111 if (hadError && FullyStructuredList)
1112 FullyStructuredList->markError();
1113}
1114
1115int InitListChecker::numArrayElements(QualType DeclType) {
1116 // FIXME: use a proper constant
1117 int maxElements = 0x7FFFFFFF;
1118 if (const ConstantArrayType *CAT =
1119 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1120 maxElements = static_cast<int>(CAT->getZExtSize());
1121 }
1122 return maxElements;
1123}
1124
1125int InitListChecker::numStructUnionElements(QualType DeclType) {
1126 auto *structDecl = DeclType->castAsRecordDecl();
1127 int InitializableMembers = 0;
1128 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1129 InitializableMembers += CXXRD->getNumBases();
1130 for (const auto *Field : structDecl->fields())
1131 if (!Field->isUnnamedBitField())
1132 ++InitializableMembers;
1133
1134 if (structDecl->isUnion())
1135 return std::min(InitializableMembers, 1);
1136 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1137}
1138
1139/// Determine whether Entity is an entity for which it is idiomatic to elide
1140/// the braces in aggregate initialization.
1142 // Recursive initialization of the one and only field within an aggregate
1143 // class is considered idiomatic. This case arises in particular for
1144 // initialization of std::array, where the C++ standard suggests the idiom of
1145 //
1146 // std::array<T, N> arr = {1, 2, 3};
1147 //
1148 // (where std::array is an aggregate struct containing a single array field.
1149
1150 if (!Entity.getParent())
1151 return false;
1152
1153 // Allows elide brace initialization for aggregates with empty base.
1154 if (Entity.getKind() == InitializedEntity::EK_Base) {
1155 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1156 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1157 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1158 }
1159
1160 // Allow brace elision if the only subobject is a field.
1161 if (Entity.getKind() == InitializedEntity::EK_Member) {
1162 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1163 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1164 if (CXXRD->getNumBases()) {
1165 return false;
1166 }
1167 }
1168 auto FieldIt = ParentRD->field_begin();
1169 assert(FieldIt != ParentRD->field_end() &&
1170 "no fields but have initializer for member?");
1171 return ++FieldIt == ParentRD->field_end();
1172 }
1173
1174 return false;
1175}
1176
1177/// Check whether the range of the initializer \p ParentIList from element
1178/// \p Index onwards can be used to initialize an object of type \p T. Update
1179/// \p Index to indicate how many elements of the list were consumed.
1180///
1181/// This also fills in \p StructuredList, from element \p StructuredIndex
1182/// onwards, with the fully-braced, desugared form of the initialization.
1183void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1184 InitListExpr *ParentIList,
1185 QualType T, unsigned &Index,
1186 InitListExpr *StructuredList,
1187 unsigned &StructuredIndex) {
1188 int maxElements = 0;
1189
1190 if (T->isArrayType())
1191 maxElements = numArrayElements(T);
1192 else if (T->isRecordType())
1193 maxElements = numStructUnionElements(T);
1194 else if (T->isVectorType())
1195 maxElements = T->castAs<VectorType>()->getNumElements();
1196 else
1197 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1198
1199 if (maxElements == 0) {
1200 if (!VerifyOnly)
1201 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1202 diag::err_implicit_empty_initializer);
1203 ++Index;
1204 hadError = true;
1205 return;
1206 }
1207
1208 // Build a structured initializer list corresponding to this subobject.
1209 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1210 ParentIList, Index, T, StructuredList, StructuredIndex,
1211 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1212 ParentIList->getSourceRange().getEnd()));
1213 unsigned StructuredSubobjectInitIndex = 0;
1214
1215 // Check the element types and build the structural subobject.
1216 unsigned StartIndex = Index;
1217 CheckListElementTypes(Entity, ParentIList, T,
1218 /*SubobjectIsDesignatorContext=*/false, Index,
1219 StructuredSubobjectInitList,
1220 StructuredSubobjectInitIndex);
1221
1222 if (StructuredSubobjectInitList) {
1223 StructuredSubobjectInitList->setType(T);
1224
1225 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1226 // Update the structured sub-object initializer so that it's ending
1227 // range corresponds with the end of the last initializer it used.
1228 if (EndIndex < ParentIList->getNumInits() &&
1229 ParentIList->getInit(EndIndex)) {
1230 SourceLocation EndLoc
1231 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1232 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1233 }
1234
1235 // Complain about missing braces.
1236 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1237 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1239 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1240 diag::warn_missing_braces)
1241 << StructuredSubobjectInitList->getSourceRange()
1243 StructuredSubobjectInitList->getBeginLoc(), "{")
1245 SemaRef.getLocForEndOfToken(
1246 StructuredSubobjectInitList->getEndLoc()),
1247 "}");
1248 }
1249
1250 // Warn if this type won't be an aggregate in future versions of C++.
1251 auto *CXXRD = T->getAsCXXRecordDecl();
1252 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1253 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1254 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1255 << StructuredSubobjectInitList->getSourceRange() << T;
1256 }
1257 }
1258}
1259
1260/// Warn that \p Entity was of scalar type and was initialized by a
1261/// single-element braced initializer list.
1262static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1264 // Don't warn during template instantiation. If the initialization was
1265 // non-dependent, we warned during the initial parse; otherwise, the
1266 // type might not be scalar in some uses of the template.
1268 return;
1269
1270 unsigned DiagID = 0;
1271
1272 switch (Entity.getKind()) {
1282 // Extra braces here are suspicious.
1283 DiagID = diag::warn_braces_around_init;
1284 break;
1285
1287 // Warn on aggregate initialization but not on ctor init list or
1288 // default member initializer.
1289 if (Entity.getParent())
1290 DiagID = diag::warn_braces_around_init;
1291 break;
1292
1295 // No warning, might be direct-list-initialization.
1296 // FIXME: Should we warn for copy-list-initialization in these cases?
1297 break;
1298
1302 // No warning, braces are part of the syntax of the underlying construct.
1303 break;
1304
1306 // No warning, we already warned when initializing the result.
1307 break;
1308
1316 llvm_unreachable("unexpected braced scalar init");
1317 }
1318
1319 if (DiagID) {
1320 S.Diag(Braces.getBegin(), DiagID)
1321 << Entity.getType()->isSizelessBuiltinType() << Braces
1322 << FixItHint::CreateRemoval(Braces.getBegin())
1323 << FixItHint::CreateRemoval(Braces.getEnd());
1324 }
1325}
1326
1327/// Check whether the initializer \p IList (that was written with explicit
1328/// braces) can be used to initialize an object of type \p T.
1329///
1330/// This also fills in \p StructuredList with the fully-braced, desugared
1331/// form of the initialization.
1332void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1333 InitListExpr *IList, QualType &T,
1334 InitListExpr *StructuredList,
1335 bool TopLevelObject) {
1336 unsigned Index = 0, StructuredIndex = 0;
1337 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1338 Index, StructuredList, StructuredIndex, TopLevelObject);
1339 if (StructuredList) {
1340 QualType ExprTy = T;
1341 if (!ExprTy->isArrayType())
1342 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1343 if (!VerifyOnly)
1344 IList->setType(ExprTy);
1345 StructuredList->setType(ExprTy);
1346 }
1347 if (hadError)
1348 return;
1349
1350 // Don't complain for incomplete types, since we'll get an error elsewhere.
1351 if ((Index < IList->getNumInits() || CurEmbed) && !T->isIncompleteType()) {
1352 // We have leftover initializers
1353 Expr *ExtraInit =
1354 Index < IList->getNumInits() ? IList->getInit(Index) : CurEmbed;
1355 SourceLocation ExtraInitLoc =
1356 ExtraInit ? ExtraInit->getBeginLoc() : IList->getEndLoc();
1357 SourceRange ExtraInitRange =
1358 ExtraInit ? ExtraInit->getSourceRange() : IList->getSourceRange();
1359 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1360 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1361 hadError = ExtraInitsIsError;
1362 if (VerifyOnly) {
1363 return;
1364 } else if (StructuredIndex == 1 && StructuredList->getNumInits() != 0 &&
1365 StructuredList->getInit(0) &&
1366 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1367 SIF_None) {
1368 unsigned DK =
1369 ExtraInitsIsError
1370 ? diag::err_excess_initializers_in_char_array_initializer
1371 : diag::ext_excess_initializers_in_char_array_initializer;
1372 SemaRef.Diag(ExtraInitLoc, DK) << ExtraInitRange;
1373 } else if (T->isSizelessBuiltinType()) {
1374 unsigned DK = ExtraInitsIsError
1375 ? diag::err_excess_initializers_for_sizeless_type
1376 : diag::ext_excess_initializers_for_sizeless_type;
1377 SemaRef.Diag(ExtraInitLoc, DK) << T << ExtraInitRange;
1378 } else {
1379 int initKind = T->isArrayType() ? 0
1380 : T->isVectorType() ? 1
1381 : T->isMatrixType() ? 2
1382 : T->isScalarType() ? 3
1383 : T->isUnionType() ? 4
1384 : 5;
1385
1386 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1387 : diag::ext_excess_initializers;
1388 SemaRef.Diag(ExtraInitLoc, DK) << initKind << ExtraInitRange;
1389 }
1390 }
1391
1392 if (!VerifyOnly) {
1393 if (T->isScalarType() && IList->getNumInits() == 1 &&
1394 !isa<InitListExpr>(IList->getInit(0)))
1395 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1396
1397 // Warn if this is a class type that won't be an aggregate in future
1398 // versions of C++.
1399 auto *CXXRD = T->getAsCXXRecordDecl();
1400 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1401 // Don't warn if there's an equivalent default constructor that would be
1402 // used instead.
1403 bool HasEquivCtor = false;
1404 if (IList->getNumInits() == 0) {
1405 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1406 HasEquivCtor = CD && !CD->isDeleted();
1407 }
1408
1409 if (!HasEquivCtor) {
1410 SemaRef.Diag(IList->getBeginLoc(),
1411 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1412 << IList->getSourceRange() << T;
1413 }
1414 }
1415 }
1416}
1417
1418void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1419 InitListExpr *IList,
1420 QualType &DeclType,
1421 bool SubobjectIsDesignatorContext,
1422 unsigned &Index,
1423 InitListExpr *StructuredList,
1424 unsigned &StructuredIndex,
1425 bool TopLevelObject) {
1426 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1427 // Explicitly braced initializer for complex type can be real+imaginary
1428 // parts.
1429 CheckComplexType(Entity, IList, DeclType, Index,
1430 StructuredList, StructuredIndex);
1431 } else if (DeclType->isScalarType()) {
1432 CheckScalarType(Entity, IList, DeclType, Index,
1433 StructuredList, StructuredIndex);
1434 } else if (DeclType->isVectorType()) {
1435 CheckVectorType(Entity, IList, DeclType, Index,
1436 StructuredList, StructuredIndex);
1437 } else if (DeclType->isMatrixType()) {
1438 CheckMatrixType(Entity, IList, DeclType, Index, StructuredList,
1439 StructuredIndex);
1440 } else if (const RecordDecl *RD = DeclType->getAsRecordDecl()) {
1441 auto Bases =
1444 if (DeclType->isRecordType()) {
1445 assert(DeclType->isAggregateType() &&
1446 "non-aggregate records should be handed in CheckSubElementType");
1447 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1448 Bases = CXXRD->bases();
1449 } else {
1450 Bases = cast<CXXRecordDecl>(RD)->bases();
1451 }
1452 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1453 SubobjectIsDesignatorContext, Index, StructuredList,
1454 StructuredIndex, TopLevelObject);
1455 } else if (DeclType->isArrayType()) {
1456 llvm::APSInt Zero(
1457 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1458 false);
1459 CheckArrayType(Entity, IList, DeclType, Zero,
1460 SubobjectIsDesignatorContext, Index,
1461 StructuredList, StructuredIndex);
1462 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1463 // This type is invalid, issue a diagnostic.
1464 ++Index;
1465 if (!VerifyOnly)
1466 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1467 << DeclType;
1468 hadError = true;
1469 } else if (DeclType->isReferenceType()) {
1470 CheckReferenceType(Entity, IList, DeclType, Index,
1471 StructuredList, StructuredIndex);
1472 } else if (DeclType->isObjCObjectType()) {
1473 if (!VerifyOnly)
1474 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1475 hadError = true;
1476 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1477 DeclType->isSizelessBuiltinType()) {
1478 // Checks for scalar type are sufficient for these types too.
1479 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1480 StructuredIndex);
1481 } else if (DeclType->isDependentType()) {
1482 // C++ [over.match.class.deduct]p1.5:
1483 // brace elision is not considered for any aggregate element that has a
1484 // dependent non-array type or an array type with a value-dependent bound
1485 ++Index;
1486 assert(AggrDeductionCandidateParamTypes);
1487 AggrDeductionCandidateParamTypes->push_back(DeclType);
1488 } else {
1489 if (!VerifyOnly)
1490 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1491 << DeclType;
1492 hadError = true;
1493 }
1494}
1495
1496void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1497 InitListExpr *IList,
1498 QualType ElemType,
1499 unsigned &Index,
1500 InitListExpr *StructuredList,
1501 unsigned &StructuredIndex,
1502 bool DirectlyDesignated) {
1503 Expr *expr = IList->getInit(Index);
1504
1505 if (ElemType->isReferenceType())
1506 return CheckReferenceType(Entity, IList, ElemType, Index,
1507 StructuredList, StructuredIndex);
1508
1509 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1510 if (SubInitList->getNumInits() == 1 &&
1511 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1512 SIF_None) {
1513 // FIXME: It would be more faithful and no less correct to include an
1514 // InitListExpr in the semantic form of the initializer list in this case.
1515 expr = SubInitList->getInit(0);
1516 }
1517 // Nested aggregate initialization and C++ initialization are handled later.
1518 } else if (isa<ImplicitValueInitExpr>(expr)) {
1519 // This happens during template instantiation when we see an InitListExpr
1520 // that we've already checked once.
1521 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1522 "found implicit initialization for the wrong type");
1523 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1524 ++Index;
1525 return;
1526 }
1527
1528 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1529 // C++ [dcl.init.aggr]p2:
1530 // Each member is copy-initialized from the corresponding
1531 // initializer-clause.
1532
1533 // FIXME: Better EqualLoc?
1534 InitializationKind Kind =
1535 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1536
1537 // Vector elements can be initialized from other vectors in which case
1538 // we need initialization entity with a type of a vector (and not a vector
1539 // element!) initializing multiple vector elements.
1540 auto TmpEntity =
1541 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1543 : Entity;
1544
1545 if (TmpEntity.getType()->isDependentType()) {
1546 // C++ [over.match.class.deduct]p1.5:
1547 // brace elision is not considered for any aggregate element that has a
1548 // dependent non-array type or an array type with a value-dependent
1549 // bound
1550 assert(AggrDeductionCandidateParamTypes);
1551
1552 // In the presence of a braced-init-list within the initializer, we should
1553 // not perform brace-elision, even if brace elision would otherwise be
1554 // applicable. For example, given:
1555 //
1556 // template <class T> struct Foo {
1557 // T t[2];
1558 // };
1559 //
1560 // Foo t = {{1, 2}};
1561 //
1562 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1563 // {{1, 2}}.
1565 !isa_and_present<ConstantArrayType>(
1566 SemaRef.Context.getAsArrayType(ElemType))) {
1567 ++Index;
1568 AggrDeductionCandidateParamTypes->push_back(ElemType);
1569 return;
1570 }
1571 } else {
1572 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1573 /*TopLevelOfInitList*/ true);
1574 // C++14 [dcl.init.aggr]p13:
1575 // If the assignment-expression can initialize a member, the member is
1576 // initialized. Otherwise [...] brace elision is assumed
1577 //
1578 // Brace elision is never performed if the element is not an
1579 // assignment-expression.
1580 if (Seq || isa<InitListExpr>(expr)) {
1581 if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1582 expr = HandleEmbed(Embed, Entity);
1583 }
1584 if (!VerifyOnly) {
1585 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1586 if (Result.isInvalid())
1587 hadError = true;
1588
1589 UpdateStructuredListElement(StructuredList, StructuredIndex,
1590 Result.getAs<Expr>());
1591 } else if (!Seq) {
1592 hadError = true;
1593 } else if (StructuredList) {
1594 UpdateStructuredListElement(StructuredList, StructuredIndex,
1595 getDummyInit());
1596 }
1597 if (!CurEmbed)
1598 ++Index;
1599 if (AggrDeductionCandidateParamTypes)
1600 AggrDeductionCandidateParamTypes->push_back(ElemType);
1601 return;
1602 }
1603 }
1604
1605 // Fall through for subaggregate initialization
1606 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1607 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1608 return CheckScalarType(Entity, IList, ElemType, Index,
1609 StructuredList, StructuredIndex);
1610 } else if (const ArrayType *arrayType =
1611 SemaRef.Context.getAsArrayType(ElemType)) {
1612 // arrayType can be incomplete if we're initializing a flexible
1613 // array member. There's nothing we can do with the completed
1614 // type here, though.
1615
1616 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1617 // FIXME: Should we do this checking in verify-only mode?
1618 if (!VerifyOnly)
1619 CheckStringInit(expr, ElemType, arrayType, SemaRef, Entity,
1620 SemaRef.getLangOpts().C23 &&
1622 if (StructuredList)
1623 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1624 ++Index;
1625 return;
1626 }
1627
1628 // Fall through for subaggregate initialization.
1629
1630 } else {
1631 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1632 ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) &&
1633 "Unexpected type");
1634
1635 // C99 6.7.8p13:
1636 //
1637 // The initializer for a structure or union object that has
1638 // automatic storage duration shall be either an initializer
1639 // list as described below, or a single expression that has
1640 // compatible structure or union type. In the latter case, the
1641 // initial value of the object, including unnamed members, is
1642 // that of the expression.
1643 ExprResult ExprRes = expr;
1644 if (SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
1645 !VerifyOnly) !=
1646 AssignConvertType::Incompatible) {
1647 if (ExprRes.isInvalid())
1648 hadError = true;
1649 else {
1650 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1651 if (ExprRes.isInvalid())
1652 hadError = true;
1653 }
1654 UpdateStructuredListElement(StructuredList, StructuredIndex,
1655 ExprRes.getAs<Expr>());
1656 ++Index;
1657 return;
1658 }
1659 ExprRes.get();
1660 // Fall through for subaggregate initialization
1661 }
1662
1663 // C++ [dcl.init.aggr]p12:
1664 //
1665 // [...] Otherwise, if the member is itself a non-empty
1666 // subaggregate, brace elision is assumed and the initializer is
1667 // considered for the initialization of the first member of
1668 // the subaggregate.
1669 // OpenCL vector initializer is handled elsewhere.
1670 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1671 ElemType->isAggregateType()) {
1672 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1673 StructuredIndex);
1674 ++StructuredIndex;
1675
1676 // In C++20, brace elision is not permitted for a designated initializer.
1677 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1678 if (InOverloadResolution)
1679 hadError = true;
1680 if (!VerifyOnly) {
1681 SemaRef.Diag(expr->getBeginLoc(),
1682 diag::ext_designated_init_brace_elision)
1683 << expr->getSourceRange()
1684 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1686 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1687 }
1688 }
1689 } else {
1690 if (!VerifyOnly) {
1691 // We cannot initialize this element, so let PerformCopyInitialization
1692 // produce the appropriate diagnostic. We already checked that this
1693 // initialization will fail.
1695 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1696 /*TopLevelOfInitList=*/true);
1697 (void)Copy;
1698 assert(Copy.isInvalid() &&
1699 "expected non-aggregate initialization to fail");
1700 }
1701 hadError = true;
1702 ++Index;
1703 ++StructuredIndex;
1704 }
1705}
1706
1707void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1708 InitListExpr *IList, QualType DeclType,
1709 unsigned &Index,
1710 InitListExpr *StructuredList,
1711 unsigned &StructuredIndex) {
1712 assert(Index == 0 && "Index in explicit init list must be zero");
1713
1714 // As an extension, clang supports complex initializers, which initialize
1715 // a complex number component-wise. When an explicit initializer list for
1716 // a complex number contains two initializers, this extension kicks in:
1717 // it expects the initializer list to contain two elements convertible to
1718 // the element type of the complex type. The first element initializes
1719 // the real part, and the second element intitializes the imaginary part.
1720
1721 if (IList->getNumInits() < 2)
1722 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1723 StructuredIndex);
1724
1725 // This is an extension in C. (The builtin _Complex type does not exist
1726 // in the C++ standard.)
1727 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1728 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1729 << IList->getSourceRange();
1730
1731 // Initialize the complex number.
1732 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1733 InitializedEntity ElementEntity =
1735
1736 for (unsigned i = 0; i < 2; ++i) {
1737 ElementEntity.setElementIndex(Index);
1738 CheckSubElementType(ElementEntity, IList, elementType, Index,
1739 StructuredList, StructuredIndex);
1740 }
1741}
1742
1743void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1744 InitListExpr *IList, QualType DeclType,
1745 unsigned &Index,
1746 InitListExpr *StructuredList,
1747 unsigned &StructuredIndex) {
1748 if (Index >= IList->getNumInits()) {
1749 if (!VerifyOnly) {
1750 if (SemaRef.getLangOpts().CPlusPlus) {
1751 if (DeclType->isSizelessBuiltinType())
1752 SemaRef.Diag(IList->getBeginLoc(),
1753 SemaRef.getLangOpts().CPlusPlus11
1754 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1755 : diag::err_empty_sizeless_initializer)
1756 << DeclType << IList->getSourceRange();
1757 else
1758 SemaRef.Diag(IList->getBeginLoc(),
1759 SemaRef.getLangOpts().CPlusPlus11
1760 ? diag::warn_cxx98_compat_empty_scalar_initializer
1761 : diag::err_empty_scalar_initializer)
1762 << IList->getSourceRange();
1763 }
1764 }
1765 hadError =
1766 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1767 ++Index;
1768 ++StructuredIndex;
1769 return;
1770 }
1771
1772 Expr *expr = IList->getInit(Index);
1773 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1774 // FIXME: This is invalid, and accepting it causes overload resolution
1775 // to pick the wrong overload in some corner cases.
1776 if (!VerifyOnly)
1777 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1778 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1779
1780 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1781 StructuredIndex);
1782 return;
1783 } else if (isa<DesignatedInitExpr>(expr)) {
1784 if (!VerifyOnly)
1785 SemaRef.Diag(expr->getBeginLoc(),
1786 diag::err_designator_for_scalar_or_sizeless_init)
1787 << DeclType->isSizelessBuiltinType() << DeclType
1788 << expr->getSourceRange();
1789 hadError = true;
1790 ++Index;
1791 ++StructuredIndex;
1792 return;
1793 } else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1794 expr = HandleEmbed(Embed, Entity);
1795 }
1796
1798 if (VerifyOnly) {
1799 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1800 Result = getDummyInit();
1801 else
1802 Result = ExprError();
1803 } else {
1804 Result =
1805 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1806 /*TopLevelOfInitList=*/true);
1807 }
1808
1809 Expr *ResultExpr = nullptr;
1810
1811 if (Result.isInvalid())
1812 hadError = true; // types weren't compatible.
1813 else {
1814 ResultExpr = Result.getAs<Expr>();
1815
1816 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1817 // The type was promoted, update initializer list.
1818 // FIXME: Why are we updating the syntactic init list?
1819 IList->setInit(Index, ResultExpr);
1820 }
1821 }
1822
1823 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1824 if (!CurEmbed)
1825 ++Index;
1826 if (AggrDeductionCandidateParamTypes)
1827 AggrDeductionCandidateParamTypes->push_back(DeclType);
1828}
1829
1830void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1831 InitListExpr *IList, QualType DeclType,
1832 unsigned &Index,
1833 InitListExpr *StructuredList,
1834 unsigned &StructuredIndex) {
1835 if (Index >= IList->getNumInits()) {
1836 // FIXME: It would be wonderful if we could point at the actual member. In
1837 // general, it would be useful to pass location information down the stack,
1838 // so that we know the location (or decl) of the "current object" being
1839 // initialized.
1840 if (!VerifyOnly)
1841 SemaRef.Diag(IList->getBeginLoc(),
1842 diag::err_init_reference_member_uninitialized)
1843 << DeclType << IList->getSourceRange();
1844 hadError = true;
1845 ++Index;
1846 ++StructuredIndex;
1847 return;
1848 }
1849
1850 Expr *expr = IList->getInit(Index);
1851 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1852 if (!VerifyOnly)
1853 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1854 << DeclType << IList->getSourceRange();
1855 hadError = true;
1856 ++Index;
1857 ++StructuredIndex;
1858 return;
1859 }
1860
1862 if (VerifyOnly) {
1863 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1864 Result = getDummyInit();
1865 else
1866 Result = ExprError();
1867 } else {
1868 Result =
1869 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1870 /*TopLevelOfInitList=*/true);
1871 }
1872
1873 if (Result.isInvalid())
1874 hadError = true;
1875
1876 expr = Result.getAs<Expr>();
1877 // FIXME: Why are we updating the syntactic init list?
1878 if (!VerifyOnly && expr)
1879 IList->setInit(Index, expr);
1880
1881 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1882 ++Index;
1883 if (AggrDeductionCandidateParamTypes)
1884 AggrDeductionCandidateParamTypes->push_back(DeclType);
1885}
1886
1887void InitListChecker::CheckMatrixType(const InitializedEntity &Entity,
1888 InitListExpr *IList, QualType DeclType,
1889 unsigned &Index,
1890 InitListExpr *StructuredList,
1891 unsigned &StructuredIndex) {
1892 if (!SemaRef.getLangOpts().HLSL)
1893 return;
1894
1895 const ConstantMatrixType *MT = DeclType->castAs<ConstantMatrixType>();
1896
1897 // For HLSL, the error reporting for this case is handled in SemaHLSL's
1898 // initializer list diagnostics. That means the execution should require
1899 // getNumElementsFlattened to equal getNumInits. In other words the execution
1900 // should never reach this point if this condition is not true".
1901 assert(IList->getNumInits() == MT->getNumElementsFlattened() &&
1902 "Inits must equal Matrix element count");
1903
1904 QualType ElemTy = MT->getElementType();
1905
1906 Index = 0;
1907 InitializedEntity Element =
1909
1910 while (Index < IList->getNumInits()) {
1911 // Not a sublist: just consume directly.
1912 // Note: In HLSL, elements of the InitListExpr are in row-major order, so no
1913 // change is needed to the Index.
1914 Element.setElementIndex(Index);
1915 CheckSubElementType(Element, IList, ElemTy, Index, StructuredList,
1916 StructuredIndex);
1917 }
1918}
1919
1920void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1921 InitListExpr *IList, QualType DeclType,
1922 unsigned &Index,
1923 InitListExpr *StructuredList,
1924 unsigned &StructuredIndex) {
1925 const VectorType *VT = DeclType->castAs<VectorType>();
1926 unsigned maxElements = VT->getNumElements();
1927 unsigned numEltsInit = 0;
1928 QualType elementType = VT->getElementType();
1929
1930 if (Index >= IList->getNumInits()) {
1931 // Make sure the element type can be value-initialized.
1932 CheckEmptyInitializable(
1934 IList->getEndLoc());
1935 return;
1936 }
1937
1938 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1939 // If the initializing element is a vector, try to copy-initialize
1940 // instead of breaking it apart (which is doomed to failure anyway).
1941 Expr *Init = IList->getInit(Index);
1942 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1944 if (VerifyOnly) {
1945 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1946 Result = getDummyInit();
1947 else
1948 Result = ExprError();
1949 } else {
1950 Result =
1951 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1952 /*TopLevelOfInitList=*/true);
1953 }
1954
1955 Expr *ResultExpr = nullptr;
1956 if (Result.isInvalid())
1957 hadError = true; // types weren't compatible.
1958 else {
1959 ResultExpr = Result.getAs<Expr>();
1960
1961 if (ResultExpr != Init && !VerifyOnly) {
1962 // The type was promoted, update initializer list.
1963 // FIXME: Why are we updating the syntactic init list?
1964 IList->setInit(Index, ResultExpr);
1965 }
1966 }
1967 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1968 ++Index;
1969 if (AggrDeductionCandidateParamTypes)
1970 AggrDeductionCandidateParamTypes->push_back(elementType);
1971 return;
1972 }
1973
1974 InitializedEntity ElementEntity =
1976
1977 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1978 // Don't attempt to go past the end of the init list
1979 if (Index >= IList->getNumInits()) {
1980 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1981 break;
1982 }
1983
1984 ElementEntity.setElementIndex(Index);
1985 CheckSubElementType(ElementEntity, IList, elementType, Index,
1986 StructuredList, StructuredIndex);
1987 }
1988
1989 if (VerifyOnly)
1990 return;
1991
1992 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1993 const VectorType *T = Entity.getType()->castAs<VectorType>();
1994 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1995 T->getVectorKind() == VectorKind::NeonPoly)) {
1996 // The ability to use vector initializer lists is a GNU vector extension
1997 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1998 // endian machines it works fine, however on big endian machines it
1999 // exhibits surprising behaviour:
2000 //
2001 // uint32x2_t x = {42, 64};
2002 // return vget_lane_u32(x, 0); // Will return 64.
2003 //
2004 // Because of this, explicitly call out that it is non-portable.
2005 //
2006 SemaRef.Diag(IList->getBeginLoc(),
2007 diag::warn_neon_vector_initializer_non_portable);
2008
2009 const char *typeCode;
2010 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
2011
2012 if (elementType->isFloatingType())
2013 typeCode = "f";
2014 else if (elementType->isSignedIntegerType())
2015 typeCode = "s";
2016 else if (elementType->isUnsignedIntegerType())
2017 typeCode = "u";
2018 else if (elementType->isMFloat8Type())
2019 typeCode = "mf";
2020 else
2021 llvm_unreachable("Invalid element type!");
2022
2023 SemaRef.Diag(IList->getBeginLoc(),
2024 SemaRef.Context.getTypeSize(VT) > 64
2025 ? diag::note_neon_vector_initializer_non_portable_q
2026 : diag::note_neon_vector_initializer_non_portable)
2027 << typeCode << typeSize;
2028 }
2029
2030 return;
2031 }
2032
2033 InitializedEntity ElementEntity =
2035
2036 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2037 for (unsigned i = 0; i < maxElements; ++i) {
2038 // Don't attempt to go past the end of the init list
2039 if (Index >= IList->getNumInits())
2040 break;
2041
2042 ElementEntity.setElementIndex(Index);
2043
2044 QualType IType = IList->getInit(Index)->getType();
2045 if (!IType->isVectorType()) {
2046 CheckSubElementType(ElementEntity, IList, elementType, Index,
2047 StructuredList, StructuredIndex);
2048 ++numEltsInit;
2049 } else {
2050 QualType VecType;
2051 const VectorType *IVT = IType->castAs<VectorType>();
2052 unsigned numIElts = IVT->getNumElements();
2053
2054 if (IType->isExtVectorType())
2055 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
2056 else
2057 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
2058 IVT->getVectorKind());
2059 CheckSubElementType(ElementEntity, IList, VecType, Index,
2060 StructuredList, StructuredIndex);
2061 numEltsInit += numIElts;
2062 }
2063 }
2064
2065 // OpenCL and HLSL require all elements to be initialized.
2066 if (numEltsInit != maxElements) {
2067 if (!VerifyOnly)
2068 SemaRef.Diag(IList->getBeginLoc(),
2069 diag::err_vector_incorrect_num_elements)
2070 << (numEltsInit < maxElements) << maxElements << numEltsInit
2071 << /*initialization*/ 0;
2072 hadError = true;
2073 }
2074}
2075
2076/// Check if the type of a class element has an accessible destructor, and marks
2077/// it referenced. Returns true if we shouldn't form a reference to the
2078/// destructor.
2079///
2080/// Aggregate initialization requires a class element's destructor be
2081/// accessible per 11.6.1 [dcl.init.aggr]:
2082///
2083/// The destructor for each element of class type is potentially invoked
2084/// (15.4 [class.dtor]) from the context where the aggregate initialization
2085/// occurs.
2087 Sema &SemaRef) {
2088 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2089 // Bail out on incomplete record types: a forward-declared class has no
2090 // destructor to look up, and `LookupDestructor` (via `LookupSpecialMember`)
2091 // asserts that the record is fully defined. Error recovery for init lists
2092 // of incomplete element types reaches this point even after the parser has
2093 // already diagnosed the incompleteness.
2094 if (!CXXRD || !CXXRD->hasDefinition())
2095 return false;
2096
2098 if (!Destructor)
2099 return false;
2100
2101 SemaRef.CheckDestructorAccess(Loc, Destructor,
2102 SemaRef.PDiag(diag::err_access_dtor_temp)
2103 << ElementType);
2104 SemaRef.MarkFunctionReferenced(Loc, Destructor);
2105 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
2106}
2107
2108static bool
2110 const InitializedEntity &Entity,
2111 ASTContext &Context) {
2112 QualType InitType = Entity.getType();
2113 const InitializedEntity *Parent = &Entity;
2114
2115 while (Parent) {
2116 InitType = Parent->getType();
2117 Parent = Parent->getParent();
2118 }
2119
2120 // Only one initializer, it's an embed and the types match;
2121 EmbedExpr *EE =
2122 ExprList.size() == 1
2123 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2124 : nullptr;
2125 if (!EE)
2126 return false;
2127
2128 if (InitType->isArrayType()) {
2129 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2131 return IsStringInit(SL, InitArrayType, Context) == SIF_None;
2132 }
2133 return false;
2134}
2135
2136void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2137 InitListExpr *IList, QualType &DeclType,
2138 llvm::APSInt elementIndex,
2139 bool SubobjectIsDesignatorContext,
2140 unsigned &Index,
2141 InitListExpr *StructuredList,
2142 unsigned &StructuredIndex) {
2143 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2144
2145 if (!VerifyOnly) {
2146 if (checkDestructorReference(arrayType->getElementType(),
2147 IList->getEndLoc(), SemaRef)) {
2148 hadError = true;
2149 return;
2150 }
2151 }
2152
2153 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2154 SemaRef.Context)) {
2155 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2156 IList->setInit(0, Embed->getDataStringLiteral());
2157 }
2158
2159 // Check for the special-case of initializing an array with a string.
2160 if (Index < IList->getNumInits()) {
2161 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2162 SIF_None) {
2163 // We place the string literal directly into the resulting
2164 // initializer list. This is the only place where the structure
2165 // of the structured initializer list doesn't match exactly,
2166 // because doing so would involve allocating one character
2167 // constant for each string.
2168 // FIXME: Should we do these checks in verify-only mode too?
2169 if (!VerifyOnly)
2171 IList->getInit(Index), DeclType, arrayType, SemaRef, Entity,
2172 SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2173 if (StructuredList) {
2174 UpdateStructuredListElement(StructuredList, StructuredIndex,
2175 IList->getInit(Index));
2176 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2177 }
2178 ++Index;
2179 if (AggrDeductionCandidateParamTypes)
2180 AggrDeductionCandidateParamTypes->push_back(DeclType);
2181 return;
2182 }
2183 }
2184 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2185 // Check for VLAs; in standard C it would be possible to check this
2186 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2187 // them in all sorts of strange places).
2188 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2189 if (!VerifyOnly) {
2190 // C23 6.7.10p4: An entity of variable length array type shall not be
2191 // initialized except by an empty initializer.
2192 //
2193 // The C extension warnings are issued from ParseBraceInitializer() and
2194 // do not need to be issued here. However, we continue to issue an error
2195 // in the case there are initializers or we are compiling C++. We allow
2196 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2197 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2198 // FIXME: should we allow this construct in C++ when it makes sense to do
2199 // so?
2200 if (HasErr)
2201 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2202 diag::err_variable_object_no_init)
2203 << VAT->getSizeExpr()->getSourceRange();
2204 }
2205 hadError = HasErr;
2206 ++Index;
2207 ++StructuredIndex;
2208 return;
2209 }
2210
2211 // We might know the maximum number of elements in advance.
2212 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2213 elementIndex.isUnsigned());
2214 bool maxElementsKnown = false;
2215 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2216 maxElements = CAT->getSize();
2217 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2218 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2219 maxElementsKnown = true;
2220 }
2221
2222 QualType elementType = arrayType->getElementType();
2223 while (Index < IList->getNumInits()) {
2224 Expr *Init = IList->getInit(Index);
2225 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2226 // If we're not the subobject that matches up with the '{' for
2227 // the designator, we shouldn't be handling the
2228 // designator. Return immediately.
2229 if (!SubobjectIsDesignatorContext)
2230 return;
2231
2232 // Handle this designated initializer. elementIndex will be
2233 // updated to be the next array element we'll initialize.
2234 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2235 DeclType, nullptr, &elementIndex, Index,
2236 StructuredList, StructuredIndex, true,
2237 false)) {
2238 hadError = true;
2239 continue;
2240 }
2241
2242 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2243 maxElements = maxElements.extend(elementIndex.getBitWidth());
2244 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2245 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2246 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2247
2248 // If the array is of incomplete type, keep track of the number of
2249 // elements in the initializer.
2250 if (!maxElementsKnown && elementIndex > maxElements)
2251 maxElements = elementIndex;
2252
2253 continue;
2254 }
2255
2256 // If we know the maximum number of elements, and we've already
2257 // hit it, stop consuming elements in the initializer list.
2258 if (maxElementsKnown && elementIndex == maxElements)
2259 break;
2260
2261 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2262 SemaRef.Context, StructuredIndex, Entity);
2263 ElementEntity.setElementIndex(elementIndex.getExtValue());
2264
2265 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2266 // Check this element.
2267 CheckSubElementType(ElementEntity, IList, elementType, Index,
2268 StructuredList, StructuredIndex);
2269 ++elementIndex;
2270 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2271 if (CurEmbed) {
2272 elementIndex =
2273 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2274 } else {
2275 auto Embed = cast<EmbedExpr>(Init);
2276 elementIndex = elementIndex + Embed->getDataElementCount() -
2277 EmbedElementIndexBeforeInit - 1;
2278 }
2279 }
2280
2281 // If the array is of incomplete type, keep track of the number of
2282 // elements in the initializer.
2283 if (!maxElementsKnown && elementIndex > maxElements)
2284 maxElements = elementIndex;
2285 }
2286 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2287 // If this is an incomplete array type, the actual type needs to
2288 // be calculated here.
2289 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2290 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2291 // Sizing an array implicitly to zero is not allowed by ISO C,
2292 // but is supported by GNU.
2293 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2294 }
2295
2296 DeclType = SemaRef.Context.getConstantArrayType(
2297 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2298 }
2299 if (!hadError) {
2300 // If there are any members of the array that get value-initialized, check
2301 // that is possible. That happens if we know the bound and don't have
2302 // enough elements, or if we're performing an array new with an unknown
2303 // bound.
2304 if ((maxElementsKnown && elementIndex < maxElements) ||
2305 Entity.isVariableLengthArrayNew())
2306 CheckEmptyInitializable(
2308 IList->getEndLoc());
2309 }
2310}
2311
2312bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2313 Expr *InitExpr,
2314 FieldDecl *Field,
2315 bool TopLevelObject) {
2316 // Handle GNU flexible array initializers.
2317 unsigned FlexArrayDiag;
2318 if (isa<InitListExpr>(InitExpr) &&
2319 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2320 // Empty flexible array init always allowed as an extension
2321 FlexArrayDiag = diag::ext_flexible_array_init;
2322 } else if (!TopLevelObject) {
2323 // Disallow flexible array init on non-top-level object
2324 FlexArrayDiag = diag::err_flexible_array_init;
2325 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2326 // Disallow flexible array init on anything which is not a variable.
2327 FlexArrayDiag = diag::err_flexible_array_init;
2328 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2329 // Disallow flexible array init on local variables.
2330 FlexArrayDiag = diag::err_flexible_array_init;
2331 } else {
2332 // Allow other cases.
2333 FlexArrayDiag = diag::ext_flexible_array_init;
2334 }
2335
2336 if (!VerifyOnly) {
2337 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2338 << InitExpr->getBeginLoc();
2339 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2340 << Field;
2341 }
2342
2343 return FlexArrayDiag != diag::ext_flexible_array_init;
2344}
2345
2346static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2347 return StructuredList && StructuredList->getNumInits() == 1U;
2348}
2349
2350void InitListChecker::CheckStructUnionTypes(
2351 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2353 bool SubobjectIsDesignatorContext, unsigned &Index,
2354 InitListExpr *StructuredList, unsigned &StructuredIndex,
2355 bool TopLevelObject) {
2356 const RecordDecl *RD = DeclType->getAsRecordDecl();
2357
2358 // If the record is invalid, some of it's members are invalid. To avoid
2359 // confusion, we forgo checking the initializer for the entire record.
2360 if (RD->isInvalidDecl()) {
2361 // Assume it was supposed to consume a single initializer.
2362 ++Index;
2363 hadError = true;
2364 return;
2365 }
2366
2367 if (RD->isUnion() && IList->getNumInits() == 0) {
2368 if (!VerifyOnly)
2369 for (FieldDecl *FD : RD->fields()) {
2370 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2371 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2372 hadError = true;
2373 return;
2374 }
2375 }
2376
2377 // If there's a default initializer, use it.
2378 if (isa<CXXRecordDecl>(RD) &&
2379 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2380 if (!StructuredList)
2381 return;
2382 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2383 Field != FieldEnd; ++Field) {
2384 if (Field->hasInClassInitializer() ||
2385 (Field->isAnonymousStructOrUnion() &&
2386 Field->getType()
2387 ->castAsCXXRecordDecl()
2388 ->hasInClassInitializer())) {
2389 StructuredList->setInitializedFieldInUnion(*Field);
2390 // FIXME: Actually build a CXXDefaultInitExpr?
2391 return;
2392 }
2393 }
2394 llvm_unreachable("Couldn't find in-class initializer");
2395 }
2396
2397 // Value-initialize the first member of the union that isn't an unnamed
2398 // bitfield.
2399 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2400 Field != FieldEnd; ++Field) {
2401 if (!Field->isUnnamedBitField()) {
2402 CheckEmptyInitializable(
2403 InitializedEntity::InitializeMember(*Field, &Entity),
2404 IList->getEndLoc());
2405 if (StructuredList)
2406 StructuredList->setInitializedFieldInUnion(*Field);
2407 break;
2408 }
2409 }
2410 return;
2411 }
2412
2413 bool InitializedSomething = false;
2414
2415 // If we have any base classes, they are initialized prior to the fields.
2416 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2417 auto &Base = *I;
2418 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2419
2420 // Designated inits always initialize fields, so if we see one, all
2421 // remaining base classes have no explicit initializer.
2422 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2423 Init = nullptr;
2424
2425 // C++ [over.match.class.deduct]p1.6:
2426 // each non-trailing aggregate element that is a pack expansion is assumed
2427 // to correspond to no elements of the initializer list, and (1.7) a
2428 // trailing aggregate element that is a pack expansion is assumed to
2429 // correspond to all remaining elements of the initializer list (if any).
2430
2431 // C++ [over.match.class.deduct]p1.9:
2432 // ... except that additional parameter packs of the form P_j... are
2433 // inserted into the parameter list in their original aggregate element
2434 // position corresponding to each non-trailing aggregate element of
2435 // type P_j that was skipped because it was a parameter pack, and the
2436 // trailing sequence of parameters corresponding to a trailing
2437 // aggregate element that is a pack expansion (if any) is replaced
2438 // by a single parameter of the form T_n....
2439 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2440 AggrDeductionCandidateParamTypes->push_back(
2441 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2442
2443 // Trailing pack expansion
2444 if (I + 1 == E && RD->field_empty()) {
2445 if (Index < IList->getNumInits())
2446 Index = IList->getNumInits();
2447 return;
2448 }
2449
2450 continue;
2451 }
2452
2453 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2454 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2455 SemaRef.Context, &Base, false, &Entity);
2456 if (Init) {
2457 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2458 StructuredList, StructuredIndex);
2459 InitializedSomething = true;
2460 } else {
2461 CheckEmptyInitializable(BaseEntity, InitLoc);
2462 }
2463
2464 if (!VerifyOnly)
2465 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2466 hadError = true;
2467 return;
2468 }
2469 }
2470
2471 // If structDecl is a forward declaration, this loop won't do
2472 // anything except look at designated initializers; That's okay,
2473 // because an error should get printed out elsewhere. It might be
2474 // worthwhile to skip over the rest of the initializer, though.
2475 RecordDecl::field_iterator FieldEnd = RD->field_end();
2476 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2477 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2478 });
2479 bool HasDesignatedInit = false;
2480
2481 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2482
2483 while (Index < IList->getNumInits()) {
2484 Expr *Init = IList->getInit(Index);
2485 SourceLocation InitLoc = Init->getBeginLoc();
2486
2487 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2488 // If we're not the subobject that matches up with the '{' for
2489 // the designator, we shouldn't be handling the
2490 // designator. Return immediately.
2491 if (!SubobjectIsDesignatorContext)
2492 return;
2493
2494 HasDesignatedInit = true;
2495
2496 // Handle this designated initializer. Field will be updated to
2497 // the next field that we'll be initializing.
2498 bool DesignatedInitFailed = CheckDesignatedInitializer(
2499 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2500 StructuredList, StructuredIndex, true, TopLevelObject);
2501 if (DesignatedInitFailed)
2502 hadError = true;
2503
2504 // Find the field named by the designated initializer.
2505 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2506 if (!VerifyOnly && D->isFieldDesignator()) {
2507 FieldDecl *F = D->getFieldDecl();
2508 InitializedFields.insert(F);
2509 if (!DesignatedInitFailed) {
2510 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2511 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2512 hadError = true;
2513 return;
2514 }
2515 }
2516 }
2517
2518 InitializedSomething = true;
2519 continue;
2520 }
2521
2522 // Check if this is an initializer of forms:
2523 //
2524 // struct foo f = {};
2525 // struct foo g = {0};
2526 //
2527 // These are okay for randomized structures. [C99 6.7.8p19]
2528 //
2529 // Also, if there is only one element in the structure, we allow something
2530 // like this, because it's really not randomized in the traditional sense.
2531 //
2532 // struct foo h = {bar};
2533 auto IsZeroInitializer = [&](const Expr *I) {
2534 if (IList->getNumInits() == 1) {
2535 if (NumRecordDecls == 1)
2536 return true;
2537 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2538 return IL->getValue().isZero();
2539 }
2540 return false;
2541 };
2542
2543 // Don't allow non-designated initializers on randomized structures.
2544 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2545 if (!VerifyOnly)
2546 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2547 hadError = true;
2548 break;
2549 }
2550
2551 if (Field == FieldEnd) {
2552 // We've run out of fields. We're done.
2553 break;
2554 }
2555
2556 // We've already initialized a member of a union. We can stop entirely.
2557 if (InitializedSomething && RD->isUnion())
2558 return;
2559
2560 // Stop if we've hit a flexible array member.
2561 if (Field->getType()->isIncompleteArrayType())
2562 break;
2563
2564 if (Field->isUnnamedBitField()) {
2565 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2566 ++Field;
2567 continue;
2568 }
2569
2570 // Make sure we can use this declaration.
2571 bool InvalidUse;
2572 if (VerifyOnly)
2573 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2574 else
2575 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2576 *Field, IList->getInit(Index)->getBeginLoc());
2577 if (InvalidUse) {
2578 ++Index;
2579 ++Field;
2580 hadError = true;
2581 continue;
2582 }
2583
2584 if (!VerifyOnly) {
2585 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2586 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2587 hadError = true;
2588 return;
2589 }
2590 }
2591
2592 InitializedEntity MemberEntity =
2593 InitializedEntity::InitializeMember(*Field, &Entity);
2594 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2595 StructuredList, StructuredIndex);
2596 InitializedSomething = true;
2597 InitializedFields.insert(*Field);
2598 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2599 // Initialize the first field within the union.
2600 StructuredList->setInitializedFieldInUnion(*Field);
2601 }
2602
2603 ++Field;
2604 }
2605
2606 // Emit warnings for missing struct field initializers.
2607 // This check is disabled for designated initializers in C.
2608 // This matches gcc behaviour.
2609 bool IsCDesignatedInitializer =
2610 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2611 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2612 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2613 !IsCDesignatedInitializer) {
2614 // It is possible we have one or more unnamed bitfields remaining.
2615 // Find first (if any) named field and emit warning.
2616 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2617 : Field,
2618 end = RD->field_end();
2619 it != end; ++it) {
2620 if (HasDesignatedInit && InitializedFields.count(*it))
2621 continue;
2622
2623 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2624 !it->getType()->isIncompleteArrayType()) {
2625 auto Diag = HasDesignatedInit
2626 ? diag::warn_missing_designated_field_initializers
2627 : diag::warn_missing_field_initializers;
2628 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2629 break;
2630 }
2631 }
2632 }
2633
2634 // Check that any remaining fields can be value-initialized if we're not
2635 // building a structured list. (If we are, we'll check this later.)
2636 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2637 !Field->getType()->isIncompleteArrayType()) {
2638 for (; Field != FieldEnd && !hadError; ++Field) {
2639 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2640 CheckEmptyInitializable(
2641 InitializedEntity::InitializeMember(*Field, &Entity),
2642 IList->getEndLoc());
2643 }
2644 }
2645
2646 // Check that the types of the remaining fields have accessible destructors.
2647 if (!VerifyOnly) {
2648 // If the initializer expression has a designated initializer, check the
2649 // elements for which a designated initializer is not provided too.
2650 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2651 : Field;
2652 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2653 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2654 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2655 hadError = true;
2656 return;
2657 }
2658 }
2659 }
2660
2661 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2662 Index >= IList->getNumInits())
2663 return;
2664
2665 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2666 TopLevelObject)) {
2667 hadError = true;
2668 ++Index;
2669 return;
2670 }
2671
2672 InitializedEntity MemberEntity =
2673 InitializedEntity::InitializeMember(*Field, &Entity);
2674
2675 if (isa<InitListExpr>(IList->getInit(Index)) ||
2676 AggrDeductionCandidateParamTypes)
2677 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2678 StructuredList, StructuredIndex);
2679 else
2680 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2681 StructuredList, StructuredIndex);
2682
2683 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2684 // Initialize the first field within the union.
2685 StructuredList->setInitializedFieldInUnion(*Field);
2686 }
2687}
2688
2689/// Expand a field designator that refers to a member of an
2690/// anonymous struct or union into a series of field designators that
2691/// refers to the field within the appropriate subobject.
2692///
2694 DesignatedInitExpr *DIE,
2695 unsigned DesigIdx,
2696 IndirectFieldDecl *IndirectField) {
2698
2699 // Build the replacement designators.
2700 SmallVector<Designator, 4> Replacements;
2701 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2702 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2703 if (PI + 1 == PE)
2704 Replacements.push_back(Designator::CreateFieldDesignator(
2705 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2706 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2707 else
2708 Replacements.push_back(Designator::CreateFieldDesignator(
2709 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2710 assert(isa<FieldDecl>(*PI));
2711 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2712 }
2713
2714 // Expand the current designator into the set of replacement
2715 // designators, so we have a full subobject path down to where the
2716 // member of the anonymous struct/union is actually stored.
2717 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2718 &Replacements[0] + Replacements.size());
2719}
2720
2722 DesignatedInitExpr *DIE) {
2723 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2724 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2725 for (unsigned I = 0; I < NumIndexExprs; ++I)
2726 IndexExprs[I] = DIE->getSubExpr(I + 1);
2727 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2728 IndexExprs,
2729 DIE->getEqualOrColonLoc(),
2730 DIE->usesGNUSyntax(), DIE->getInit());
2731}
2732
2733namespace {
2734
2735// Callback to only accept typo corrections that are for field members of
2736// the given struct or union.
2737class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2738 public:
2739 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2740 : Record(RD) {}
2741
2742 bool ValidateCandidate(const TypoCorrection &candidate) override {
2743 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2744 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2745 }
2746
2747 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2748 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2749 }
2750
2751 private:
2752 const RecordDecl *Record;
2753};
2754
2755} // end anonymous namespace
2756
2757/// Check the well-formedness of a C99 designated initializer.
2758///
2759/// Determines whether the designated initializer @p DIE, which
2760/// resides at the given @p Index within the initializer list @p
2761/// IList, is well-formed for a current object of type @p DeclType
2762/// (C99 6.7.8). The actual subobject that this designator refers to
2763/// within the current subobject is returned in either
2764/// @p NextField or @p NextElementIndex (whichever is appropriate).
2765///
2766/// @param IList The initializer list in which this designated
2767/// initializer occurs.
2768///
2769/// @param DIE The designated initializer expression.
2770///
2771/// @param DesigIdx The index of the current designator.
2772///
2773/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2774/// into which the designation in @p DIE should refer.
2775///
2776/// @param NextField If non-NULL and the first designator in @p DIE is
2777/// a field, this will be set to the field declaration corresponding
2778/// to the field named by the designator. On input, this is expected to be
2779/// the next field that would be initialized in the absence of designation,
2780/// if the complete object being initialized is a struct.
2781///
2782/// @param NextElementIndex If non-NULL and the first designator in @p
2783/// DIE is an array designator or GNU array-range designator, this
2784/// will be set to the last index initialized by this designator.
2785///
2786/// @param Index Index into @p IList where the designated initializer
2787/// @p DIE occurs.
2788///
2789/// @param StructuredList The initializer list expression that
2790/// describes all of the subobject initializers in the order they'll
2791/// actually be initialized.
2792///
2793/// @returns true if there was an error, false otherwise.
2794bool
2795InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2796 InitListExpr *IList,
2797 DesignatedInitExpr *DIE,
2798 unsigned DesigIdx,
2799 QualType &CurrentObjectType,
2800 RecordDecl::field_iterator *NextField,
2801 llvm::APSInt *NextElementIndex,
2802 unsigned &Index,
2803 InitListExpr *StructuredList,
2804 unsigned &StructuredIndex,
2805 bool FinishSubobjectInit,
2806 bool TopLevelObject) {
2807 if (DesigIdx == DIE->size()) {
2808 // C++20 designated initialization can result in direct-list-initialization
2809 // of the designated subobject. This is the only way that we can end up
2810 // performing direct initialization as part of aggregate initialization, so
2811 // it needs special handling.
2812 if (DIE->isDirectInit()) {
2813 Expr *Init = DIE->getInit();
2814 assert(isa<InitListExpr>(Init) &&
2815 "designator result in direct non-list initialization?");
2816 InitializationKind Kind = InitializationKind::CreateDirectList(
2817 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2818 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2819 /*TopLevelOfInitList*/ true);
2820 if (StructuredList) {
2821 ExprResult Result = VerifyOnly
2822 ? getDummyInit()
2823 : Seq.Perform(SemaRef, Entity, Kind, Init);
2824 UpdateStructuredListElement(StructuredList, StructuredIndex,
2825 Result.get());
2826 }
2827 ++Index;
2828 if (AggrDeductionCandidateParamTypes)
2829 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2830 return !Seq;
2831 }
2832
2833 // Check the actual initialization for the designated object type.
2834 bool prevHadError = hadError;
2835
2836 // Temporarily remove the designator expression from the
2837 // initializer list that the child calls see, so that we don't try
2838 // to re-process the designator.
2839 unsigned OldIndex = Index;
2840 auto *OldDIE =
2841 dyn_cast_if_present<DesignatedInitExpr>(IList->getInit(OldIndex));
2842 if (!OldDIE)
2843 OldDIE = DIE;
2844 IList->setInit(OldIndex, OldDIE->getInit());
2845
2846 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2847 StructuredIndex, /*DirectlyDesignated=*/true);
2848
2849 // Restore the designated initializer expression in the syntactic
2850 // form of the initializer list.
2851 if (IList->getInit(OldIndex) != OldDIE->getInit())
2852 OldDIE->setInit(IList->getInit(OldIndex));
2853 IList->setInit(OldIndex, OldDIE);
2854
2855 return hadError && !prevHadError;
2856 }
2857
2858 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2859 bool IsFirstDesignator = (DesigIdx == 0);
2860 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2861 // Determine the structural initializer list that corresponds to the
2862 // current subobject.
2863 if (IsFirstDesignator)
2864 StructuredList = FullyStructuredList;
2865 else {
2866 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2867 StructuredList->getInit(StructuredIndex) : nullptr;
2868 if (!ExistingInit && StructuredList->hasArrayFiller())
2869 ExistingInit = StructuredList->getArrayFiller();
2870
2871 if (!ExistingInit)
2872 StructuredList = getStructuredSubobjectInit(
2873 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2874 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2875 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2876 StructuredList = Result;
2877 else {
2878 // We are creating an initializer list that initializes the
2879 // subobjects of the current object, but there was already an
2880 // initialization that completely initialized the current
2881 // subobject, e.g., by a compound literal:
2882 //
2883 // struct X { int a, b; };
2884 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2885 //
2886 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2887 // designated initializer re-initializes only its current object
2888 // subobject [0].b.
2889 diagnoseInitOverride(ExistingInit,
2890 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2891 /*UnionOverride=*/false,
2892 /*FullyOverwritten=*/false);
2893
2894 if (!VerifyOnly) {
2895 if (DesignatedInitUpdateExpr *E =
2896 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2897 StructuredList = E->getUpdater();
2898 else {
2899 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2900 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2901 ExistingInit, DIE->getEndLoc());
2902 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2903 StructuredList = DIUE->getUpdater();
2904 }
2905 } else {
2906 // We don't need to track the structured representation of a
2907 // designated init update of an already-fully-initialized object in
2908 // verify-only mode. The only reason we would need the structure is
2909 // to determine where the uninitialized "holes" are, and in this
2910 // case, we know there aren't any and we can't introduce any.
2911 StructuredList = nullptr;
2912 }
2913 }
2914 }
2915 }
2916
2917 if (D->isFieldDesignator()) {
2918 // C99 6.7.8p7:
2919 //
2920 // If a designator has the form
2921 //
2922 // . identifier
2923 //
2924 // then the current object (defined below) shall have
2925 // structure or union type and the identifier shall be the
2926 // name of a member of that type.
2927 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2928 if (!RD) {
2929 SourceLocation Loc = D->getDotLoc();
2930 if (Loc.isInvalid())
2931 Loc = D->getFieldLoc();
2932 if (!VerifyOnly)
2933 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2934 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2935 ++Index;
2936 return true;
2937 }
2938
2939 FieldDecl *KnownField = D->getFieldDecl();
2940 if (!KnownField) {
2941 const IdentifierInfo *FieldName = D->getFieldName();
2942 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2943 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2944 KnownField = FD;
2945 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2946 // In verify mode, don't modify the original.
2947 if (VerifyOnly)
2948 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2949 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2950 D = DIE->getDesignator(DesigIdx);
2951 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2952 }
2953 if (!KnownField) {
2954 if (VerifyOnly) {
2955 ++Index;
2956 return true; // No typo correction when just trying this out.
2957 }
2958
2959 // We found a placeholder variable
2960 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2961 FieldName)) {
2962 ++Index;
2963 return true;
2964 }
2965 // Name lookup found something, but it wasn't a field.
2966 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2967 !Lookup.empty()) {
2968 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2969 << FieldName;
2970 SemaRef.Diag(Lookup.front()->getLocation(),
2971 diag::note_field_designator_found);
2972 ++Index;
2973 return true;
2974 }
2975
2976 // Name lookup didn't find anything.
2977 // Determine whether this was a typo for another field name.
2978 FieldInitializerValidatorCCC CCC(RD);
2979 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2980 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2981 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2982 CorrectTypoKind::ErrorRecovery, RD)) {
2983 SemaRef.diagnoseTypo(
2984 Corrected,
2985 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2986 << FieldName << CurrentObjectType);
2987 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2988 hadError = true;
2989 } else {
2990 // Typo correction didn't find anything.
2991 SourceLocation Loc = D->getFieldLoc();
2992
2993 // The loc can be invalid with a "null" designator (i.e. an anonymous
2994 // union/struct). Do our best to approximate the location.
2995 if (Loc.isInvalid())
2996 Loc = IList->getBeginLoc();
2997
2998 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2999 << FieldName << CurrentObjectType << DIE->getSourceRange();
3000 ++Index;
3001 return true;
3002 }
3003 }
3004 }
3005
3006 unsigned NumBases = 0;
3007 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3008 NumBases = CXXRD->getNumBases();
3009
3010 unsigned FieldIndex = NumBases;
3011
3012 for (auto *FI : RD->fields()) {
3013 if (FI->isUnnamedBitField())
3014 continue;
3015 if (declaresSameEntity(KnownField, FI)) {
3016 KnownField = FI;
3017 break;
3018 }
3019 ++FieldIndex;
3020 }
3021
3023 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3024
3025 // All of the fields of a union are located at the same place in
3026 // the initializer list.
3027 if (RD->isUnion()) {
3028 FieldIndex = 0;
3029 if (StructuredList) {
3030 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3031 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
3032 assert(StructuredList->getNumInits() == 1
3033 && "A union should never have more than one initializer!");
3034
3035 Expr *ExistingInit = StructuredList->getInit(0);
3036 if (ExistingInit) {
3037 // We're about to throw away an initializer, emit warning.
3038 diagnoseInitOverride(
3039 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3040 /*UnionOverride=*/true,
3041 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3042 : true);
3043 }
3044
3045 // remove existing initializer
3046 StructuredList->resizeInits(SemaRef.Context, 0);
3047 StructuredList->setInitializedFieldInUnion(nullptr);
3048 }
3049
3050 StructuredList->setInitializedFieldInUnion(*Field);
3051 }
3052 }
3053
3054 // Make sure we can use this declaration.
3055 bool InvalidUse;
3056 if (VerifyOnly)
3057 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
3058 else
3059 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
3060 if (InvalidUse) {
3061 ++Index;
3062 return true;
3063 }
3064
3065 // C++20 [dcl.init.list]p3:
3066 // The ordered identifiers in the designators of the designated-
3067 // initializer-list shall form a subsequence of the ordered identifiers
3068 // in the direct non-static data members of T.
3069 //
3070 // Note that this is not a condition on forming the aggregate
3071 // initialization, only on actually performing initialization,
3072 // so it is not checked in VerifyOnly mode.
3073 //
3074 // FIXME: This is the only reordering diagnostic we produce, and it only
3075 // catches cases where we have a top-level field designator that jumps
3076 // backwards. This is the only such case that is reachable in an
3077 // otherwise-valid C++20 program, so is the only case that's required for
3078 // conformance, but for consistency, we should diagnose all the other
3079 // cases where a designator takes us backwards too.
3080 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3081 NextField &&
3082 (*NextField == RD->field_end() ||
3083 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3084 // Find the field that we just initialized.
3085 FieldDecl *PrevField = nullptr;
3086 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3087 if (FI->isUnnamedBitField())
3088 continue;
3089 if (*NextField != RD->field_end() &&
3090 declaresSameEntity(*FI, **NextField))
3091 break;
3092 PrevField = *FI;
3093 }
3094
3095 const auto GenerateDesignatedInitReorderingFixit =
3096 [&](SemaBase::SemaDiagnosticBuilder &Diag) {
3097 struct ReorderInfo {
3098 int Pos{};
3099 const Expr *InitExpr{};
3100 };
3101
3102 llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{};
3103 llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{};
3104
3105 const auto *CxxRecord =
3107
3108 for (const FieldDecl *Field : CxxRecord->fields())
3109 MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex();
3110
3111 for (const Expr *Init : IList->inits()) {
3112 if (const auto *DI =
3113 dyn_cast_if_present<DesignatedInitExpr>(Init)) {
3114 // We expect only one Designator
3115 if (DI->size() != 1)
3116 return;
3117
3118 const IdentifierInfo *const FieldName =
3119 DI->getDesignator(0)->getFieldName();
3120 // In case we have an unknown initializer in the source, not in
3121 // the record
3122 if (MemberNameInx.contains(FieldName))
3123 ReorderedInitExprs.emplace_back(
3124 ReorderInfo{MemberNameInx.at(FieldName), Init});
3125 }
3126 }
3127
3128 llvm::sort(ReorderedInitExprs,
3129 [](const ReorderInfo &A, const ReorderInfo &B) {
3130 return A.Pos < B.Pos;
3131 });
3132
3133 llvm::SmallString<128> FixedInitList{};
3134 SourceManager &SM = SemaRef.getSourceManager();
3135 const LangOptions &LangOpts = SemaRef.getLangOpts();
3136
3137 // In a derived Record, first n base-classes are initialized first.
3138 // They do not use designated init, so skip them
3139 const ArrayRef<clang::Expr *> IListInits =
3140 IList->inits().drop_front(CxxRecord->getNumBases());
3141 // loop over each existing expressions and apply replacement
3142 for (const auto &[OrigExpr, Repl] :
3143 llvm::zip(IListInits, ReorderedInitExprs)) {
3144 CharSourceRange CharRange = CharSourceRange::getTokenRange(
3145 Repl.InitExpr->getSourceRange());
3146 const StringRef InitText =
3147 Lexer::getSourceText(CharRange, SM, LangOpts);
3148
3149 Diag << FixItHint::CreateReplacement(OrigExpr->getSourceRange(),
3150 InitText.str());
3151 }
3152 };
3153
3154 if (PrevField &&
3155 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3156 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3157 diag::ext_designated_init_reordered)
3158 << KnownField << PrevField << DIE->getSourceRange();
3159
3160 unsigned OldIndex = StructuredIndex - 1;
3161 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3162 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3163 auto Diag = SemaRef.Diag(PrevInit->getBeginLoc(),
3164 diag::note_previous_field_init)
3165 << PrevField << PrevInit->getSourceRange();
3166 GenerateDesignatedInitReorderingFixit(Diag);
3167 }
3168 }
3169 }
3170 }
3171
3172
3173 // Update the designator with the field declaration.
3174 if (!VerifyOnly)
3175 D->setFieldDecl(*Field);
3176
3177 // Make sure that our non-designated initializer list has space
3178 // for a subobject corresponding to this field.
3179 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3180 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3181
3182 // This designator names a flexible array member.
3183 if (Field->getType()->isIncompleteArrayType()) {
3184 bool Invalid = false;
3185 if ((DesigIdx + 1) != DIE->size()) {
3186 // We can't designate an object within the flexible array
3187 // member (because GCC doesn't allow it).
3188 if (!VerifyOnly) {
3189 DesignatedInitExpr::Designator *NextD
3190 = DIE->getDesignator(DesigIdx + 1);
3191 SemaRef.Diag(NextD->getBeginLoc(),
3192 diag::err_designator_into_flexible_array_member)
3193 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3194 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3195 << *Field;
3196 }
3197 Invalid = true;
3198 }
3199
3200 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3201 !isa<StringLiteral>(DIE->getInit())) {
3202 // The initializer is not an initializer list.
3203 if (!VerifyOnly) {
3204 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3205 diag::err_flexible_array_init_needs_braces)
3206 << DIE->getInit()->getSourceRange();
3207 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3208 << *Field;
3209 }
3210 Invalid = true;
3211 }
3212
3213 // Check GNU flexible array initializer.
3214 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3215 TopLevelObject))
3216 Invalid = true;
3217
3218 if (Invalid) {
3219 ++Index;
3220 return true;
3221 }
3222
3223 // Initialize the array.
3224 bool prevHadError = hadError;
3225 unsigned newStructuredIndex = FieldIndex;
3226 unsigned OldIndex = Index;
3227 IList->setInit(Index, DIE->getInit());
3228
3229 InitializedEntity MemberEntity =
3230 InitializedEntity::InitializeMember(*Field, &Entity);
3231 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3232 StructuredList, newStructuredIndex);
3233
3234 IList->setInit(OldIndex, DIE);
3235 if (hadError && !prevHadError) {
3236 ++Field;
3237 ++FieldIndex;
3238 if (NextField)
3239 *NextField = Field;
3240 StructuredIndex = FieldIndex;
3241 return true;
3242 }
3243 } else {
3244 // Recurse to check later designated subobjects.
3245 QualType FieldType = Field->getType();
3246 unsigned newStructuredIndex = FieldIndex;
3247
3248 InitializedEntity MemberEntity =
3249 InitializedEntity::InitializeMember(*Field, &Entity);
3250 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3251 FieldType, nullptr, nullptr, Index,
3252 StructuredList, newStructuredIndex,
3253 FinishSubobjectInit, false))
3254 return true;
3255 }
3256
3257 // Find the position of the next field to be initialized in this
3258 // subobject.
3259 ++Field;
3260 ++FieldIndex;
3261
3262 // If this the first designator, our caller will continue checking
3263 // the rest of this struct/class/union subobject.
3264 if (IsFirstDesignator) {
3265 if (Field != RD->field_end() && Field->isUnnamedBitField())
3266 ++Field;
3267
3268 if (NextField)
3269 *NextField = Field;
3270
3271 StructuredIndex = FieldIndex;
3272 return false;
3273 }
3274
3275 if (!FinishSubobjectInit)
3276 return false;
3277
3278 // We've already initialized something in the union; we're done.
3279 if (RD->isUnion())
3280 return hadError;
3281
3282 // Check the remaining fields within this class/struct/union subobject.
3283 bool prevHadError = hadError;
3284
3285 auto NoBases =
3288 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3289 false, Index, StructuredList, FieldIndex);
3290 return hadError && !prevHadError;
3291 }
3292
3293 // C99 6.7.8p6:
3294 //
3295 // If a designator has the form
3296 //
3297 // [ constant-expression ]
3298 //
3299 // then the current object (defined below) shall have array
3300 // type and the expression shall be an integer constant
3301 // expression. If the array is of unknown size, any
3302 // nonnegative value is valid.
3303 //
3304 // Additionally, cope with the GNU extension that permits
3305 // designators of the form
3306 //
3307 // [ constant-expression ... constant-expression ]
3308 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3309 if (!AT) {
3310 if (!VerifyOnly)
3311 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3312 << CurrentObjectType;
3313 ++Index;
3314 return true;
3315 }
3316
3317 Expr *IndexExpr = nullptr;
3318 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3319 if (D->isArrayDesignator()) {
3320 IndexExpr = DIE->getArrayIndex(*D);
3321 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3322 DesignatedEndIndex = DesignatedStartIndex;
3323 } else {
3324 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3325
3326 DesignatedStartIndex =
3328 DesignatedEndIndex =
3330 IndexExpr = DIE->getArrayRangeEnd(*D);
3331
3332 // Codegen can't handle evaluating array range designators that have side
3333 // effects, because we replicate the AST value for each initialized element.
3334 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3335 // elements with something that has a side effect, so codegen can emit an
3336 // "error unsupported" error instead of miscompiling the app.
3337 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3338 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3339 FullyStructuredList->sawArrayRangeDesignator();
3340 }
3341
3342 if (isa<ConstantArrayType>(AT)) {
3343 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3344 DesignatedStartIndex
3345 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3346 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3347 DesignatedEndIndex
3348 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3349 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3350 if (DesignatedEndIndex >= MaxElements) {
3351 if (!VerifyOnly)
3352 SemaRef.Diag(IndexExpr->getBeginLoc(),
3353 diag::err_array_designator_too_large)
3354 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3355 << IndexExpr->getSourceRange();
3356 ++Index;
3357 return true;
3358 }
3359 } else {
3360 unsigned DesignatedIndexBitWidth =
3362 DesignatedStartIndex =
3363 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3364 DesignatedEndIndex =
3365 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3366 DesignatedStartIndex.setIsUnsigned(true);
3367 DesignatedEndIndex.setIsUnsigned(true);
3368 }
3369
3370 bool IsStringLiteralInitUpdate =
3371 StructuredList && StructuredList->isStringLiteralInit();
3372 if (IsStringLiteralInitUpdate && VerifyOnly) {
3373 // We're just verifying an update to a string literal init. We don't need
3374 // to split the string up into individual characters to do that.
3375 StructuredList = nullptr;
3376 } else if (IsStringLiteralInitUpdate) {
3377 // We're modifying a string literal init; we have to decompose the string
3378 // so we can modify the individual characters.
3379 ASTContext &Context = SemaRef.Context;
3380 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3381
3382 // Compute the character type
3383 QualType CharTy = AT->getElementType();
3384
3385 // Compute the type of the integer literals.
3386 QualType PromotedCharTy = CharTy;
3387 if (Context.isPromotableIntegerType(CharTy))
3388 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3389 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3390
3391 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3392 // Get the length of the string.
3393 uint64_t StrLen = SL->getLength();
3394 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3395 CAT && CAT->getSize().ult(StrLen))
3396 StrLen = CAT->getZExtSize();
3397 StructuredList->resizeInits(Context, StrLen);
3398
3399 // Build a literal for each character in the string, and put them into
3400 // the init list.
3401 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3402 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3403 Expr *Init = new (Context) IntegerLiteral(
3404 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3405 if (CharTy != PromotedCharTy)
3406 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3407 Init, nullptr, VK_PRValue,
3408 FPOptionsOverride());
3409 StructuredList->updateInit(Context, i, Init);
3410 }
3411 } else {
3412 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3413 std::string Str;
3414 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3415
3416 // Get the length of the string.
3417 uint64_t StrLen = Str.size();
3418 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3419 CAT && CAT->getSize().ult(StrLen))
3420 StrLen = CAT->getZExtSize();
3421 StructuredList->resizeInits(Context, StrLen);
3422
3423 // Build a literal for each character in the string, and put them into
3424 // the init list.
3425 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3426 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3427 Expr *Init = new (Context) IntegerLiteral(
3428 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3429 if (CharTy != PromotedCharTy)
3430 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3431 Init, nullptr, VK_PRValue,
3432 FPOptionsOverride());
3433 StructuredList->updateInit(Context, i, Init);
3434 }
3435 }
3436 }
3437
3438 // Make sure that our non-designated initializer list has space
3439 // for a subobject corresponding to this array element.
3440 if (StructuredList &&
3441 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3442 StructuredList->resizeInits(SemaRef.Context,
3443 DesignatedEndIndex.getZExtValue() + 1);
3444
3445 // Repeatedly perform subobject initializations in the range
3446 // [DesignatedStartIndex, DesignatedEndIndex].
3447
3448 // Move to the next designator
3449 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3450 unsigned OldIndex = Index;
3451
3452 InitializedEntity ElementEntity =
3454
3455 while (DesignatedStartIndex <= DesignatedEndIndex) {
3456 // Recurse to check later designated subobjects.
3457 QualType ElementType = AT->getElementType();
3458 Index = OldIndex;
3459
3460 ElementEntity.setElementIndex(ElementIndex);
3461 if (CheckDesignatedInitializer(
3462 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3463 nullptr, Index, StructuredList, ElementIndex,
3464 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3465 false))
3466 return true;
3467
3468 // Move to the next index in the array that we'll be initializing.
3469 ++DesignatedStartIndex;
3470 ElementIndex = DesignatedStartIndex.getZExtValue();
3471 }
3472
3473 // If this the first designator, our caller will continue checking
3474 // the rest of this array subobject.
3475 if (IsFirstDesignator) {
3476 if (NextElementIndex)
3477 *NextElementIndex = std::move(DesignatedStartIndex);
3478 StructuredIndex = ElementIndex;
3479 return false;
3480 }
3481
3482 if (!FinishSubobjectInit)
3483 return false;
3484
3485 // Check the remaining elements within this array subobject.
3486 bool prevHadError = hadError;
3487 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3488 /*SubobjectIsDesignatorContext=*/false, Index,
3489 StructuredList, ElementIndex);
3490 return hadError && !prevHadError;
3491}
3492
3493// Get the structured initializer list for a subobject of type
3494// @p CurrentObjectType.
3495InitListExpr *
3496InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3497 QualType CurrentObjectType,
3498 InitListExpr *StructuredList,
3499 unsigned StructuredIndex,
3500 SourceRange InitRange,
3501 bool IsFullyOverwritten) {
3502 if (!StructuredList)
3503 return nullptr;
3504
3505 Expr *ExistingInit = nullptr;
3506 if (StructuredIndex < StructuredList->getNumInits())
3507 ExistingInit = StructuredList->getInit(StructuredIndex);
3508
3509 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3510 // There might have already been initializers for subobjects of the current
3511 // object, but a subsequent initializer list will overwrite the entirety
3512 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3513 //
3514 // struct P { char x[6]; };
3515 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3516 //
3517 // The first designated initializer is ignored, and l.x is just "f".
3518 if (!IsFullyOverwritten)
3519 return Result;
3520
3521 if (ExistingInit) {
3522 // We are creating an initializer list that initializes the
3523 // subobjects of the current object, but there was already an
3524 // initialization that completely initialized the current
3525 // subobject:
3526 //
3527 // struct X { int a, b; };
3528 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3529 //
3530 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3531 // designated initializer overwrites the [0].b initializer
3532 // from the prior initialization.
3533 //
3534 // When the existing initializer is an expression rather than an
3535 // initializer list, we cannot decompose and update it in this way.
3536 // For example:
3537 //
3538 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3539 //
3540 // This case is handled by CheckDesignatedInitializer.
3541 diagnoseInitOverride(ExistingInit, InitRange);
3542 }
3543
3544 unsigned ExpectedNumInits = 0;
3545 if (Index < IList->getNumInits()) {
3546 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3547 ExpectedNumInits = Init->getNumInits();
3548 else
3549 ExpectedNumInits = IList->getNumInits() - Index;
3550 }
3551
3552 InitListExpr *Result = createInitListExpr(
3553 CurrentObjectType, InitRange, ExpectedNumInits, /*IsExplicit=*/false);
3554
3555 // Link this new initializer list into the structured initializer
3556 // lists.
3557 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3558 return Result;
3559}
3560
3561InitListExpr *InitListChecker::createInitListExpr(QualType CurrentObjectType,
3562 SourceRange InitRange,
3563 unsigned ExpectedNumInits,
3564 bool IsExplicit) {
3565 InitListExpr *Result =
3566 new (SemaRef.Context) InitListExpr(SemaRef.Context, InitRange.getBegin(),
3567 {}, InitRange.getEnd(), IsExplicit);
3568
3569 QualType ResultType = CurrentObjectType;
3570 if (!ResultType->isArrayType())
3571 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3572 Result->setType(ResultType);
3573
3574 // Pre-allocate storage for the structured initializer list.
3575 unsigned NumElements = 0;
3576
3577 if (const ArrayType *AType
3578 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3579 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3580 NumElements = CAType->getZExtSize();
3581 // Simple heuristic so that we don't allocate a very large
3582 // initializer with many empty entries at the end.
3583 if (NumElements > ExpectedNumInits)
3584 NumElements = 0;
3585 }
3586 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3587 NumElements = VType->getNumElements();
3588 } else if (CurrentObjectType->isRecordType()) {
3589 NumElements = numStructUnionElements(CurrentObjectType);
3590 } else if (CurrentObjectType->isDependentType()) {
3591 NumElements = 1;
3592 }
3593
3594 Result->reserveInits(SemaRef.Context, NumElements);
3595
3596 return Result;
3597}
3598
3599/// Update the initializer at index @p StructuredIndex within the
3600/// structured initializer list to the value @p expr.
3601void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3602 unsigned &StructuredIndex,
3603 Expr *expr) {
3604 // No structured initializer list to update
3605 if (!StructuredList)
3606 return;
3607
3608 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3609 StructuredIndex, expr)) {
3610 // This initializer overwrites a previous initializer.
3611 // No need to diagnose when `expr` is nullptr because a more relevant
3612 // diagnostic has already been issued and this diagnostic is potentially
3613 // noise.
3614 if (expr)
3615 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3616 }
3617
3618 ++StructuredIndex;
3619}
3620
3622 const InitializedEntity &Entity, InitListExpr *From) {
3623 QualType Type = Entity.getType();
3624 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3625 /*TreatUnavailableAsInvalid=*/false,
3626 /*InOverloadResolution=*/true);
3627 return !Check.HadError();
3628}
3629
3630/// Check that the given Index expression is a valid array designator
3631/// value. This is essentially just a wrapper around
3632/// VerifyIntegerConstantExpression that also checks for negative values
3633/// and produces a reasonable diagnostic if there is a
3634/// failure. Returns the index expression, possibly with an implicit cast
3635/// added, on success. If everything went okay, Value will receive the
3636/// value of the constant expression.
3637static ExprResult
3638CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3639 SourceLocation Loc = Index->getBeginLoc();
3640
3641 // Make sure this is an integer constant expression.
3644 if (Result.isInvalid())
3645 return Result;
3646
3647 if (Value.isSigned() && Value.isNegative())
3648 return S.Diag(Loc, diag::err_array_designator_negative)
3649 << toString(Value, 10) << Index->getSourceRange();
3650
3651 Value.setIsUnsigned(true);
3652 return Result;
3653}
3654
3656 SourceLocation EqualOrColonLoc,
3657 bool GNUSyntax,
3658 ExprResult Init) {
3659 typedef DesignatedInitExpr::Designator ASTDesignator;
3660
3661 bool Invalid = false;
3663 SmallVector<Expr *, 32> InitExpressions;
3664
3665 // Build designators and check array designator expressions.
3666 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3667 const Designator &D = Desig.getDesignator(Idx);
3668
3669 if (D.isFieldDesignator()) {
3670 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3671 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3672 } else if (D.isArrayDesignator()) {
3673 Expr *Index = D.getArrayIndex();
3674 llvm::APSInt IndexValue;
3675 if (!Index->isTypeDependent() && !Index->isValueDependent())
3676 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3677 if (!Index)
3678 Invalid = true;
3679 else {
3680 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3681 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3682 InitExpressions.push_back(Index);
3683 }
3684 } else if (D.isArrayRangeDesignator()) {
3685 Expr *StartIndex = D.getArrayRangeStart();
3686 Expr *EndIndex = D.getArrayRangeEnd();
3687 llvm::APSInt StartValue;
3688 llvm::APSInt EndValue;
3689 bool StartDependent = StartIndex->isTypeDependent() ||
3690 StartIndex->isValueDependent();
3691 bool EndDependent = EndIndex->isTypeDependent() ||
3692 EndIndex->isValueDependent();
3693 if (!StartDependent)
3694 StartIndex =
3695 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3696 if (!EndDependent)
3697 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3698
3699 if (!StartIndex || !EndIndex)
3700 Invalid = true;
3701 else {
3702 // Make sure we're comparing values with the same bit width.
3703 if (StartDependent || EndDependent) {
3704 // Nothing to compute.
3705 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3706 EndValue = EndValue.extend(StartValue.getBitWidth());
3707 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3708 StartValue = StartValue.extend(EndValue.getBitWidth());
3709
3710 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3711 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3712 << toString(StartValue, 10) << toString(EndValue, 10)
3713 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3714 Invalid = true;
3715 } else {
3716 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3717 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3718 D.getRBracketLoc()));
3719 InitExpressions.push_back(StartIndex);
3720 InitExpressions.push_back(EndIndex);
3721 }
3722 }
3723 }
3724 }
3725
3726 if (Invalid || Init.isInvalid())
3727 return ExprError();
3728
3729 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3730 EqualOrColonLoc, GNUSyntax,
3731 Init.getAs<Expr>());
3732}
3733
3734//===----------------------------------------------------------------------===//
3735// Initialization entity
3736//===----------------------------------------------------------------------===//
3737
3738InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3739 const InitializedEntity &Parent)
3740 : Parent(&Parent), Index(Index)
3741{
3742 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3743 Kind = EK_ArrayElement;
3744 Type = AT->getElementType();
3745 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3746 Kind = EK_VectorElement;
3747 Type = VT->getElementType();
3748 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3749 Kind = EK_MatrixElement;
3750 Type = MT->getElementType();
3751 } else {
3752 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3753 assert(CT && "Unexpected type");
3754 Kind = EK_ComplexElement;
3755 Type = CT->getElementType();
3756 }
3757}
3758
3761 const CXXBaseSpecifier *Base,
3762 bool IsInheritedVirtualBase,
3763 const InitializedEntity *Parent) {
3764 InitializedEntity Result;
3765 Result.Kind = EK_Base;
3766 Result.Parent = Parent;
3767 Result.Base = {Base, IsInheritedVirtualBase};
3768 Result.Type = Base->getType();
3769 return Result;
3770}
3771
3773 switch (getKind()) {
3774 case EK_Parameter:
3776 ParmVarDecl *D = Parameter.getPointer();
3777 return (D ? D->getDeclName() : DeclarationName());
3778 }
3779
3780 case EK_Variable:
3781 case EK_Member:
3783 case EK_Binding:
3785 return Variable.VariableOrMember->getDeclName();
3786
3787 case EK_LambdaCapture:
3788 return DeclarationName(Capture.VarID);
3789
3790 case EK_Result:
3791 case EK_StmtExprResult:
3792 case EK_Exception:
3793 case EK_New:
3794 case EK_Temporary:
3795 case EK_Base:
3796 case EK_Delegating:
3797 case EK_ArrayElement:
3798 case EK_VectorElement:
3799 case EK_MatrixElement:
3800 case EK_ComplexElement:
3801 case EK_BlockElement:
3804 case EK_RelatedResult:
3805 return DeclarationName();
3806 }
3807
3808 llvm_unreachable("Invalid EntityKind!");
3809}
3810
3812 switch (getKind()) {
3813 case EK_Variable:
3814 case EK_Member:
3816 case EK_Binding:
3818 return cast<ValueDecl>(Variable.VariableOrMember);
3819
3820 case EK_Parameter:
3822 return Parameter.getPointer();
3823
3824 case EK_Result:
3825 case EK_StmtExprResult:
3826 case EK_Exception:
3827 case EK_New:
3828 case EK_Temporary:
3829 case EK_Base:
3830 case EK_Delegating:
3831 case EK_ArrayElement:
3832 case EK_VectorElement:
3833 case EK_MatrixElement:
3834 case EK_ComplexElement:
3835 case EK_BlockElement:
3837 case EK_LambdaCapture:
3839 case EK_RelatedResult:
3840 return nullptr;
3841 }
3842
3843 llvm_unreachable("Invalid EntityKind!");
3844}
3845
3847 switch (getKind()) {
3848 case EK_Result:
3849 case EK_Exception:
3850 return LocAndNRVO.NRVO == NRVOKind::Allowed;
3851
3852 case EK_StmtExprResult:
3853 case EK_Variable:
3854 case EK_Parameter:
3857 case EK_Member:
3859 case EK_Binding:
3860 case EK_New:
3861 case EK_Temporary:
3863 case EK_Base:
3864 case EK_Delegating:
3865 case EK_ArrayElement:
3866 case EK_VectorElement:
3867 case EK_MatrixElement:
3868 case EK_ComplexElement:
3869 case EK_BlockElement:
3871 case EK_LambdaCapture:
3872 case EK_RelatedResult:
3873 break;
3874 }
3875
3876 return false;
3877}
3878
3879unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3880 assert(getParent() != this);
3881 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3882 for (unsigned I = 0; I != Depth; ++I)
3883 OS << "`-";
3884
3885 switch (getKind()) {
3886 case EK_Variable: OS << "Variable"; break;
3887 case EK_Parameter: OS << "Parameter"; break;
3888 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3889 break;
3890 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3891 case EK_Result: OS << "Result"; break;
3892 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3893 case EK_Exception: OS << "Exception"; break;
3894 case EK_Member:
3896 OS << "Member";
3897 break;
3898 case EK_Binding: OS << "Binding"; break;
3899 case EK_New: OS << "New"; break;
3900 case EK_Temporary: OS << "Temporary"; break;
3901 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3902 case EK_RelatedResult: OS << "RelatedResult"; break;
3903 case EK_Base: OS << "Base"; break;
3904 case EK_Delegating: OS << "Delegating"; break;
3905 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3906 case EK_VectorElement: OS << "VectorElement " << Index; break;
3907 case EK_MatrixElement:
3908 OS << "MatrixElement " << Index;
3909 break;
3910 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3911 case EK_BlockElement: OS << "Block"; break;
3913 OS << "Block (lambda)";
3914 break;
3915 case EK_LambdaCapture:
3916 OS << "LambdaCapture ";
3917 OS << DeclarationName(Capture.VarID);
3918 break;
3919 }
3920
3921 if (auto *D = getDecl()) {
3922 OS << " ";
3923 D->printQualifiedName(OS);
3924 }
3925
3926 OS << " '" << getType() << "'\n";
3927
3928 return Depth + 1;
3929}
3930
3931LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3932 dumpImpl(llvm::errs());
3933}
3934
3935//===----------------------------------------------------------------------===//
3936// Initialization sequence
3937//===----------------------------------------------------------------------===//
3938
3985
3987 // There can be some lvalue adjustments after the SK_BindReference step.
3988 for (const Step &S : llvm::reverse(Steps)) {
3989 if (S.Kind == SK_BindReference)
3990 return true;
3991 if (S.Kind == SK_BindReferenceToTemporary)
3992 return false;
3993 }
3994 return false;
3995}
3996
3998 if (!Failed())
3999 return false;
4000
4001 switch (getFailureKind()) {
4012 case FK_AddressOfOverloadFailed: // FIXME: Could do better
4029 case FK_Incomplete:
4034 case FK_PlaceholderType:
4040 return false;
4041
4046 return FailedOverloadResult == OR_Ambiguous;
4047 }
4048
4049 llvm_unreachable("Invalid EntityKind!");
4050}
4051
4053 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
4054}
4055
4056void
4057InitializationSequence
4058::AddAddressOverloadResolutionStep(FunctionDecl *Function,
4060 bool HadMultipleCandidates) {
4061 Step S;
4063 S.Type = Function->getType();
4064 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4067 Steps.push_back(S);
4068}
4069
4071 ExprValueKind VK) {
4072 Step S;
4073 switch (VK) {
4074 case VK_PRValue:
4076 break;
4077 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4078 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4079 }
4080 S.Type = BaseType;
4081 Steps.push_back(S);
4082}
4083
4085 bool BindingTemporary) {
4086 Step S;
4087 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4088 S.Type = T;
4089 Steps.push_back(S);
4090}
4091
4093 Step S;
4094 S.Kind = SK_FinalCopy;
4095 S.Type = T;
4096 Steps.push_back(S);
4097}
4098
4100 Step S;
4102 S.Type = T;
4103 Steps.push_back(S);
4104}
4105
4106void
4108 DeclAccessPair FoundDecl,
4109 QualType T,
4110 bool HadMultipleCandidates) {
4111 Step S;
4113 S.Type = T;
4114 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4116 S.Function.FoundDecl = FoundDecl;
4117 Steps.push_back(S);
4118}
4119
4121 ExprValueKind VK) {
4122 Step S;
4123 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4124 switch (VK) {
4125 case VK_PRValue:
4127 break;
4128 case VK_XValue:
4130 break;
4131 case VK_LValue:
4133 break;
4134 }
4135 S.Type = Ty;
4136 Steps.push_back(S);
4137}
4138
4140 Step S;
4142 S.Type = Ty;
4143 Steps.push_back(S);
4144}
4145
4147 Step S;
4149 S.Type = Ty;
4150 Steps.push_back(S);
4151}
4152
4155 bool TopLevelOfInitList) {
4156 Step S;
4157 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4159 S.Type = T;
4160 S.ICS = new ImplicitConversionSequence(ICS);
4161 Steps.push_back(S);
4162}
4163
4165 Step S;
4167 S.Type = T;
4168 Steps.push_back(S);
4169}
4170
4173 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4174 Step S;
4175 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4178 S.Type = T;
4179 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4181 S.Function.FoundDecl = FoundDecl;
4182 Steps.push_back(S);
4183}
4184
4186 Step S;
4188 S.Type = T;
4189 Steps.push_back(S);
4190}
4191
4193 Step S;
4194 S.Kind = SK_CAssignment;
4195 S.Type = T;
4196 Steps.push_back(S);
4197}
4198
4200 Step S;
4201 S.Kind = SK_StringInit;
4202 S.Type = T;
4203 Steps.push_back(S);
4204}
4205
4207 Step S;
4209 S.Type = T;
4210 Steps.push_back(S);
4211}
4212
4214 Step S;
4215 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4216 S.Type = T;
4217 Steps.push_back(S);
4218}
4219
4221 Step S;
4223 S.Type = EltT;
4224 Steps.insert(Steps.begin(), S);
4225
4227 S.Type = T;
4228 Steps.push_back(S);
4229}
4230
4232 Step S;
4234 S.Type = T;
4235 Steps.push_back(S);
4236}
4237
4239 bool shouldCopy) {
4240 Step s;
4241 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4243 s.Type = type;
4244 Steps.push_back(s);
4245}
4246
4248 Step S;
4250 S.Type = T;
4251 Steps.push_back(S);
4252}
4253
4255 Step S;
4257 S.Type = T;
4258 Steps.push_back(S);
4259}
4260
4262 Step S;
4264 S.Type = T;
4265 Steps.push_back(S);
4266}
4267
4269 Step S;
4271 S.Type = T;
4272 Steps.push_back(S);
4273}
4274
4276 Step S;
4278 S.Type = T;
4279 Steps.push_back(S);
4280}
4281
4283 InitListExpr *Syntactic) {
4284 assert(Syntactic->getNumInits() == 1 &&
4285 "Can only unwrap trivial init lists.");
4286 Step S;
4288 S.Type = Syntactic->getInit(0)->getType();
4289 Steps.insert(Steps.begin(), S);
4290}
4291
4293 InitListExpr *Syntactic) {
4294 assert(Syntactic->getNumInits() == 1 &&
4295 "Can only rewrap trivial init lists.");
4296 Step S;
4298 S.Type = Syntactic->getInit(0)->getType();
4299 Steps.insert(Steps.begin(), S);
4300
4302 S.Type = T;
4303 S.WrappingSyntacticList = Syntactic;
4304 Steps.push_back(S);
4305}
4306
4308 Step S;
4310 S.Type = T;
4311 Steps.push_back(S);
4312}
4313
4317 this->Failure = Failure;
4318 this->FailedOverloadResult = Result;
4319}
4320
4321//===----------------------------------------------------------------------===//
4322// Attempt initialization
4323//===----------------------------------------------------------------------===//
4324
4325/// Tries to add a zero initializer. Returns true if that worked.
4326static bool
4328 const InitializedEntity &Entity) {
4330 return false;
4331
4332 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4333 if (VD->getInit() || VD->getEndLoc().isMacroID())
4334 return false;
4335
4336 QualType VariableTy = VD->getType().getCanonicalType();
4338 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4339 if (!Init.empty()) {
4340 Sequence.AddZeroInitializationStep(Entity.getType());
4341 Sequence.SetZeroInitializationFixit(Init, Loc);
4342 return true;
4343 }
4344 return false;
4345}
4346
4348 InitializationSequence &Sequence,
4349 const InitializedEntity &Entity) {
4350 if (!S.getLangOpts().ObjCAutoRefCount) return;
4351
4352 /// When initializing a parameter, produce the value if it's marked
4353 /// __attribute__((ns_consumed)).
4354 if (Entity.isParameterKind()) {
4355 if (!Entity.isParameterConsumed())
4356 return;
4357
4358 assert(Entity.getType()->isObjCRetainableType() &&
4359 "consuming an object of unretainable type?");
4360 Sequence.AddProduceObjCObjectStep(Entity.getType());
4361
4362 /// When initializing a return value, if the return type is a
4363 /// retainable type, then returns need to immediately retain the
4364 /// object. If an autorelease is required, it will be done at the
4365 /// last instant.
4366 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4368 if (!Entity.getType()->isObjCRetainableType())
4369 return;
4370
4371 Sequence.AddProduceObjCObjectStep(Entity.getType());
4372 }
4373}
4374
4375/// Initialize an array from another array
4376static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4377 const InitializedEntity &Entity, Expr *Initializer,
4378 QualType DestType, InitializationSequence &Sequence,
4379 bool TreatUnavailableAsInvalid) {
4380 // If source is a prvalue, use it directly.
4381 if (Initializer->isPRValue()) {
4382 Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4383 return;
4384 }
4385
4386 // Emit element-at-a-time copy loop.
4387 InitializedEntity Element =
4389 QualType InitEltT =
4391
4392 // FIXME: Here's a functional memory leak cuz we don't have a temporary
4393 // allocator at the moment
4395 Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(),
4396 Initializer->getObjectKind());
4397 Expr *OVEAsExpr = OVE;
4398 Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4399 /*TopLevelOfInitList*/ false,
4400 TreatUnavailableAsInvalid);
4401 if (Sequence)
4402 Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4403}
4404
4405static void TryListInitialization(Sema &S,
4406 const InitializedEntity &Entity,
4407 const InitializationKind &Kind,
4408 InitListExpr *InitList,
4409 InitializationSequence &Sequence,
4410 bool TreatUnavailableAsInvalid);
4411
4412/// When initializing from init list via constructor, handle
4413/// initialization of an object of type std::initializer_list<T>.
4414///
4415/// \return true if we have handled initialization of an object of type
4416/// std::initializer_list<T>, false otherwise.
4418 InitListExpr *List,
4419 QualType DestType,
4420 InitializationSequence &Sequence,
4421 bool TreatUnavailableAsInvalid) {
4422 QualType E;
4423 if (!S.isStdInitializerList(DestType, &E))
4424 return false;
4425
4426 if (!S.isCompleteType(List->getExprLoc(), E)) {
4427 Sequence.setIncompleteTypeFailure(E);
4428 return true;
4429 }
4430
4431 // Try initializing a temporary array from the init list.
4433 E.withConst(),
4434 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4437 InitializedEntity HiddenArray =
4440 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4441 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4442 TreatUnavailableAsInvalid);
4443 if (Sequence)
4444 Sequence.AddStdInitializerListConstructionStep(DestType);
4445 return true;
4446}
4447
4448/// Determine if the constructor has the signature of a copy or move
4449/// constructor for the type T of the class in which it was found. That is,
4450/// determine if its first parameter is of type T or reference to (possibly
4451/// cv-qualified) T.
4453 const ConstructorInfo &Info) {
4454 if (Info.Constructor->getNumParams() == 0)
4455 return false;
4456
4457 QualType ParmT =
4459 CanQualType ClassT = Ctx.getCanonicalTagType(
4461
4462 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4463}
4464
4466 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4467 OverloadCandidateSet &CandidateSet, QualType DestType,
4469 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4470 bool IsListInit, bool RequireActualConstructor,
4471 bool SecondStepOfCopyInit = false) {
4473 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4474
4475 for (NamedDecl *D : Ctors) {
4476 auto Info = getConstructorInfo(D);
4477 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4478 continue;
4479
4480 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4481 continue;
4482
4483 // C++11 [over.best.ics]p4:
4484 // ... and the constructor or user-defined conversion function is a
4485 // candidate by
4486 // - 13.3.1.3, when the argument is the temporary in the second step
4487 // of a class copy-initialization, or
4488 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4489 // - the second phase of 13.3.1.7 when the initializer list has exactly
4490 // one element that is itself an initializer list, and the target is
4491 // the first parameter of a constructor of class X, and the conversion
4492 // is to X or reference to (possibly cv-qualified X),
4493 // user-defined conversion sequences are not considered.
4494 bool SuppressUserConversions =
4495 SecondStepOfCopyInit ||
4496 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4498
4499 if (Info.ConstructorTmpl)
4501 Info.ConstructorTmpl, Info.FoundDecl,
4502 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4503 /*PartialOverloading=*/false, AllowExplicit);
4504 else {
4505 // C++ [over.match.copy]p1:
4506 // - When initializing a temporary to be bound to the first parameter
4507 // of a constructor [for type T] that takes a reference to possibly
4508 // cv-qualified T as its first argument, called with a single
4509 // argument in the context of direct-initialization, explicit
4510 // conversion functions are also considered.
4511 // FIXME: What if a constructor template instantiates to such a signature?
4512 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4513 Args.size() == 1 &&
4515 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4516 CandidateSet, SuppressUserConversions,
4517 /*PartialOverloading=*/false, AllowExplicit,
4518 AllowExplicitConv);
4519 }
4520 }
4521
4522 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4523 //
4524 // When initializing an object of class type T by constructor
4525 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4526 // from a single expression of class type U, conversion functions of
4527 // U that convert to the non-reference type cv T are candidates.
4528 // Explicit conversion functions are only candidates during
4529 // direct-initialization.
4530 //
4531 // Note: SecondStepOfCopyInit is only ever true in this case when
4532 // evaluating whether to produce a C++98 compatibility warning.
4533 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4534 !RequireActualConstructor && !SecondStepOfCopyInit) {
4535 Expr *Initializer = Args[0];
4536 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4537 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4538 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4539 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4540 NamedDecl *D = *I;
4542 D = D->getUnderlyingDecl();
4543
4544 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4545 CXXConversionDecl *Conv;
4546 if (ConvTemplate)
4547 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4548 else
4549 Conv = cast<CXXConversionDecl>(D);
4550
4551 if (ConvTemplate)
4553 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4554 CandidateSet, AllowExplicit, AllowExplicit,
4555 /*AllowResultConversion*/ false);
4556 else
4557 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4558 DestType, CandidateSet, AllowExplicit,
4559 AllowExplicit,
4560 /*AllowResultConversion*/ false);
4561 }
4562 }
4563 }
4564
4565 // Perform overload resolution and return the result.
4566 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4567}
4568
4569/// Attempt initialization by constructor (C++ [dcl.init]), which
4570/// enumerates the constructors of the initialized entity and performs overload
4571/// resolution to select the best.
4572/// \param DestType The destination class type.
4573/// \param DestArrayType The destination type, which is either DestType or
4574/// a (possibly multidimensional) array of DestType.
4575/// \param IsListInit Is this list-initialization?
4576/// \param IsInitListCopy Is this non-list-initialization resulting from a
4577/// list-initialization from {x} where x is the same
4578/// aggregate type as the entity?
4580 const InitializedEntity &Entity,
4581 const InitializationKind &Kind,
4582 MultiExprArg Args, QualType DestType,
4583 QualType DestArrayType,
4584 InitializationSequence &Sequence,
4585 bool IsListInit = false,
4586 bool IsInitListCopy = false) {
4587 assert(((!IsListInit && !IsInitListCopy) ||
4588 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4589 "IsListInit/IsInitListCopy must come with a single initializer list "
4590 "argument.");
4591 InitListExpr *ILE =
4592 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4593 MultiExprArg UnwrappedArgs =
4594 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4595
4596 // The type we're constructing needs to be complete.
4597 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4598 Sequence.setIncompleteTypeFailure(DestType);
4599 return;
4600 }
4601
4602 bool RequireActualConstructor =
4603 !(Entity.getKind() != InitializedEntity::EK_Base &&
4605 Entity.getKind() !=
4607
4608 bool CopyElisionPossible = false;
4609 auto ElideConstructor = [&] {
4610 // Convert qualifications if necessary.
4611 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4612 if (ILE)
4613 Sequence.RewrapReferenceInitList(DestType, ILE);
4614 };
4615
4616 // C++17 [dcl.init]p17:
4617 // - If the initializer expression is a prvalue and the cv-unqualified
4618 // version of the source type is the same class as the class of the
4619 // destination, the initializer expression is used to initialize the
4620 // destination object.
4621 // Per DR (no number yet), this does not apply when initializing a base
4622 // class or delegating to another constructor from a mem-initializer.
4623 // ObjC++: Lambda captured by the block in the lambda to block conversion
4624 // should avoid copy elision.
4625 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4626 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4627 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4628 if (ILE && !DestType->isAggregateType()) {
4629 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4630 // Make this an elision if this won't call an initializer-list
4631 // constructor. (Always on an aggregate type or check constructors first.)
4632
4633 // This effectively makes our resolution as follows. The parts in angle
4634 // brackets are additions.
4635 // C++17 [over.match.list]p(1.2):
4636 // - If no viable initializer-list constructor is found <and the
4637 // initializer list does not consist of exactly a single element with
4638 // the same cv-unqualified class type as T>, [...]
4639 // C++17 [dcl.init.list]p(3.6):
4640 // - Otherwise, if T is a class type, constructors are considered. The
4641 // applicable constructors are enumerated and the best one is chosen
4642 // through overload resolution. <If no constructor is found and the
4643 // initializer list consists of exactly a single element with the same
4644 // cv-unqualified class type as T, the object is initialized from that
4645 // element (by copy-initialization for copy-list-initialization, or by
4646 // direct-initialization for direct-list-initialization). Otherwise, >
4647 // if a narrowing conversion [...]
4648 assert(!IsInitListCopy &&
4649 "IsInitListCopy only possible with aggregate types");
4650 CopyElisionPossible = true;
4651 } else {
4652 ElideConstructor();
4653 return;
4654 }
4655 }
4656
4657 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4658 // Build the candidate set directly in the initialization sequence
4659 // structure, so that it will persist if we fail.
4660 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4661
4662 // Determine whether we are allowed to call explicit constructors or
4663 // explicit conversion operators.
4664 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4665 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4666
4667 // - Otherwise, if T is a class type, constructors are considered. The
4668 // applicable constructors are enumerated, and the best one is chosen
4669 // through overload resolution.
4670 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4671
4674 bool AsInitializerList = false;
4675
4676 // C++11 [over.match.list]p1, per DR1467:
4677 // When objects of non-aggregate type T are list-initialized, such that
4678 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4679 // according to the rules in this section, overload resolution selects
4680 // the constructor in two phases:
4681 //
4682 // - Initially, the candidate functions are the initializer-list
4683 // constructors of the class T and the argument list consists of the
4684 // initializer list as a single argument.
4685 if (IsListInit) {
4686 AsInitializerList = true;
4687
4688 // If the initializer list has no elements and T has a default constructor,
4689 // the first phase is omitted.
4690 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4692 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4693 CopyInitialization, AllowExplicit,
4694 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4695
4696 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4697 // No initializer list candidate
4698 ElideConstructor();
4699 return;
4700 }
4701 }
4702
4703 // if the initialization is direct-initialization, or if it is
4704 // copy-initialization where the cv-unqualified version of the source type is
4705 // the same as or is derived from the class of the destination type,
4706 // constructors are considered.
4707 if ((Kind.getKind() == InitializationKind::IK_Direct ||
4708 Kind.getKind() == InitializationKind::IK_Copy) &&
4709 Args.size() == 1 &&
4711 Args[0]->getType().getNonReferenceType(),
4712 DestType.getNonReferenceType()))
4713 RequireActualConstructor = true;
4714
4715 // C++11 [over.match.list]p1:
4716 // - If no viable initializer-list constructor is found, overload resolution
4717 // is performed again, where the candidate functions are all the
4718 // constructors of the class T and the argument list consists of the
4719 // elements of the initializer list.
4721 AsInitializerList = false;
4723 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4724 Best, CopyInitialization, AllowExplicit,
4725 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4726 }
4727 if (Result) {
4728 Sequence.SetOverloadFailure(
4731 Result);
4732
4733 if (Result != OR_Deleted)
4734 return;
4735 }
4736
4737 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4738
4739 // In C++17, ResolveConstructorOverload can select a conversion function
4740 // instead of a constructor.
4741 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4742 // Add the user-defined conversion step that calls the conversion function.
4743 QualType ConvType = CD->getConversionType();
4744 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4745 "should not have selected this conversion function");
4746 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4747 HadMultipleCandidates);
4748 if (!S.Context.hasSameType(ConvType, DestType))
4749 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4750 if (IsListInit)
4751 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4752 return;
4753 }
4754
4755 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4756 if (Result != OR_Deleted) {
4757 if (!IsListInit &&
4758 (Kind.getKind() == InitializationKind::IK_Default ||
4759 Kind.getKind() == InitializationKind::IK_Direct) &&
4760 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4761 DestRecordDecl->isAggregate() &&
4762 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4763 !S.isUnevaluatedContext()) {
4764 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4765 << /* Var-in-Record */ 1 << DestRecordDecl;
4766 emitUninitializedExplicitInitFields(S, DestRecordDecl);
4767 }
4768
4769 // C++11 [dcl.init]p6:
4770 // If a program calls for the default initialization of an object
4771 // of a const-qualified type T, T shall be a class type with a
4772 // user-provided default constructor.
4773 // C++ core issue 253 proposal:
4774 // If the implicit default constructor initializes all subobjects, no
4775 // initializer should be required.
4776 // The 253 proposal is for example needed to process libstdc++ headers
4777 // in 5.x.
4778 if (Kind.getKind() == InitializationKind::IK_Default &&
4779 Entity.getType().isConstQualified()) {
4780 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4781 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4783 return;
4784 }
4785 }
4786
4787 // C++11 [over.match.list]p1:
4788 // In copy-list-initialization, if an explicit constructor is chosen, the
4789 // initializer is ill-formed.
4790 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4792 return;
4793 }
4794 }
4795
4796 // [class.copy.elision]p3:
4797 // In some copy-initialization contexts, a two-stage overload resolution
4798 // is performed.
4799 // If the first overload resolution selects a deleted function, we also
4800 // need the initialization sequence to decide whether to perform the second
4801 // overload resolution.
4802 // For deleted functions in other contexts, there is no need to get the
4803 // initialization sequence.
4804 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4805 return;
4806
4807 // Add the constructor initialization step. Any cv-qualification conversion is
4808 // subsumed by the initialization.
4810 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4811 IsListInit | IsInitListCopy, AsInitializerList);
4812}
4813
4815 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4816 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4817 ExprResult *Result = nullptr);
4818
4819/// Attempt to initialize an object of a class type either by
4820/// direct-initialization, or by copy-initialization from an
4821/// expression of the same or derived class type. This corresponds
4822/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4823///
4824/// \param IsAggrListInit Is this non-list-initialization being done as
4825/// part of a list-initialization of an aggregate
4826/// from a single expression of the same or
4827/// derived class type (C++2c [dcl.init.list] p3.2)?
4829 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4830 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4831 bool IsAggrListInit) {
4832 // C++2c [dcl.init.general] p16.6:
4833 // * Otherwise, if the destination type is a class type:
4834 // * If the initializer expression is a prvalue and
4835 // the cv-unqualified version of the source type is the same
4836 // as the destination type, the initializer expression is used
4837 // to initialize the destination object.
4838 // * Otherwise, if the initialization is direct-initialization,
4839 // or if it is copy-initialization where the cv-unqualified
4840 // version of the source type is the same as or is derived from
4841 // the class of the destination type, constructors are considered.
4842 // The applicable constructors are enumerated, and the best one
4843 // is chosen through overload resolution. Then:
4844 // * If overload resolution is successful, the selected
4845 // constructor is called to initialize the object, with
4846 // the initializer expression or expression-list as its
4847 // argument(s).
4848 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
4849 Sequence, /*IsListInit=*/false, IsAggrListInit);
4850
4851 // * Otherwise, if no constructor is viable, the destination type
4852 // is an aggregate class, and the initializer is a parenthesized
4853 // expression-list, the object is initialized as follows. [...]
4854 // Parenthesized initialization of aggregates is a C++20 feature.
4855 if (S.getLangOpts().CPlusPlus20 &&
4856 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4857 Sequence.getFailureKind() ==
4860 (IsAggrListInit || DestType->isAggregateType()))
4861 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4862 /*VerifyOnly=*/true);
4863
4864 // * Otherwise, the initialization is ill-formed.
4865}
4866
4867static bool
4870 QualType &SourceType,
4871 QualType &UnqualifiedSourceType,
4872 QualType UnqualifiedTargetType,
4873 InitializationSequence &Sequence) {
4874 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4875 S.Context.OverloadTy) {
4877 bool HadMultipleCandidates = false;
4878 if (FunctionDecl *Fn
4880 UnqualifiedTargetType,
4881 false, Found,
4882 &HadMultipleCandidates)) {
4884 HadMultipleCandidates);
4885 SourceType = Fn->getType();
4886 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4887 } else if (!UnqualifiedTargetType->isRecordType()) {
4889 return true;
4890 }
4891 }
4892 return false;
4893}
4894
4895static void TryReferenceInitializationCore(Sema &S,
4896 const InitializedEntity &Entity,
4897 const InitializationKind &Kind,
4898 Expr *Initializer,
4899 QualType cv1T1, QualType T1,
4900 Qualifiers T1Quals,
4901 QualType cv2T2, QualType T2,
4902 Qualifiers T2Quals,
4903 InitializationSequence &Sequence,
4904 bool TopLevelOfInitList);
4905
4906static void TryValueInitialization(Sema &S,
4907 const InitializedEntity &Entity,
4908 const InitializationKind &Kind,
4909 InitializationSequence &Sequence,
4910 InitListExpr *InitList = nullptr);
4911
4912/// Attempt list initialization of a reference.
4914 const InitializedEntity &Entity,
4915 const InitializationKind &Kind,
4916 InitListExpr *InitList,
4917 InitializationSequence &Sequence,
4918 bool TreatUnavailableAsInvalid) {
4919 // First, catch C++03 where this isn't possible.
4920 if (!S.getLangOpts().CPlusPlus11) {
4922 return;
4923 }
4924 // Can't reference initialize a compound literal.
4927 return;
4928 }
4929
4930 QualType DestType = Entity.getType();
4931 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4932 Qualifiers T1Quals;
4933 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4934
4935 // Reference initialization via an initializer list works thus:
4936 // If the initializer list consists of a single element that is
4937 // reference-related to the referenced type, bind directly to that element
4938 // (possibly creating temporaries).
4939 // Otherwise, initialize a temporary with the initializer list and
4940 // bind to that.
4941 if (InitList->getNumInits() == 1) {
4942 Expr *Initializer = InitList->getInit(0);
4944 Qualifiers T2Quals;
4945 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4946
4947 // If this fails, creating a temporary wouldn't work either.
4949 T1, Sequence))
4950 return;
4951
4952 SourceLocation DeclLoc = Initializer->getBeginLoc();
4953 Sema::ReferenceCompareResult RefRelationship
4954 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4955 if (RefRelationship >= Sema::Ref_Related) {
4956 // Try to bind the reference here.
4957 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4958 T1Quals, cv2T2, T2, T2Quals, Sequence,
4959 /*TopLevelOfInitList=*/true);
4960 if (Sequence)
4961 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4962 return;
4963 }
4964
4965 // Update the initializer if we've resolved an overloaded function.
4966 if (!Sequence.steps().empty())
4967 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4968 }
4969 // Perform address space compatibility check.
4970 QualType cv1T1IgnoreAS = cv1T1;
4971 if (T1Quals.hasAddressSpace()) {
4972 Qualifiers T2Quals;
4973 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4974 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
4975 Sequence.SetFailed(
4977 return;
4978 }
4979 // Ignore address space of reference type at this point and perform address
4980 // space conversion after the reference binding step.
4981 cv1T1IgnoreAS =
4983 }
4984 // Not reference-related. Create a temporary and bind to that.
4985 InitializedEntity TempEntity =
4987
4988 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4989 TreatUnavailableAsInvalid);
4990 if (Sequence) {
4991 if (DestType->isRValueReferenceType() ||
4992 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4993 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4994 /*BindingTemporary=*/true);
4995 if (S.getLangOpts().CPlusPlus20 &&
4997 DestType->isRValueReferenceType()) {
4998 // C++20 [dcl.init.list]p3.10:
4999 // List-initialization of an object or reference of type T is defined as
5000 // follows:
5001 // ..., unless T is “reference to array of unknown bound of U”, in which
5002 // case the type of the prvalue is the type of x in the declaration U
5003 // x[] H, where H is the initializer list.
5004
5005 // The call to AddReferenceBindingStep above converts the rvalue to an
5006 // xvalue. Convert that xvalue to the incomplete array type.
5008 }
5009 if (T1Quals.hasAddressSpace())
5011 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
5012 } else
5013 Sequence.SetFailed(
5015 }
5016}
5017
5018/// Attempt list initialization (C++0x [dcl.init.list])
5020 const InitializedEntity &Entity,
5021 const InitializationKind &Kind,
5022 InitListExpr *InitList,
5023 InitializationSequence &Sequence,
5024 bool TreatUnavailableAsInvalid) {
5025 QualType DestType = Entity.getType();
5026
5027 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, InitList)) {
5029 return;
5030 }
5031
5032 // C++ doesn't allow scalar initialization with more than one argument.
5033 // But C99 complex numbers are scalars and it makes sense there.
5034 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
5035 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
5037 return;
5038 }
5039 if (DestType->isReferenceType()) {
5040 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
5041 TreatUnavailableAsInvalid);
5042 return;
5043 }
5044
5045 if (DestType->isRecordType() &&
5046 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
5047 Sequence.setIncompleteTypeFailure(DestType);
5048 return;
5049 }
5050
5051 // C++20 [dcl.init.list]p3:
5052 // - If the braced-init-list contains a designated-initializer-list, T shall
5053 // be an aggregate class. [...] Aggregate initialization is performed.
5054 //
5055 // We allow arrays here too in order to support array designators.
5056 //
5057 // FIXME: This check should precede the handling of reference initialization.
5058 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
5059 // as a tentative DR resolution.
5060 bool IsDesignatedInit = InitList->hasDesignatedInit();
5061 if (!DestType->isAggregateType() && IsDesignatedInit) {
5062 Sequence.SetFailed(
5064 return;
5065 }
5066
5067 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
5068 // - If T is an aggregate class and the initializer list has a single element
5069 // of type cv U, where U is T or a class derived from T, the object is
5070 // initialized from that element (by copy-initialization for
5071 // copy-list-initialization, or by direct-initialization for
5072 // direct-list-initialization).
5073 // - Otherwise, if T is a character array and the initializer list has a
5074 // single element that is an appropriately-typed string literal
5075 // (8.5.2 [dcl.init.string]), initialization is performed as described
5076 // in that section.
5077 // - Otherwise, if T is an aggregate, [...] (continue below).
5078 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
5079 !IsDesignatedInit) {
5080 if (DestType->isRecordType() && DestType->isAggregateType()) {
5081 QualType InitType = InitList->getInit(0)->getType();
5082 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
5083 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
5084 InitializationKind SubKind =
5086 ? InitializationKind::CreateDirect(Kind.getLocation(),
5087 InitList->getLBraceLoc(),
5088 InitList->getRBraceLoc())
5089 : Kind;
5090 Expr *InitListAsExpr = InitList;
5092 S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
5093 /*IsAggrListInit=*/true);
5094 return;
5095 }
5096 }
5097 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
5098 Expr *SubInit[1] = {InitList->getInit(0)};
5099
5100 // C++17 [dcl.struct.bind]p1:
5101 // ... If the assignment-expression in the initializer has array type A
5102 // and no ref-qualifier is present, e has type cv A and each element is
5103 // copy-initialized or direct-initialized from the corresponding element
5104 // of the assignment-expression as specified by the form of the
5105 // initializer. ...
5106 //
5107 // This is a special case not following list-initialization.
5108 if (isa<ConstantArrayType>(DestAT) &&
5110 isa<DecompositionDecl>(Entity.getDecl())) {
5111 assert(
5112 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5113 "Deduced to other type?");
5114 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5115 "List-initialize structured bindings but not "
5116 "direct-list-initialization?");
5117 TryArrayCopy(S,
5118 InitializationKind::CreateDirect(Kind.getLocation(),
5119 InitList->getLBraceLoc(),
5120 InitList->getRBraceLoc()),
5121 Entity, SubInit[0], DestType, Sequence,
5122 TreatUnavailableAsInvalid);
5123 if (Sequence)
5124 Sequence.AddUnwrapInitListInitStep(InitList);
5125 return;
5126 }
5127
5128 if (!isa<VariableArrayType>(DestAT) &&
5129 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
5130 InitializationKind SubKind =
5132 ? InitializationKind::CreateDirect(Kind.getLocation(),
5133 InitList->getLBraceLoc(),
5134 InitList->getRBraceLoc())
5135 : Kind;
5136 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5137 /*TopLevelOfInitList*/ true,
5138 TreatUnavailableAsInvalid);
5139
5140 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5141 // the element is not an appropriately-typed string literal, in which
5142 // case we should proceed as in C++11 (below).
5143 if (Sequence) {
5144 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5145 return;
5146 }
5147 }
5148 }
5149 }
5150
5151 // C++11 [dcl.init.list]p3:
5152 // - If T is an aggregate, aggregate initialization is performed.
5153 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5154 (S.getLangOpts().CPlusPlus11 &&
5155 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
5156 if (S.getLangOpts().CPlusPlus11) {
5157 // - Otherwise, if the initializer list has no elements and T is a
5158 // class type with a default constructor, the object is
5159 // value-initialized.
5160 if (InitList->getNumInits() == 0) {
5161 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5162 if (S.LookupDefaultConstructor(RD)) {
5163 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5164 return;
5165 }
5166 }
5167
5168 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5169 // an initializer_list object constructed [...]
5170 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
5171 TreatUnavailableAsInvalid))
5172 return;
5173
5174 // - Otherwise, if T is a class type, constructors are considered.
5175 Expr *InitListAsExpr = InitList;
5176 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
5177 DestType, Sequence, /*InitListSyntax*/true);
5178 } else
5180 return;
5181 }
5182
5183 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5184 InitList->getNumInits() == 1) {
5185 Expr *E = InitList->getInit(0);
5186
5187 // - Otherwise, if T is an enumeration with a fixed underlying type,
5188 // the initializer-list has a single element v, and the initialization
5189 // is direct-list-initialization, the object is initialized with the
5190 // value T(v); if a narrowing conversion is required to convert v to
5191 // the underlying type of T, the program is ill-formed.
5192 if (S.getLangOpts().CPlusPlus17 &&
5193 Kind.getKind() == InitializationKind::IK_DirectList &&
5194 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5195 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
5197 E->getType()->isFloatingType())) {
5198 // There are two ways that T(v) can work when T is an enumeration type.
5199 // If there is either an implicit conversion sequence from v to T or
5200 // a conversion function that can convert from v to T, then we use that.
5201 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5202 // type, it is converted to the enumeration type via its underlying type.
5203 // There is no overlap possible between these two cases (except when the
5204 // source value is already of the destination type), and the first
5205 // case is handled by the general case for single-element lists below.
5207 ICS.setStandard();
5209 if (!E->isPRValue())
5211 // If E is of a floating-point type, then the conversion is ill-formed
5212 // due to narrowing, but go through the motions in order to produce the
5213 // right diagnostic.
5217 ICS.Standard.setFromType(E->getType());
5218 ICS.Standard.setToType(0, E->getType());
5219 ICS.Standard.setToType(1, DestType);
5220 ICS.Standard.setToType(2, DestType);
5221 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
5222 /*TopLevelOfInitList*/true);
5223 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5224 return;
5225 }
5226
5227 // - Otherwise, if the initializer list has a single element of type E
5228 // [...references are handled above...], the object or reference is
5229 // initialized from that element (by copy-initialization for
5230 // copy-list-initialization, or by direct-initialization for
5231 // direct-list-initialization); if a narrowing conversion is required
5232 // to convert the element to T, the program is ill-formed.
5233 //
5234 // Per core-24034, this is direct-initialization if we were performing
5235 // direct-list-initialization and copy-initialization otherwise.
5236 // We can't use InitListChecker for this, because it always performs
5237 // copy-initialization. This only matters if we might use an 'explicit'
5238 // conversion operator, or for the special case conversion of nullptr_t to
5239 // bool, so we only need to handle those cases.
5240 //
5241 // FIXME: Why not do this in all cases?
5242 Expr *Init = InitList->getInit(0);
5243 if (Init->getType()->isRecordType() ||
5244 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5245 InitializationKind SubKind =
5247 ? InitializationKind::CreateDirect(Kind.getLocation(),
5248 InitList->getLBraceLoc(),
5249 InitList->getRBraceLoc())
5250 : Kind;
5251 Expr *SubInit[1] = { Init };
5252 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5253 /*TopLevelOfInitList*/true,
5254 TreatUnavailableAsInvalid);
5255 if (Sequence)
5256 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5257 return;
5258 }
5259 }
5260
5261 InitListChecker CheckInitList(S, Entity, InitList,
5262 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5263 if (CheckInitList.HadError()) {
5265 return;
5266 }
5267
5268 // Add the list initialization step with the built init list.
5269 Sequence.AddListInitializationStep(DestType);
5270}
5271
5272/// Try a reference initialization that involves calling a conversion
5273/// function.
5275 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5276 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5277 InitializationSequence &Sequence) {
5278 QualType DestType = Entity.getType();
5279 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5280 QualType T1 = cv1T1.getUnqualifiedType();
5281 QualType cv2T2 = Initializer->getType();
5282 QualType T2 = cv2T2.getUnqualifiedType();
5283
5284 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5285 "Must have incompatible references when binding via conversion");
5286
5287 // Build the candidate set directly in the initialization sequence
5288 // structure, so that it will persist if we fail.
5289 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5291
5292 // Determine whether we are allowed to call explicit conversion operators.
5293 // Note that none of [over.match.copy], [over.match.conv], nor
5294 // [over.match.ref] permit an explicit constructor to be chosen when
5295 // initializing a reference, not even for direct-initialization.
5296 bool AllowExplicitCtors = false;
5297 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5298
5299 if (AllowRValues && T1->isRecordType() &&
5300 S.isCompleteType(Kind.getLocation(), T1)) {
5301 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5302 if (T1RecordDecl->isInvalidDecl())
5303 return OR_No_Viable_Function;
5304 // The type we're converting to is a class type. Enumerate its constructors
5305 // to see if there is a suitable conversion.
5306 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
5307 auto Info = getConstructorInfo(D);
5308 if (!Info.Constructor)
5309 continue;
5310
5311 if (!Info.Constructor->isInvalidDecl() &&
5312 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5313 if (Info.ConstructorTmpl)
5315 Info.ConstructorTmpl, Info.FoundDecl,
5316 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5317 /*SuppressUserConversions=*/true,
5318 /*PartialOverloading*/ false, AllowExplicitCtors);
5319 else
5321 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
5322 /*SuppressUserConversions=*/true,
5323 /*PartialOverloading*/ false, AllowExplicitCtors);
5324 }
5325 }
5326 }
5327
5328 if (T2->isRecordType() && S.isCompleteType(Kind.getLocation(), T2)) {
5329 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5330 if (T2RecordDecl->isInvalidDecl())
5331 return OR_No_Viable_Function;
5332 // The type we're converting from is a class type, enumerate its conversion
5333 // functions.
5334 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5335 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5336 NamedDecl *D = *I;
5338 if (isa<UsingShadowDecl>(D))
5339 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5340
5341 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5342 CXXConversionDecl *Conv;
5343 if (ConvTemplate)
5344 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5345 else
5346 Conv = cast<CXXConversionDecl>(D);
5347
5348 // If the conversion function doesn't return a reference type,
5349 // it can't be considered for this conversion unless we're allowed to
5350 // consider rvalues.
5351 // FIXME: Do we need to make sure that we only consider conversion
5352 // candidates with reference-compatible results? That might be needed to
5353 // break recursion.
5354 if ((AllowRValues ||
5356 if (ConvTemplate)
5358 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5359 CandidateSet,
5360 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5361 else
5363 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5364 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5365 }
5366 }
5367 }
5368
5369 SourceLocation DeclLoc = Initializer->getBeginLoc();
5370
5371 // Perform overload resolution. If it fails, return the failed result.
5374 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5375 return Result;
5376
5377 FunctionDecl *Function = Best->Function;
5378 // This is the overload that will be used for this initialization step if we
5379 // use this initialization. Mark it as referenced.
5380 Function->setReferenced();
5381
5382 // Compute the returned type and value kind of the conversion.
5383 QualType cv3T3;
5384 if (isa<CXXConversionDecl>(Function))
5385 cv3T3 = Function->getReturnType();
5386 else
5387 cv3T3 = T1;
5388
5390 if (cv3T3->isLValueReferenceType())
5391 VK = VK_LValue;
5392 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5393 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5394 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5395
5396 // Add the user-defined conversion step.
5397 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5398 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5399 HadMultipleCandidates);
5400
5401 // Determine whether we'll need to perform derived-to-base adjustments or
5402 // other conversions.
5404 Sema::ReferenceCompareResult NewRefRelationship =
5405 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5406
5407 // Add the final conversion sequence, if necessary.
5408 if (NewRefRelationship == Sema::Ref_Incompatible) {
5409 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5410 "should not have conversion after constructor");
5411
5413 ICS.setStandard();
5414 ICS.Standard = Best->FinalConversion;
5415 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5416
5417 // Every implicit conversion results in a prvalue, except for a glvalue
5418 // derived-to-base conversion, which we handle below.
5419 cv3T3 = ICS.Standard.getToType(2);
5420 VK = VK_PRValue;
5421 }
5422
5423 // If the converted initializer is a prvalue, its type T4 is adjusted to
5424 // type "cv1 T4" and the temporary materialization conversion is applied.
5425 //
5426 // We adjust the cv-qualifications to match the reference regardless of
5427 // whether we have a prvalue so that the AST records the change. In this
5428 // case, T4 is "cv3 T3".
5429 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5430 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5431 Sequence.AddQualificationConversionStep(cv1T4, VK);
5432 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5433 VK = IsLValueRef ? VK_LValue : VK_XValue;
5434
5435 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5436 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5437 else if (RefConv & Sema::ReferenceConversions::ObjC)
5438 Sequence.AddObjCObjectConversionStep(cv1T1);
5439 else if (RefConv & Sema::ReferenceConversions::Function)
5440 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5441 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5442 if (!S.Context.hasSameType(cv1T4, cv1T1))
5443 Sequence.AddQualificationConversionStep(cv1T1, VK);
5444 }
5445
5446 return OR_Success;
5447}
5448
5449static void CheckCXX98CompatAccessibleCopy(Sema &S,
5450 const InitializedEntity &Entity,
5451 Expr *CurInitExpr);
5452
5453/// Attempt reference initialization (C++0x [dcl.init.ref])
5455 const InitializationKind &Kind,
5457 InitializationSequence &Sequence,
5458 bool TopLevelOfInitList) {
5459 QualType DestType = Entity.getType();
5460 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5461 Qualifiers T1Quals;
5462 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5464 Qualifiers T2Quals;
5465 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5466
5467 // If the initializer is the address of an overloaded function, try
5468 // to resolve the overloaded function. If all goes well, T2 is the
5469 // type of the resulting function.
5471 T1, Sequence))
5472 return;
5473
5474 // Delegate everything else to a subfunction.
5475 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5476 T1Quals, cv2T2, T2, T2Quals, Sequence,
5477 TopLevelOfInitList);
5478}
5479
5480/// Determine whether an expression is a non-referenceable glvalue (one to
5481/// which a reference can never bind). Attempting to bind a reference to
5482/// such a glvalue will always create a temporary.
5484 return E->refersToBitField() || E->refersToVectorElement() ||
5486}
5487
5488/// Reference initialization without resolving overloaded functions.
5489///
5490/// We also can get here in C if we call a builtin which is declared as
5491/// a function with a parameter of reference type (such as __builtin_va_end()).
5493 const InitializedEntity &Entity,
5494 const InitializationKind &Kind,
5496 QualType cv1T1, QualType T1,
5497 Qualifiers T1Quals,
5498 QualType cv2T2, QualType T2,
5499 Qualifiers T2Quals,
5500 InitializationSequence &Sequence,
5501 bool TopLevelOfInitList) {
5502 QualType DestType = Entity.getType();
5503 SourceLocation DeclLoc = Initializer->getBeginLoc();
5504
5505 // Compute some basic properties of the types and the initializer.
5506 bool isLValueRef = DestType->isLValueReferenceType();
5507 bool isRValueRef = !isLValueRef;
5508 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5509
5511 Sema::ReferenceCompareResult RefRelationship =
5512 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5513
5514 // C++0x [dcl.init.ref]p5:
5515 // A reference to type "cv1 T1" is initialized by an expression of type
5516 // "cv2 T2" as follows:
5517 //
5518 // - If the reference is an lvalue reference and the initializer
5519 // expression
5520 // Note the analogous bullet points for rvalue refs to functions. Because
5521 // there are no function rvalues in C++, rvalue refs to functions are treated
5522 // like lvalue refs.
5523 OverloadingResult ConvOvlResult = OR_Success;
5524 bool T1Function = T1->isFunctionType();
5525 if (isLValueRef || T1Function) {
5526 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5527 (RefRelationship == Sema::Ref_Compatible ||
5528 (Kind.isCStyleOrFunctionalCast() &&
5529 RefRelationship == Sema::Ref_Related))) {
5530 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5531 // reference-compatible with "cv2 T2," or
5532 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5533 Sema::ReferenceConversions::ObjC)) {
5534 // If we're converting the pointee, add any qualifiers first;
5535 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5536 if (RefConv & (Sema::ReferenceConversions::Qualification))
5538 S.Context.getQualifiedType(T2, T1Quals),
5539 Initializer->getValueKind());
5540 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5541 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5542 else
5543 Sequence.AddObjCObjectConversionStep(cv1T1);
5544 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5545 // Perform a (possibly multi-level) qualification conversion.
5546 Sequence.AddQualificationConversionStep(cv1T1,
5547 Initializer->getValueKind());
5548 } else if (RefConv & Sema::ReferenceConversions::Function) {
5549 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5550 }
5551
5552 // We only create a temporary here when binding a reference to a
5553 // bit-field or vector element. Those cases are't supposed to be
5554 // handled by this bullet, but the outcome is the same either way.
5555 Sequence.AddReferenceBindingStep(cv1T1, false);
5556 return;
5557 }
5558
5559 // - has a class type (i.e., T2 is a class type), where T1 is not
5560 // reference-related to T2, and can be implicitly converted to an
5561 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5562 // with "cv3 T3" (this conversion is selected by enumerating the
5563 // applicable conversion functions (13.3.1.6) and choosing the best
5564 // one through overload resolution (13.3)),
5565 // If we have an rvalue ref to function type here, the rhs must be
5566 // an rvalue. DR1287 removed the "implicitly" here.
5567 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5568 (isLValueRef || InitCategory.isRValue())) {
5569 if (S.getLangOpts().CPlusPlus) {
5570 // Try conversion functions only for C++.
5571 ConvOvlResult = TryRefInitWithConversionFunction(
5572 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5573 /*IsLValueRef*/ isLValueRef, Sequence);
5574 if (ConvOvlResult == OR_Success)
5575 return;
5576 if (ConvOvlResult != OR_No_Viable_Function)
5577 Sequence.SetOverloadFailure(
5579 ConvOvlResult);
5580 } else {
5581 ConvOvlResult = OR_No_Viable_Function;
5582 }
5583 }
5584 }
5585
5586 // - Otherwise, the reference shall be an lvalue reference to a
5587 // non-volatile const type (i.e., cv1 shall be const), or the reference
5588 // shall be an rvalue reference.
5589 // For address spaces, we interpret this to mean that an addr space
5590 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5591 if (isLValueRef &&
5592 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5593 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5596 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5597 Sequence.SetOverloadFailure(
5599 ConvOvlResult);
5600 else if (!InitCategory.isLValue())
5601 Sequence.SetFailed(
5602 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())
5606 else {
5608 switch (RefRelationship) {
5610 if (Initializer->refersToBitField())
5611 FK = InitializationSequence::
5612 FK_NonConstLValueReferenceBindingToBitfield;
5613 else if (Initializer->refersToVectorElement())
5614 FK = InitializationSequence::
5615 FK_NonConstLValueReferenceBindingToVectorElement;
5616 else if (Initializer->refersToMatrixElement())
5617 FK = InitializationSequence::
5618 FK_NonConstLValueReferenceBindingToMatrixElement;
5619 else
5620 llvm_unreachable("unexpected kind of compatible initializer");
5621 break;
5622 case Sema::Ref_Related:
5624 break;
5626 FK = InitializationSequence::
5627 FK_NonConstLValueReferenceBindingToUnrelated;
5628 break;
5629 }
5630 Sequence.SetFailed(FK);
5631 }
5632 return;
5633 }
5634
5635 // - If the initializer expression
5636 // - is an
5637 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5638 // [1z] rvalue (but not a bit-field) or
5639 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5640 //
5641 // Note: functions are handled above and below rather than here...
5642 if (!T1Function &&
5643 (RefRelationship == Sema::Ref_Compatible ||
5644 (Kind.isCStyleOrFunctionalCast() &&
5645 RefRelationship == Sema::Ref_Related)) &&
5646 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5647 (InitCategory.isPRValue() &&
5648 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5649 T2->isArrayType())))) {
5650 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5651 if (InitCategory.isPRValue() && T2->isRecordType()) {
5652 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5653 // compiler the freedom to perform a copy here or bind to the
5654 // object, while C++0x requires that we bind directly to the
5655 // object. Hence, we always bind to the object without making an
5656 // extra copy. However, in C++03 requires that we check for the
5657 // presence of a suitable copy constructor:
5658 //
5659 // The constructor that would be used to make the copy shall
5660 // be callable whether or not the copy is actually done.
5661 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5662 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5663 else if (S.getLangOpts().CPlusPlus11)
5665 }
5666
5667 // C++1z [dcl.init.ref]/5.2.1.2:
5668 // If the converted initializer is a prvalue, its type T4 is adjusted
5669 // to type "cv1 T4" and the temporary materialization conversion is
5670 // applied.
5671 // Postpone address space conversions to after the temporary materialization
5672 // conversion to allow creating temporaries in the alloca address space.
5673 auto T1QualsIgnoreAS = T1Quals;
5674 auto T2QualsIgnoreAS = T2Quals;
5675 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5676 T1QualsIgnoreAS.removeAddressSpace();
5677 T2QualsIgnoreAS.removeAddressSpace();
5678 }
5679 // Strip the existing ObjC lifetime qualifier from cv2T2 before combining
5680 // with T1's qualifiers.
5681 QualType T2ForQualConv = cv2T2;
5682 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) {
5683 Qualifiers T2BaseQuals =
5684 T2ForQualConv.getQualifiers().withoutObjCLifetime();
5685 T2ForQualConv = S.Context.getQualifiedType(
5686 T2ForQualConv.getUnqualifiedType(), T2BaseQuals);
5687 }
5688 QualType cv1T4 = S.Context.getQualifiedType(T2ForQualConv, T1QualsIgnoreAS);
5689 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5690 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5691 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5692 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5693 // Add addr space conversion if required.
5694 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5695 auto T4Quals = cv1T4.getQualifiers();
5696 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5697 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5698 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5699 cv1T4 = cv1T4WithAS;
5700 }
5701
5702 // In any case, the reference is bound to the resulting glvalue (or to
5703 // an appropriate base class subobject).
5704 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5705 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5706 else if (RefConv & Sema::ReferenceConversions::ObjC)
5707 Sequence.AddObjCObjectConversionStep(cv1T1);
5708 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5709 if (!S.Context.hasSameType(cv1T4, cv1T1))
5710 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5711 }
5712 return;
5713 }
5714
5715 // - has a class type (i.e., T2 is a class type), where T1 is not
5716 // reference-related to T2, and can be implicitly converted to an
5717 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5718 // where "cv1 T1" is reference-compatible with "cv3 T3",
5719 //
5720 // DR1287 removes the "implicitly" here.
5721 if (T2->isRecordType()) {
5722 if (RefRelationship == Sema::Ref_Incompatible) {
5723 ConvOvlResult = TryRefInitWithConversionFunction(
5724 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5725 /*IsLValueRef*/ isLValueRef, Sequence);
5726 if (ConvOvlResult)
5727 Sequence.SetOverloadFailure(
5729 ConvOvlResult);
5730
5731 return;
5732 }
5733
5734 if (RefRelationship == Sema::Ref_Compatible &&
5735 isRValueRef && InitCategory.isLValue()) {
5736 Sequence.SetFailed(
5738 return;
5739 }
5740
5742 return;
5743 }
5744
5745 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5746 // from the initializer expression using the rules for a non-reference
5747 // copy-initialization (8.5). The reference is then bound to the
5748 // temporary. [...]
5749
5750 // Ignore address space of reference type at this point and perform address
5751 // space conversion after the reference binding step.
5752 QualType cv1T1IgnoreAS =
5753 T1Quals.hasAddressSpace()
5755 : cv1T1;
5756
5757 InitializedEntity TempEntity =
5759
5760 // FIXME: Why do we use an implicit conversion here rather than trying
5761 // copy-initialization?
5763 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5764 /*SuppressUserConversions=*/false,
5765 Sema::AllowedExplicit::None,
5766 /*FIXME:InOverloadResolution=*/false,
5767 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5768 /*AllowObjCWritebackConversion=*/false);
5769
5770 if (ICS.isBad()) {
5771 // FIXME: Use the conversion function set stored in ICS to turn
5772 // this into an overloading ambiguity diagnostic. However, we need
5773 // to keep that set as an OverloadCandidateSet rather than as some
5774 // other kind of set.
5775 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5776 Sequence.SetOverloadFailure(
5778 ConvOvlResult);
5779 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5781 else
5783 return;
5784 } else {
5785 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5786 TopLevelOfInitList);
5787 }
5788
5789 // [...] If T1 is reference-related to T2, cv1 must be the
5790 // same cv-qualification as, or greater cv-qualification
5791 // than, cv2; otherwise, the program is ill-formed.
5792 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5793 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5794 if (RefRelationship == Sema::Ref_Related &&
5795 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5796 !T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5798 return;
5799 }
5800
5801 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5802 // reference, the initializer expression shall not be an lvalue.
5803 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5804 InitCategory.isLValue()) {
5805 Sequence.SetFailed(
5807 return;
5808 }
5809
5810 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5811
5812 if (T1Quals.hasAddressSpace()) {
5815 Sequence.SetFailed(
5817 return;
5818 }
5819 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5820 : VK_XValue);
5821 }
5822}
5823
5824/// Attempt character array initialization from a string literal
5825/// (C++ [dcl.init.string], C99 6.7.8).
5827 const InitializedEntity &Entity,
5828 const InitializationKind &Kind,
5830 InitializationSequence &Sequence) {
5831 Sequence.AddStringInitStep(Entity.getType());
5832}
5833
5834/// Attempt value initialization (C++ [dcl.init]p7).
5836 const InitializedEntity &Entity,
5837 const InitializationKind &Kind,
5838 InitializationSequence &Sequence,
5839 InitListExpr *InitList) {
5840 assert((!InitList || InitList->getNumInits() == 0) &&
5841 "Shouldn't use value-init for non-empty init lists");
5842
5843 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5844 //
5845 // To value-initialize an object of type T means:
5846 QualType T = Entity.getType();
5847 assert(!T->isVoidType() && "Cannot value-init void");
5848
5849 // -- if T is an array type, then each element is value-initialized;
5851
5852 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5853 bool NeedZeroInitialization = true;
5854 // C++98:
5855 // -- if T is a class type (clause 9) with a user-declared constructor
5856 // (12.1), then the default constructor for T is called (and the
5857 // initialization is ill-formed if T has no accessible default
5858 // constructor);
5859 // C++11:
5860 // -- if T is a class type (clause 9) with either no default constructor
5861 // (12.1 [class.ctor]) or a default constructor that is user-provided
5862 // or deleted, then the object is default-initialized;
5863 //
5864 // Note that the C++11 rule is the same as the C++98 rule if there are no
5865 // defaulted or deleted constructors, so we just use it unconditionally.
5867 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5868 NeedZeroInitialization = false;
5869
5870 // -- if T is a (possibly cv-qualified) non-union class type without a
5871 // user-provided or deleted default constructor, then the object is
5872 // zero-initialized and, if T has a non-trivial default constructor,
5873 // default-initialized;
5874 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5875 // constructor' part was removed by DR1507.
5876 if (NeedZeroInitialization)
5877 Sequence.AddZeroInitializationStep(Entity.getType());
5878
5879 // C++03:
5880 // -- if T is a non-union class type without a user-declared constructor,
5881 // then every non-static data member and base class component of T is
5882 // value-initialized;
5883 // [...] A program that calls for [...] value-initialization of an
5884 // entity of reference type is ill-formed.
5885 //
5886 // C++11 doesn't need this handling, because value-initialization does not
5887 // occur recursively there, and the implicit default constructor is
5888 // defined as deleted in the problematic cases.
5889 if (!S.getLangOpts().CPlusPlus11 &&
5890 ClassDecl->hasUninitializedReferenceMember()) {
5892 return;
5893 }
5894
5895 // If this is list-value-initialization, pass the empty init list on when
5896 // building the constructor call. This affects the semantics of a few
5897 // things (such as whether an explicit default constructor can be called).
5898 Expr *InitListAsExpr = InitList;
5899 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5900 bool InitListSyntax = InitList;
5901
5902 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5903 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5905 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5906 }
5907
5908 Sequence.AddZeroInitializationStep(Entity.getType());
5909}
5910
5911/// Attempt default initialization (C++ [dcl.init]p6).
5913 const InitializedEntity &Entity,
5914 const InitializationKind &Kind,
5915 InitializationSequence &Sequence) {
5916 assert(Kind.getKind() == InitializationKind::IK_Default);
5917
5918 // C++ [dcl.init]p6:
5919 // To default-initialize an object of type T means:
5920 // - if T is an array type, each element is default-initialized;
5921 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5922
5923 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5924 // constructor for T is called (and the initialization is ill-formed if
5925 // T has no accessible default constructor);
5926 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5927 TryConstructorInitialization(S, Entity, Kind, {}, DestType,
5928 Entity.getType(), Sequence);
5929 return;
5930 }
5931
5932 // - otherwise, no initialization is performed.
5933
5934 // If a program calls for the default initialization of an object of
5935 // a const-qualified type T, T shall be a class type with a user-provided
5936 // default constructor.
5937 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5938 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5940 return;
5941 }
5942
5943 // If the destination type has a lifetime property, zero-initialize it.
5944 if (DestType.getQualifiers().hasObjCLifetime()) {
5945 Sequence.AddZeroInitializationStep(Entity.getType());
5946 return;
5947 }
5948}
5949
5951 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5952 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5953 ExprResult *Result) {
5954 unsigned EntityIndexToProcess = 0;
5955 SmallVector<Expr *, 4> InitExprs;
5956 QualType ResultType;
5957 Expr *ArrayFiller = nullptr;
5958 FieldDecl *InitializedFieldInUnion = nullptr;
5959
5960 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5961 const InitializationKind &SubKind,
5962 Expr *Arg, Expr **InitExpr = nullptr) {
5964 S, SubEntity, SubKind,
5965 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5966
5967 if (IS.Failed()) {
5968 if (!VerifyOnly) {
5969 IS.Diagnose(S, SubEntity, SubKind,
5970 Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5971 } else {
5972 Sequence.SetFailed(
5974 }
5975
5976 return false;
5977 }
5978 if (!VerifyOnly) {
5979 ExprResult ER;
5980 ER = IS.Perform(S, SubEntity, SubKind,
5981 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5982
5983 if (ER.isInvalid())
5984 return false;
5985
5986 if (InitExpr)
5987 *InitExpr = ER.get();
5988 else
5989 InitExprs.push_back(ER.get());
5990 }
5991 return true;
5992 };
5993
5994 if (const ArrayType *AT =
5995 S.getASTContext().getAsArrayType(Entity.getType())) {
5996 uint64_t ArrayLength;
5997 // C++ [dcl.init]p16.5
5998 // if the destination type is an array, the object is initialized as
5999 // follows. Let x1, . . . , xk be the elements of the expression-list. If
6000 // the destination type is an array of unknown bound, it is defined as
6001 // having k elements.
6002 if (const ConstantArrayType *CAT =
6004 ArrayLength = CAT->getZExtSize();
6005 ResultType = Entity.getType();
6006 } else if (const VariableArrayType *VAT =
6008 // Braced-initialization of variable array types is not allowed, even if
6009 // the size is greater than or equal to the number of args, so we don't
6010 // allow them to be initialized via parenthesized aggregate initialization
6011 // either.
6012 const Expr *SE = VAT->getSizeExpr();
6013 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
6014 << SE->getSourceRange();
6015 return;
6016 } else {
6017 assert(Entity.getType()->isIncompleteArrayType());
6018 ArrayLength = Args.size();
6019 }
6020 EntityIndexToProcess = ArrayLength;
6021
6022 // ...the ith array element is copy-initialized with xi for each
6023 // 1 <= i <= k
6024 for (Expr *E : Args) {
6026 S.getASTContext(), EntityIndexToProcess, Entity);
6028 E->getExprLoc(), /*isDirectInit=*/false, E);
6029 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6030 return;
6031 }
6032 // ...and value-initialized for each k < i <= n;
6033 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
6035 S.getASTContext(), Args.size(), Entity);
6037 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6038 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
6039 return;
6040 }
6041
6042 if (ResultType.isNull()) {
6043 ResultType = S.Context.getConstantArrayType(
6044 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
6045 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
6046 }
6047 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
6048 bool IsUnion = RD->isUnion();
6049 if (RD->isInvalidDecl()) {
6050 // Exit early to avoid confusion when processing members.
6051 // We do the same for braced list initialization in
6052 // `CheckStructUnionTypes`.
6053 Sequence.SetFailed(
6055 return;
6056 }
6057
6058 if (!IsUnion) {
6059 for (const CXXBaseSpecifier &Base : RD->bases()) {
6061 S.getASTContext(), &Base, false, &Entity);
6062 if (EntityIndexToProcess < Args.size()) {
6063 // C++ [dcl.init]p16.6.2.2.
6064 // ...the object is initialized is follows. Let e1, ..., en be the
6065 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
6066 // the elements of the expression-list...The element ei is
6067 // copy-initialized with xi for 1 <= i <= k.
6068 Expr *E = Args[EntityIndexToProcess];
6070 E->getExprLoc(), /*isDirectInit=*/false, E);
6071 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6072 return;
6073 } else {
6074 // We've processed all of the args, but there are still base classes
6075 // that have to be initialized.
6076 // C++ [dcl.init]p17.6.2.2
6077 // The remaining elements...otherwise are value initialzed
6079 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
6080 /*IsImplicit=*/true);
6081 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6082 return;
6083 }
6084 EntityIndexToProcess++;
6085 }
6086 }
6087
6088 for (FieldDecl *FD : RD->fields()) {
6089 // Unnamed bitfields should not be initialized at all, either with an arg
6090 // or by default.
6091 if (FD->isUnnamedBitField())
6092 continue;
6093
6094 InitializedEntity SubEntity =
6096
6097 if (EntityIndexToProcess < Args.size()) {
6098 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6099 Expr *E = Args[EntityIndexToProcess];
6100
6101 // Incomplete array types indicate flexible array members. Do not allow
6102 // paren list initializations of structs with these members, as GCC
6103 // doesn't either.
6104 if (FD->getType()->isIncompleteArrayType()) {
6105 if (!VerifyOnly) {
6106 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
6107 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6108 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
6109 }
6110 Sequence.SetFailed(
6112 return;
6113 }
6114
6116 E->getExprLoc(), /*isDirectInit=*/false, E);
6117 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6118 return;
6119
6120 // Unions should have only one initializer expression, so we bail out
6121 // after processing the first field. If there are more initializers then
6122 // it will be caught when we later check whether EntityIndexToProcess is
6123 // less than Args.size();
6124 if (IsUnion) {
6125 InitializedFieldInUnion = FD;
6126 EntityIndexToProcess = 1;
6127 break;
6128 }
6129 } else {
6130 // We've processed all of the args, but there are still members that
6131 // have to be initialized.
6132 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6133 !S.isUnevaluatedContext()) {
6134 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
6135 << /* Var-in-Record */ 0 << FD;
6136 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
6137 }
6138
6139 if (FD->hasInClassInitializer()) {
6140 if (!VerifyOnly) {
6141 // C++ [dcl.init]p16.6.2.2
6142 // The remaining elements are initialized with their default
6143 // member initializers, if any
6145 Kind.getParenOrBraceRange().getEnd(), FD, SubEntity);
6146 if (DIE.isInvalid())
6147 return;
6148 InitExprs.push_back(DIE.get());
6149 }
6150 } else {
6151 // C++ [dcl.init]p17.6.2.2
6152 // The remaining elements...otherwise are value initialzed
6153 if (FD->getType()->isReferenceType()) {
6154 Sequence.SetFailed(
6156 if (!VerifyOnly) {
6157 SourceRange SR = Kind.getParenOrBraceRange();
6158 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
6159 << FD->getType() << SR;
6160 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
6161 }
6162 return;
6163 }
6165 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6166 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6167 return;
6168 }
6169 }
6170 EntityIndexToProcess++;
6171 }
6172 ResultType = Entity.getType();
6173 }
6174
6175 // Not all of the args have been processed, so there must've been more args
6176 // than were required to initialize the element.
6177 if (EntityIndexToProcess < Args.size()) {
6179 if (!VerifyOnly) {
6180 QualType T = Entity.getType();
6181 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6182 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6183 Args.back()->getEndLoc());
6184 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6185 << InitKind << ExcessInitSR;
6186 }
6187 return;
6188 }
6189
6190 if (VerifyOnly) {
6192 Sequence.AddParenthesizedListInitStep(Entity.getType());
6193 } else if (Result) {
6194 SourceRange SR = Kind.getParenOrBraceRange();
6195 auto *CPLIE = CXXParenListInitExpr::Create(
6196 S.getASTContext(), InitExprs, ResultType, Args.size(),
6197 Kind.getLocation(), SR.getBegin(), SR.getEnd());
6198 if (ArrayFiller)
6199 CPLIE->setArrayFiller(ArrayFiller);
6200 if (InitializedFieldInUnion)
6201 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6202 *Result = CPLIE;
6203 S.Diag(Kind.getLocation(),
6204 diag::warn_cxx17_compat_aggregate_init_paren_list)
6205 << Kind.getLocation() << SR << ResultType;
6206 }
6207}
6208
6209/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6210/// which enumerates all conversion functions and performs overload resolution
6211/// to select the best.
6213 QualType DestType,
6214 const InitializationKind &Kind,
6216 InitializationSequence &Sequence,
6217 bool TopLevelOfInitList) {
6218 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6219 QualType SourceType = Initializer->getType();
6220 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6221 "Must have a class type to perform a user-defined conversion");
6222
6223 // Build the candidate set directly in the initialization sequence
6224 // structure, so that it will persist if we fail.
6225 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6227 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6228
6229 // Determine whether we are allowed to call explicit constructors or
6230 // explicit conversion operators.
6231 bool AllowExplicit = Kind.AllowExplicit();
6232
6233 if (DestType->isRecordType()) {
6234 // The type we're converting to is a class type. Enumerate its constructors
6235 // to see if there is a suitable conversion.
6236 // Try to complete the type we're converting to.
6237 if (S.isCompleteType(Kind.getLocation(), DestType)) {
6238 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6239 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
6240 auto Info = getConstructorInfo(D);
6241 if (!Info.Constructor)
6242 continue;
6243
6244 if (!Info.Constructor->isInvalidDecl() &&
6245 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6246 if (Info.ConstructorTmpl)
6248 Info.ConstructorTmpl, Info.FoundDecl,
6249 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
6250 /*SuppressUserConversions=*/true,
6251 /*PartialOverloading*/ false, AllowExplicit);
6252 else
6253 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
6254 Initializer, CandidateSet,
6255 /*SuppressUserConversions=*/true,
6256 /*PartialOverloading*/ false, AllowExplicit);
6257 }
6258 }
6259 }
6260 }
6261
6262 SourceLocation DeclLoc = Initializer->getBeginLoc();
6263
6264 if (SourceType->isRecordType()) {
6265 // The type we're converting from is a class type, enumerate its conversion
6266 // functions.
6267
6268 // We can only enumerate the conversion functions for a complete type; if
6269 // the type isn't complete, simply skip this step.
6270 if (S.isCompleteType(DeclLoc, SourceType)) {
6271 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6272 const auto &Conversions =
6273 SourceRecordDecl->getVisibleConversionFunctions();
6274 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6275 NamedDecl *D = *I;
6277 if (isa<UsingShadowDecl>(D))
6278 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6279
6280 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6281 CXXConversionDecl *Conv;
6282 if (ConvTemplate)
6283 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6284 else
6285 Conv = cast<CXXConversionDecl>(D);
6286
6287 if (ConvTemplate)
6289 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
6290 CandidateSet, AllowExplicit, AllowExplicit);
6291 else
6292 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
6293 DestType, CandidateSet, AllowExplicit,
6294 AllowExplicit);
6295 }
6296 }
6297 }
6298
6299 // Perform overload resolution. If it fails, return the failed result.
6302 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
6303 Sequence.SetOverloadFailure(
6305
6306 // [class.copy.elision]p3:
6307 // In some copy-initialization contexts, a two-stage overload resolution
6308 // is performed.
6309 // If the first overload resolution selects a deleted function, we also
6310 // need the initialization sequence to decide whether to perform the second
6311 // overload resolution.
6312 if (!(Result == OR_Deleted &&
6313 Kind.getKind() == InitializationKind::IK_Copy))
6314 return;
6315 }
6316
6317 FunctionDecl *Function = Best->Function;
6318 Function->setReferenced();
6319 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6320
6321 if (isa<CXXConstructorDecl>(Function)) {
6322 // Add the user-defined conversion step. Any cv-qualification conversion is
6323 // subsumed by the initialization. Per DR5, the created temporary is of the
6324 // cv-unqualified type of the destination.
6325 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
6326 DestType.getUnqualifiedType(),
6327 HadMultipleCandidates);
6328
6329 // C++14 and before:
6330 // - if the function is a constructor, the call initializes a temporary
6331 // of the cv-unqualified version of the destination type. The [...]
6332 // temporary [...] is then used to direct-initialize, according to the
6333 // rules above, the object that is the destination of the
6334 // copy-initialization.
6335 // Note that this just performs a simple object copy from the temporary.
6336 //
6337 // C++17:
6338 // - if the function is a constructor, the call is a prvalue of the
6339 // cv-unqualified version of the destination type whose return object
6340 // is initialized by the constructor. The call is used to
6341 // direct-initialize, according to the rules above, the object that
6342 // is the destination of the copy-initialization.
6343 // Therefore we need to do nothing further.
6344 //
6345 // FIXME: Mark this copy as extraneous.
6346 if (!S.getLangOpts().CPlusPlus17)
6347 Sequence.AddFinalCopy(DestType);
6348 else if (DestType.hasQualifiers())
6349 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6350 return;
6351 }
6352
6353 // Add the user-defined conversion step that calls the conversion function.
6354 QualType ConvType = Function->getCallResultType();
6355 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6356 HadMultipleCandidates);
6357
6358 if (ConvType->isRecordType()) {
6359 if (S.getLangOpts().HLSL &&
6360 ConvType.getAddressSpace() == LangAS::hlsl_constant &&
6361 S.Context.hasSameUnqualifiedType(ConvType, DestType)) {
6362 Sequence.AddHLSLBufferConversionStep(ConvType);
6363 return;
6364 }
6365
6366 // The call is used to direct-initialize [...] the object that is the
6367 // destination of the copy-initialization.
6368 //
6369 // In C++17, this does not call a constructor if we enter /17.6.1:
6370 // - If the initializer expression is a prvalue and the cv-unqualified
6371 // version of the source type is the same as the class of the
6372 // destination [... do not make an extra copy]
6373 //
6374 // FIXME: Mark this copy as extraneous.
6375 if (!S.getLangOpts().CPlusPlus17 ||
6376 Function->getReturnType()->isReferenceType() ||
6377 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6378 Sequence.AddFinalCopy(DestType);
6379 else if (!S.Context.hasSameType(ConvType, DestType))
6380 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6381 return;
6382 }
6383
6384 // If the conversion following the call to the conversion function
6385 // is interesting, add it as a separate step.
6386 assert(Best->HasFinalConversion);
6387 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6388 Best->FinalConversion.Third) {
6390 ICS.setStandard();
6391 ICS.Standard = Best->FinalConversion;
6392 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6393 }
6394}
6395
6396/// The non-zero enum values here are indexes into diagnostic alternatives.
6398
6399/// Determines whether this expression is an acceptable ICR source.
6401 bool isAddressOf, bool &isWeakAccess) {
6402 // Skip parens.
6403 e = e->IgnoreParens();
6404
6405 // Skip address-of nodes.
6406 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6407 if (op->getOpcode() == UO_AddrOf)
6408 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6409 isWeakAccess);
6410
6411 // Skip certain casts.
6412 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6413 switch (ce->getCastKind()) {
6414 case CK_Dependent:
6415 case CK_BitCast:
6416 case CK_LValueBitCast:
6417 case CK_NoOp:
6418 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6419
6420 case CK_ArrayToPointerDecay:
6421 return IIK_nonscalar;
6422
6423 case CK_NullToPointer:
6424 return IIK_okay;
6425
6426 default:
6427 break;
6428 }
6429
6430 // If we have a declaration reference, it had better be a local variable.
6431 } else if (isa<DeclRefExpr>(e)) {
6432 // set isWeakAccess to true, to mean that there will be an implicit
6433 // load which requires a cleanup.
6435 isWeakAccess = true;
6436
6437 if (!isAddressOf) return IIK_nonlocal;
6438
6439 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6440 if (!var) return IIK_nonlocal;
6441
6442 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6443
6444 // If we have a conditional operator, check both sides.
6445 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6446 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6447 isWeakAccess))
6448 return iik;
6449
6450 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6451
6452 // These are never scalar.
6453 } else if (isa<ArraySubscriptExpr>(e)) {
6454 return IIK_nonscalar;
6455
6456 // Otherwise, it needs to be a null pointer constant.
6457 } else {
6460 }
6461
6462 return IIK_nonlocal;
6463}
6464
6465/// Check whether the given expression is a valid operand for an
6466/// indirect copy/restore.
6468 assert(src->isPRValue());
6469 bool isWeakAccess = false;
6470 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6471 // If isWeakAccess to true, there will be an implicit
6472 // load which requires a cleanup.
6473 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6475
6476 if (iik == IIK_okay) return;
6477
6478 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6479 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6480 << src->getSourceRange();
6481}
6482
6483/// Determine whether we have compatible array types for the
6484/// purposes of GNU by-copy array initialization.
6485static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6486 const ArrayType *Source) {
6487 // If the source and destination array types are equivalent, we're
6488 // done.
6489 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6490 return true;
6491
6492 // Make sure that the element types are the same.
6493 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6494 return false;
6495
6496 // The only mismatch we allow is when the destination is an
6497 // incomplete array type and the source is a constant array type.
6498 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6499}
6500
6502 InitializationSequence &Sequence,
6503 const InitializedEntity &Entity,
6504 Expr *Initializer) {
6505 bool ArrayDecay = false;
6506 QualType ArgType = Initializer->getType();
6507 QualType ArgPointee;
6508 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6509 ArrayDecay = true;
6510 ArgPointee = ArgArrayType->getElementType();
6511 ArgType = S.Context.getPointerType(ArgPointee);
6512 }
6513
6514 // Handle write-back conversion.
6515 QualType ConvertedArgType;
6516 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6517 ConvertedArgType))
6518 return false;
6519
6520 // We should copy unless we're passing to an argument explicitly
6521 // marked 'out'.
6522 bool ShouldCopy = true;
6523 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6524 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6525
6526 // Do we need an lvalue conversion?
6527 if (ArrayDecay || Initializer->isGLValue()) {
6529 ICS.setStandard();
6531
6532 QualType ResultType;
6533 if (ArrayDecay) {
6535 ResultType = S.Context.getPointerType(ArgPointee);
6536 } else {
6538 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6539 }
6540
6541 Sequence.AddConversionSequenceStep(ICS, ResultType);
6542 }
6543
6544 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6545 return true;
6546}
6547
6549 InitializationSequence &Sequence,
6550 QualType DestType,
6551 Expr *Initializer) {
6552 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6553 (!Initializer->isIntegerConstantExpr(S.Context) &&
6554 !Initializer->getType()->isSamplerT()))
6555 return false;
6556
6557 Sequence.AddOCLSamplerInitStep(DestType);
6558 return true;
6559}
6560
6561static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6562 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6563 return Value && Value->isZero();
6564}
6565
6567 InitializationSequence &Sequence,
6568 QualType DestType,
6569 Expr *Initializer) {
6570 if (!S.getLangOpts().OpenCL)
6571 return false;
6572
6573 //
6574 // OpenCL 1.2 spec, s6.12.10
6575 //
6576 // The event argument can also be used to associate the
6577 // async_work_group_copy with a previous async copy allowing
6578 // an event to be shared by multiple async copies; otherwise
6579 // event should be zero.
6580 //
6581 if (DestType->isEventT() || DestType->isQueueT()) {
6583 return false;
6584
6585 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6586 return true;
6587 }
6588
6589 // We should allow zero initialization for all types defined in the
6590 // cl_intel_device_side_avc_motion_estimation extension, except
6591 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6593 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6594 DestType->isOCLIntelSubgroupAVCType()) {
6595 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6596 DestType->isOCLIntelSubgroupAVCMceResultType())
6597 return false;
6599 return false;
6600
6601 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6602 return true;
6603 }
6604
6605 return false;
6606}
6607
6609 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6610 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6611 : FailedOverloadResult(OR_Success),
6612 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6613 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6614 TreatUnavailableAsInvalid);
6615}
6616
6617/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6618/// address of that function, this returns true. Otherwise, it returns false.
6619static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6620 auto *DRE = dyn_cast<DeclRefExpr>(E);
6621 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6622 return false;
6623
6625 cast<FunctionDecl>(DRE->getDecl()));
6626}
6627
6628/// Determine whether we can perform an elementwise array copy for this kind
6629/// of entity.
6630static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6631 switch (Entity.getKind()) {
6633 // C++ [expr.prim.lambda]p24:
6634 // For array members, the array elements are direct-initialized in
6635 // increasing subscript order.
6636 return true;
6637
6639 // C++ [dcl.decomp]p1:
6640 // [...] each element is copy-initialized or direct-initialized from the
6641 // corresponding element of the assignment-expression [...]
6642 return isa<DecompositionDecl>(Entity.getDecl());
6643
6645 // C++ [class.copy.ctor]p14:
6646 // - if the member is an array, each element is direct-initialized with
6647 // the corresponding subobject of x
6648 return Entity.isImplicitMemberInitializer();
6649
6651 // All the above cases are intended to apply recursively, even though none
6652 // of them actually say that.
6653 if (auto *E = Entity.getParent())
6654 return canPerformArrayCopy(*E);
6655 break;
6656
6657 default:
6658 break;
6659 }
6660
6661 return false;
6662}
6663
6664static const FieldDecl *getConstField(const RecordDecl *RD) {
6665 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6666 for (const FieldDecl *FD : RD->fields()) {
6667 // If the field is a flexible array member, we don't want to consider it
6668 // as a const field because there's no way to initialize the FAM anyway.
6669 const ASTContext &Ctx = FD->getASTContext();
6671 Ctx, FD, FD->getType(),
6672 Ctx.getLangOpts().getStrictFlexArraysLevel(),
6673 /*IgnoreTemplateOrMacroSubstitution=*/true))
6674 continue;
6675
6676 QualType QT = FD->getType();
6677 if (QT.isConstQualified())
6678 return FD;
6679 if (const auto *RD = QT->getAsRecordDecl()) {
6680 if (const FieldDecl *FD = getConstField(RD))
6681 return FD;
6682 }
6683 }
6684 return nullptr;
6685}
6686
6688 const InitializedEntity &Entity,
6689 const InitializationKind &Kind,
6690 MultiExprArg Args,
6691 bool TopLevelOfInitList,
6692 bool TreatUnavailableAsInvalid) {
6693 ASTContext &Context = S.Context;
6694
6695 // Eliminate non-overload placeholder types in the arguments. We
6696 // need to do this before checking whether types are dependent
6697 // because lowering a pseudo-object expression might well give us
6698 // something of dependent type.
6699 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6700 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6701 // FIXME: should we be doing this here?
6702 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6703 if (result.isInvalid()) {
6705 return;
6706 }
6707 Args[I] = result.get();
6708 }
6709
6710 // C++0x [dcl.init]p16:
6711 // The semantics of initializers are as follows. The destination type is
6712 // the type of the object or reference being initialized and the source
6713 // type is the type of the initializer expression. The source type is not
6714 // defined when the initializer is a braced-init-list or when it is a
6715 // parenthesized list of expressions.
6716 QualType DestType = Entity.getType();
6717
6718 if (DestType->isDependentType() ||
6721 return;
6722 }
6723
6724 // Almost everything is a normal sequence.
6726
6727 QualType SourceType;
6728 Expr *Initializer = nullptr;
6729 if (Args.size() == 1) {
6730 Initializer = Args[0];
6731 if (S.getLangOpts().ObjC) {
6733 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6734 Initializer) ||
6736 Args[0] = Initializer;
6737 }
6739 SourceType = Initializer->getType();
6740 }
6741
6742 // - If the initializer is a (non-parenthesized) braced-init-list, the
6743 // object is list-initialized (8.5.4).
6744 if (Kind.getKind() != InitializationKind::IK_Direct) {
6745 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6746 TryListInitialization(S, Entity, Kind, InitList, *this,
6747 TreatUnavailableAsInvalid);
6748 return;
6749 }
6750 }
6751
6752 if (!S.getLangOpts().CPlusPlus &&
6753 Kind.getKind() == InitializationKind::IK_Default) {
6754 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6755 VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6756 if (Rec->hasUninitializedExplicitInitFields()) {
6757 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6758 S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6759 << /* Var-in-Record */ 1 << Rec;
6761 }
6762 }
6763 // If the record has any members which are const (recursively checked),
6764 // then we want to diagnose those as being uninitialized if there is no
6765 // initializer present. However, we only do this for structure types, not
6766 // union types, because an unitialized field in a union is generally
6767 // reasonable, especially in C where unions can be used for type punning.
6768 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6769 if (const FieldDecl *FD = getConstField(Rec)) {
6770 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6771 if (Var->getStorageDuration() == SD_Static ||
6772 Var->getStorageDuration() == SD_Thread)
6773 DiagID = diag::warn_default_init_const_field;
6774
6775 bool EmitCppCompat = !S.Diags.isIgnored(
6776 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6777 Var->getLocation());
6778
6779 S.Diag(Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6780 S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6781 }
6782 }
6783 }
6784 }
6785
6786 // - If the destination type is a reference type, see 8.5.3.
6787 if (DestType->isReferenceType()) {
6788 // C++0x [dcl.init.ref]p1:
6789 // A variable declared to be a T& or T&&, that is, "reference to type T"
6790 // (8.3.2), shall be initialized by an object, or function, of type T or
6791 // by an object that can be converted into a T.
6792 // (Therefore, multiple arguments are not permitted.)
6793 if (Args.size() != 1)
6795 // C++17 [dcl.init.ref]p5:
6796 // A reference [...] is initialized by an expression [...] as follows:
6797 // If the initializer is not an expression, presumably we should reject,
6798 // but the standard fails to actually say so.
6799 else if (isa<InitListExpr>(Args[0]))
6801 else
6802 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6803 TopLevelOfInitList);
6804 return;
6805 }
6806
6807 // - If the initializer is (), the object is value-initialized.
6808 if (Kind.getKind() == InitializationKind::IK_Value ||
6809 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6810 TryValueInitialization(S, Entity, Kind, *this);
6811 return;
6812 }
6813
6814 // Handle default initialization.
6815 if (Kind.getKind() == InitializationKind::IK_Default) {
6816 TryDefaultInitialization(S, Entity, Kind, *this);
6817 return;
6818 }
6819
6820 // - If the destination type is an array of characters, an array of
6821 // char16_t, an array of char32_t, or an array of wchar_t, and the
6822 // initializer is a string literal, see 8.5.2.
6823 // - Otherwise, if the destination type is an array, the program is
6824 // ill-formed.
6825 // - Except in HLSL, where non-decaying array parameters behave like
6826 // non-array types for initialization.
6827 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6828 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6829 if (Initializer && isa<VariableArrayType>(DestAT)) {
6831 return;
6832 }
6833
6834 if (Initializer) {
6835 switch (IsStringInit(Initializer, DestAT, Context)) {
6836 case SIF_None:
6837 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6838 return;
6841 return;
6844 return;
6847 return;
6850 return;
6853 return;
6854 case SIF_Other:
6855 break;
6856 }
6857 }
6858
6859 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(DestAT)) {
6860 QualType SrcType = Entity.getType();
6861 if (SrcType->isArrayParameterType())
6862 SrcType =
6863 cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6864 if (S.Context.hasSameUnqualifiedType(DestType, SrcType)) {
6865 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6866 TreatUnavailableAsInvalid);
6867 return;
6868 }
6869 }
6870
6871 // Some kinds of initialization permit an array to be initialized from
6872 // another array of the same type, and perform elementwise initialization.
6873 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6875 Entity.getType()) &&
6876 canPerformArrayCopy(Entity)) {
6877 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6878 TreatUnavailableAsInvalid);
6879 return;
6880 }
6881
6882 // Note: as an GNU C extension, we allow initialization of an
6883 // array from a compound literal that creates an array of the same
6884 // type, so long as the initializer has no side effects.
6885 if (!S.getLangOpts().CPlusPlus && Initializer &&
6886 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6887 Initializer->getType()->isArrayType()) {
6888 const ArrayType *SourceAT
6889 = Context.getAsArrayType(Initializer->getType());
6890 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6892 else if (Initializer->HasSideEffects(S.Context))
6894 else {
6895 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6896 }
6897 }
6898 // Note: as a GNU C++ extension, we allow list-initialization of a
6899 // class member of array type from a parenthesized initializer list.
6900 else if (S.getLangOpts().CPlusPlus &&
6902 isa_and_nonnull<InitListExpr>(Initializer)) {
6904 *this, TreatUnavailableAsInvalid);
6906 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6907 Kind.getKind() == InitializationKind::IK_Direct)
6908 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6909 /*VerifyOnly=*/true);
6910 else if (DestAT->getElementType()->isCharType())
6912 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6914 else
6916
6917 return;
6918 }
6919
6920 // Determine whether we should consider writeback conversions for
6921 // Objective-C ARC.
6922 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6923 Entity.isParameterKind();
6924
6925 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6926 return;
6927
6928 // We're at the end of the line for C: it's either a write-back conversion
6929 // or it's a C assignment. There's no need to check anything else.
6930 if (!S.getLangOpts().CPlusPlus) {
6931 assert(Initializer && "Initializer must be non-null");
6932 // If allowed, check whether this is an Objective-C writeback conversion.
6933 if (allowObjCWritebackConversion &&
6934 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6935 return;
6936 }
6937
6938 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6939 return;
6940
6941 // Handle initialization in C
6942 AddCAssignmentStep(DestType);
6943 MaybeProduceObjCObject(S, *this, Entity);
6944 return;
6945 }
6946
6947 assert(S.getLangOpts().CPlusPlus);
6948
6949 // - If the destination type is a (possibly cv-qualified) class type:
6950 // (except for HLSL, where user-defined record types do not have
6951 // constructors or conversion functions)
6952 if (DestType->isRecordType() &&
6953 (!S.getLangOpts().HLSL ||
6954 DestType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
6955 // - If the initialization is direct-initialization, or if it is
6956 // copy-initialization where the cv-unqualified version of the
6957 // source type is the same class as, or a derived class of, the
6958 // class of the destination, constructors are considered. [...]
6959 if (Kind.getKind() == InitializationKind::IK_Direct ||
6960 (Kind.getKind() == InitializationKind::IK_Copy &&
6961 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6962 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6963 SourceType, DestType))))) {
6964 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6965 *this, /*IsAggrListInit=*/false);
6966 } else {
6967 // - Otherwise (i.e., for the remaining copy-initialization cases),
6968 // user-defined conversion sequences that can convert from the
6969 // source type to the destination type or (when a conversion
6970 // function is used) to a derived class thereof are enumerated as
6971 // described in 13.3.1.4, and the best one is chosen through
6972 // overload resolution (13.3).
6973 assert(Initializer && "Initializer must be non-null");
6974 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6975 TopLevelOfInitList);
6976 }
6977 return;
6978 }
6979
6980 assert(Args.size() >= 1 && "Zero-argument case handled above");
6981
6982 // For HLSL ext vector types we allow list initialization behavior for C++
6983 // functional cast expressions which look like constructor syntax. This is
6984 // accomplished by converting initialization arguments to InitListExpr.
6985 auto ShouldTryListInitialization = [&]() -> bool {
6986 // Only try list initialization for HLSL.
6987 if (!S.getLangOpts().HLSL)
6988 return false;
6989
6990 bool DestIsVec = DestType->isExtVectorType();
6991 bool DestIsMat = DestType->isConstantMatrixType();
6992
6993 // If the destination type is neither a vector nor a matrix, then don't try
6994 // list initialization.
6995 if (!DestIsVec && !DestIsMat)
6996 return false;
6997
6998 // If there is only a single source argument, then only try list
6999 // initialization if initializing a matrix with a vector or vice versa.
7000 if (Args.size() == 1) {
7001 assert(!SourceType.isNull() &&
7002 "Source QualType should not be null when arg size is exactly 1");
7003 bool SourceIsVec = SourceType->isExtVectorType();
7004 bool SourceIsMat = SourceType->isConstantMatrixType();
7005
7006 if (DestIsMat && !SourceIsVec)
7007 return false;
7008 if (DestIsVec && !SourceIsMat)
7009 return false;
7010 }
7011
7012 // Try list initialization if the source type is null or if the
7013 // destination and source types differ.
7014 return SourceType.isNull() ||
7015 !Context.hasSameUnqualifiedType(SourceType, DestType);
7016 };
7017 if (ShouldTryListInitialization()) {
7018 InitListExpr *ILE = new (Context)
7019 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
7020 Args.back()->getEndLoc(), /*isExplicit=*/false);
7021 ILE->setType(DestType);
7022 Args[0] = ILE;
7023 TryListInitialization(S, Entity, Kind, ILE, *this,
7024 TreatUnavailableAsInvalid);
7025 return;
7026 }
7027
7028 // The remaining cases all need a source type.
7029 if (Args.size() > 1) {
7031 return;
7032 } else if (isa<InitListExpr>(Args[0])) {
7034 return;
7035 }
7036
7037 // - Otherwise, if the source type is a (possibly cv-qualified) class
7038 // type, conversion functions are considered.
7039 // (except for HLSL, where user-defined record types do not have
7040 // constructors or conversion functions).
7041 if (!SourceType.isNull() && SourceType->isRecordType() &&
7042 (!S.getLangOpts().HLSL ||
7043 SourceType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
7044 assert(Initializer && "Initializer must be non-null");
7045 // For a conversion to _Atomic(T) from either T or a class type derived
7046 // from T, initialize the T object then convert to _Atomic type.
7047 bool NeedAtomicConversion = false;
7048 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
7049 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
7050 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
7051 Atomic->getValueType())) {
7052 DestType = Atomic->getValueType();
7053 NeedAtomicConversion = true;
7054 }
7055 }
7056
7057 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
7058 TopLevelOfInitList);
7059 MaybeProduceObjCObject(S, *this, Entity);
7060 if (!Failed() && NeedAtomicConversion)
7062 return;
7063 }
7064
7065 // - Otherwise, if the initialization is direct-initialization, the source
7066 // type is std::nullptr_t, and the destination type is bool, the initial
7067 // value of the object being initialized is false.
7068 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
7069 DestType->isBooleanType() &&
7070 Kind.getKind() == InitializationKind::IK_Direct) {
7073 Initializer->isGLValue()),
7074 DestType);
7075 return;
7076 }
7077
7078 // - Otherwise, the initial value of the object being initialized is the
7079 // (possibly converted) value of the initializer expression. Standard
7080 // conversions (Clause 4) will be used, if necessary, to convert the
7081 // initializer expression to the cv-unqualified version of the
7082 // destination type; no user-defined conversions are considered.
7083
7085 = S.TryImplicitConversion(Initializer, DestType,
7086 /*SuppressUserConversions*/true,
7087 Sema::AllowedExplicit::None,
7088 /*InOverloadResolution*/ false,
7089 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
7090 allowObjCWritebackConversion);
7091
7092 if (ICS.isStandard() &&
7094 // Objective-C ARC writeback conversion.
7095
7096 // We should copy unless we're passing to an argument explicitly
7097 // marked 'out'.
7098 bool ShouldCopy = true;
7099 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
7100 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
7101
7102 // If there was an lvalue adjustment, add it as a separate conversion.
7103 if (ICS.Standard.First == ICK_Array_To_Pointer ||
7106 LvalueICS.setStandard();
7108 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
7109 LvalueICS.Standard.First = ICS.Standard.First;
7110 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
7111 }
7112
7113 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
7114 } else if (ICS.isBad()) {
7116 Initializer->getType() == Context.OverloadTy &&
7118 /*Complain=*/false, Found))
7120 else if (Initializer->getType()->isFunctionType() &&
7123 else
7125 } else {
7126 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
7127
7128 MaybeProduceObjCObject(S, *this, Entity);
7129 }
7130}
7131
7133 for (auto &S : Steps)
7134 S.Destroy();
7135}
7136
7137//===----------------------------------------------------------------------===//
7138// Perform initialization
7139//===----------------------------------------------------------------------===//
7141 bool Diagnose = false) {
7142 switch(Entity.getKind()) {
7149
7151 if (Entity.getDecl() &&
7154
7156
7158 if (Entity.getDecl() &&
7161
7162 return !Diagnose ? AssignmentAction::Passing
7164
7166 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7168
7171 // FIXME: Can we tell apart casting vs. converting?
7173
7175 // This is really initialization, but refer to it as conversion for
7176 // consistency with CheckConvertedConstantExpression.
7178
7191 }
7192
7193 llvm_unreachable("Invalid EntityKind!");
7194}
7195
7196/// Whether we should bind a created object as a temporary when
7197/// initializing the given entity.
7230
7231/// Whether the given entity, when initialized with an object
7232/// created for that initialization, requires destruction.
7265
7266/// Get the location at which initialization diagnostics should appear.
7305
7306/// Make a (potentially elidable) temporary copy of the object
7307/// provided by the given initializer by calling the appropriate copy
7308/// constructor.
7309///
7310/// \param S The Sema object used for type-checking.
7311///
7312/// \param T The type of the temporary object, which must either be
7313/// the type of the initializer expression or a superclass thereof.
7314///
7315/// \param Entity The entity being initialized.
7316///
7317/// \param CurInit The initializer expression.
7318///
7319/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7320/// is permitted in C++03 (but not C++0x) when binding a reference to
7321/// an rvalue.
7322///
7323/// \returns An expression that copies the initializer expression into
7324/// a temporary object, or an error expression if a copy could not be
7325/// created.
7327 QualType T,
7328 const InitializedEntity &Entity,
7329 ExprResult CurInit,
7330 bool IsExtraneousCopy) {
7331 if (CurInit.isInvalid())
7332 return CurInit;
7333 // Determine which class type we're copying to.
7334 Expr *CurInitExpr = (Expr *)CurInit.get();
7335 auto *Class = T->getAsCXXRecordDecl();
7336 if (!Class)
7337 return CurInit;
7338
7339 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
7340
7341 // Make sure that the type we are copying is complete.
7342 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
7343 return CurInit;
7344
7345 // Perform overload resolution using the class's constructors. Per
7346 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7347 // is direct-initialization.
7350
7353 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
7354 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7355 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7356 /*RequireActualConstructor=*/false,
7357 /*SecondStepOfCopyInit=*/true)) {
7358 case OR_Success:
7359 break;
7360
7362 CandidateSet.NoteCandidates(
7364 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
7365 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7366 : diag::err_temp_copy_no_viable)
7367 << (int)Entity.getKind() << CurInitExpr->getType()
7368 << CurInitExpr->getSourceRange()),
7369 S, OCD_AllCandidates, CurInitExpr);
7370 if (!IsExtraneousCopy || S.isSFINAEContext())
7371 return ExprError();
7372 return CurInit;
7373
7374 case OR_Ambiguous:
7375 CandidateSet.NoteCandidates(
7376 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
7377 << (int)Entity.getKind()
7378 << CurInitExpr->getType()
7379 << CurInitExpr->getSourceRange()),
7380 S, OCD_AmbiguousCandidates, CurInitExpr);
7381 return ExprError();
7382
7383 case OR_Deleted:
7384 S.Diag(Loc, diag::err_temp_copy_deleted)
7385 << (int)Entity.getKind() << CurInitExpr->getType()
7386 << CurInitExpr->getSourceRange();
7387 S.NoteDeletedFunction(Best->Function);
7388 return ExprError();
7389 }
7390
7391 bool HadMultipleCandidates = CandidateSet.size() > 1;
7392
7394 SmallVector<Expr*, 8> ConstructorArgs;
7395 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7396
7397 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7398 IsExtraneousCopy);
7399
7400 if (IsExtraneousCopy) {
7401 // If this is a totally extraneous copy for C++03 reference
7402 // binding purposes, just return the original initialization
7403 // expression. We don't generate an (elided) copy operation here
7404 // because doing so would require us to pass down a flag to avoid
7405 // infinite recursion, where each step adds another extraneous,
7406 // elidable copy.
7407
7408 // Instantiate the default arguments of any extra parameters in
7409 // the selected copy constructor, as if we were going to create a
7410 // proper call to the copy constructor.
7411 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7412 ParmVarDecl *Parm = Constructor->getParamDecl(I);
7413 if (S.RequireCompleteType(Loc, Parm->getType(),
7414 diag::err_call_incomplete_argument))
7415 break;
7416
7417 // Build the default argument expression; we don't actually care
7418 // if this succeeds or not, because this routine will complain
7419 // if there was a problem.
7420 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7421 }
7422
7423 return CurInitExpr;
7424 }
7425
7426 // Determine the arguments required to actually perform the
7427 // constructor call (we might have derived-to-base conversions, or
7428 // the copy constructor may have default arguments).
7429 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7430 ConstructorArgs))
7431 return ExprError();
7432
7433 // C++0x [class.copy]p32:
7434 // When certain criteria are met, an implementation is allowed to
7435 // omit the copy/move construction of a class object, even if the
7436 // copy/move constructor and/or destructor for the object have
7437 // side effects. [...]
7438 // - when a temporary class object that has not been bound to a
7439 // reference (12.2) would be copied/moved to a class object
7440 // with the same cv-unqualified type, the copy/move operation
7441 // can be omitted by constructing the temporary object
7442 // directly into the target of the omitted copy/move
7443 //
7444 // Note that the other three bullets are handled elsewhere. Copy
7445 // elision for return statements and throw expressions are handled as part
7446 // of constructor initialization, while copy elision for exception handlers
7447 // is handled by the run-time.
7448 //
7449 // FIXME: If the function parameter is not the same type as the temporary, we
7450 // should still be able to elide the copy, but we don't have a way to
7451 // represent in the AST how much should be elided in this case.
7452 bool Elidable =
7453 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7455 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7456 CurInitExpr->getType());
7457
7458 // Actually perform the constructor call.
7459 CurInit = S.BuildCXXConstructExpr(
7460 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7461 HadMultipleCandidates,
7462 /*ListInit*/ false,
7463 /*StdInitListInit*/ false,
7464 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7465
7466 // If we're supposed to bind temporaries, do so.
7467 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7468 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7469 return CurInit;
7470}
7471
7472/// Check whether elidable copy construction for binding a reference to
7473/// a temporary would have succeeded if we were building in C++98 mode, for
7474/// -Wc++98-compat.
7476 const InitializedEntity &Entity,
7477 Expr *CurInitExpr) {
7478 assert(S.getLangOpts().CPlusPlus11);
7479
7480 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7481 if (!Record)
7482 return;
7483
7484 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7485 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7486 return;
7487
7488 // Find constructors which would have been considered.
7491
7492 // Perform overload resolution.
7495 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7496 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7497 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7498 /*RequireActualConstructor=*/false,
7499 /*SecondStepOfCopyInit=*/true);
7500
7501 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7502 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7503 << CurInitExpr->getSourceRange();
7504
7505 switch (OR) {
7506 case OR_Success:
7507 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7508 Best->FoundDecl, Entity, Diag);
7509 // FIXME: Check default arguments as far as that's possible.
7510 break;
7511
7513 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7514 OCD_AllCandidates, CurInitExpr);
7515 break;
7516
7517 case OR_Ambiguous:
7518 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7519 OCD_AmbiguousCandidates, CurInitExpr);
7520 break;
7521
7522 case OR_Deleted:
7523 S.Diag(Loc, Diag);
7524 S.NoteDeletedFunction(Best->Function);
7525 break;
7526 }
7527}
7528
7529void InitializationSequence::PrintInitLocationNote(Sema &S,
7530 const InitializedEntity &Entity) {
7531 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7532 if (Entity.getDecl()->getLocation().isInvalid())
7533 return;
7534
7535 if (Entity.getDecl()->getDeclName())
7536 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7537 << Entity.getDecl()->getDeclName();
7538 else
7539 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7540 }
7541 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7542 Entity.getMethodDecl())
7543 S.Diag(Entity.getMethodDecl()->getLocation(),
7544 diag::note_method_return_type_change)
7545 << Entity.getMethodDecl()->getDeclName();
7546}
7547
7548/// Returns true if the parameters describe a constructor initialization of
7549/// an explicit temporary object, e.g. "Point(x, y)".
7550static bool isExplicitTemporary(const InitializedEntity &Entity,
7551 const InitializationKind &Kind,
7552 unsigned NumArgs) {
7553 switch (Entity.getKind()) {
7557 break;
7558 default:
7559 return false;
7560 }
7561
7562 switch (Kind.getKind()) {
7564 return true;
7565 // FIXME: Hack to work around cast weirdness.
7568 return NumArgs != 1;
7569 default:
7570 return false;
7571 }
7572}
7573
7574static ExprResult
7576 const InitializedEntity &Entity,
7577 const InitializationKind &Kind,
7578 MultiExprArg Args,
7579 const InitializationSequence::Step& Step,
7580 bool &ConstructorInitRequiresZeroInit,
7581 bool IsListInitialization,
7582 bool IsStdInitListInitialization,
7583 SourceLocation LBraceLoc,
7584 SourceLocation RBraceLoc) {
7585 unsigned NumArgs = Args.size();
7588 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7589
7590 // Build a call to the selected constructor.
7591 SmallVector<Expr*, 8> ConstructorArgs;
7592 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7593 ? Kind.getEqualLoc()
7594 : Kind.getLocation();
7595
7596 if (Kind.getKind() == InitializationKind::IK_Default) {
7597 // Force even a trivial, implicit default constructor to be
7598 // semantically checked. We do this explicitly because we don't build
7599 // the definition for completely trivial constructors.
7600 assert(Constructor->getParent() && "No parent class for constructor.");
7601 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7602 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7603 S.runWithSufficientStackSpace(Loc, [&] {
7605 });
7606 }
7607 }
7608
7609 ExprResult CurInit((Expr *)nullptr);
7610
7611 // C++ [over.match.copy]p1:
7612 // - When initializing a temporary to be bound to the first parameter
7613 // of a constructor that takes a reference to possibly cv-qualified
7614 // T as its first argument, called with a single argument in the
7615 // context of direct-initialization, explicit conversion functions
7616 // are also considered.
7617 bool AllowExplicitConv =
7618 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7621
7622 // A smart pointer constructed from a nullable pointer is nullable.
7623 if (NumArgs == 1 && !Kind.isExplicitCast())
7625 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7626
7627 // Determine the arguments required to actually perform the constructor
7628 // call.
7629 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7630 ConstructorArgs, AllowExplicitConv,
7631 IsListInitialization))
7632 return ExprError();
7633
7634 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7635 // An explicitly-constructed temporary, e.g., X(1, 2).
7636 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7637 return ExprError();
7638
7639 if (Kind.getKind() == InitializationKind::IK_Value &&
7640 Constructor->isImplicit()) {
7641 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7642 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7643 unsigned I = 0;
7644 for (const FieldDecl *FD : RD->fields()) {
7645 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7646 !S.isUnevaluatedContext()) {
7647 S.Diag(Loc, diag::warn_field_requires_explicit_init)
7648 << /* Var-in-Record */ 0 << FD;
7649 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
7650 }
7651 ++I;
7652 }
7653 }
7654 }
7655
7656 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7657 if (!TSInfo)
7658 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7659 SourceRange ParenOrBraceRange =
7660 (Kind.getKind() == InitializationKind::IK_DirectList)
7661 ? SourceRange(LBraceLoc, RBraceLoc)
7662 : Kind.getParenOrBraceRange();
7663
7664 CXXConstructorDecl *CalleeDecl = Constructor;
7665 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7666 Step.Function.FoundDecl.getDecl())) {
7667 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7668 }
7669 S.MarkFunctionReferenced(Loc, CalleeDecl);
7670
7671 CurInit = S.CheckForImmediateInvocation(
7673 S.Context, CalleeDecl,
7674 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7675 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7676 IsListInitialization, IsStdInitListInitialization,
7677 ConstructorInitRequiresZeroInit),
7678 CalleeDecl);
7679 } else {
7681
7682 if (Entity.getKind() == InitializedEntity::EK_Base) {
7683 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7686 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7687 ConstructKind = CXXConstructionKind::Delegating;
7688 }
7689
7690 // Only get the parenthesis or brace range if it is a list initialization or
7691 // direct construction.
7692 SourceRange ParenOrBraceRange;
7693 if (IsListInitialization)
7694 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7695 else if (Kind.getKind() == InitializationKind::IK_Direct)
7696 ParenOrBraceRange = Kind.getParenOrBraceRange();
7697
7698 // If the entity allows NRVO, mark the construction as elidable
7699 // unconditionally.
7700 if (Entity.allowsNRVO())
7701 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7702 Step.Function.FoundDecl,
7703 Constructor, /*Elidable=*/true,
7704 ConstructorArgs,
7705 HadMultipleCandidates,
7706 IsListInitialization,
7707 IsStdInitListInitialization,
7708 ConstructorInitRequiresZeroInit,
7709 ConstructKind,
7710 ParenOrBraceRange);
7711 else
7712 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7713 Step.Function.FoundDecl,
7715 ConstructorArgs,
7716 HadMultipleCandidates,
7717 IsListInitialization,
7718 IsStdInitListInitialization,
7719 ConstructorInitRequiresZeroInit,
7720 ConstructKind,
7721 ParenOrBraceRange);
7722 }
7723 if (CurInit.isInvalid())
7724 return ExprError();
7725
7726 // Only check access if all of that succeeded.
7729 return ExprError();
7730
7731 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7733 return ExprError();
7734
7735 if (shouldBindAsTemporary(Entity))
7736 CurInit = S.MaybeBindToTemporary(CurInit.get());
7737
7738 return CurInit;
7739}
7740
7742 Expr *Init) {
7743 return sema::checkInitLifetime(*this, Entity, Init);
7744}
7745
7746static void DiagnoseNarrowingInInitList(Sema &S,
7747 const ImplicitConversionSequence &ICS,
7748 QualType PreNarrowingType,
7749 QualType EntityType,
7750 const Expr *PostInit);
7751
7752static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7753 QualType ToType, Expr *Init);
7754
7755/// Provide warnings when std::move is used on construction.
7756static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7757 bool IsReturnStmt) {
7758 if (!InitExpr)
7759 return;
7760
7762 return;
7763
7764 QualType DestType = InitExpr->getType();
7765 if (!DestType->isRecordType())
7766 return;
7767
7768 unsigned DiagID = 0;
7769 if (IsReturnStmt) {
7770 const CXXConstructExpr *CCE =
7771 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7772 if (!CCE || CCE->getNumArgs() != 1)
7773 return;
7774
7776 return;
7777
7778 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7779 }
7780
7781 // Find the std::move call and get the argument.
7782 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7783 if (!CE || !CE->isCallToStdMove())
7784 return;
7785
7786 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7787
7788 if (IsReturnStmt) {
7789 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7790 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7791 return;
7792
7793 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7794 if (!VD || !VD->hasLocalStorage())
7795 return;
7796
7797 // __block variables are not moved implicitly.
7798 if (VD->hasAttr<BlocksAttr>())
7799 return;
7800
7801 QualType SourceType = VD->getType();
7802 if (!SourceType->isRecordType())
7803 return;
7804
7805 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7806 return;
7807 }
7808
7809 // If we're returning a function parameter, copy elision
7810 // is not possible.
7811 if (isa<ParmVarDecl>(VD))
7812 DiagID = diag::warn_redundant_move_on_return;
7813 else
7814 DiagID = diag::warn_pessimizing_move_on_return;
7815 } else {
7816 DiagID = diag::warn_pessimizing_move_on_initialization;
7817 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7818 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7819 return;
7820 }
7821
7822 S.Diag(CE->getBeginLoc(), DiagID);
7823
7824 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7825 // is within a macro.
7826 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7827 if (CallBegin.isMacroID())
7828 return;
7829 SourceLocation RParen = CE->getRParenLoc();
7830 if (RParen.isMacroID())
7831 return;
7832 SourceLocation LParen;
7833 SourceLocation ArgLoc = Arg->getBeginLoc();
7834
7835 // Special testing for the argument location. Since the fix-it needs the
7836 // location right before the argument, the argument location can be in a
7837 // macro only if it is at the beginning of the macro.
7838 while (ArgLoc.isMacroID() &&
7841 }
7842
7843 if (LParen.isMacroID())
7844 return;
7845
7846 LParen = ArgLoc.getLocWithOffset(-1);
7847
7848 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7849 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7850 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7851}
7852
7853static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7854 // Check to see if we are dereferencing a null pointer. If so, this is
7855 // undefined behavior, so warn about it. This only handles the pattern
7856 // "*null", which is a very syntactic check.
7857 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7858 if (UO->getOpcode() == UO_Deref &&
7859 UO->getSubExpr()->IgnoreParenCasts()->
7860 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7861 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7862 S.PDiag(diag::warn_binding_null_to_reference)
7863 << UO->getSubExpr()->getSourceRange());
7864 }
7865}
7866
7869 bool BoundToLvalueReference) {
7870 auto MTE = new (Context)
7871 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7872
7873 // Order an ExprWithCleanups for lifetime marks.
7874 //
7875 // TODO: It'll be good to have a single place to check the access of the
7876 // destructor and generate ExprWithCleanups for various uses. Currently these
7877 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7878 // but there may be a chance to merge them.
7879 Cleanup.setExprNeedsCleanups(false);
7882 return MTE;
7883}
7884
7886 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7887 // same rule, but C99 is broken without this behavior and so we treat the
7888 // change as applying to all C language modes.
7889 // FIXME: This means that AST consumers need to deal with "prvalues" that
7890 // denote materialized temporaries. Maybe we should add another ValueKind
7891 // for "xvalue pretending to be a prvalue" for C++98 support.
7892 if (!E->isPRValue() ||
7894 return E;
7895
7896 // C++1z [conv.rval]/1: T shall be a complete type.
7897 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7898 // If so, we should check for a non-abstract class type here too.
7899 QualType T = E->getType();
7900 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7901 return ExprError();
7902
7903 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7904}
7905
7909
7910 CastKind CK = CK_NoOp;
7911
7912 if (VK == VK_PRValue) {
7913 auto PointeeTy = Ty->getPointeeType();
7914 auto ExprPointeeTy = E->getType()->getPointeeType();
7915 if (!PointeeTy.isNull() &&
7916 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7917 CK = CK_AddressSpaceConversion;
7918 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7919 CK = CK_AddressSpaceConversion;
7920 }
7921
7922 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7923}
7924
7926 const InitializedEntity &Entity,
7927 const InitializationKind &Kind,
7928 MultiExprArg Args,
7929 QualType *ResultType) {
7930 if (Failed()) {
7931 Diagnose(S, Entity, Kind, Args);
7932 return ExprError();
7933 }
7934 if (!ZeroInitializationFixit.empty()) {
7935 const Decl *D = Entity.getDecl();
7936 const auto *VD = dyn_cast_or_null<VarDecl>(D);
7937 QualType DestType = Entity.getType();
7938
7939 // The initialization would have succeeded with this fixit. Since the fixit
7940 // is on the error, we need to build a valid AST in this case, so this isn't
7941 // handled in the Failed() branch above.
7942 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7943 // Use a more useful diagnostic for constexpr variables.
7944 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7945 << VD
7946 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7947 ZeroInitializationFixit);
7948 } else {
7949 unsigned DiagID = diag::err_default_init_const;
7950 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7951 DiagID = diag::ext_default_init_const;
7952
7953 S.Diag(Kind.getLocation(), DiagID)
7954 << DestType << DestType->isRecordType()
7955 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7956 ZeroInitializationFixit);
7957 }
7958 }
7959
7960 if (getKind() == DependentSequence) {
7961 // If the declaration is a non-dependent, incomplete array type
7962 // that has an initializer, then its type will be completed once
7963 // the initializer is instantiated.
7964 if (ResultType && !Entity.getType()->isDependentType() &&
7965 Args.size() == 1) {
7966 QualType DeclType = Entity.getType();
7967 if (const IncompleteArrayType *ArrayT
7968 = S.Context.getAsIncompleteArrayType(DeclType)) {
7969 // FIXME: We don't currently have the ability to accurately
7970 // compute the length of an initializer list without
7971 // performing full type-checking of the initializer list
7972 // (since we have to determine where braces are implicitly
7973 // introduced and such). So, we fall back to making the array
7974 // type a dependently-sized array type with no specified
7975 // bound.
7976 if (isa<InitListExpr>((Expr *)Args[0]))
7977 *ResultType = S.Context.getDependentSizedArrayType(
7978 ArrayT->getElementType(),
7979 /*NumElts=*/nullptr, ArrayT->getSizeModifier(),
7980 ArrayT->getIndexTypeCVRQualifiers());
7981 }
7982 }
7983 if (Kind.getKind() == InitializationKind::IK_Direct &&
7984 !Kind.isExplicitCast()) {
7985 // Rebuild the ParenListExpr.
7986 SourceRange ParenRange = Kind.getParenOrBraceRange();
7987 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
7988 Args);
7989 }
7990 assert(Kind.getKind() == InitializationKind::IK_Copy ||
7991 Kind.isExplicitCast() ||
7992 Kind.getKind() == InitializationKind::IK_DirectList);
7993 return ExprResult(Args[0]);
7994 }
7995
7996 // No steps means no initialization.
7997 if (Steps.empty())
7998 return ExprResult((Expr *)nullptr);
7999
8000 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8001 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8002 !Entity.isParamOrTemplateParamKind()) {
8003 // Produce a C++98 compatibility warning if we are initializing a reference
8004 // from an initializer list. For parameters, we produce a better warning
8005 // elsewhere.
8006 Expr *Init = Args[0];
8007 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8008 << Init->getSourceRange();
8009 }
8010
8011 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8012 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8013 // Produce a Microsoft compatibility warning when initializing from a
8014 // predefined expression since MSVC treats predefined expressions as string
8015 // literals.
8016 Expr *Init = Args[0];
8017 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8018 }
8019
8020 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8021 QualType ETy = Entity.getType();
8022 bool HasGlobalAS = ETy.hasAddressSpace() &&
8024
8025 if (S.getLangOpts().OpenCLVersion >= 200 &&
8026 ETy->isAtomicType() && !HasGlobalAS &&
8027 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8028 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8029 << 1
8030 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8031 return ExprError();
8032 }
8033
8034 QualType DestType = Entity.getType().getNonReferenceType();
8035 // FIXME: Ugly hack around the fact that Entity.getType() is not
8036 // the same as Entity.getDecl()->getType() in cases involving type merging,
8037 // and we want latter when it makes sense.
8038 if (ResultType)
8039 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8040 Entity.getType();
8041
8042 ExprResult CurInit((Expr *)nullptr);
8043 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8044
8045 // HLSL allows vector/matrix initialization to function like list
8046 // initialization, but use the syntax of a C++-like constructor.
8047 bool IsHLSLVectorOrMatrixInit =
8048 S.getLangOpts().HLSL &&
8049 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
8050 isa<InitListExpr>(Args[0]);
8051 (void)IsHLSLVectorOrMatrixInit;
8052
8053 // For initialization steps that start with a single initializer,
8054 // grab the only argument out the Args and place it into the "current"
8055 // initializer.
8056 switch (Steps.front().Kind) {
8061 case SK_BindReference:
8063 case SK_FinalCopy:
8065 case SK_UserConversion:
8074 case SK_UnwrapInitList:
8075 case SK_RewrapInitList:
8076 case SK_CAssignment:
8077 case SK_StringInit:
8079 case SK_ArrayLoopIndex:
8080 case SK_ArrayLoopInit:
8081 case SK_ArrayInit:
8082 case SK_GNUArrayInit:
8088 case SK_OCLSamplerInit:
8091 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
8092 CurInit = Args[0];
8093 if (!CurInit.get()) return ExprError();
8094 break;
8095 }
8096
8102 break;
8103 }
8104
8105 // Promote from an unevaluated context to an unevaluated list context in
8106 // C++11 list-initialization; we need to instantiate entities usable in
8107 // constant expressions here in order to perform narrowing checks =(
8110 isa_and_nonnull<InitListExpr>(CurInit.get()));
8111
8112 // C++ [class.abstract]p2:
8113 // no objects of an abstract class can be created except as subobjects
8114 // of a class derived from it
8115 auto checkAbstractType = [&](QualType T) -> bool {
8116 if (Entity.getKind() == InitializedEntity::EK_Base ||
8118 return false;
8119 return S.RequireNonAbstractType(Kind.getLocation(), T,
8120 diag::err_allocation_of_abstract_type);
8121 };
8122
8123 // Walk through the computed steps for the initialization sequence,
8124 // performing the specified conversions along the way.
8125 bool ConstructorInitRequiresZeroInit = false;
8126 for (step_iterator Step = step_begin(), StepEnd = step_end();
8127 Step != StepEnd; ++Step) {
8128 if (CurInit.isInvalid())
8129 return ExprError();
8130
8131 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8132
8133 switch (Step->Kind) {
8135 // Overload resolution determined which function invoke; update the
8136 // initializer to reflect that choice.
8138 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8139 return ExprError();
8140 CurInit = S.FixOverloadedFunctionReference(CurInit,
8143 // We might get back another placeholder expression if we resolved to a
8144 // builtin.
8145 if (!CurInit.isInvalid())
8146 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8147 break;
8148
8152 // We have a derived-to-base cast that produces either an rvalue or an
8153 // lvalue. Perform that cast.
8154
8155 CXXCastPath BasePath;
8156
8157 // Casts to inaccessible base classes are allowed with C-style casts.
8158 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8160 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8161 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8162 return ExprError();
8163
8166 ? VK_LValue
8168 : VK_PRValue);
8170 CK_DerivedToBase, CurInit.get(),
8171 &BasePath, VK, FPOptionsOverride());
8172 break;
8173 }
8174
8175 case SK_BindReference:
8176 // Reference binding does not have any corresponding ASTs.
8177
8178 // Check exception specifications
8179 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8180 return ExprError();
8181
8182 // We don't check for e.g. function pointers here, since address
8183 // availability checks should only occur when the function first decays
8184 // into a pointer or reference.
8185 if (CurInit.get()->getType()->isFunctionProtoType()) {
8186 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8187 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8188 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8189 DRE->getBeginLoc()))
8190 return ExprError();
8191 }
8192 }
8193 }
8194
8195 CheckForNullPointerDereference(S, CurInit.get());
8196 break;
8197
8199 // Make sure the "temporary" is actually an rvalue.
8200 assert(CurInit.get()->isPRValue() && "not a temporary");
8201
8202 // Check exception specifications
8203 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8204 return ExprError();
8205
8206 QualType MTETy = Step->Type;
8207
8208 // When this is an incomplete array type (such as when this is
8209 // initializing an array of unknown bounds from an init list), use THAT
8210 // type instead so that we propagate the array bounds.
8211 if (MTETy->isIncompleteArrayType() &&
8212 !CurInit.get()->getType()->isIncompleteArrayType() &&
8215 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8216 MTETy = CurInit.get()->getType();
8217
8218 // Materialize the temporary into memory.
8220 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8221 CurInit = MTE;
8222
8223 // If we're extending this temporary to automatic storage duration -- we
8224 // need to register its cleanup during the full-expression's cleanups.
8225 if (MTE->getStorageDuration() == SD_Automatic &&
8226 MTE->getType().isDestructedType())
8228 break;
8229 }
8230
8231 case SK_FinalCopy:
8232 if (checkAbstractType(Step->Type))
8233 return ExprError();
8234
8235 // If the overall initialization is initializing a temporary, we already
8236 // bound our argument if it was necessary to do so. If not (if we're
8237 // ultimately initializing a non-temporary), our argument needs to be
8238 // bound since it's initializing a function parameter.
8239 // FIXME: This is a mess. Rationalize temporary destruction.
8240 if (!shouldBindAsTemporary(Entity))
8241 CurInit = S.MaybeBindToTemporary(CurInit.get());
8242 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8243 /*IsExtraneousCopy=*/false);
8244 break;
8245
8247 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8248 /*IsExtraneousCopy=*/true);
8249 break;
8250
8251 case SK_UserConversion: {
8252 // We have a user-defined conversion that invokes either a constructor
8253 // or a conversion function.
8257 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8258 bool CreatedObject = false;
8259 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8260 // Build a call to the selected constructor.
8261 SmallVector<Expr*, 8> ConstructorArgs;
8262 SourceLocation Loc = CurInit.get()->getBeginLoc();
8263
8264 // Determine the arguments required to actually perform the constructor
8265 // call.
8266 Expr *Arg = CurInit.get();
8268 MultiExprArg(&Arg, 1), Loc,
8269 ConstructorArgs))
8270 return ExprError();
8271
8272 // Build an expression that constructs a temporary.
8273 CurInit = S.BuildCXXConstructExpr(
8274 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8275 HadMultipleCandidates,
8276 /*ListInit*/ false,
8277 /*StdInitListInit*/ false,
8278 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8279 if (CurInit.isInvalid())
8280 return ExprError();
8281
8282 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8283 Entity);
8284 if (S.DiagnoseUseOfOverloadedDecl(Constructor, Kind.getLocation()))
8285 return ExprError();
8286
8287 CastKind = CK_ConstructorConversion;
8288 CreatedObject = true;
8289 } else {
8290 // Build a call to the conversion function.
8292 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8293 FoundFn);
8294 if (S.DiagnoseUseOfOverloadedDecl(Conversion, Kind.getLocation()))
8295 return ExprError();
8296
8297 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8298 HadMultipleCandidates);
8299 if (CurInit.isInvalid())
8300 return ExprError();
8301
8302 CastKind = CK_UserDefinedConversion;
8303 CreatedObject = Conversion->getReturnType()->isRecordType();
8304 }
8305
8306 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8307 return ExprError();
8308
8309 CurInit = ImplicitCastExpr::Create(
8310 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8311 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8312
8313 if (shouldBindAsTemporary(Entity))
8314 // The overall entity is temporary, so this expression should be
8315 // destroyed at the end of its full-expression.
8316 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8317 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8318 // The object outlasts the full-expression, but we need to prepare for
8319 // a destructor being run on it.
8320 // FIXME: It makes no sense to do this here. This should happen
8321 // regardless of how we initialized the entity.
8322 QualType T = CurInit.get()->getType();
8323 if (auto *Record = T->castAsCXXRecordDecl()) {
8326 S.PDiag(diag::err_access_dtor_temp) << T);
8328 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8329 return ExprError();
8330 }
8331 }
8332 break;
8333 }
8334
8338 // Perform a qualification conversion; these can never go wrong.
8341 ? VK_LValue
8343 : VK_PRValue);
8344 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8345 break;
8346 }
8347
8349 assert(CurInit.get()->isLValue() &&
8350 "function reference should be lvalue");
8351 CurInit =
8352 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8353 break;
8354
8355 case SK_AtomicConversion: {
8356 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8357 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8358 CK_NonAtomicToAtomic, VK_PRValue);
8359 break;
8360 }
8361
8364 if (const auto *FromPtrType =
8365 CurInit.get()->getType()->getAs<PointerType>()) {
8366 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8367 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8368 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8369 // Do not check static casts here because they are checked earlier
8370 // in Sema::ActOnCXXNamedCast()
8371 if (!Kind.isStaticCast()) {
8372 S.Diag(CurInit.get()->getExprLoc(),
8373 diag::warn_noderef_to_dereferenceable_pointer)
8374 << CurInit.get()->getSourceRange();
8375 }
8376 }
8377 }
8378 }
8379 Expr *Init = CurInit.get();
8381 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8382 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8383 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8385 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8386 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
8387 if (CurInitExprRes.isInvalid())
8388 return ExprError();
8389
8391
8392 CurInit = CurInitExprRes;
8393
8395 S.getLangOpts().CPlusPlus)
8396 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8397 CurInit.get());
8398
8399 break;
8400 }
8401
8402 case SK_ListInitialization: {
8403 if (checkAbstractType(Step->Type))
8404 return ExprError();
8405
8406 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8407 // If we're not initializing the top-level entity, we need to create an
8408 // InitializeTemporary entity for our target type.
8409 QualType Ty = Step->Type;
8410 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8411 InitializedEntity InitEntity =
8412 IsTemporary ? InitializedEntity::InitializeTemporary(Ty) : Entity;
8413 InitListChecker PerformInitList(S, InitEntity,
8414 InitList, Ty, /*VerifyOnly=*/false,
8415 /*TreatUnavailableAsInvalid=*/false);
8416 if (PerformInitList.HadError())
8417 return ExprError();
8418
8419 // Hack: We must update *ResultType if available in order to set the
8420 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8421 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8422 if (ResultType &&
8423 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8424 if ((*ResultType)->isRValueReferenceType())
8426 else if ((*ResultType)->isLValueReferenceType())
8428 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8429 *ResultType = Ty;
8430 }
8431
8432 InitListExpr *StructuredInitList =
8433 PerformInitList.getFullyStructuredList();
8434 CurInit = shouldBindAsTemporary(InitEntity)
8435 ? S.MaybeBindToTemporary(StructuredInitList)
8436 : StructuredInitList;
8437 break;
8438 }
8439
8441 if (checkAbstractType(Step->Type))
8442 return ExprError();
8443
8444 // When an initializer list is passed for a parameter of type "reference
8445 // to object", we don't get an EK_Temporary entity, but instead an
8446 // EK_Parameter entity with reference type.
8447 // FIXME: This is a hack. What we really should do is create a user
8448 // conversion step for this case, but this makes it considerably more
8449 // complicated. For now, this will do.
8451 Entity.getType().getNonReferenceType());
8452 bool UseTemporary = Entity.getType()->isReferenceType();
8453 assert(Args.size() == 1 && "expected a single argument for list init");
8454 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8455 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8456 << InitList->getSourceRange();
8457 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8458 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8459 Entity,
8460 Kind, Arg, *Step,
8461 ConstructorInitRequiresZeroInit,
8462 /*IsListInitialization*/true,
8463 /*IsStdInitListInit*/false,
8464 InitList->getLBraceLoc(),
8465 InitList->getRBraceLoc());
8466 break;
8467 }
8468
8469 case SK_UnwrapInitList:
8470 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8471 break;
8472
8473 case SK_RewrapInitList: {
8474 Expr *E = CurInit.get();
8476 InitListExpr *ILE = new (S.Context)
8477 InitListExpr(S.Context, Syntactic->getLBraceLoc(), E,
8478 Syntactic->getRBraceLoc(), Syntactic->isExplicit());
8479 ILE->setSyntacticForm(Syntactic);
8480 ILE->setType(E->getType());
8481 ILE->setValueKind(E->getValueKind());
8482 CurInit = ILE;
8483 break;
8484 }
8485
8488 if (checkAbstractType(Step->Type))
8489 return ExprError();
8490
8491 // When an initializer list is passed for a parameter of type "reference
8492 // to object", we don't get an EK_Temporary entity, but instead an
8493 // EK_Parameter entity with reference type.
8494 // FIXME: This is a hack. What we really should do is create a user
8495 // conversion step for this case, but this makes it considerably more
8496 // complicated. For now, this will do.
8498 Entity.getType().getNonReferenceType());
8499 bool UseTemporary = Entity.getType()->isReferenceType();
8500 bool IsStdInitListInit =
8502 Expr *Source = CurInit.get();
8503 SourceRange Range = Kind.hasParenOrBraceRange()
8504 ? Kind.getParenOrBraceRange()
8505 : SourceRange();
8507 S, UseTemporary ? TempEntity : Entity, Kind,
8508 Source ? MultiExprArg(Source) : Args, *Step,
8509 ConstructorInitRequiresZeroInit,
8510 /*IsListInitialization*/ IsStdInitListInit,
8511 /*IsStdInitListInitialization*/ IsStdInitListInit,
8512 /*LBraceLoc*/ Range.getBegin(),
8513 /*RBraceLoc*/ Range.getEnd());
8514 break;
8515 }
8516
8517 case SK_ZeroInitialization: {
8518 step_iterator NextStep = Step;
8519 ++NextStep;
8520 if (NextStep != StepEnd &&
8521 (NextStep->Kind == SK_ConstructorInitialization ||
8522 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8523 // The need for zero-initialization is recorded directly into
8524 // the call to the object's constructor within the next step.
8525 ConstructorInitRequiresZeroInit = true;
8526 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8527 S.getLangOpts().CPlusPlus &&
8528 !Kind.isImplicitValueInit()) {
8529 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8530 if (!TSInfo)
8532 Kind.getRange().getBegin());
8533
8534 CurInit = new (S.Context) CXXScalarValueInitExpr(
8535 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8536 Kind.getRange().getEnd());
8537 } else {
8538 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8539 // Note the return value isn't used to return a ExprError() when
8540 // initialization fails . For struct initialization allows all field
8541 // assignments to be checked rather than bailing on the first error.
8542 S.BoundsSafetyCheckInitialization(Entity, Kind,
8544 Step->Type, CurInit.get());
8545 }
8546 break;
8547 }
8548
8549 case SK_CAssignment: {
8550 QualType SourceType = CurInit.get()->getType();
8551 Expr *Init = CurInit.get();
8552
8553 // Save off the initial CurInit in case we need to emit a diagnostic
8554 ExprResult InitialCurInit = Init;
8557 Step->Type, Result, true,
8559 if (Result.isInvalid())
8560 return ExprError();
8561 CurInit = Result;
8562
8563 // If this is a call, allow conversion to a transparent union.
8564 ExprResult CurInitExprRes = CurInit;
8565 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8567 Step->Type, CurInitExprRes) == AssignConvertType::Compatible)
8569 if (CurInitExprRes.isInvalid())
8570 return ExprError();
8571 CurInit = CurInitExprRes;
8572
8573 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8574 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8575 CurInit.get());
8576
8577 // C23 6.7.1p6: If an object or subobject declared with storage-class
8578 // specifier constexpr has pointer, integer, or arithmetic type, any
8579 // explicit initializer value for it shall be null, an integer
8580 // constant expression, or an arithmetic constant expression,
8581 // respectively.
8583 if (Entity.getType()->getAs<PointerType>() &&
8584 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8585 (ER.Val.isLValue() && !ER.Val.isNullPointer())) {
8586 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8587 return ExprError();
8588 }
8589 }
8590
8591 // Note the return value isn't used to return a ExprError() when
8592 // initialization fails. For struct initialization this allows all field
8593 // assignments to be checked rather than bailing on the first error.
8594 S.BoundsSafetyCheckInitialization(Entity, Kind,
8595 getAssignmentAction(Entity, true),
8596 Step->Type, InitialCurInit.get());
8597
8598 bool Complained;
8599 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8600 Step->Type, SourceType,
8601 InitialCurInit.get(),
8602 getAssignmentAction(Entity, true),
8603 &Complained)) {
8604 PrintInitLocationNote(S, Entity);
8605 return ExprError();
8606 } else if (Complained)
8607 PrintInitLocationNote(S, Entity);
8608 break;
8609 }
8610
8611 case SK_StringInit: {
8612 QualType Ty = Step->Type;
8613 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8614 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8615 S.Context.getAsArrayType(Ty), S, Entity,
8616 S.getLangOpts().C23 &&
8618 break;
8619 }
8620
8622 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8623 CK_ObjCObjectLValueCast,
8624 CurInit.get()->getValueKind());
8625 break;
8626
8627 case SK_ArrayLoopIndex: {
8628 Expr *Cur = CurInit.get();
8629 Expr *BaseExpr = new (S.Context)
8630 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8631 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8632 Expr *IndexExpr =
8635 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8636 ArrayLoopCommonExprs.push_back(BaseExpr);
8637 break;
8638 }
8639
8640 case SK_ArrayLoopInit: {
8641 assert(!ArrayLoopCommonExprs.empty() &&
8642 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8643 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8644 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8645 CurInit.get());
8646 break;
8647 }
8648
8649 case SK_GNUArrayInit:
8650 // Okay: we checked everything before creating this step. Note that
8651 // this is a GNU extension.
8652 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8653 << Step->Type << CurInit.get()->getType()
8654 << CurInit.get()->getSourceRange();
8656 [[fallthrough]];
8657 case SK_ArrayInit:
8658 // If the destination type is an incomplete array type, update the
8659 // type accordingly.
8660 if (ResultType) {
8661 if (const IncompleteArrayType *IncompleteDest
8663 if (const ConstantArrayType *ConstantSource
8664 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8665 *ResultType = S.Context.getConstantArrayType(
8666 IncompleteDest->getElementType(), ConstantSource->getSize(),
8667 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8668 }
8669 }
8670 }
8671 break;
8672
8674 // Okay: we checked everything before creating this step. Note that
8675 // this is a GNU extension.
8676 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8677 << CurInit.get()->getSourceRange();
8678 break;
8679
8682 checkIndirectCopyRestoreSource(S, CurInit.get());
8683 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8684 CurInit.get(), Step->Type,
8686 break;
8687
8689 CurInit = ImplicitCastExpr::Create(
8690 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8692 break;
8693
8694 case SK_StdInitializerList: {
8695 S.Diag(CurInit.get()->getExprLoc(),
8696 diag::warn_cxx98_compat_initializer_list_init)
8697 << CurInit.get()->getSourceRange();
8698
8699 // Materialize the temporary into memory.
8701 CurInit.get()->getType(), CurInit.get(),
8702 /*BoundToLvalueReference=*/false);
8703
8704 // Wrap it in a construction of a std::initializer_list<T>.
8705 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8706
8707 if (!Step->Type->isDependentType()) {
8708 QualType ElementType;
8709 [[maybe_unused]] bool IsStdInitializerList =
8710 S.isStdInitializerList(Step->Type, &ElementType);
8711 assert(IsStdInitializerList &&
8712 "StdInitializerList step to non-std::initializer_list");
8713 const auto *Record = Step->Type->castAsCXXRecordDecl();
8714 assert(Record->isCompleteDefinition() &&
8715 "std::initializer_list should have already be "
8716 "complete/instantiated by this point");
8717
8718 auto InvalidType = [&] {
8719 S.Diag(Record->getLocation(),
8720 diag::err_std_initializer_list_malformed)
8722 return ExprError();
8723 };
8724
8725 if (Record->isUnion() || Record->getNumBases() != 0 ||
8726 Record->isPolymorphic())
8727 return InvalidType();
8728
8729 RecordDecl::field_iterator Field = Record->field_begin();
8730 if (Field == Record->field_end())
8731 return InvalidType();
8732
8733 // Start pointer
8734 if (!Field->getType()->isPointerType() ||
8735 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8736 ElementType.withConst()))
8737 return InvalidType();
8738
8739 if (++Field == Record->field_end())
8740 return InvalidType();
8741
8742 // Size or end pointer
8743 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8744 if (!S.Context.hasSameType(PT->getPointeeType(),
8745 ElementType.withConst()))
8746 return InvalidType();
8747 } else {
8748 if (Field->isBitField() ||
8749 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8750 return InvalidType();
8751 }
8752
8753 if (++Field != Record->field_end())
8754 return InvalidType();
8755 }
8756
8757 // Bind the result, in case the library has given initializer_list a
8758 // non-trivial destructor.
8759 if (shouldBindAsTemporary(Entity))
8760 CurInit = S.MaybeBindToTemporary(CurInit.get());
8761 break;
8762 }
8763
8764 case SK_OCLSamplerInit: {
8765 // Sampler initialization have 5 cases:
8766 // 1. function argument passing
8767 // 1a. argument is a file-scope variable
8768 // 1b. argument is a function-scope variable
8769 // 1c. argument is one of caller function's parameters
8770 // 2. variable initialization
8771 // 2a. initializing a file-scope variable
8772 // 2b. initializing a function-scope variable
8773 //
8774 // For file-scope variables, since they cannot be initialized by function
8775 // call of __translate_sampler_initializer in LLVM IR, their references
8776 // need to be replaced by a cast from their literal initializers to
8777 // sampler type. Since sampler variables can only be used in function
8778 // calls as arguments, we only need to replace them when handling the
8779 // argument passing.
8780 assert(Step->Type->isSamplerT() &&
8781 "Sampler initialization on non-sampler type.");
8782 Expr *Init = CurInit.get()->IgnoreParens();
8783 QualType SourceType = Init->getType();
8784 // Case 1
8785 if (Entity.isParameterKind()) {
8786 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8787 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8788 << SourceType;
8789 break;
8790 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8791 auto Var = cast<VarDecl>(DRE->getDecl());
8792 // Case 1b and 1c
8793 // No cast from integer to sampler is needed.
8794 if (!Var->hasGlobalStorage()) {
8795 CurInit = ImplicitCastExpr::Create(
8796 S.Context, Step->Type, CK_LValueToRValue, Init,
8797 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8798 break;
8799 }
8800 // Case 1a
8801 // For function call with a file-scope sampler variable as argument,
8802 // get the integer literal.
8803 // Do not diagnose if the file-scope variable does not have initializer
8804 // since this has already been diagnosed when parsing the variable
8805 // declaration.
8806 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8807 break;
8808 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8809 Var->getInit()))->getSubExpr();
8810 SourceType = Init->getType();
8811 }
8812 } else {
8813 // Case 2
8814 // Check initializer is 32 bit integer constant.
8815 // If the initializer is taken from global variable, do not diagnose since
8816 // this has already been done when parsing the variable declaration.
8817 if (!Init->isConstantInitializer(S.Context))
8818 break;
8819
8820 if (!SourceType->isIntegerType() ||
8821 32 != S.Context.getIntWidth(SourceType)) {
8822 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8823 << SourceType;
8824 break;
8825 }
8826
8827 Expr::EvalResult EVResult;
8828 Init->EvaluateAsInt(EVResult, S.Context);
8829 llvm::APSInt Result = EVResult.Val.getInt();
8830 const uint64_t SamplerValue = Result.getLimitedValue();
8831 // 32-bit value of sampler's initializer is interpreted as
8832 // bit-field with the following structure:
8833 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8834 // |31 6|5 4|3 1| 0|
8835 // This structure corresponds to enum values of sampler properties
8836 // defined in SPIR spec v1.2 and also opencl-c.h
8837 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8838 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8839 if (FilterMode != 1 && FilterMode != 2 &&
8841 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8842 S.Diag(Kind.getLocation(),
8843 diag::warn_sampler_initializer_invalid_bits)
8844 << "Filter Mode";
8845 if (AddressingMode > 4)
8846 S.Diag(Kind.getLocation(),
8847 diag::warn_sampler_initializer_invalid_bits)
8848 << "Addressing Mode";
8849 }
8850
8851 // Cases 1a, 2a and 2b
8852 // Insert cast from integer to sampler.
8854 CK_IntToOCLSampler);
8855 break;
8856 }
8857 case SK_OCLZeroOpaqueType: {
8858 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8860 "Wrong type for initialization of OpenCL opaque type.");
8861
8862 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8863 CK_ZeroToOCLOpaqueType,
8864 CurInit.get()->getValueKind());
8865 break;
8866 }
8868 CurInit = nullptr;
8869 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8870 /*VerifyOnly=*/false, &CurInit);
8871 if (CurInit.get() && ResultType)
8872 *ResultType = CurInit.get()->getType();
8873 if (shouldBindAsTemporary(Entity))
8874 CurInit = S.MaybeBindToTemporary(CurInit.get());
8875 break;
8876 }
8878 CurInit = ImplicitCastExpr::Create(
8879 S.Context, Step->Type.getLocalUnqualifiedType(), CK_LValueToRValue,
8880 CurInit.get(),
8881 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8882 break;
8883 }
8884 }
8885 }
8886
8887 Expr *Init = CurInit.get();
8888 if (!Init)
8889 return ExprError();
8890
8891 // Check whether the initializer has a shorter lifetime than the initialized
8892 // entity, and if not, either lifetime-extend or warn as appropriate.
8893 S.checkInitializerLifetime(Entity, Init);
8894
8895 // Diagnose non-fatal problems with the completed initialization.
8896 if (InitializedEntity::EntityKind EK = Entity.getKind();
8899 cast<FieldDecl>(Entity.getDecl())->isBitField())
8900 S.CheckBitFieldInitialization(Kind.getLocation(),
8901 cast<FieldDecl>(Entity.getDecl()), Init);
8902
8903 // Check for std::move on construction.
8906
8907 return Init;
8908}
8909
8910/// Somewhere within T there is an uninitialized reference subobject.
8911/// Dig it out and diagnose it.
8913 QualType T) {
8914 if (T->isReferenceType()) {
8915 S.Diag(Loc, diag::err_reference_without_init)
8916 << T.getNonReferenceType();
8917 return true;
8918 }
8919
8920 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8921 if (!RD || !RD->hasUninitializedReferenceMember())
8922 return false;
8923
8924 for (const auto *FI : RD->fields()) {
8925 if (FI->isUnnamedBitField())
8926 continue;
8927
8928 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8929 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8930 return true;
8931 }
8932 }
8933
8934 for (const auto &BI : RD->bases()) {
8935 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8936 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8937 return true;
8938 }
8939 }
8940
8941 return false;
8942}
8943
8944
8945//===----------------------------------------------------------------------===//
8946// Diagnose initialization failures
8947//===----------------------------------------------------------------------===//
8948
8949/// Emit notes associated with an initialization that failed due to a
8950/// "simple" conversion failure.
8951static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8952 Expr *op) {
8953 QualType destType = entity.getType();
8954 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8956
8957 // Emit a possible note about the conversion failing because the
8958 // operand is a message send with a related result type.
8960
8961 // Emit a possible note about a return failing because we're
8962 // expecting a related result type.
8963 if (entity.getKind() == InitializedEntity::EK_Result)
8965 }
8966 QualType fromType = op->getType();
8967 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8968 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8969 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8970 auto *destDecl = destType->getPointeeCXXRecordDecl();
8971 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8972 destDecl->getDeclKind() == Decl::CXXRecord &&
8973 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8974 !fromDecl->hasDefinition() &&
8975 destPointeeType.getQualifiers().compatiblyIncludes(
8976 fromPointeeType.getQualifiers(), S.getASTContext()))
8977 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8978 << S.getASTContext().getCanonicalTagType(fromDecl)
8979 << S.getASTContext().getCanonicalTagType(destDecl);
8980}
8981
8982static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8983 InitListExpr *InitList) {
8984 QualType DestType = Entity.getType();
8985
8986 QualType E;
8987 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8989 E.withConst(),
8990 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8991 InitList->getNumInits()),
8993 InitializedEntity HiddenArray =
8995 return diagnoseListInit(S, HiddenArray, InitList);
8996 }
8997
8998 if (DestType->isReferenceType()) {
8999 // A list-initialization failure for a reference means that we tried to
9000 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9001 // inner initialization failed.
9002 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9004 SourceLocation Loc = InitList->getBeginLoc();
9005 if (auto *D = Entity.getDecl())
9006 Loc = D->getLocation();
9007 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9008 return;
9009 }
9010
9011 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9012 /*VerifyOnly=*/false,
9013 /*TreatUnavailableAsInvalid=*/false);
9014 assert(DiagnoseInitList.HadError() &&
9015 "Inconsistent init list check result.");
9016}
9017
9019 const InitializedEntity &Entity,
9020 const InitializationKind &Kind,
9021 ArrayRef<Expr *> Args) {
9022 if (!Failed())
9023 return false;
9024
9025 QualType DestType = Entity.getType();
9026
9027 // When we want to diagnose only one element of a braced-init-list,
9028 // we need to factor it out.
9029 Expr *OnlyArg;
9030 if (Args.size() == 1) {
9031 auto *List = dyn_cast<InitListExpr>(Args[0]);
9032 if (List && List->getNumInits() == 1)
9033 OnlyArg = List->getInit(0);
9034 else
9035 OnlyArg = Args[0];
9036
9037 if (OnlyArg->getType() == S.Context.OverloadTy) {
9040 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
9041 Found)) {
9042 if (Expr *Resolved =
9043 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
9044 OnlyArg = Resolved;
9045 }
9046 }
9047 }
9048 else
9049 OnlyArg = nullptr;
9050
9051 switch (Failure) {
9053 // FIXME: Customize for the initialized entity?
9054 if (Args.empty()) {
9055 // Dig out the reference subobject which is uninitialized and diagnose it.
9056 // If this is value-initialization, this could be nested some way within
9057 // the target type.
9058 assert(Kind.getKind() == InitializationKind::IK_Value ||
9059 DestType->isReferenceType());
9060 bool Diagnosed =
9061 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9062 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9063 (void)Diagnosed;
9064 } else // FIXME: diagnostic below could be better!
9065 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9066 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9067 break;
9069 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9070 << 1 << Entity.getType() << Args[0]->getSourceRange();
9071 break;
9072
9074 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9075 break;
9077 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9078 break;
9080 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9081 break;
9083 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9084 break;
9086 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9087 break;
9089 S.Diag(Kind.getLocation(),
9090 diag::err_array_init_incompat_wide_string_into_wchar);
9091 break;
9093 S.Diag(Kind.getLocation(),
9094 diag::err_array_init_plain_string_into_char8_t);
9095 S.Diag(Args.front()->getBeginLoc(),
9096 diag::note_array_init_plain_string_into_char8_t)
9097 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9098 break;
9100 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9101 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9102 break;
9105 S.Diag(Kind.getLocation(),
9106 (Failure == FK_ArrayTypeMismatch
9107 ? diag::err_array_init_different_type
9108 : diag::err_array_init_non_constant_array))
9109 << DestType.getNonReferenceType()
9110 << OnlyArg->getType()
9111 << Args[0]->getSourceRange();
9112 break;
9113
9115 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9116 << Args[0]->getSourceRange();
9117 break;
9118
9122 DestType.getNonReferenceType(),
9123 true,
9124 Found);
9125 break;
9126 }
9127
9129 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9130 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9131 OnlyArg->getBeginLoc());
9132 break;
9133 }
9134
9137 switch (FailedOverloadResult) {
9138 case OR_Ambiguous:
9139
9140 FailedCandidateSet.NoteCandidates(
9142 Kind.getLocation(),
9144 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9145 << OnlyArg->getType() << DestType
9146 << Args[0]->getSourceRange())
9147 : (S.PDiag(diag::err_ref_init_ambiguous)
9148 << DestType << OnlyArg->getType()
9149 << Args[0]->getSourceRange())),
9150 S, OCD_AmbiguousCandidates, Args);
9151 break;
9152
9153 case OR_No_Viable_Function: {
9154 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9155 if (!S.RequireCompleteType(Kind.getLocation(),
9156 DestType.getNonReferenceType(),
9157 diag::err_typecheck_nonviable_condition_incomplete,
9158 OnlyArg->getType(), Args[0]->getSourceRange()))
9159 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9160 << (Entity.getKind() == InitializedEntity::EK_Result)
9161 << OnlyArg->getType() << Args[0]->getSourceRange()
9162 << DestType.getNonReferenceType();
9163
9164 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9165 break;
9166 }
9167 case OR_Deleted: {
9170 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9171
9172 StringLiteral *Msg = Best->Function->getDeletedMessage();
9173 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9174 << OnlyArg->getType() << DestType.getNonReferenceType()
9175 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9176 << Args[0]->getSourceRange();
9177 if (Ovl == OR_Deleted) {
9178 S.NoteDeletedFunction(Best->Function);
9179 } else {
9180 llvm_unreachable("Inconsistent overload resolution?");
9181 }
9182 break;
9183 }
9184
9185 case OR_Success:
9186 llvm_unreachable("Conversion did not fail!");
9187 }
9188 break;
9189
9191 if (isa<InitListExpr>(Args[0])) {
9192 S.Diag(Kind.getLocation(),
9193 diag::err_lvalue_reference_bind_to_initlist)
9195 << DestType.getNonReferenceType()
9196 << Args[0]->getSourceRange();
9197 break;
9198 }
9199 [[fallthrough]];
9200
9202 S.Diag(Kind.getLocation(),
9204 ? diag::err_lvalue_reference_bind_to_temporary
9205 : diag::err_lvalue_reference_bind_to_unrelated)
9207 << DestType.getNonReferenceType()
9208 << OnlyArg->getType()
9209 << Args[0]->getSourceRange();
9210 break;
9211
9213 // We don't necessarily have an unambiguous source bit-field.
9214 FieldDecl *BitField = Args[0]->getSourceBitField();
9215 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9216 << DestType.isVolatileQualified()
9217 << (BitField ? BitField->getDeclName() : DeclarationName())
9218 << (BitField != nullptr)
9219 << Args[0]->getSourceRange();
9220 if (BitField)
9221 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9222 break;
9223 }
9224
9226 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9227 << DestType.isVolatileQualified()
9228 << Args[0]->getSourceRange();
9229 break;
9230
9232 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9233 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9234 break;
9235
9237 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9238 << DestType.getNonReferenceType() << OnlyArg->getType()
9239 << Args[0]->getSourceRange();
9240 break;
9241
9243 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9244 << DestType << Args[0]->getSourceRange();
9245 break;
9246
9248 QualType SourceType = OnlyArg->getType();
9249 QualType NonRefType = DestType.getNonReferenceType();
9250 Qualifiers DroppedQualifiers =
9251 SourceType.getQualifiers() - NonRefType.getQualifiers();
9252
9253 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9254 SourceType.getQualifiers(), S.getASTContext()))
9255 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9256 << NonRefType << SourceType << 1 /*addr space*/
9257 << Args[0]->getSourceRange();
9258 else if (DroppedQualifiers.hasQualifiers())
9259 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9260 << NonRefType << SourceType << 0 /*cv quals*/
9261 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9262 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9263 else
9264 // FIXME: Consider decomposing the type and explaining which qualifiers
9265 // were dropped where, or on which level a 'const' is missing, etc.
9266 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9267 << NonRefType << SourceType << 2 /*incompatible quals*/
9268 << Args[0]->getSourceRange();
9269 break;
9270 }
9271
9273 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9274 << DestType.getNonReferenceType()
9275 << DestType.getNonReferenceType()->isIncompleteType()
9276 << OnlyArg->isLValue()
9277 << OnlyArg->getType()
9278 << Args[0]->getSourceRange();
9279 emitBadConversionNotes(S, Entity, Args[0]);
9280 break;
9281
9282 case FK_ConversionFailed: {
9283 QualType FromType = OnlyArg->getType();
9284 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op
9285 // type, although this is almost always an error and we advise against it.
9286 if (FromType == S.Context.AMDGPUFeaturePredicateTy &&
9287 DestType == S.Context.getLogicalOperationType()) {
9288 S.Diag(OnlyArg->getExprLoc(),
9289 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
9290 << OnlyArg << DestType;
9291 break;
9292 }
9293 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9294 << (int)Entity.getKind()
9295 << DestType
9296 << OnlyArg->isLValue()
9297 << FromType
9298 << Args[0]->getSourceRange();
9299 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9300 S.Diag(Kind.getLocation(), PDiag);
9301 emitBadConversionNotes(S, Entity, Args[0]);
9302 break;
9303 }
9304
9306 // No-op. This error has already been reported.
9307 break;
9308
9310 SourceRange R;
9311
9312 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9313 if (InitList && InitList->getNumInits() >= 1) {
9314 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9315 } else {
9316 assert(Args.size() > 1 && "Expected multiple initializers!");
9317 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9318 }
9319
9320 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9321 if (Kind.isCStyleOrFunctionalCast())
9322 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9323 << R;
9324 else
9325 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9326 << /*scalar=*/3 << R;
9327 break;
9328 }
9329
9331 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9332 << 0 << Entity.getType() << Args[0]->getSourceRange();
9333 break;
9334
9336 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9337 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9338 break;
9339
9341 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9342 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9343 break;
9344
9347 SourceRange ArgsRange;
9348 if (Args.size())
9349 ArgsRange =
9350 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9351
9352 if (Failure == FK_ListConstructorOverloadFailed) {
9353 assert(Args.size() == 1 &&
9354 "List construction from other than 1 argument.");
9355 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9356 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9357 }
9358
9359 // FIXME: Using "DestType" for the entity we're printing is probably
9360 // bad.
9361 switch (FailedOverloadResult) {
9362 case OR_Ambiguous:
9363 FailedCandidateSet.NoteCandidates(
9364 PartialDiagnosticAt(Kind.getLocation(),
9365 S.PDiag(diag::err_ovl_ambiguous_init)
9366 << DestType << ArgsRange),
9367 S, OCD_AmbiguousCandidates, Args);
9368 break;
9369
9371 if (Kind.getKind() == InitializationKind::IK_Default &&
9372 (Entity.getKind() == InitializedEntity::EK_Base ||
9376 // This is implicit default initialization of a member or
9377 // base within a constructor. If no viable function was
9378 // found, notify the user that they need to explicitly
9379 // initialize this base/member.
9382 const CXXRecordDecl *InheritedFrom = nullptr;
9383 if (auto Inherited = Constructor->getInheritedConstructor())
9384 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9385 if (Entity.getKind() == InitializedEntity::EK_Base) {
9386 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9387 << (InheritedFrom ? 2
9388 : Constructor->isImplicit() ? 1
9389 : 0)
9390 << S.Context.getCanonicalTagType(Constructor->getParent())
9391 << /*base=*/0 << Entity.getType() << InheritedFrom;
9392
9393 auto *BaseDecl =
9395 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9396 << S.Context.getCanonicalTagType(BaseDecl);
9397 } else {
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 << /*member=*/1 << Entity.getName() << InheritedFrom;
9404 S.Diag(Entity.getDecl()->getLocation(),
9405 diag::note_member_declared_at);
9406
9407 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9408 S.Diag(Record->getDecl()->getLocation(), diag::note_previous_decl)
9409 << S.Context.getCanonicalTagType(Record->getDecl());
9410 }
9411 break;
9412 }
9413
9414 FailedCandidateSet.NoteCandidates(
9416 Kind.getLocation(),
9417 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9418 << DestType << ArgsRange),
9419 S, OCD_AllCandidates, Args);
9420 break;
9421
9422 case OR_Deleted: {
9425 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9426 if (Ovl != OR_Deleted) {
9427 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9428 << DestType << ArgsRange;
9429 llvm_unreachable("Inconsistent overload resolution?");
9430 break;
9431 }
9432
9433 // If this is a defaulted or implicitly-declared function, then
9434 // it was implicitly deleted. Make it clear that the deletion was
9435 // implicit.
9436 if (S.isImplicitlyDeleted(Best->Function))
9437 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9438 << cast<CXXMethodDecl>(Best->Function)->getSpecialMemberKind()
9439 << DestType << ArgsRange;
9440 else {
9441 StringLiteral *Msg = Best->Function->getDeletedMessage();
9442 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9443 << DestType << (Msg != nullptr)
9444 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9445 }
9446
9447 // If it's a default constructed member, but it's not in the
9448 // constructor's initializer list, explicitly note where the member is
9449 // declared so the user can see which member is erroneously initialized
9450 // with a deleted default constructor.
9451 if (Kind.getKind() == InitializationKind::IK_Default &&
9454 S.Diag(Entity.getDecl()->getLocation(),
9455 diag::note_default_constructed_field)
9456 << Entity.getDecl();
9457 }
9458 S.NoteDeletedFunction(Best->Function);
9459 break;
9460 }
9461
9462 case OR_Success:
9463 llvm_unreachable("Conversion did not fail!");
9464 }
9465 }
9466 break;
9467
9469 if (Entity.getKind() == InitializedEntity::EK_Member &&
9471 // This is implicit default-initialization of a const member in
9472 // a constructor. Complain that it needs to be explicitly
9473 // initialized.
9475 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9476 << (Constructor->getInheritedConstructor() ? 2
9477 : Constructor->isImplicit() ? 1
9478 : 0)
9479 << S.Context.getCanonicalTagType(Constructor->getParent())
9480 << /*const=*/1 << Entity.getName();
9481 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9482 << Entity.getName();
9483 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9484 VD && VD->isConstexpr()) {
9485 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9486 << VD;
9487 } else {
9488 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9489 << DestType << DestType->isRecordType();
9490 }
9491 break;
9492
9493 case FK_Incomplete:
9494 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9495 diag::err_init_incomplete_type);
9496 break;
9497
9499 // Run the init list checker again to emit diagnostics.
9500 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9501 diagnoseListInit(S, Entity, InitList);
9502 break;
9503 }
9504
9505 case FK_PlaceholderType: {
9506 // FIXME: Already diagnosed!
9507 break;
9508 }
9509
9511 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9512 // allows us to diagnose the failure when it happens in the
9513 // TryListInitialization call instead of delaying the diagnosis, which is
9514 // beneficial because the flattening is also expensive.
9515 break;
9516 }
9517
9519 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9520 << Args[0]->getSourceRange();
9523 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9524 (void)Ovl;
9525 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9526 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9527 S.Diag(CtorDecl->getLocation(),
9528 diag::note_explicit_ctor_deduction_guide_here) << false;
9529 break;
9530 }
9531
9533 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9534 /*VerifyOnly=*/false);
9535 break;
9536
9538 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9539 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9540 << Entity.getType() << InitList->getSourceRange();
9541 break;
9542 }
9543
9544 PrintInitLocationNote(S, Entity);
9545 return true;
9546}
9547
9548void InitializationSequence::dump(raw_ostream &OS) const {
9549 switch (SequenceKind) {
9550 case FailedSequence: {
9551 OS << "Failed sequence: ";
9552 switch (Failure) {
9554 OS << "too many initializers for reference";
9555 break;
9556
9558 OS << "parenthesized list init for reference";
9559 break;
9560
9562 OS << "array requires initializer list";
9563 break;
9564
9566 OS << "address of unaddressable function was taken";
9567 break;
9568
9570 OS << "array requires initializer list or string literal";
9571 break;
9572
9574 OS << "array requires initializer list or wide string literal";
9575 break;
9576
9578 OS << "narrow string into wide char array";
9579 break;
9580
9582 OS << "wide string into char array";
9583 break;
9584
9586 OS << "incompatible wide string into wide char array";
9587 break;
9588
9590 OS << "plain string literal into char8_t array";
9591 break;
9592
9594 OS << "u8 string literal into char array";
9595 break;
9596
9598 OS << "array type mismatch";
9599 break;
9600
9602 OS << "non-constant array initializer";
9603 break;
9604
9606 OS << "address of overloaded function failed";
9607 break;
9608
9610 OS << "overload resolution for reference initialization failed";
9611 break;
9612
9614 OS << "non-const lvalue reference bound to temporary";
9615 break;
9616
9618 OS << "non-const lvalue reference bound to bit-field";
9619 break;
9620
9622 OS << "non-const lvalue reference bound to vector element";
9623 break;
9624
9626 OS << "non-const lvalue reference bound to matrix element";
9627 break;
9628
9630 OS << "non-const lvalue reference bound to unrelated type";
9631 break;
9632
9634 OS << "rvalue reference bound to an lvalue";
9635 break;
9636
9638 OS << "reference initialization drops qualifiers";
9639 break;
9640
9642 OS << "reference with mismatching address space bound to temporary";
9643 break;
9644
9646 OS << "reference initialization failed";
9647 break;
9648
9650 OS << "conversion failed";
9651 break;
9652
9654 OS << "conversion from property failed";
9655 break;
9656
9658 OS << "too many initializers for scalar";
9659 break;
9660
9662 OS << "parenthesized list init for reference";
9663 break;
9664
9666 OS << "referencing binding to initializer list";
9667 break;
9668
9670 OS << "initializer list for non-aggregate, non-scalar type";
9671 break;
9672
9674 OS << "overloading failed for user-defined conversion";
9675 break;
9676
9678 OS << "constructor overloading failed";
9679 break;
9680
9682 OS << "default initialization of a const variable";
9683 break;
9684
9685 case FK_Incomplete:
9686 OS << "initialization of incomplete type";
9687 break;
9688
9690 OS << "list initialization checker failure";
9691 break;
9692
9694 OS << "variable length array has an initializer";
9695 break;
9696
9697 case FK_PlaceholderType:
9698 OS << "initializer expression isn't contextually valid";
9699 break;
9700
9702 OS << "list constructor overloading failed";
9703 break;
9704
9706 OS << "list copy initialization chose explicit constructor";
9707 break;
9708
9710 OS << "parenthesized list initialization failed";
9711 break;
9712
9714 OS << "designated initializer for non-aggregate type";
9715 break;
9716
9718 OS << "HLSL initialization list flattening failed";
9719 break;
9720 }
9721 OS << '\n';
9722 return;
9723 }
9724
9725 case DependentSequence:
9726 OS << "Dependent sequence\n";
9727 return;
9728
9729 case NormalSequence:
9730 OS << "Normal sequence: ";
9731 break;
9732 }
9733
9734 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9735 if (S != step_begin()) {
9736 OS << " -> ";
9737 }
9738
9739 switch (S->Kind) {
9741 OS << "resolve address of overloaded function";
9742 break;
9743
9745 OS << "derived-to-base (prvalue)";
9746 break;
9747
9749 OS << "derived-to-base (xvalue)";
9750 break;
9751
9753 OS << "derived-to-base (lvalue)";
9754 break;
9755
9756 case SK_BindReference:
9757 OS << "bind reference to lvalue";
9758 break;
9759
9761 OS << "bind reference to a temporary";
9762 break;
9763
9764 case SK_FinalCopy:
9765 OS << "final copy in class direct-initialization";
9766 break;
9767
9769 OS << "extraneous C++03 copy to temporary";
9770 break;
9771
9772 case SK_UserConversion:
9773 OS << "user-defined conversion via " << *S->Function.Function;
9774 break;
9775
9777 OS << "qualification conversion (prvalue)";
9778 break;
9779
9781 OS << "qualification conversion (xvalue)";
9782 break;
9783
9785 OS << "qualification conversion (lvalue)";
9786 break;
9787
9789 OS << "function reference conversion";
9790 break;
9791
9793 OS << "non-atomic-to-atomic conversion";
9794 break;
9795
9797 OS << "implicit conversion sequence (";
9798 S->ICS->dump(); // FIXME: use OS
9799 OS << ")";
9800 break;
9801
9803 OS << "implicit conversion sequence with narrowing prohibited (";
9804 S->ICS->dump(); // FIXME: use OS
9805 OS << ")";
9806 break;
9807
9809 OS << "list aggregate initialization";
9810 break;
9811
9812 case SK_UnwrapInitList:
9813 OS << "unwrap reference initializer list";
9814 break;
9815
9816 case SK_RewrapInitList:
9817 OS << "rewrap reference initializer list";
9818 break;
9819
9821 OS << "constructor initialization";
9822 break;
9823
9825 OS << "list initialization via constructor";
9826 break;
9827
9829 OS << "zero initialization";
9830 break;
9831
9832 case SK_CAssignment:
9833 OS << "C assignment";
9834 break;
9835
9836 case SK_StringInit:
9837 OS << "string initialization";
9838 break;
9839
9841 OS << "Objective-C object conversion";
9842 break;
9843
9844 case SK_ArrayLoopIndex:
9845 OS << "indexing for array initialization loop";
9846 break;
9847
9848 case SK_ArrayLoopInit:
9849 OS << "array initialization loop";
9850 break;
9851
9852 case SK_ArrayInit:
9853 OS << "array initialization";
9854 break;
9855
9856 case SK_GNUArrayInit:
9857 OS << "array initialization (GNU extension)";
9858 break;
9859
9861 OS << "parenthesized array initialization";
9862 break;
9863
9865 OS << "pass by indirect copy and restore";
9866 break;
9867
9869 OS << "pass by indirect restore";
9870 break;
9871
9873 OS << "Objective-C object retension";
9874 break;
9875
9877 OS << "std::initializer_list from initializer list";
9878 break;
9879
9881 OS << "list initialization from std::initializer_list";
9882 break;
9883
9884 case SK_OCLSamplerInit:
9885 OS << "OpenCL sampler_t from integer constant";
9886 break;
9887
9889 OS << "OpenCL opaque type from zero";
9890 break;
9891
9893 OS << "initialization from a parenthesized list of values";
9894 break;
9895
9897 OS << "HLSL buffer conversion";
9898 break;
9899 }
9900
9901 OS << " [" << S->Type << ']';
9902 }
9903
9904 OS << '\n';
9905}
9906
9908 dump(llvm::errs());
9909}
9910
9912 const ImplicitConversionSequence &ICS,
9913 QualType PreNarrowingType,
9914 QualType EntityType,
9915 const Expr *PostInit) {
9916 const StandardConversionSequence *SCS = nullptr;
9917 switch (ICS.getKind()) {
9919 SCS = &ICS.Standard;
9920 break;
9922 SCS = &ICS.UserDefined.After;
9923 break;
9928 return;
9929 }
9930
9931 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9932 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9933 unsigned DiagID;
9934 auto &L = S.getLangOpts();
9935 if (L.CPlusPlus11 && !L.HLSL &&
9936 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9937 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9938 else
9939 DiagID = WarnDiagID;
9940 return S.Diag(PostInit->getBeginLoc(), DiagID)
9941 << PostInit->getSourceRange();
9942 };
9943
9944 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9945 APValue ConstantValue;
9946 QualType ConstantType;
9947 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9948 ConstantType)) {
9949 case NK_Not_Narrowing:
9951 // No narrowing occurred.
9952 return;
9953
9954 case NK_Type_Narrowing: {
9955 // This was a floating-to-integer conversion, which is always considered a
9956 // narrowing conversion even if the value is a constant and can be
9957 // represented exactly as an integer.
9958 QualType T = EntityType.getNonReferenceType();
9959 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9960 diag::ext_init_list_type_narrowing_const_reference,
9961 diag::warn_init_list_type_narrowing)
9962 << PreNarrowingType.getLocalUnqualifiedType()
9963 << T.getLocalUnqualifiedType();
9964 break;
9965 }
9966
9967 case NK_Constant_Narrowing: {
9968 // A constant value was narrowed.
9969 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9970 diag::ext_init_list_constant_narrowing,
9971 diag::ext_init_list_constant_narrowing_const_reference,
9972 diag::warn_init_list_constant_narrowing)
9973 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9975 break;
9976 }
9977
9978 case NK_Variable_Narrowing: {
9979 // A variable's value may have been narrowed.
9980 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9981 diag::ext_init_list_variable_narrowing,
9982 diag::ext_init_list_variable_narrowing_const_reference,
9983 diag::warn_init_list_variable_narrowing)
9984 << PreNarrowingType.getLocalUnqualifiedType()
9986 break;
9987 }
9988 }
9989
9990 SmallString<128> StaticCast;
9991 llvm::raw_svector_ostream OS(StaticCast);
9992 OS << "static_cast<";
9993 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9994 // It's important to use the typedef's name if there is one so that the
9995 // fixit doesn't break code using types like int64_t.
9996 //
9997 // FIXME: This will break if the typedef requires qualification. But
9998 // getQualifiedNameAsString() includes non-machine-parsable components.
9999 OS << *TT->getDecl();
10000 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10001 OS << BT->getName(S.getLangOpts());
10002 else {
10003 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10004 // with a broken cast.
10005 return;
10006 }
10007 OS << ">(";
10008 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10009 << PostInit->getSourceRange()
10010 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10012 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10013}
10014
10016 QualType ToType, Expr *Init) {
10017 assert(S.getLangOpts().C23);
10019 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10020 Sema::AllowedExplicit::None,
10021 /*InOverloadResolution*/ false,
10022 /*CStyle*/ false,
10023 /*AllowObjCWritebackConversion=*/false);
10024
10025 if (!ICS.isStandard())
10026 return;
10027
10028 APValue Value;
10029 QualType PreNarrowingType;
10030 // Reuse C++ narrowing check.
10031 switch (ICS.Standard.getNarrowingKind(
10032 S.Context, Init, Value, PreNarrowingType,
10033 /*IgnoreFloatToIntegralConversion*/ false)) {
10034 // The value doesn't fit.
10036 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10037 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10038 return;
10039
10040 // Conversion to a narrower type.
10041 case NK_Type_Narrowing:
10042 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10043 << ToType << FromType;
10044 return;
10045
10046 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10047 // not really interested in these cases.
10050 case NK_Not_Narrowing:
10051 return;
10052 }
10053 llvm_unreachable("unhandled case in switch");
10054}
10055
10057 Sema &SemaRef, QualType &TT) {
10058 assert(SemaRef.getLangOpts().C23);
10059 // character that string literal contains fits into TT - target type.
10060 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10061 QualType CharType = AT->getElementType();
10062 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10063 bool isUnsigned = CharType->isUnsignedIntegerType();
10064 llvm::APSInt Value(BitWidth, isUnsigned);
10065 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10066 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10067 Value = C;
10068 if (Value != C) {
10069 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10070 diag::err_c23_constexpr_init_not_representable)
10071 << C << CharType;
10072 return;
10073 }
10074 }
10075}
10076
10077//===----------------------------------------------------------------------===//
10078// Initialization helper functions
10079//===----------------------------------------------------------------------===//
10080bool
10082 ExprResult Init) {
10083 if (Init.isInvalid())
10084 return false;
10085
10086 Expr *InitE = Init.get();
10087 assert(InitE && "No initialization expression");
10088
10089 InitializationKind Kind =
10091 InitializationSequence Seq(*this, Entity, Kind, InitE);
10092 return !Seq.Failed();
10093}
10094
10097 SourceLocation EqualLoc,
10099 bool TopLevelOfInitList,
10100 bool AllowExplicit) {
10101 if (Init.isInvalid())
10102 return ExprError();
10103
10104 Expr *InitE = Init.get();
10105 assert(InitE && "No initialization expression?");
10106
10107 if (EqualLoc.isInvalid())
10108 EqualLoc = InitE->getBeginLoc();
10109
10110 if (Entity.getType().getDesugaredType(Context) ==
10111 Context.AMDGPUFeaturePredicateTy &&
10112 Entity.getDecl()) {
10113 Diag(EqualLoc, diag::err_amdgcn_predicate_type_is_not_constructible)
10114 << Entity.getDecl();
10115 return ExprError();
10116 }
10117
10119 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10120 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10121
10122 // Prevent infinite recursion when performing parameter copy-initialization.
10123 const bool ShouldTrackCopy =
10124 Entity.isParameterKind() && Seq.isConstructorInitialization();
10125 if (ShouldTrackCopy) {
10126 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10127 Seq.SetOverloadFailure(
10130
10131 // Try to give a meaningful diagnostic note for the problematic
10132 // constructor.
10133 const auto LastStep = Seq.step_end() - 1;
10134 assert(LastStep->Kind ==
10136 const FunctionDecl *Function = LastStep->Function.Function;
10137 auto Candidate =
10138 llvm::find_if(Seq.getFailedCandidateSet(),
10139 [Function](const OverloadCandidate &Candidate) -> bool {
10140 return Candidate.Viable &&
10141 Candidate.Function == Function &&
10142 Candidate.Conversions.size() > 0;
10143 });
10144 if (Candidate != Seq.getFailedCandidateSet().end() &&
10145 Function->getNumParams() > 0) {
10146 Candidate->Viable = false;
10149 InitE,
10150 Function->getParamDecl(0)->getType());
10151 }
10152 }
10153 CurrentParameterCopyTypes.push_back(Entity.getType());
10154 }
10155
10156 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10157
10158 if (ShouldTrackCopy)
10159 CurrentParameterCopyTypes.pop_back();
10160
10161 return Result;
10162}
10163
10164/// Determine whether RD is, or is derived from, a specialization of CTD.
10166 ClassTemplateDecl *CTD) {
10167 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10168 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10169 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10170 };
10171 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10172}
10173
10175 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10176 const InitializationKind &Kind, MultiExprArg Inits) {
10177 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10178 TSInfo->getType()->getContainedDeducedType());
10179 assert(DeducedTST && "not a deduced template specialization type");
10180
10181 auto TemplateName = DeducedTST->getTemplateName();
10183 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10184
10185 // We can only perform deduction for class templates or alias templates.
10186 auto *Template =
10187 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10188 TemplateDecl *LookupTemplateDecl = Template;
10189 if (!Template) {
10190 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10192 DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
10193 LookupTemplateDecl = AliasTemplate;
10194 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10195 ->getUnderlyingType()
10196 .getCanonicalType();
10197 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10198 // of the form
10199 // [typename] [nested-name-specifier] [template] simple-template-id
10200 if (const auto *TST =
10201 UnderlyingType->getAs<TemplateSpecializationType>()) {
10202 Template = dyn_cast_or_null<ClassTemplateDecl>(
10203 TST->getTemplateName().getAsTemplateDecl());
10204 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10205 // Cases where template arguments in the RHS of the alias are not
10206 // dependent. e.g.
10207 // using AliasFoo = Foo<bool>;
10208 if (const auto *CTSD =
10209 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
10210 Template = CTSD->getSpecializedTemplate();
10211 }
10212 }
10213 }
10214 if (!Template) {
10215 Diag(Kind.getLocation(),
10216 diag::err_deduced_non_class_or_alias_template_specialization_type)
10218 if (auto *TD = TemplateName.getAsTemplateDecl())
10220 return QualType();
10221 }
10222
10223 // Can't deduce from dependent arguments.
10225 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10226 diag::warn_cxx14_compat_class_template_argument_deduction)
10227 << TSInfo->getTypeLoc().getSourceRange() << 0;
10228 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10229 }
10230
10231 // FIXME: Perform "exact type" matching first, per CWG discussion?
10232 // Or implement this via an implied 'T(T) -> T' deduction guide?
10233
10234 // Look up deduction guides, including those synthesized from constructors.
10235 //
10236 // C++1z [over.match.class.deduct]p1:
10237 // A set of functions and function templates is formed comprising:
10238 // - For each constructor of the class template designated by the
10239 // template-name, a function template [...]
10240 // - For each deduction-guide, a function or function template [...]
10241 DeclarationNameInfo NameInfo(
10242 Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),
10243 TSInfo->getTypeLoc().getEndLoc());
10244 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10245 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10246
10247 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10248 // clear on this, but they're not found by name so access does not apply.
10249 Guides.suppressDiagnostics();
10250
10251 // Figure out if this is list-initialization.
10253 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10254 ? dyn_cast<InitListExpr>(Inits[0])
10255 : nullptr;
10256
10257 // C++1z [over.match.class.deduct]p1:
10258 // Initialization and overload resolution are performed as described in
10259 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10260 // (as appropriate for the type of initialization performed) for an object
10261 // of a hypothetical class type, where the selected functions and function
10262 // templates are considered to be the constructors of that class type
10263 //
10264 // Since we know we're initializing a class type of a type unrelated to that
10265 // of the initializer, this reduces to something fairly reasonable.
10266 OverloadCandidateSet Candidates(Kind.getLocation(),
10269
10270 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10271
10272 // Return true if the candidate is added successfully, false otherwise.
10273 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10275 DeclAccessPair FoundDecl,
10276 bool OnlyListConstructors,
10277 bool AllowAggregateDeductionCandidate) {
10278 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10279 // For copy-initialization, the candidate functions are all the
10280 // converting constructors (12.3.1) of that class.
10281 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10282 // The converting constructors of T are candidate functions.
10283 if (!AllowExplicit) {
10284 // Overload resolution checks whether the deduction guide is declared
10285 // explicit for us.
10286
10287 // When looking for a converting constructor, deduction guides that
10288 // could never be called with one argument are not interesting to
10289 // check or note.
10290 if (GD->getMinRequiredArguments() > 1 ||
10291 (GD->getNumParams() == 0 && !GD->isVariadic()))
10292 return;
10293 }
10294
10295 // C++ [over.match.list]p1.1: (first phase list initialization)
10296 // Initially, the candidate functions are the initializer-list
10297 // constructors of the class T
10298 if (OnlyListConstructors && !isInitListConstructor(GD))
10299 return;
10300
10301 if (!AllowAggregateDeductionCandidate &&
10302 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10303 return;
10304
10305 // C++ [over.match.list]p1.2: (second phase list initialization)
10306 // the candidate functions are all the constructors of the class T
10307 // C++ [over.match.ctor]p1: (all other cases)
10308 // the candidate functions are all the constructors of the class of
10309 // the object being initialized
10310
10311 // C++ [over.best.ics]p4:
10312 // When [...] the constructor [...] is a candidate by
10313 // - [over.match.copy] (in all cases)
10314 if (TD) {
10315
10316 // As template candidates are not deduced immediately,
10317 // persist the array in the overload set.
10318 MutableArrayRef<Expr *> TmpInits =
10319 Candidates.getPersistentArgsArray(Inits.size());
10320
10321 for (auto [I, E] : llvm::enumerate(Inits)) {
10322 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10323 TmpInits[I] = DI->getInit();
10324 else
10325 TmpInits[I] = E;
10326 }
10327
10329 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10330 /*SuppressUserConversions=*/false,
10331 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10332 /*PO=*/{}, AllowAggregateDeductionCandidate);
10333 } else {
10334 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10335 /*SuppressUserConversions=*/false,
10336 /*PartialOverloading=*/false, AllowExplicit);
10337 }
10338 };
10339
10340 bool FoundDeductionGuide = false;
10341
10342 auto TryToResolveOverload =
10343 [&](bool OnlyListConstructors) -> OverloadingResult {
10345 bool HasAnyDeductionGuide = false;
10346
10347 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10348 auto *Pattern = Template;
10349 while (Pattern->getInstantiatedFromMemberTemplate()) {
10350 if (Pattern->isMemberSpecialization())
10351 break;
10352 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10353 }
10354
10355 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10356 if (!(RD->getDefinition() && RD->isAggregate()))
10357 return;
10358 QualType Ty = Context.getCanonicalTagType(RD);
10359 SmallVector<QualType, 8> ElementTypes;
10360
10361 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10362 if (!CheckInitList.HadError()) {
10363 // C++ [over.match.class.deduct]p1.8:
10364 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10365 // rvalue reference to the declared type of e_i and
10366 // C++ [over.match.class.deduct]p1.9:
10367 // if e_i is of array type and x_i is a string-literal, T_i is an
10368 // lvalue reference to the const-qualified declared type of e_i and
10369 // C++ [over.match.class.deduct]p1.10:
10370 // otherwise, T_i is the declared type of e_i
10371 for (int I = 0, E = ListInit->getNumInits();
10372 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10373 if (ElementTypes[I]->isArrayType()) {
10375 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10376 else if (isa<StringLiteral>(
10377 ListInit->getInit(I)->IgnoreParenImpCasts()))
10378 ElementTypes[I] =
10379 Context.getLValueReferenceType(ElementTypes[I].withConst());
10380 }
10381
10382 if (CXXDeductionGuideDecl *GD =
10384 LookupTemplateDecl, ElementTypes,
10385 TSInfo->getTypeLoc().getEndLoc())) {
10386 auto *TD = GD->getDescribedFunctionTemplate();
10387 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10388 OnlyListConstructors,
10389 /*AllowAggregateDeductionCandidate=*/true);
10390 HasAnyDeductionGuide = true;
10391 }
10392 }
10393 };
10394
10395 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10396 NamedDecl *D = (*I)->getUnderlyingDecl();
10397 if (D->isInvalidDecl())
10398 continue;
10399
10400 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10401 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10402 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10403 if (!GD)
10404 continue;
10405
10406 if (!GD->isImplicit())
10407 HasAnyDeductionGuide = true;
10408
10409 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10410 /*AllowAggregateDeductionCandidate=*/false);
10411 }
10412
10413 // C++ [over.match.class.deduct]p1.4:
10414 // if C is defined and its definition satisfies the conditions for an
10415 // aggregate class ([dcl.init.aggr]) with the assumption that any
10416 // dependent base class has no virtual functions and no virtual base
10417 // classes, and the initializer is a non-empty braced-init-list or
10418 // parenthesized expression-list, and there are no deduction-guides for
10419 // C, the set contains an additional function template, called the
10420 // aggregate deduction candidate, defined as follows.
10421 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10422 if (ListInit && ListInit->getNumInits()) {
10423 SynthesizeAggrGuide(ListInit);
10424 } else if (Inits.size()) { // parenthesized expression-list
10425 // Inits are expressions inside the parentheses. We don't have
10426 // the parentheses source locations, use the begin/end of Inits as the
10427 // best heuristic.
10428 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10429 Inits, Inits.back()->getEndLoc(),
10430 /*isExplicit=*/false);
10431 SynthesizeAggrGuide(&TempListInit);
10432 }
10433 }
10434
10435 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10436
10437 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10438 };
10439
10441
10442 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10443 // try initializer-list constructors.
10444 if (ListInit) {
10445 bool TryListConstructors = true;
10446
10447 // Try list constructors unless the list is empty and the class has one or
10448 // more default constructors, in which case those constructors win.
10449 if (!ListInit->getNumInits()) {
10450 for (NamedDecl *D : Guides) {
10451 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10452 if (FD && FD->getMinRequiredArguments() == 0) {
10453 TryListConstructors = false;
10454 break;
10455 }
10456 }
10457 } else if (ListInit->getNumInits() == 1) {
10458 // C++ [over.match.class.deduct]:
10459 // As an exception, the first phase in [over.match.list] (considering
10460 // initializer-list constructors) is omitted if the initializer list
10461 // consists of a single expression of type cv U, where U is a
10462 // specialization of C or a class derived from a specialization of C.
10463 Expr *E = ListInit->getInit(0);
10464 auto *RD = E->getType()->getAsCXXRecordDecl();
10465 if (!isa<InitListExpr>(E) && RD &&
10466 isCompleteType(Kind.getLocation(), E->getType()) &&
10468 TryListConstructors = false;
10469 }
10470
10471 if (TryListConstructors)
10472 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10473 // Then unwrap the initializer list and try again considering all
10474 // constructors.
10475 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10476 }
10477
10478 // If list-initialization fails, or if we're doing any other kind of
10479 // initialization, we (eventually) consider constructors.
10481 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10482
10483 switch (Result) {
10484 case OR_Ambiguous:
10485 // FIXME: For list-initialization candidates, it'd usually be better to
10486 // list why they were not viable when given the initializer list itself as
10487 // an argument.
10488 Candidates.NoteCandidates(
10490 Kind.getLocation(),
10491 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10492 << TemplateName),
10494 return QualType();
10495
10496 case OR_No_Viable_Function: {
10497 CXXRecordDecl *Primary =
10498 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10499 bool Complete = isCompleteType(Kind.getLocation(),
10500 Context.getCanonicalTagType(Primary));
10501 Candidates.NoteCandidates(
10503 Kind.getLocation(),
10504 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10505 : diag::err_deduced_class_template_incomplete)
10506 << TemplateName << !Guides.empty()),
10507 *this, OCD_AllCandidates, Inits);
10508 return QualType();
10509 }
10510
10511 case OR_Deleted: {
10512 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10513 // like we ever get here; attempts to trigger this seem to yield a
10514 // generic c'all to deleted function' diagnostic instead.
10515 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10516 << TemplateName;
10517 NoteDeletedFunction(Best->Function);
10518 return QualType();
10519 }
10520
10521 case OR_Success:
10522 // C++ [over.match.list]p1:
10523 // In copy-list-initialization, if an explicit constructor is chosen, the
10524 // initialization is ill-formed.
10525 if (Kind.isCopyInit() && ListInit &&
10526 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10527 bool IsDeductionGuide = !Best->Function->isImplicit();
10528 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10529 << TemplateName << IsDeductionGuide;
10530 Diag(Best->Function->getLocation(),
10531 diag::note_explicit_ctor_deduction_guide_here)
10532 << IsDeductionGuide;
10533 return QualType();
10534 }
10535
10536 // Make sure we didn't select an unusable deduction guide, and mark it
10537 // as referenced.
10538 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
10539 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10540 break;
10541 }
10542
10543 // C++ [dcl.type.class.deduct]p1:
10544 // The placeholder is replaced by the return type of the function selected
10545 // by overload resolution for class template deduction.
10546 QualType DeducedType =
10547 SubstAutoTypeSourceInfo(TSInfo, Best->Function->getReturnType())
10548 ->getType();
10549 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10550 diag::warn_cxx14_compat_class_template_argument_deduction)
10551 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10552
10553 // Warn if CTAD was used on a type that does not have any user-defined
10554 // deduction guides.
10555 if (!FoundDeductionGuide) {
10556 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10557 diag::warn_ctad_maybe_unsupported)
10558 << TemplateName;
10559 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10560 }
10561
10562 return DeducedType;
10563}
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:123
APSInt & getInt()
Definition APValue.h:512
bool isLValue() const
Definition APValue.h:494
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:985
bool isNullPointer() const
Definition APValue.cpp:1048
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
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
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:965
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:3813
QualType getElementType() const
Definition TypeBase.h:3825
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:2642
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2882
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2719
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:2977
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3013
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:2001
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
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:1168
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1407
CXXBaseSpecifier * base_class_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:518
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition DeclCXX.h:606
base_class_range bases()
Definition DeclCXX.h:609
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:603
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1569
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:521
llvm::iterator_range< base_class_iterator > base_class_range
Definition DeclCXX.h:605
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:3851
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:374
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3927
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4500
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:2279
DeclContextLookupResult lookup_result
Definition DeclBase.h:2627
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:2423
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:4829
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:4938
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:4933
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:4945
MutableArrayRef< Designator > designators()
Definition Expr.h:5834
Expr * getArrayIndex(const Designator &D) const
Definition Expr.cpp:4928
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:4907
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4924
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:4870
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:970
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:4326
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:4891
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
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:3889
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:3868
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:4000
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:3708
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:4428
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4442
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:1491
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:1413
@ 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:3396
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:8512
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8517
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3810
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:8428
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8554
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8468
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:8613
QualType getCanonicalType() const
Definition TypeBase.h:8480
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8522
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8501
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8549
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:3726
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:5340
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3671
bool isSpelledAsLValue() const
Definition TypeBase.h:3684
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:9394
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9402
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:10468
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10471
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10477
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10475
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:6971
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.
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:9079
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:7007
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10496
ExprResult BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field, const InitializedEntity &MemberEntity)
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:8240
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8107
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7019
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:8232
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:14079
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:13822
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15623
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)
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)
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:8399
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:8410
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9037
bool isBooleanType() const
Definition TypeBase.h:9174
bool isMFloat8Type() const
Definition TypeBase.h:9062
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9224
bool isIncompleteArrayType() const
Definition TypeBase.h:8772
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2388
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2295
bool isRValueReferenceType() const
Definition TypeBase.h:8697
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:8764
bool isCharType() const
Definition Type.cpp:2315
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isConstantMatrixType() const
Definition TypeBase.h:8832
bool isArrayParameterType() const
Definition TypeBase.h:8780
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9081
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9331
bool isReferenceType() const
Definition TypeBase.h:8689
bool isEnumeralType() const
Definition TypeBase.h:8796
bool isScalarType() const
Definition TypeBase.h:9143
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:2076
bool isChar8Type() const
Definition Type.cpp:2331
bool isSizelessBuiltinType() const
Definition Type.cpp:2747
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:881
bool isExtVectorType() const
Definition TypeBase.h:8808
bool isOCLIntelSubgroupAVCType() const
Definition TypeBase.h:8950
bool isLValueReferenceType() const
Definition TypeBase.h:8693
bool isOpenCLSpecificType() const
Definition TypeBase.h:8965
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:2627
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8800
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2231
bool isQueueT() const
Definition TypeBase.h:8921
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9217
bool isAtomicType() const
Definition TypeBase.h:8857
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8828
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isObjCObjectType() const
Definition TypeBase.h:8848
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9317
bool isEventT() const
Definition TypeBase.h:8913
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2651
bool isFunctionType() const
Definition TypeBase.h:8661
bool isObjCObjectPointerType() const
Definition TypeBase.h:8844
bool isVectorType() const
Definition TypeBase.h:8804
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2529
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:2513
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:2456
bool isSamplerT() const
Definition TypeBase.h:8909
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9264
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:782
bool isNullPtrType() const
Definition TypeBase.h:9074
bool isRecordType() const
Definition TypeBase.h:8792
bool isObjCRetainableType() const
Definition Type.cpp:5591
bool isUnionType() const
Definition Type.cpp:847
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:4057
Represents a GCC generic vector type.
Definition TypeBase.h:4266
unsigned getNumElements() const
Definition TypeBase.h:4281
VectorKind getVectorKind() const
Definition TypeBase.h:4286
QualType getElementType() const
Definition TypeBase.h:4280
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:1524
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
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_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:1516
DeclAccessPair FoundDecl
Definition Overload.h:1515
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
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6861
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:507